From b064f658f1fe0ea3ef4a8ea5e2cc507232569c50 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:14:07 +0800 Subject: [PATCH 001/458] feat(satin): price the history bytes a deployment appends The byte table gains the sizes of a transaction body, an EIP-7702 authorization and an access-list entry, next to the log and write-record sizes the layer already counted, and the engine gains what a byte of history costs: every count times the cost per history byte, read from the same prices the state entries are built from. The schedule gives code_deposit_history_gas the price of one byte, which is the one history charge revm makes itself, so a deployment now pays for the bytes every node has to carry: a thirty-two byte deployment draws 2,816 history gas beside its state gas. --- crates/mega-evm/src/evm/history.rs | 112 +++++++++++++++++++ crates/mega-evm/src/evm/mod.rs | 2 + crates/mega-evm/src/evm/prices.rs | 19 ++-- crates/mega-evm/src/evm/schedule.rs | 43 +++++-- crates/mega-evm/src/limit/mod.rs | 48 ++++++++ crates/mega-evm/tests/satin/common.rs | 10 ++ crates/mega-evm/tests/satin/history_gas.rs | 67 +++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/pricing-table.md | 6 +- crates/mega-evm/tests/satin/pricing_table.rs | 10 +- 10 files changed, 291 insertions(+), 27 deletions(-) create mode 100644 crates/mega-evm/src/evm/history.rs create mode 100644 crates/mega-evm/tests/satin/history_gas.rs diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs new file mode 100644 index 000000000..dc6bc856f --- /dev/null +++ b/crates/mega-evm/src/evm/history.rs @@ -0,0 +1,112 @@ +//! 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 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)?) +} + +/// The history bytes a `LOG` with `topics` topics and `data_len` bytes of data 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) +} + +/// 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}; + + /// 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"); + } + + /// 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"); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 45dd80c3f..d8d2f21ee 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; @@ -23,6 +24,7 @@ pub use context::*; pub use execution::*; pub use factory::*; pub use frame::*; +pub use history::*; pub use host::*; pub use inspector::*; pub use precompiles::*; diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index eff2c8ce1..2539f5768 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. @@ -427,8 +425,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 +439,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/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 85edbf934..134c284d1 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -22,9 +22,12 @@ //! 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. //! +//! The one entry outside Amsterdam's table is the history price of deposited code +//! ([`HISTORY_GAS_PRICED`]): 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. +//! //! 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 @@ -93,6 +96,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 @@ -116,6 +126,9 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { 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 +136,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}, }; @@ -201,15 +216,16 @@ mod tests { /// 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_other_prices_move_only_the_byte_priced_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); + STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || + HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id); if rebuilt { continue; } @@ -232,12 +248,14 @@ mod tests { } } - /// History gas is a later mechanism; until it lands the schedule prices no history byte, the - /// way Osaka and Amsterdam do not. + /// 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_the_history_entry_is_not_priced_yet() { + 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 +284,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 +297,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/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 4b15f1d45..851a51689 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -8,6 +8,13 @@ //! 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. +//! +//! # 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, 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. mod frame_limit; #[allow(clippy::module_inception)] @@ -30,6 +37,33 @@ pub const LOG_BASE_SIZE: u64 = 32; /// Bytes every log topic counts. pub const LOG_TOPIC_SIZE: u64 = 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; + +/// 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; + /// 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. @@ -227,6 +261,20 @@ impl LimitCheck { 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!(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); + } + #[test] fn test_limit_usage_arithmetic_saturates() { let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 054d77f6e..628d68dfb 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -7,6 +7,7 @@ use mega_evm::{ active_satin_prices, test_utils::{op_transaction, zero_fee_l1_block_info}, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, }; use revm::{ context::{result::ResultAndState, BlockEnv, TxEnv}, @@ -59,6 +60,15 @@ 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") +} + /// 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 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..c75e70847 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -0,0 +1,67 @@ +//! 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}, + test_utils::{BytecodeBuilder, MemoryDatabase}, +}; +use revm::bytecode::opcode::{PUSH0, RETURN, REVERT}; + +use crate::common::{create, execute, runs_at_measurement_prices}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); + +/// 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; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) +} + +/// Init code that deploys `len` zero bytes: `PUSH len; PUSH0; RETURN`. +fn deploying(len: u64) -> Bytes { + BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() +} + +/// 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, 32 * CPHB, "the deployed bytes"); + assert_eq!(reverted.gas.history, 0, "nothing was deployed"); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6c6ddbe74..7c65a01a5 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,6 +4,7 @@ mod common; mod contract_size; mod db_error; mod equivalence; +mod history_gas; mod inspector; mod intrinsic; mod outcome; diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index ff4f1592b..a837a9a34 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-8038 repricing pressed back to Osaka, 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 three applies. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -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 @@ -73,7 +73,7 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | 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 | +| create transaction deploying 32 bytes | 259484 | 24108 | 232560 | 2816 | ## SALT scaling diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 9389ff4ba..d05dc1000 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -141,9 +141,9 @@ 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-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", + pressed back to Osaka, 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 three applies.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -309,7 +309,8 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { // 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. + // 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, [ @@ -327,6 +328,7 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { "tx_create_cost", "sstore_set_refund", "sstore_reset_refund", + "code_deposit_history_gas", ], "the entries Satin prices differently from Amsterdam" ); From 7877727b774c59f78d90ea6212349c2be3cdb683 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:29:22 +0800 Subject: [PATCH 002/458] feat(satin): charge the transaction body's history as intrinsic gas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A transaction's body is fixed before it runs — its envelope, the write records its inclusion makes, its calldata, its authorizations and its access list — so its history is part of what a gas limit has to cover for the transaction to be valid: a limit that falls short is rejected before inclusion rather than included as an out-of-gas that burns the whole limit. The charge rides in the EIP-8037 intrinsic state-gas slot, which is the pool it is paid from, reservoir first, so it does not take the execution cap away from computation; post-execution takes it back out of the state gas the result reports. Three kinds of transaction pay none of it: a deposit, a transaction the protocol itself produced and a system call. They run a schedule that prices a deposited byte at zero, so the one history charge revm makes itself is off them too. State gas is charged as usual. The EIP-7623 calldata floor is still computed and validated and no longer decides a bill: history charges the same bytes at a higher rate, so a Satin transaction is above its own floor from the first byte on. The equivalence baseline holds every transaction to op-revm's total plus the history ledger, with the refund cap and the floor comparison following the larger total as they already do for state gas. --- crates/mega-evm/src/evm/context.rs | 51 ++++- crates/mega-evm/src/evm/execution.rs | 104 ++++++++- crates/mega-evm/src/evm/schedule.rs | 33 +++ crates/mega-evm/src/limit/limit.rs | 18 ++ crates/mega-evm/tests/block/counters.rs | 9 +- crates/mega-evm/tests/block/limits.rs | 3 +- crates/mega-evm/tests/block/rules.rs | 7 +- crates/mega-evm/tests/satin/equivalence.rs | 199 +++++++++++++++--- .../mega-evm/tests/satin/history_exemption.rs | 167 +++++++++++++++ crates/mega-evm/tests/satin/history_gas.rs | 60 +++++- crates/mega-evm/tests/satin/intrinsic.rs | 166 ++++++++++++--- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/outcome.rs | 13 +- crates/mega-evm/tests/satin/pricing-table.md | 30 +-- crates/mega-evm/tests/satin/schedule.rs | 35 ++- crates/mega-evm/tests/satin/strategic_stop.rs | 41 +++- .../tests/satin/synthetic_frame_gas.rs | 21 +- crates/mega-evm/tests/satin/write_records.rs | 15 +- 18 files changed, 844 insertions(+), 129 deletions(-) create mode 100644 crates/mega-evm/tests/satin/history_exemption.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 79edf4446..298b208d2 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,16 +1,20 @@ //! The execution context of the Satin engine. 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}, + context::{ + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, + Transaction, + }, + context_interface::cfg::GasId, primitives::{Address, StorageKey}, Database, Journal, }; use crate::{ constants, - evm::schedule::satin_gas_params, + evm::schedule::{satin_gas_params, satin_gas_params_history_exempt}, system::{self, MEGA_SYSTEM_ADDRESS}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, @@ -45,6 +49,8 @@ pub struct MegaContext MegaContext { @@ -71,6 +77,7 @@ impl MegaContext { block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), system_originated: false, + prices_history: true, } } @@ -195,6 +202,23 @@ impl MegaContext { self.system_originated } + /// Whether the running (or last) transaction pays history gas for the bytes it appends. + /// + /// 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 or system call. Every entry /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. /// @@ -204,6 +228,8 @@ impl MegaContext { self.additional_limit.reset(); self.bucket_multipliers.reset(); self.system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); + let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || self.system_originated; + self.set_history_exempt(exempt); } /// Prepares the context for a system call. Every system-call entry point of @@ -214,6 +240,25 @@ impl MegaContext { pub(crate) fn on_new_system_call(&mut self) { self.on_new_tx(); self.system_originated = true; + self.set_history_exempt(true); + } + + /// 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. + fn set_history_exempt(&mut self, exempt: bool) { + 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. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 441be53ff..9e3149677 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -17,8 +17,9 @@ 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::{AccessListItemTr, TransactionType}, + ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, @@ -44,8 +45,8 @@ use revm::{ }; use crate::{ - evm::inspector::frame_end_checked, - synthetic_frame_result, + evm::{history::tx_body_history_bytes, inspector::frame_end_checked}, + history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, MegaInstructions, }; @@ -150,11 +151,55 @@ where 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. + /// + /// 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. + fn validate_initial_tx_gas( + &self, + evm: &mut Self::Evm, + ) -> Result { + let mut gas = self.op.validate_initial_tx_gas(evm)?; + let history = + if evm.ctx_ref().prices_history() { tx_body_history_gas(evm.ctx_ref()) } else { 0 }; + if history == 0 { + return Ok(gas); + } + 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_gas(history); + Ok(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. + /// Keeps the history gas the transaction spent: what the body was charged, and what the frames + /// charged net of what they gave back. fn last_frame_result( &mut self, evm: &mut Self::Evm, @@ -163,11 +208,30 @@ 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); + 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); 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, @@ -601,6 +665,32 @@ fn inspect_logs( } } +/// The history gas a transaction's body costs: its envelope and the write records its inclusion +/// makes, its calldata, its authorizations and its access list, at the cost per history byte. +/// +/// A byte count large enough to have no price saturates to `u64::MAX`, which no gas limit covers, +/// so such a transaction is rejected for not covering its own intrinsic gas. +fn tx_body_history_gas( + ctx: &MegaContext, +) -> u64 { + let tx = ctx.tx(); + 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(); + let bytes = tx_body_history_bytes( + tx.input().len() as u64, + tx.authorization_list_len() as u64, + addresses, + slots, + ); + history_gas(bytes).unwrap_or(u64::MAX) +} + /// 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. diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 134c284d1..2e894a781 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -115,6 +115,23 @@ 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 gas schedule at `prices`. pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { let osaka = GasParams::new_spec(SpecId::OSAKA); @@ -248,6 +265,22 @@ mod tests { } } + /// 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] diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d6622c6ff..8c7720f11 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -47,6 +47,9 @@ pub struct AdditionalLimit { /// 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 validation charged for the transaction's body, part of + /// [`history_gas_spent`](Self::history_gas_spent). + intrinsic_history_gas: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, } @@ -75,6 +78,7 @@ impl AdditionalLimit { self.target_is_authority = false; self.sender = Address::ZERO; self.frame_began = false; + self.intrinsic_history_gas = 0; self.history_gas_spent = 0; } @@ -140,6 +144,20 @@ 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. + pub(crate) const fn set_intrinsic_history_gas(&mut self, gas: u64) { + self.intrinsic_history_gas = gas; + } + /// 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; diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index b2183ea81..72b453821 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -123,6 +123,9 @@ fn test_the_execution_limit_packs_the_crossing_transaction_and_skips_the_next() /// 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. +/// +/// 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_state_and_history_ledgers_refuse_nothing() { let mut state = state_with_writer(); @@ -135,5 +138,9 @@ fn test_the_state_and_history_ledgers_refuse_nothing() { 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"); + assert_eq!( + counters.history, + 3 * mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE, + "three empty bodies, and these transactions append nothing else", + ); } diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 3df9fa232..2595d497e 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -476,7 +476,8 @@ 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 intrinsic charge and the body's history. + const TX_GAS_LIMIT: u64 = 300_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); diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index d9c12c9fe..98aba7f75 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -174,9 +174,10 @@ fn test_da_footprint_over_the_block_budget_refuses_the_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; + // Above what the transaction has to pay under the Satin gas table — its intrinsic charge and + // its body's history — and below the footprint the scalar yields, so the block's gas limit + // still fits the transaction's gas. + const GAS_LIMIT: u64 = 2_200_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); diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 69debde23..6d37aaff9 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -1,12 +1,17 @@ //! 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 +//! 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. The six cases at the end are the ones that diverge for a reason of their own — 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. +//! 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. //! //! 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,20 +19,23 @@ //! 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, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, }; -use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use op_revm::{constants::BASE_FEE_RECIPIENT, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ context::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, - context_interface::cfg::gas_params::Eip2780TxInfo, + context_interface::cfg::{gas_params::Eip2780TxInfo, GasId}, inspector::NoOpInspector, state::EvmState, ExecuteEvm, Journal, @@ -58,8 +66,9 @@ 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()) } @@ -68,9 +77,9 @@ 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 +100,56 @@ 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 as it is, 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 > 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!(mega.state, op.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"); @@ -137,8 +194,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] @@ -156,7 +218,7 @@ 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_same_but_history(&mega, &op); } #[test] @@ -180,7 +242,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"); @@ -210,7 +272,26 @@ fn test_fees_match_op_revm() { 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); + 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,7 +312,22 @@ 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. + // 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()); + 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(), + satin_gas_params().get(GasId::sstore_clearing_slot_refund()), + "Satin keeps the whole clearing refund", + ); + assert_same_but_history(&mega, &op); } /// A system call runs exactly as op-revm runs it. @@ -425,8 +521,10 @@ fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { // 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(); + // The two run the same bytecode on the same input, so what is left once the history ledger + // every Satin transaction carries is taken off is the charge. + 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 @@ -454,11 +552,58 @@ fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { "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, + mega.result.gas().tx_gas_used() - op.result.gas().tx_gas_used() - mega.gas.history < + charged, "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", ); } +/// 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!( + 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!( + with_data.result.gas().total_gas_spent() - op_with_data.result.gas().total_gas_spent(), + with_data.gas.history, + ); + 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. /// /// The transaction, the configuration, the block and the database are the ones @@ -486,7 +631,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,9 +645,9 @@ 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 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..35e932f10 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -0,0 +1,167 @@ +//! 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 mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::context::TxEnv; + +use crate::common::{context, 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 — one of each history site the engine charges. +fn program() -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .push_number(0u64) + .push_number(32u64) + .push_number(0u64) + .append(revm::bytecode::opcode::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(revm::bytecode::opcode::CALL) + .append(revm::bytecode::opcode::POP) + // CREATE(0, 0, 0): an empty deployment, which still creates an account + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .append(revm::bytecode::opcode::CREATE) + .append(revm::bytecode::opcode::POP) + .stop() + .build() +} + +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) +} + +/// 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() + })) +} + +/// Runs `tx` and reports its history and state ledgers. +fn ledgers(tx: MegaTransaction) -> (u64, u64) { + 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) +} + +/// 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) = 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"); +} + +/// 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 mut tx = call_from(CALLER, CONTRACT); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.base.gas_price = 0; + let (history, state) = ledgers(tx); + assert_eq!(history, 0, "a deposit pays no history gas"); + assert!(state > 0, "the exemption is history's alone"); +} + +/// 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 it writes a slot of its own. + let tx = call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + 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"); +} + +/// 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"); +} + +/// 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 mut deposit = call_from(CALLER, CONTRACT); + deposit.0.deposit.source_hash = B256::repeat_byte(0x11); + deposit.0.base.gas_price = 0; + let exempt = evm.execute_transaction(deposit).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"); +} diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index c75e70847..09adb5ce9 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -7,12 +7,14 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}, test_utils::{BytecodeBuilder, MemoryDatabase}, + TX_BODY_SIZE, }; use revm::bytecode::opcode::{PUSH0, RETURN, REVERT}; -use crate::common::{create, execute, runs_at_measurement_prices}; +use crate::common::{call, call_with_data, create, execute, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const CALLEE: Address = address!("0000000000000000000000000000000000200001"); /// Room for the state gas of a new account and the code it deposits. const GAS_LIMIT: u64 = 50_000_000; @@ -20,6 +22,11 @@ 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))) } @@ -62,6 +69,53 @@ fn test_a_reverted_deployment_pays_no_code_deposit_history() { assert!(deployed.result.is_success(), "{:?}", deployed.result); assert!(!reverted.result.is_success(), "the creation reverts"); - assert_eq!(deployed.gas.history, 32 * CPHB, "the deployed bytes"); - assert_eq!(reverted.gas.history, 0, "nothing was deployed"); + assert_eq!( + deployed.gas.history, + body(deploying(32).len() as u64) + 32 * CPHB, + "the body the init code travels in, and the deployed bytes", + ); + assert_eq!( + reverted.gas.history, + body(reverting().len() as u64), + "the body alone: nothing was deployed", + ); +} + +/* ---------- the transaction body ---------- */ + +/// Every transaction pays for its own body before it runs: the envelope and the records of the +/// writes its inclusion makes, whatever else it does. +#[test] +fn test_every_transaction_pays_for_its_body() { + if runs_at_measurement_prices() { + return; + } + let db = || funded().account_code(CALLEE, Bytes::new()); + let empty = execute(db(), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + + assert!(empty.result.is_success(), "{:?}", empty.result); + assert_eq!(empty.gas.history, body(0)); + assert_eq!(empty.gas.history, 310 * 88, "310 bytes at the cost per history byte"); + assert_eq!(empty.gas.state, 0, "the body is history, not state"); +} + +/// 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"); } diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 4b9d75581..a1c2e3149 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -1,19 +1,24 @@ -//! 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. +//! +//! 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 revm::{ context::{ @@ -42,6 +47,14 @@ const EMPTY_CALL: u64 = 15_000; /// 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. +const HISTORY_PER_BYTE: u64 = COST_PER_HISTORY_BYTE; + +/// The history gas a transaction carrying `bytes` bytes beside its envelope pays for its body. +const fn body_history(bytes: u64) -> u64 { + (TX_BODY_SIZE + bytes) * HISTORY_PER_BYTE +} + /// A database where the sender can pay and `CALLEE` exists. fn funded() -> MemoryDatabase { MemoryDatabase::default() @@ -51,11 +64,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 +105,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 +123,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 +131,40 @@ 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. #[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); + assert_eq!( + non_zeros.gas_used - zeros.gas_used, + 1_024 * 12, + "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 ---------- */ @@ -134,7 +191,12 @@ fn with_access_list(keys: usize) -> MegaTransaction { /// 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)); + 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 + 2_400 + 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 @@ -144,18 +206,16 @@ fn test_an_access_list_address_is_priced_at_the_pre_eip8038_rate() { 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] { 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(EMPTY_CALL + 2_400 + 1_900 * keys + body_history(20 + 32 * keys)), + "{keys} keys: the intrinsic charge and the entry's bytes of history" ); } } @@ -166,19 +226,25 @@ fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { /// 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 +255,12 @@ 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); + assert_eq!( + charged.gas_used, + EMPTY_CALL + 4 * LARGEST_CALLDATA + body_history(LARGEST_CALLDATA) + ); let expected = format!( "{:?}", @@ -287,5 +358,34 @@ fn test_a_gas_limit_below_the_intrinsic_charge_is_rejected() { /// 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. +#[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); + let expected = |gas_limit| { + format!( + "{:?}", + InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas: minimum } + ) + }; + for gas_limit in [EMPTY_CALL, EMPTY_CALL + 1, minimum - 1] { + assert_eq!( + gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, gas_limit)), + Err(expected(gas_limit)), + "a gas limit of {gas_limit} does not cover the body", + ); + } + assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, minimum)), Ok(minimum)); + assert_sender_untouched(); } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 7c65a01a5..fcbc1dbed 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,6 +4,7 @@ mod common; mod contract_size; mod db_error; mod equivalence; +mod history_exemption; mod history_gas; mod inspector; mod intrinsic; diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 95fd050d9..67363706f 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -3,10 +3,10 @@ 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}; @@ -48,8 +48,12 @@ 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"); + // The body's history comes out of the same reservoir, before the state gas does. + assert_eq!(gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE, "the transaction's body"); + 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: 2 * WRITE_RECORD_SIZE, write_records: 2 }); assert_eq!(outcome.limit_exceeded, None); @@ -58,6 +62,7 @@ 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. diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index a837a9a34..5b0fd1af5 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -65,15 +65,15 @@ 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 | 259484 | 24108 | 232560 | 2816 | +| empty call | 42280 | 15000 | 0 | 27280 | +| value transfer to an existing account | 48280 | 21000 | 0 | 27280 | +| self-transfer | 39280 | 12000 | 0 | 27280 | +| SSTORE 0 -> 1 | 162306 | 37106 | 97920 | 27280 | +| SSTORE 0 -> 1 -> 0 | 51594 | 37212 | 0 | 27280 | +| value CALL to an empty account | 260201 | 49321 | 183600 | 27280 | +| LOG1 with 32 data bytes | 43298 | 16018 | 0 | 27280 | +| create transaction deploying 0 bytes | 235935 | 24087 | 183600 | 28248 | +| create transaction deploying 32 bytes | 287732 | 24108 | 232560 | 31064 | ## SALT scaling @@ -81,12 +81,12 @@ The same probes again, with the SALT bucket the state charge lands in at `m` tim | 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 | 162306 | 37106 | 97920 | 27280 | +| SSTORE 0 -> 1 | 2 | 260226 | 37106 | 195840 | 27280 | +| SSTORE 0 -> 1 | 8 | 847746 | 37106 | 783360 | 27280 | +| value CALL to an empty account | 1 | 260201 | 49321 | 183600 | 27280 | +| value CALL to an empty account | 2 | 443801 | 49321 | 367200 | 27280 | +| value CALL to an empty account | 8 | 1545401 | 49321 | 1468800 | 27280 | ## The execution cap diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 3a2e1c780..6f02c7485 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -3,6 +3,10 @@ //! 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}; @@ -23,18 +27,27 @@ const CALLEE: Address = address!("0000000000000000000000000000000000900001"); const GAS_LIMIT: u64 = 1_000_000; -/// The gas a transaction used and the state gas inside it. +/// The gas a transaction used, the state gas inside it and the history gas the schedule does not +/// price. struct Spend { gas_used: u64, state: u64, + history: 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 } } /// A database where `CALLEE` exists and runs `code`. @@ -54,7 +67,7 @@ fn with_code(code: Bytes) -> MemoryDatabase { #[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.schedule_gas(), 15_000); assert_eq!(spent.state, 0); } @@ -64,7 +77,7 @@ fn test_an_empty_call_costs_fifteen_thousand() { 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.schedule_gas(), 21_000); assert_eq!(spent.state, 0); } @@ -78,7 +91,7 @@ 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); + 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 @@ -87,7 +100,7 @@ fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas( 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.schedule_gas(), 12_000); assert_eq!(spent.state, 0); } @@ -102,7 +115,7 @@ fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_g 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"); + 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 @@ -118,7 +131,7 @@ fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { // 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, + spent.schedule_gas() - spent.state, fixed + token * len + word * words, "{len} bytes of init code" ); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 50bc64773..a57da9837 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -88,6 +88,17 @@ fn run( (result, evm.ctx().additional_limit().latched().copied()) } +/// The history gas an empty transaction body costs, which every transaction here pays before its +/// first frame and keeps whatever that frame does. +const fn body_history() -> u64 { + mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE +} + +/// The same for a creation transaction, whose init code travels as the body's data. +const fn create_body_history(init_code_len: u64) -> u64 { + (mega_evm::TX_BODY_SIZE + init_code_len) * mega_evm::constants::COST_PER_HISTORY_BYTE +} + fn cap(bytes: u64) -> EvmTxRuntimeLimits { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) } @@ -255,7 +266,11 @@ fn test_stop_refills_the_reservoir_at_any_gas_limit() { 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,7 +280,7 @@ 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 gas_limit = 21_000 + body_history() + 5_000; let (result, latched) = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); assert!( matches!( @@ -321,7 +336,11 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { 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, @@ -434,9 +453,13 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { 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 init_code = writer(); + let tx = crate::common::create(CALLER, init_code.clone(), 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); + 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 @@ -514,7 +537,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. @@ -545,13 +569,14 @@ 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, body_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); + // The body is charged before the first frame, so the stop keeps it and takes back the rest. let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); assert_stopped(&stopped.result, LimitKind::DataSize, 180); - assert_eq!(stopped.gas.history, 0); + assert_eq!(stopped.gas.history, body_history()); } /// Under the latch every returned result is the stop, whatever an inspector made of it: rewriting diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 8e9752edc..2b7468020 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -45,6 +45,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. +const fn body_history(calldata_len: u64) -> u64 { + (mega_evm::TX_BODY_SIZE + calldata_len) * mega_evm::constants::COST_PER_HISTORY_BYTE +} + fn call_frame_init(depth: usize) -> FrameInit { FrameInit { depth, @@ -191,7 +198,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()); } @@ -272,7 +279,8 @@ enum Expected { /// `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. + /// 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 +321,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(), diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 0367cedb4..8bea20109 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -653,23 +653,24 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { tx.0.base.gas_limit = gas_limit; tx }; - let run_at = - |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)).unwrap(); + let run_at = |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)); + // 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"); + let (mut fails, mut succeeds) = (0u64, 1_000_000u64); + 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); + let outcome = run_at(succeeds - 1).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.limit_exceeded, None); From 13f8e44bdbc5b325f73185033926baa7265ed29b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:34:03 +0800 Subject: [PATCH 003/458] feat(satin): charge history gas where the Host stages a record The wrapper of SSTORE, LOG0..LOG4 and SELFDESTRUCT already commits what the Host staged once the opcode completed; it now charges the running frame the history the record costs, which is the record's own data size: a log pays for its address, its topics and its data, a storage write and a destructed account's beneficiary for the forty bytes of one write record. A slot written back to its original value leaves no record and takes its charge back at the same price, whichever frame made it. A frame that fails pays for none of it, because the charge unwinds with the frame the way its state gas does. A history charge the frame cannot pay is an ordinary out-of-gas. --- crates/mega-evm/src/evm/instructions.rs | 49 +++++- crates/mega-evm/src/limit/limit.rs | 20 ++- crates/mega-evm/src/limit/mod.rs | 1 + crates/mega-evm/src/limit/record.rs | 55 +++++++ crates/mega-evm/tests/block/counters.rs | 9 +- crates/mega-evm/tests/satin/history_gas.rs | 148 +++++++++++++++++- crates/mega-evm/tests/satin/outcome.rs | 9 +- crates/mega-evm/tests/satin/pricing-table.md | 10 +- crates/mega-evm/tests/satin/strategic_stop.rs | 6 +- 9 files changed, 282 insertions(+), 25 deletions(-) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index e3d5edc1e..a51b1774d 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -6,11 +6,18 @@ //! //! 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. +//! 3. commit the record if the opcode completed, discard it if the opcode failed; +//! 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). +//! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). A history charge the frame +//! cannot pay is an ordinary out-of-gas, which burns the frame's gas the way any other does. //! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -36,7 +43,7 @@ use revm::{ Database, }; -use crate::{ExternalEnvTypes, LimitCheck, MegaContext}; +use crate::{history_gas, limit::HistoryBytes, ExternalEnvTypes, LimitCheck, MegaContext}; use super::MegaInstructions; @@ -70,7 +77,8 @@ 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 @@ -91,13 +99,44 @@ fn commit_after( host.additional_limit.discard_staged_record(); return result; } - let check = host.additional_limit.commit_staged_record(); + let (check, history) = host.additional_limit.commit_staged_record(); + if host.prices_history() { + settle_history(interpreter, history)?; + } if check.exceeded_limit() { return Err(stop_frame(interpreter, &check)); } 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. +#[inline] +fn settle_history( + interpreter: &mut Interpreter, + history: HistoryBytes, +) -> Result<(), InstructionResult> { + match history { + HistoryBytes::None => Ok(()), + HistoryBytes::Appended(bytes) => { + let Some(cost) = history_gas(bytes) else { return Err(InstructionResult::OutOfGas) }; + if interpreter.gas.record_history_cost(cost) { + 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 /// [`MegaLimitExceeded`](crate::MegaLimitExceeded) and its gas is the frame's, so the caller gets /// the unspent part back. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 8c7720f11..8798bbcdd 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -8,7 +8,7 @@ use revm::{ use super::{ frame_limit::{FrameLimitTracker, Lane}, - record::{RecordEffect, StagedRecord}, + record::{HistoryBytes, RecordEffect, StagedRecord}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, }; @@ -176,12 +176,17 @@ 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. #[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) { + 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(); + let check = match effect { RecordEffect::None => LimitCheck::WithinLimit, RecordEffect::Record(usage) => { self.tracker.record(usage); @@ -191,7 +196,8 @@ impl AdditionalLimit { self.tracker.refund(usage); LimitCheck::WithinLimit } - } + }; + (check, history) } /// Discards the staged record. Called by an opcode's wrapper when the opcode failed, which diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 851a51689..ca634c68b 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -22,6 +22,7 @@ mod limit; mod record; pub use limit::AdditionalLimit; +pub(crate) use record::HistoryBytes; pub use record::StagedRecord; use alloy_primitives::Bytes; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 93eb729e7..2c9c0301f 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -47,6 +47,31 @@ 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. +#[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: /// @@ -91,6 +116,7 @@ impl StagedRecord { #[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,6 +157,35 @@ 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, + target_exists: 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() { diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 72b453821..73fcfd4fb 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -138,9 +138,14 @@ fn test_the_state_and_history_ledgers_refuse_nothing() { let counters = *executor.gas(); assert!(counters.state > 0, "the Satin gas table prices state gas, and these writes draw it"); + // 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); assert_eq!( counters.history, - 3 * mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE, - "three empty bodies, and these transactions append nothing else", + bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, + "three bodies, three logs and the one write record", ); } diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 09adb5ce9..cefc1b6a5 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -7,14 +7,18 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}, test_utils::{BytecodeBuilder, MemoryDatabase}, - TX_BODY_SIZE, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, RETURN, REVERT}, + context_interface::cfg::GasId, }; -use revm::bytecode::opcode::{PUSH0, RETURN, REVERT}; use crate::common::{call, call_with_data, create, 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; @@ -119,3 +123,143 @@ fn test_calldata_costs_one_history_byte_per_byte() { 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 appends its own record for the address that emitted it, one record per topic and its +/// data, and pays history for every one of those bytes. +#[test] +fn test_a_log_pays_for_its_address_its_topics_and_its_data() { + 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 bare = run(logging(0, 0)); + let one_topic = run(logging(1, 32)); + let three_topics = run(logging(3, 32)); + + assert!(bare.result.is_success(), "{:?}", bare.result); + assert_eq!(bare.gas.history, body(0) + LOG_BASE_SIZE * CPHB, "the address alone"); + assert_eq!( + one_topic.gas.history, + body(0) + (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB, + "the address, one topic and 32 bytes of data", + ); + assert_eq!( + three_topics.gas.history, + body(0) + 160 * CPHB, + "a three-topic event carrying one word is 160 bytes", + ); + assert_eq!( + three_topics.gas.history - one_topic.gas.history, + 2 * LOG_TOPIC_SIZE * CPHB, + "two topics more", + ); +} + +/// 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 storage write leaves one write record, and the record is history: the first change of a slot +/// in the transaction pays for forty bytes, and writing the slot back to its original value takes +/// that charge back. +#[test] +fn test_a_storage_write_pays_for_its_record_and_a_write_back_takes_it_back() { + if runs_at_measurement_prices() { + return; + } + let run = |code: BytecodeBuilder| { + let db = funded().account_code(CALLEE, code.stop().build()); + execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + }; + let one = run(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1))); + let three = run(BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1))); + let rewritten = run(BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::from(2))); + let restored = run(BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO)); + + assert_eq!(one.gas.history, body(0) + WRITE_RECORD_SIZE * CPHB, "one record"); + assert_eq!(three.gas.history, body(0) + 3 * WRITE_RECORD_SIZE * CPHB, "three slots, three"); + assert_eq!(rewritten.gas.history, one.gas.history, "a slot already changed records once"); + assert_eq!(restored.gas.history, body(0), "the write-back took the record's charge back"); +} + +/// A frame that fails pays for nothing it appended: its logs and its write records go back with +/// it, and its caller keeps only what it did itself. +#[test] +fn test_a_failing_frame_gives_its_history_back() { + if runs_at_measurement_prices() { + return; + } + // `CALLEE` calls `CONTRACT` and carries on whatever it answers. + let caller_code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let run = |callee: Bytes| { + let db = funded().account_code(CALLEE, caller_code.clone()).account_code(CONTRACT, callee); + execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + }; + let quiet = run(BytecodeBuilder::default().stop().build()); + let kept = run(logging(1, 32)); + let reverted = run(log_body(1, 32).append_many([PUSH0, PUSH0, REVERT]).build()); + + assert!(kept.result.is_success() && reverted.result.is_success(), "the caller survives"); + assert_eq!(kept.gas.history - quiet.gas.history, (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB); + assert_eq!(reverted.gas.history, quiet.gas.history, "the reverted frame's log is not paid for"); +} diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 67363706f..41eb0126d 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -48,8 +48,13 @@ 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); - // The body's history comes out of the same reservoir, before the state gas does. - assert_eq!(gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE, "the transaction's body"); + // 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, diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index 5b0fd1af5..b43e0d768 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -68,10 +68,10 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | empty call | 42280 | 15000 | 0 | 27280 | | value transfer to an existing account | 48280 | 21000 | 0 | 27280 | | self-transfer | 39280 | 12000 | 0 | 27280 | -| SSTORE 0 -> 1 | 162306 | 37106 | 97920 | 27280 | +| SSTORE 0 -> 1 | 165826 | 37106 | 97920 | 30800 | | SSTORE 0 -> 1 -> 0 | 51594 | 37212 | 0 | 27280 | | value CALL to an empty account | 260201 | 49321 | 183600 | 27280 | -| LOG1 with 32 data bytes | 43298 | 16018 | 0 | 27280 | +| LOG1 with 32 data bytes | 51746 | 16018 | 0 | 35728 | | create transaction deploying 0 bytes | 235935 | 24087 | 183600 | 28248 | | create transaction deploying 32 bytes | 287732 | 24108 | 232560 | 31064 | @@ -81,9 +81,9 @@ The same probes again, with the SALT bucket the state charge lands in at `m` tim | Probe | m | gas used | regular | state | history | |---|---:|---:|---:|---:|---:| -| SSTORE 0 -> 1 | 1 | 162306 | 37106 | 97920 | 27280 | -| SSTORE 0 -> 1 | 2 | 260226 | 37106 | 195840 | 27280 | -| SSTORE 0 -> 1 | 8 | 847746 | 37106 | 783360 | 27280 | +| SSTORE 0 -> 1 | 1 | 165826 | 37106 | 97920 | 30800 | +| SSTORE 0 -> 1 | 2 | 263746 | 37106 | 195840 | 30800 | +| SSTORE 0 -> 1 | 8 | 851266 | 37106 | 783360 | 30800 | | value CALL to an empty account | 1 | 260201 | 49321 | 183600 | 27280 | | value CALL to an empty account | 2 | 443801 | 49321 | 367200 | 27280 | | value CALL to an empty account | 8 | 1545401 | 49321 | 1468800 | 27280 | diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index a57da9837..ef8184b8f 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -569,11 +569,13 @@ 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, body_history() + 700); + assert_eq!(kept.gas.history, plain.gas.history + 700); + assert!(plain.gas.history > body_history(), "the chain's own writes are history too"); 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 the rest. + // 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, body_history()); From 17c07facb3e59e5396f43f192dcc33f356abc380 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:40:36 +0800 Subject: [PATCH 004/458] feat(system): add transact_deploy and SequencerRegistryConfig A declarative spec per contract and a helper that never commits: matching code is a read-only witness entry, missing code is a create, foreign code is an error. The spec list is the six MegaETH contracts then the EIP-7997 factory. SequencerRegistryConfig carries the seeded roles. --- crates/mega-evm/src/system/deploy.rs | 252 ++++++++++++++++++ crates/mega-evm/src/system/mod.rs | 9 +- .../mega-evm/src/system/sequencer_registry.rs | 67 ++++- 3 files changed, 321 insertions(+), 7 deletions(-) create mode 100644 crates/mega-evm/src/system/deploy.rs diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs new file mode 100644 index 000000000..ca2d3b432 --- /dev/null +++ b/crates/mega-evm/src/system/deploy.rs @@ -0,0 +1,252 @@ +//! Shared primitive for deploying `MegaETH` system contracts and the EIP-7997 factory. +//! +//! Every predeploy is one state patch: install the account's bytecode, optionally seed storage, +//! and mark the account touched and created. [`SystemContractSpec`] names those differences; +//! [`transact_deploy`] applies them and never commits. The caller — the block executor today, +//! the CLI later — commits the returned [`EvmState`]. +//! +//! [`system_contract_specs`] is the single list both iterate: the six `MegaETH` contracts in +//! address order, then the factory. There is one version of each (the bytecode +//! `mega-system-contracts` ships; the Oracle and the `SequencerRegistry` are their v2.0.0), and +//! a system address that already holds different code is an error rather than an upgrade. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::fmt; +use std::vec::Vec; + +use alloy_primitives::{address, b256, bytes, keccak256, Address, Bytes, B256, U256}; +use mega_system_contracts::sequencer_registry::storage_slots::{ + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, + INITIAL_SYSTEM_ADDRESS, +}; +use revm::{ + primitives::KECCAK_EMPTY, + state::{Account, Bytecode, EvmState, EvmStorageSlot, TransactionId}, + Database, +}; + +use super::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH}, + SequencerRegistryConfig, 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 contracts [`system_contract_specs`] returns: the six `MegaETH` system contracts and +/// the EIP-7997 factory. +pub const SYSTEM_CONTRACT_DEPLOY_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"); + +/// Nonce a freshly created contract account starts at (EIP-161). The factory is created, so it +/// is 1; the six `MegaETH` contracts use the same number. +pub const CREATE2_FACTORY_NONCE: u64 = 1; + +/// 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. + pub code: Bytes, + /// Keccak-256 hash of [`code`](Self::code). Used for the idempotence check. + pub code_hash: B256, + /// Nonce written on a fresh deploy. Created contract accounts start at 1. + pub nonce: u64, + /// Flat storage slots to seed `(slot, value)` on a fresh deploy. Empty for every contract + /// except the `SequencerRegistry`. + pub seed: Vec<(U256, U256)>, +} + +impl SystemContractSpec { + /// A spec with nonce 1 and no seeded storage. + pub fn new(address: Address, code: Bytes, code_hash: B256) -> Self { + Self { address, code, code_hash, nonce: 1, seed: Vec::new() } + } + + /// Sets the seeded storage slots applied on a fresh deploy. + pub fn with_seed(mut self, seed: Vec<(U256, U256)>) -> Self { + self.seed = seed; + self + } +} + +/// Why [`transact_deploy`] could not produce a witness. +#[derive(Debug)] +pub enum SystemContractDeployError { + /// The database could not load the account at the spec's address. + Database(DbError), + /// `address` already holds bytecode whose hash is `found`, not `expected`. + /// + /// A system address holding foreign code is a broken chain, not something to overwrite. + ForeignCode { + /// The system-contract address that already has code. + address: Address, + /// The hash this engine deploys. + expected: B256, + /// The hash already in state. + found: B256, + }, +} + +impl From for SystemContractDeployError { + fn from(error: DbError) -> Self { + Self::Database(error) + } +} + +impl fmt::Display for SystemContractDeployError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Database(error) => write!(f, "{error}"), + Self::ForeignCode { address, expected, found } => { + write!( + f, + "system contract at {address} has unexpected code hash {found}, expected {expected}; refusing to overwrite" + ) + } + } + } +} + +impl core::error::Error + for SystemContractDeployError +{ + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Database(error) => Some(error), + Self::ForeignCode { .. } => None, + } + } +} + +/// Deploys the contract `spec` describes, returning the [`EvmState`] witness. Nothing is +/// committed. +/// +/// - Already deployed with [`SystemContractSpec::code_hash`]: the account as a read-only entry +/// (neither touched nor created, no seeding), so the witness records the read. +/// - Absent, or present with empty code: the created account with its bytecode, nonce and every +/// seeded slot, all marked. An existing balance is kept. +/// - Present with different non-empty code: [`SystemContractDeployError::ForeignCode`]. +/// +/// # Errors +/// +/// [`SystemContractDeployError::Database`] when the account cannot be loaded; +/// [`SystemContractDeployError::ForeignCode`] when the address already holds other bytecode. +pub fn transact_deploy( + db: &mut DB, + spec: &SystemContractSpec, +) -> Result> { + debug_assert_eq!( + keccak256(spec.code.as_ref()), + spec.code_hash, + "SystemContractSpec code_hash does not match code for {:?}", + spec.address + ); + + let existing = db.basic(spec.address).map_err(SystemContractDeployError::Database)?; + + if let Some(info) = &existing { + if info.code_hash == spec.code_hash { + // `Account::from` copies the info and leaves status empty: neither touched nor + // created, which is the read-only witness entry. + return Ok(EvmState::from_iter([(spec.address, Account::from(info.clone()))])); + } + if info.code_hash != KECCAK_EMPTY { + return Err(SystemContractDeployError::ForeignCode { + address: spec.address, + expected: spec.code_hash, + found: info.code_hash, + }); + } + } + + let mut info = existing.unwrap_or_default(); + info.code_hash = spec.code_hash; + info.code = Some(Bytecode::new_raw(spec.code.clone())); + info.nonce = spec.nonce; + + let mut account: Account = info.into(); + account.mark_touch(); + account.mark_created(); + for (slot, value) in &spec.seed { + account + .storage + .insert(*slot, EvmStorageSlot::new_changed(U256::ZERO, *value, TransactionId::ZERO)); + } + + Ok(EvmState::from_iter([(spec.address, account)])) +} + +/// The seven predeploys in deploy order: Oracle, high-precision timestamp, `KeylessDeploy`, +/// `MegaAccessControl`, `MegaLimitControl`, `SequencerRegistry`, then the EIP-7997 factory. +/// +/// The registry's seeded slots come from `config`. The factory has nonce 1 and no storage. +pub fn system_contract_specs( + config: &SequencerRegistryConfig, +) -> [SystemContractSpec; SYSTEM_CONTRACT_DEPLOY_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, + ) + .with_seed(registry_seed(config)), + SystemContractSpec::new( + CREATE2_FACTORY_ADDRESS, + CREATE2_FACTORY_CODE, + CREATE2_FACTORY_CODE_HASH, + ), + ] +} + +/// 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) +} + +/// The six bootstrap slots the `SequencerRegistry` is created with. +fn registry_seed(config: &SequencerRegistryConfig) -> Vec<(U256, U256)> { + Vec::from([ + (CURRENT_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), + (CURRENT_SEQUENCER, address_to_storage_value(config.initial_sequencer)), + (ADMIN, address_to_storage_value(config.initial_admin)), + (INITIAL_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), + (INITIAL_SEQUENCER, address_to_storage_value(config.initial_sequencer)), + (INITIAL_FROM_BLOCK, U256::from(config.initial_from_block)), + ]) +} diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index d72eec85f..e08e202ae 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; [`deploy`] is the single list that deploys all +//! seven. //! //! 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,13 +15,11 @@ //! //! [`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; mod control; +mod deploy; mod intercept; mod limit_control; mod oracle; @@ -28,6 +28,7 @@ mod timestamp; mod tx; pub use control::*; +pub use deploy::*; pub use intercept::NON_ZERO_TRANSFER_REVERT_DATA; pub use limit_control::*; pub use oracle::*; diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 83dfa20a6..9cd18ef0f 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -5,11 +5,16 @@ //! 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 contract is deployed by [`transact_deploy`](crate::system::transact_deploy) with the +//! bootstrap slots [`SequencerRegistryConfig`] names. Reading the rotated system address out of +//! its storage, and the pre-block call that applies a due change, belong to the pre-block +//! system calls. use alloy_primitives::{address, Address}; +use super::MEGA_SYSTEM_ADDRESS; +use crate::{HardforkParams, HardforkParamsError, MegaHardfork}; + /// The address of the `SequencerRegistry` system contract. pub const SEQUENCER_REGISTRY_ADDRESS: Address = address!("0x6342000000000000000000000000000000000006"); @@ -20,4 +25,60 @@ 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}; + +/// Bootstrap configuration for the `SequencerRegistry`, attached to Satin via [`HardforkParams`]. +/// +/// These values seed the registry's storage on a fresh deploy. After that the live roles are +/// whatever the contract holds; rotating them is a later pre-block system call. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SequencerRegistryConfig { + /// Seeded into `_currentSystemAddress` and `_initialSystemAddress`. + pub initial_system_address: Address, + /// Seeded into `_currentSequencer` and `_initialSequencer`. + pub initial_sequencer: Address, + /// Seeded into `_admin`. + pub initial_admin: Address, + /// Seeded into `_initialFromBlock`: the first block at which historical lookups are valid. + pub initial_from_block: u64, +} + +impl SequencerRegistryConfig { + /// Placeholder roles for a chain that has none published: [`MEGA_SYSTEM_ADDRESS`] for every + /// address, and block zero. + /// + /// The unknown-chain fallback schedule uses this so a local chain can start. A real network + /// attaches the roles governance chose. + pub const fn placeholder() -> Self { + Self { + initial_system_address: MEGA_SYSTEM_ADDRESS, + initial_sequencer: MEGA_SYSTEM_ADDRESS, + initial_admin: MEGA_SYSTEM_ADDRESS, + initial_from_block: 0, + } + } +} + +impl HardforkParams for SequencerRegistryConfig { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "SequencerRegistryConfig"; + + fn validate(&self) -> Result<(), HardforkParamsError> { + if self.initial_system_address.is_zero() { + return Err(HardforkParamsError { + message: "SequencerRegistryConfig.initial_system_address must not be zero".into(), + }); + } + if self.initial_sequencer.is_zero() { + return Err(HardforkParamsError { + message: "SequencerRegistryConfig.initial_sequencer must not be zero".into(), + }); + } + if self.initial_admin.is_zero() { + return Err(HardforkParamsError { + message: "SequencerRegistryConfig.initial_admin must not be zero".into(), + }); + } + Ok(()) + } +} From 7f5a11b2040ba5c8ef4304a572112e5bc30ebdb0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:40:51 +0800 Subject: [PATCH 005/458] feat(block): require SequencerRegistryConfig at schedule load Satin cannot run without the roles the registry is seeded from. A schedule that activates the fork without those params fails when it is loaded, and the unknown-chain fallback attaches placeholder roles so a local chain still starts. --- crates/mega-evm/src/block/chain.rs | 27 ++++++++++++++++++++------- crates/mega-evm/src/block/hardfork.rs | 26 ++++++++++++++++++++------ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index ed3add095..eefc396fb 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -8,7 +8,7 @@ use alloy_hardforks::ForkCondition; use alloy_primitives::BlockTimestamp; -use crate::{MegaHardfork, MegaHardforkConfig, MegaSpecId}; +use crate::{system::SequencerRegistryConfig, MegaHardfork, MegaHardforkConfig, MegaSpecId}; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -77,6 +77,11 @@ pub fn testnet_hardforks() -> MegaHardforkConfig { } /// The schedule an unknown chain runs: every fork up to [`FALLBACK_RUNG`], active at genesis. +/// +/// Satin requires a [`SequencerRegistryConfig`]. An unknown chain has no published roles, so +/// every role is seeded with [`MEGA_SYSTEM_ADDRESS`] and `_initialFromBlock` is zero. The +/// placeholder only matters when bootstrapping a fresh registry: on a chain whose registry is +/// already deployed, the live roles are read from storage. pub fn all_activated_hardforks() -> MegaHardforkConfig { let mut config = MegaHardforkConfig::new(); for fork in MegaHardfork::VARIANTS { @@ -87,7 +92,7 @@ pub fn all_activated_hardforks() -> MegaHardforkConfig { }; config.insert(*fork, condition); } - config + config.with_params(SequencerRegistryConfig::placeholder()) } /// The hardfork schedule of `chain_id`: a known chain's table, or the unknown-chain fallback. @@ -98,7 +103,7 @@ pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { #[cfg(test)] mod tests { use super::*; - use crate::MegaHardforks; + use crate::{system::MEGA_SYSTEM_ADDRESS, MegaHardforks}; #[test] fn test_known_chains_have_satin_unscheduled() { @@ -133,8 +138,9 @@ mod tests { /// 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(); + let hf = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) } + .hardforks() + .with_params(SequencerRegistryConfig::placeholder()); assert_eq!(hf.spec_id(1_799_999_999), None); assert_eq!(hf.spec_id(1_800_000_000), Some(MegaSpecId::SATIN)); @@ -149,14 +155,21 @@ mod tests { 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. + /// The fallback schedule is one a chain can run: it carries placeholder registry params, 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(())); + let params = hf + .fork_params::() + .expect("fallback schedule must carry a SequencerRegistryConfig"); + assert_eq!(params.initial_system_address, MEGA_SYSTEM_ADDRESS); + assert_eq!(params.initial_sequencer, MEGA_SYSTEM_ADDRESS); + assert_eq!(params.initial_admin, MEGA_SYSTEM_ADDRESS); + assert_eq!(params.initial_from_block, 0); } /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index bc9f8acd0..b38a39b15 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -159,9 +159,9 @@ pub trait MegaHardforks: OpHardforks { /// [`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. + /// ([`require_params`](Self::require_params)). Satin requires + /// [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) so the registry can be + /// seeded at the first block. /// /// 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,7 +173,8 @@ pub trait MegaHardforks: OpHardforks { } } - // Required parameters, one `self.require_params::

()?` per params type. Satin has none. + // Required parameters, one `self.require_params::

()?` per params type. + self.require_params::()?; Ok(()) } @@ -412,7 +413,8 @@ mod tests { 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. + /// here, independent of the [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) + /// Satin actually requires. #[derive(Clone, Debug, PartialEq, Eq)] struct TestParams { sequencer: alloy_primitives::Address, @@ -597,7 +599,19 @@ mod tests { let with_params = no_params.with_params(params()); assert_eq!(with_params.require_params::(), Ok(())); - assert_eq!(with_params.validate_schedule(), Ok(())); + // TestParams is not SequencerRegistryConfig, so the schedule still cannot run. + assert_eq!( + with_params.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Satin, + params: "SequencerRegistryConfig", + }) + ); + + let with_registry = MegaHardforkConfig::default() + .with_all_activated() + .with_params(crate::system::SequencerRegistryConfig::placeholder()); + assert_eq!(with_registry.validate_schedule(), Ok(())); } /// The block a fork activates in carries the chain's own transactions only, and only that From d9bc28c7c839066658ca924f0c87e750d7ce15f5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:41:06 +0800 Subject: [PATCH 006/458] feat(block): deploy system contracts in pre-block Every block iterates the spec list and commits each witness in order, after the EIP-2935 and EIP-4788 calls. Those two target their own contracts and do not read MegaETH predeploys. A matching deploy is a read-only entry; foreign code fails the block. --- crates/mega-evm/src/block/executor.rs | 73 ++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 40f887fa8..3d9302c80 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -36,8 +36,9 @@ //! //! # 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. +//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) deploys the +//! system contracts and the EIP-7997 factory every block (idempotent). The pre-block system +//! calls that apply a due `SequencerRegistry` change are still an empty hook after that deploy. #[cfg(not(feature = "std"))] use alloc as std; @@ -55,7 +56,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, B256}; use op_alloy_consensus::OpDepositReceipt; use op_revm::{ constants::L1_BLOCK_CONTRACT, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, @@ -73,9 +74,13 @@ 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, + system::{ + system_contract_specs, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, + }, + BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, + MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, }; /// What the node hands block execution beside the EVM. @@ -140,6 +145,18 @@ pub enum MegaBlockExecutionError { /// The EVM runs an inspector that may rewrite what execution produces, which block execution /// does not admit. RewritingInspector, + /// A system-contract address already holds bytecode that is not the contract this engine + /// deploys. + ForeignSystemContractCode { + /// The system-contract address that already has code. + address: Address, + /// The hash this engine deploys. + expected: B256, + /// The hash already in state. + found: B256, + }, + /// Satin is scheduled but the schedule does not carry a [`SequencerRegistryConfig`]. + MissingSequencerRegistryConfig, } impl fmt::Display for MegaBlockExecutionError { @@ -160,6 +177,13 @@ impl fmt::Display for MegaBlockExecutionError { Self::RewritingInspector => f.write_str( "block execution does not admit an inspector that may rewrite execution", ), + Self::ForeignSystemContractCode { address, expected, found } => write!( + f, + "system contract at {address} has unexpected code hash {found}, expected {expected}; refusing to overwrite" + ), + Self::MissingSequencerRegistryConfig => { + f.write_str("Satin is scheduled but SequencerRegistryConfig is not configured") + } } } } @@ -363,19 +387,23 @@ 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 record, the EIP-2935 and + /// EIP-4788 pre-block calls, and the system-contract deploys. Each step'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, after the pre-block calls. + /// The EIP-2935 and EIP-4788 calls run before the deploy. 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 deploy that follows. + /// + /// The pre-block system calls that apply a due `SequencerRegistry` change are still an empty + /// hook after the deploy. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; @@ -401,7 +429,24 @@ where self.commit(state); } - // Hook point: system contract deployment. + // 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. + let config = self + .spec + .fork_params::() + .copied() + .ok_or(MegaBlockExecutionError::MissingSequencerRegistryConfig)?; + for spec in system_contract_specs(&config) { + let state = transact_deploy(self.evm.db_mut(), &spec).map_err(|error| match error { + SystemContractDeployError::Database(error) => BlockExecutionError::other(error), + SystemContractDeployError::ForeignCode { address, expected, found } => { + MegaBlockExecutionError::ForeignSystemContractCode { address, expected, found } + .into() + } + })?; + self.commit(state); + } + // Hook point: the pre-block system calls. Ok(()) From 0b966457274c5337a00b6144fc62c3fe637dce82 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:41:20 +0800 Subject: [PATCH 007/458] test: cover system-contract deploy and the CREATE2 factory The first block installs all seven predeploys with the pinned hashes, nonce 1 and the registry's seeded slots. A second block is seven read-only entries. Foreign code fails the block, missing params fail at load, and a factory call returns the CREATE2 address as 20 bytes. --- crates/mega-evm/tests/block/common.rs | 28 ++- crates/mega-evm/tests/block/deploy.rs | 212 ++++++++++++++++++++++ crates/mega-evm/tests/block/main.rs | 1 + crates/mega-evm/tests/block/schedule.rs | 50 ++--- crates/mega-evm/tests/system/deploy.rs | 231 ++++++++++++++++++++++++ crates/mega-evm/tests/system/main.rs | 1 + 6 files changed, 486 insertions(+), 37 deletions(-) create mode 100644 crates/mega-evm/tests/block/deploy.rs create mode 100644 crates/mega-evm/tests/system/deploy.rs diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index e882d2115..706736dc7 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -9,9 +9,11 @@ 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, + system::{SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS}, + test_utils::MemoryDatabase, + BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, MegaBlockExecutor, + MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, + MegaTxEnvelope, }; use op_alloy_consensus::TxDeposit; use revm::{ @@ -64,9 +66,25 @@ pub(crate) fn evm_env() -> EvmEnv { EvmEnv::new(cfg_env, block_env) } -/// A schedule that activates Satin at genesis. +/// The sequencer the tests seed into the registry, distinct from the system address and admin. +pub(crate) const SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); + +/// The admin the tests seed into the registry, distinct from the system address and sequencer. +pub(crate) const ADMIN: Address = address!("0x3333333333333333333333333333333333333333"); + +/// Registry params the block tests attach to a Satin-at-genesis schedule. +pub(crate) fn registry_config() -> SequencerRegistryConfig { + SequencerRegistryConfig { + initial_system_address: MEGA_SYSTEM_ADDRESS, + initial_sequencer: SEQUENCER, + initial_admin: ADMIN, + initial_from_block: 1, + } +} + +/// A schedule that activates Satin at genesis and can seed the `SequencerRegistry`. pub(crate) fn chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated() + MegaHardforkConfig::default().with_all_activated().with_params(registry_config()) } /// The context of a block held to `limits`. diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs new file mode 100644 index 000000000..b55ec92d1 --- /dev/null +++ b/crates/mega-evm/tests/block/deploy.rs @@ -0,0 +1,212 @@ +//! System contract deployment at the start of a block, and the EIP-7997 factory round trip. + +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{Address, Bytes, B256, U256}; +use mega_evm::{ + system::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, + storage_slots::{ + ADMIN as ADMIN_SLOT, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, + INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, + }, + system_contract_specs, transact_deploy, SequencerRegistryConfig, 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, + MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, + }, + test_utils::MemoryDatabase, + MegaHardfork, MegaHardforkConfig, MegaHardforks, +}; +use revm::{context::result::ExecutionResult, database::State, Database}; + +use crate::common::{ + self, executor, executor_with_spec, recovered, registry_config, tx, unlimited_ctx, ADMIN, + SEQUENCER, +}; + +fn expected_hashes() -> [(Address, B256); SYSTEM_CONTRACT_DEPLOY_COUNT] { + [ + (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), + ] +} + +fn assert_deployed(state: &mut State) { + for (address, hash) in expected_hashes() { + let info = state.basic(address).expect("readable").expect("deployed"); + assert_eq!(info.code_hash, hash, "{address} has the wrong code"); + assert_eq!(info.nonce, 1, "{address} is a created contract"); + assert!(info.code.is_some(), "{address} carries its bytecode"); + } +} + +fn assert_registry_seed(state: &mut State, config: &SequencerRegistryConfig) { + let addr_val = |address: Address| U256::from_be_bytes(address.into_word().0); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS).unwrap(), + addr_val(config.initial_system_address) + ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER).unwrap(), + addr_val(config.initial_sequencer) + ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN_SLOT).unwrap(), + addr_val(config.initial_admin) + ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SYSTEM_ADDRESS).unwrap(), + addr_val(config.initial_system_address) + ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SEQUENCER).unwrap(), + addr_val(config.initial_sequencer) + ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_FROM_BLOCK).unwrap(), + U256::from(config.initial_from_block) + ); +} + +/// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the +/// registry's seeded slots. +#[test] +fn test_the_first_block_deploys_every_system_contract() { + let mut state = common::state(); + { + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + } + assert_deployed(&mut state); + assert_registry_seed(&mut state, ®istry_config()); + assert_eq!(registry_config().initial_system_address, MEGA_SYSTEM_ADDRESS); + assert_eq!(registry_config().initial_sequencer, SEQUENCER); + assert_eq!(registry_config().initial_admin, ADMIN); +} + +/// A second block changes nothing: each deploy is a read-only witness entry. +#[test] +fn test_the_second_block_is_seven_read_only_entries() { + let mut state = common::state(); + { + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the first block deploys"); + } + + let specs = system_contract_specs(®istry_config()); + assert_eq!(specs.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); + for spec in &specs { + let outcome = transact_deploy(&mut state, spec).expect("the idempotent check"); + assert_eq!(outcome.len(), 1, "{} is one witness account", spec.address); + let account = outcome.get(&spec.address).unwrap(); + assert!(!account.is_touched(), "{} is not touched", spec.address); + assert!(!account.is_created(), "{} is not created", spec.address); + assert!(account.storage.is_empty(), "{} is not re-seeded", spec.address); + assert_eq!(account.info.code_hash, spec.code_hash); + } + + { + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the second block is a no-op"); + } + assert_deployed(&mut state); + assert_registry_seed(&mut state, ®istry_config()); +} + +/// A factory that already holds the right code is left as it is, including a balance it already +/// had. +#[test] +fn test_a_pre_existing_factory_with_the_right_code_is_untouched() { + let mut db = common::database(); + db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); + db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 1); + db.set_account_balance(CREATE2_FACTORY_ADDRESS, U256::from(42)); + 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"); + } + + let info = state.basic(CREATE2_FACTORY_ADDRESS).unwrap().unwrap(); + assert_eq!(info.code_hash, CREATE2_FACTORY_CODE_HASH); + assert_eq!(info.nonce, 1); + assert_eq!(info.balance, U256::from(42), "a matching factory keeps its balance"); +} + +/// Foreign code at any of the seven addresses fails the block. +#[test] +fn test_foreign_code_at_a_system_address_fails_the_block() { + for (address, _) in expected_hashes() { + let mut db = common::database(); + db.set_account_code(address, Bytes::from_static(&[0xfe])); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, unlimited_ctx()); + let err = + executor.apply_pre_execution_changes().expect_err("foreign code must fail the block"); + let message = err.to_string(); + assert!( + message.contains("refusing to overwrite"), + "{address}: unexpected error: {message}" + ); + assert!(message.contains(&address.to_string()), "{address}: error names the address"); + } +} + +/// A scheduled Satin without registry params fails at load, and a block built from one anyway +/// fails when it tries to deploy. +#[test] +fn test_missing_registry_params_fail_at_load_and_at_the_block() { + let missing = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)); + assert_eq!( + missing.validate_schedule().unwrap_err().to_string(), + "hardfork Satin is scheduled but its SequencerRegistryConfig params are not configured" + ); + + let mut state = common::state(); + let mut executor = executor_with_spec(&mut state, unlimited_ctx(), missing); + let err = executor + .apply_pre_execution_changes() + .expect_err("a block without registry params cannot deploy"); + assert!(err.to_string().contains("SequencerRegistryConfig"), "unexpected error: {err}"); +} + +/// 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 factory is deployed"); + + 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()); + + let outcome = executor + .execute_transaction_without_commit(&recovered(tx( + 0, + CREATE2_FACTORY_ADDRESS, + Bytes::from(input), + 1_000_000, + ))) + .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/main.rs b/crates/mega-evm/tests/block/main.rs index 8e51e26b1..6da67cb95 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -3,6 +3,7 @@ mod block_hashes; mod common; mod counters; +mod deploy; mod eips; mod factory; mod inspector; diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index c7644301f..856e0775b 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -2,37 +2,13 @@ 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, + chain_activation, mainnet_hardforks, system::SequencerRegistryConfig, testnet_hardforks, 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, registry_config, 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 @@ -73,16 +49,26 @@ 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" }), + missing.require_params::(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Satin, + params: "SequencerRegistryConfig", + }), "the load refuses it" ); + assert_eq!( + missing.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Satin, + params: "SequencerRegistryConfig", + }), + ); // 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(())); + let loaded = missing.with_params(registry_config()); + assert_eq!(loaded.require_params::(), Ok(())); assert_eq!(loaded.validate_schedule(), Ok(())); - assert_eq!(loaded.fork_params::(), Some(¶ms())); + assert_eq!(loaded.fork_params::(), Some(®istry_config())); let mut state = common::state(); let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), loaded); @@ -95,6 +81,6 @@ fn test_a_schedule_missing_its_fork_params_is_refused_at_load() { fn test_an_unscheduled_fork_needs_no_params() { let unscheduled = MegaHardforkConfig::default(); - assert_eq!(unscheduled.require_params::(), Ok(())); + assert_eq!(unscheduled.require_params::(), Ok(())); assert_eq!(unscheduled.validate_schedule(), Ok(())); } diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs new file mode 100644 index 000000000..11bfe1a2d --- /dev/null +++ b/crates/mega-evm/tests/system/deploy.rs @@ -0,0 +1,231 @@ +//! The system-contract deploy helper: the spec list, a fresh deploy, the idempotent read, and +//! foreign code. + +use alloy_primitives::{address, keccak256, Address, Bytes, U256}; +use mega_evm::{ + system::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, + storage_slots::{ + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, + INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, + }, + system_contract_specs, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, + SystemContractSpec, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH, + CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE, CREATE2_FACTORY_CODE_HASH, + CREATE2_FACTORY_NONCE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE_HASH, + MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, + SYSTEM_CONTRACT_DEPLOY_COUNT, + }, + test_utils::MemoryDatabase, + HardforkParams, +}; +use revm::{primitives::KECCAK_EMPTY, DatabaseCommit}; + +const SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); +const ADMIN_ADDR: Address = address!("0x3333333333333333333333333333333333333333"); + +fn config() -> SequencerRegistryConfig { + SequencerRegistryConfig { + initial_system_address: MEGA_SYSTEM_ADDRESS, + initial_sequencer: SEQUENCER, + initial_admin: ADMIN_ADDR, + initial_from_block: 7, + } +} + +fn oracle_spec() -> SystemContractSpec { + SystemContractSpec::new( + ORACLE_CONTRACT_ADDRESS, + ORACLE_CONTRACT_CODE, + ORACLE_CONTRACT_CODE_HASH, + ) +} + +/// The factory's pinned hash is the hash of the runtime the spec installs. +#[test] +fn test_the_factory_code_hashes_to_its_pinned_hash() { + assert_eq!(keccak256(CREATE2_FACTORY_CODE), CREATE2_FACTORY_CODE_HASH); + assert_eq!(CREATE2_FACTORY_NONCE, 1); +} + +/// The spec list is the six `MegaETH` contracts in address order, then the factory. +#[test] +fn test_the_spec_list_is_the_seven_predeploys_in_order() { + let specs = system_contract_specs(&config()); + assert_eq!(specs.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); + assert_eq!( + [ + specs[0].address, + specs[1].address, + specs[2].address, + specs[3].address, + specs[4].address, + specs[5].address, + specs[6].address, + ], + [ + ORACLE_CONTRACT_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + KEYLESS_DEPLOY_ADDRESS, + ACCESS_CONTROL_ADDRESS, + LIMIT_CONTROL_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + CREATE2_FACTORY_ADDRESS, + ] + ); + assert_eq!( + [ + specs[0].code_hash, + specs[1].code_hash, + specs[2].code_hash, + specs[3].code_hash, + specs[4].code_hash, + specs[5].code_hash, + specs[6].code_hash, + ], + [ + ORACLE_CONTRACT_CODE_HASH, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + KEYLESS_DEPLOY_CODE_HASH, + ACCESS_CONTROL_CODE_HASH, + LIMIT_CONTROL_CODE_HASH, + SEQUENCER_REGISTRY_CODE_HASH, + CREATE2_FACTORY_CODE_HASH, + ] + ); + for spec in &specs { + assert_eq!(spec.nonce, 1, "{} starts at nonce 1", spec.address); + assert_eq!(keccak256(&spec.code), spec.code_hash); + } + assert!(specs[..5].iter().all(|spec| spec.seed.is_empty())); + assert!(specs[6].seed.is_empty(), "the factory has no storage"); + assert_eq!(specs[5].seed.len(), 6, "the registry seeds the six bootstrap slots"); +} + +/// A fresh deploy creates the account, installs the code and seeds every slot. +#[test] +fn test_a_fresh_deploy_creates_the_account_and_seeds_storage() { + let mut db = MemoryDatabase::default(); + let specs = system_contract_specs(&config()); + let registry = &specs[5]; + let factory = &specs[6]; + + let state = transact_deploy(&mut db, registry).expect("the registry deploys"); + let account = state.get(&SEQUENCER_REGISTRY_ADDRESS).expect("the registry is in the witness"); + assert!(account.is_touched()); + assert!(account.is_created()); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(account.info.nonce, 1); + assert_eq!(account.storage.len(), 6); + assert_eq!( + account.storage.get(&CURRENT_SYSTEM_ADDRESS).unwrap().present_value, + U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0) + ); + assert_eq!( + account.storage.get(&CURRENT_SEQUENCER).unwrap().present_value, + U256::from_be_bytes(SEQUENCER.into_word().0) + ); + assert_eq!( + account.storage.get(&ADMIN).unwrap().present_value, + U256::from_be_bytes(ADMIN_ADDR.into_word().0) + ); + assert_eq!( + account.storage.get(&INITIAL_SYSTEM_ADDRESS).unwrap().present_value, + U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0) + ); + assert_eq!( + account.storage.get(&INITIAL_SEQUENCER).unwrap().present_value, + U256::from_be_bytes(SEQUENCER.into_word().0) + ); + assert_eq!(account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value, U256::from(7)); + db.commit(state); + + let state = transact_deploy(&mut db, factory).expect("the factory deploys"); + let account = state.get(&CREATE2_FACTORY_ADDRESS).expect("the factory is in the witness"); + assert!(account.is_created()); + assert_eq!(account.info.nonce, CREATE2_FACTORY_NONCE); + assert!(account.storage.is_empty()); +} + +/// Already deployed with the matching code hash is a read-only witness entry. +#[test] +fn test_a_matching_deploy_is_a_read_only_witness_entry() { + let mut db = MemoryDatabase::default(); + let spec = oracle_spec(); + let deployed = transact_deploy(&mut db, &spec).unwrap(); + db.commit(deployed); + + let state = transact_deploy(&mut db, &spec).expect("the second deploy is a no-op"); + let account = state.get(&ORACLE_CONTRACT_ADDRESS).expect("the read is in the witness"); + assert!(!account.is_touched(), "a matching deploy does not touch"); + assert!(!account.is_created(), "a matching deploy does not create"); + assert!(account.storage.is_empty(), "a matching deploy does not seed"); + assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH); +} + +/// Present with different code is an error, not an overwrite. +#[test] +fn test_foreign_code_at_a_system_address_is_an_error() { + let mut db = MemoryDatabase::default(); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0xfe])); + + let error = transact_deploy(&mut db, &oracle_spec()).expect_err("foreign code must fail"); + let message = error.to_string(); + assert!(message.contains("refusing to overwrite"), "the error names the refusal: {message}"); + match error { + SystemContractDeployError::ForeignCode { address, expected, found } => { + assert_eq!(address, ORACLE_CONTRACT_ADDRESS); + assert_eq!(expected, ORACLE_CONTRACT_CODE_HASH); + assert_eq!(found, keccak256([0xfe])); + assert_ne!(found, KECCAK_EMPTY); + } + other => panic!("expected ForeignCode, got {other}"), + } +} + +/// An account that exists with empty code (an EOA that received value) is a fresh deploy: the +/// balance is kept and the slots are seeded. +#[test] +fn test_an_empty_account_at_the_address_is_a_fresh_deploy() { + let mut db = MemoryDatabase::default(); + db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1_000)); + + let spec = system_contract_specs(&config()) + .into_iter() + .find(|spec| spec.address == SEQUENCER_REGISTRY_ADDRESS) + .unwrap(); + let state = transact_deploy(&mut db, &spec).expect("empty code is a fresh deploy"); + let account = state.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(account.is_created()); + assert_eq!(account.info.balance, U256::from(1_000)); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(account.storage.len(), 6); +} + +/// Zero addresses in the registry config fail at load, not at the first block. +#[test] +fn test_registry_config_rejects_a_zero_address() { + let mut config = config(); + config.initial_system_address = Address::ZERO; + let err = config.validate().expect_err("zero system address"); + assert!(err.message.contains("initial_system_address must not be zero")); + + config = self::config(); + config.initial_sequencer = Address::ZERO; + let err = config.validate().expect_err("zero sequencer"); + assert!(err.message.contains("initial_sequencer must not be zero")); + + config = self::config(); + config.initial_admin = Address::ZERO; + let err = config.validate().expect_err("zero admin"); + assert!(err.message.contains("initial_admin must not be zero")); +} + +/// The seeded current-system-address slot is slot 0, which is the slot a later rotation read +/// consults. +#[test] +fn test_the_seeded_system_address_slot_is_the_current_one() { + assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::ZERO); +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index 8ff049f36..e8f71296a 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 deploy; mod dispatch; mod keyless; mod limit_control; From 2318c8669d3c333c94de01063ea6da3b3bd179ca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:42:12 +0800 Subject: [PATCH 008/458] test: port parked system-contract deployment tests The rows this mechanism owns move into tests/block/deploy.rs and tests/system/deploy.rs. applyPendingChanges rows stay parked under the pre-block system calls. The pending ledger drops from 524 to 478. --- crates/mega-evm/tests/_pending/README.md | 51 +- .../tests/_pending/block_executor/main.rs | 1 - .../block_executor/sequencer_registry.rs | 620 ------------------ .../tests/_pending/mini_rex/oracle.rs | 97 --- .../tests/_pending/rex2/keyless_deploy.rs | 93 --- .../tests/_pending/rex4/deployment.rs | 165 ----- crates/mega-evm/tests/_pending/rex4/main.rs | 1 - .../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 | 198 ------ 13 files changed, 38 insertions(+), 1908 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/deployment.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 diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4c4ea6455..bf26e6567 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -34,13 +34,13 @@ Do not add a `_pending/main.rs`. | 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 pre-block system calls | 27 | 15 | 12 | 23 | 4 | 0 | +| system contract deployment | 12 | 5 | 7 | 12 | 0 | 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** | +| **Total** | **478** | **445** | **33** | **270** | **180** | **28** | ## Tests ported in place @@ -203,6 +203,24 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the | `src/system/tx.rs` | the system contract interceptors (6) | 6 | `src/system/tx.rs` | | **Total** | | **61** | | +## Tests ported by system contract deployment + +These 46 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy, 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/sequencer_registry.rs` | system contract deployment (8) | 8 | `tests/block/deploy.rs` | +| `mini_rex/oracle.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | +| `rex2/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | +| `rex4/deployment.rs` | system contract deployment (2) | 2 | `tests/block/deploy.rs` | +| `src/system/control.rs` | system contract deployment (8) | 8 | `tests/system/control.rs`, `tests/system/deploy.rs` | +| `src/system/deploy.rs` | system contract deployment (4) | 4 | `tests/system/deploy.rs` | +| `src/system/keyless_deploy.rs` | system contract deployment (2) | 2 | `tests/system/deploy.rs` | +| `src/system/limit_control.rs` | system contract deployment (5) | 5 | `tests/system/deploy.rs` | +| `src/system/oracle.rs` | system contract deployment (7) | 7 | `tests/system/deploy.rs` | +| `src/system/sequencer_registry.rs` | system contract deployment (8) | 8 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | +| **Total** | | **46** | | + ## 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. @@ -220,6 +238,20 @@ They are not counted above. | File | Test | Parked under | Reason | |---|---|---|---| +## Tests parked under a later mechanism than the inventory named + +| File | Test | Parked under | Reason | +|---|---|---|---| +| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_no_pending` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_no_registry` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_sequencer_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_system_address_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_errors_when_registry_reverts` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_respects_30m_floor` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_updates_and_clears_due_roles` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_uses_block_gas_limit` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | + ## Files Each cell lists `disposition count (mechanism · decision)`. @@ -228,7 +260,6 @@ 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` | 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) | @@ -236,18 +267,17 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/oracle.rs` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | | `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/keyless_deploy.rs` | 36 | 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) | | `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) | @@ -285,9 +315,4 @@ Each cell lists `disposition count (mechanism · decision)`. | `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) | +| `src/system/sequencer_registry.rs` | 16 | keep 7 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | diff --git a/crates/mega-evm/tests/_pending/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs index 693e3735f..3047fceae 100644 --- a/crates/mega-evm/tests/_pending/block_executor/main.rs +++ b/crates/mega-evm/tests/_pending/block_executor/main.rs @@ -2,4 +2,3 @@ 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/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs index 5d80ffc90..50cdba332 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -398,103 +398,6 @@ fn test_oracle_storage_sload_direct_call() { 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. diff --git a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs index cf4024147..ebcffe02b 100644 --- a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs @@ -1042,99 +1042,6 @@ fn test_keyless_deploy_not_intercepted_for_inner_calls() { 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 // ============================================================================= 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/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index b75668583..5f824b2b2 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -3,7 +3,6 @@ mod access_control; mod beneficiary_detention; mod create_safety; -mod deployment; mod eip7702_delegation_cycle; mod frame_limits; mod gas_detention; 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 index 8c7612abb..66d4e0ff7 100644 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -50,58 +50,6 @@ mod tests { .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 }; @@ -113,152 +61,6 @@ mod tests { ); } - #[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. From f3afa7a649aadf367d2f9986fcee432ec8abb263 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:43:24 +0800 Subject: [PATCH 009/458] bench(block): measure the idempotent system-contract deploy check A steady-state arm runs apply_pre_execution_changes on a block whose seven predeploys are already in state. A check before measurement asserts the seven witness entries are read-only. --- crates/mega-evm/benches/block.rs | 67 +++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 0e6c9ea20..62027f068 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -13,7 +13,9 @@ //! //! 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. +//! executes. A third arm, `steady_pre_block`, measures `apply_pre_execution_changes` alone on a +//! block whose seven predeploys are already in state: the per-block cost of the idempotent +//! check. #![allow(missing_docs)] use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; @@ -22,6 +24,10 @@ 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::{ + system::{ + system_contract_specs, transact_deploy, SequencerRegistryConfig, + SYSTEM_CONTRACT_DEPLOY_COUNT, + }, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, @@ -120,8 +126,27 @@ fn transactions( .collect() } +fn chain_spec() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated() + .with_params(SequencerRegistryConfig::placeholder()) +} + +/// A database on which the seven predeploys have already been installed. +fn deployed_state() -> State { + let spec = chain_spec(); + 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 first block deploys"); + } + state +} + fn bench_block(c: &mut Criterion) { - let spec = MegaHardforkConfig::default().with_all_activated(); + let spec = chain_spec(); 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. @@ -177,6 +202,44 @@ fn bench_block(c: &mut Criterion) { }); } group.finish(); + + // The idempotent pre-block path: everything is already deployed, so each of the seven + // specs is a read-only witness entry. Checked once before measurement so a broken deploy + // does not get timed. + { + let mut state = deployed_state(); + let config = SequencerRegistryConfig::placeholder(); + let mut read_only = 0usize; + for deploy_spec in system_contract_specs(&config) { + let outcome = transact_deploy(&mut state, &deploy_spec).expect("the idempotent check"); + assert_eq!(outcome.len(), 1, "{} is one witness account", deploy_spec.address); + let account = outcome.get(&deploy_spec.address).expect("the account is present"); + assert!(!account.is_touched(), "{} is not touched", deploy_spec.address); + assert!(!account.is_created(), "{} is not created", deploy_spec.address); + read_only += 1; + } + assert_eq!(read_only, SYSTEM_CONTRACT_DEPLOY_COUNT); + } + + let mut group = c.benchmark_group("block"); + group.bench_function("steady_pre_block", |b| { + b.iter_batched( + deployed_state, + |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(); + black_box(executor.limiter().block_gas_used) + }, + BatchSize::SmallInput, + ); + }); + group.finish(); } criterion_group!(benches, bench_block); From 3ffda4dbd52589ed61299a17ee9ffa525a803346 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:43:24 +0800 Subject: [PATCH 010/458] docs: record system contract deployment at activation The six MegaETH contracts and the EIP-7997 factory deploy at the start of every block. The pre-block state-change contract lives next to the helper that implements it. --- AGENTS.md | 9 +++++---- crates/mega-evm/README.md | 7 ++++--- crates/mega-evm/src/system/AGENTS.md | 29 +++++++++++++++++++++++++--- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b691789b..1164ec6fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,11 +95,11 @@ 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, 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 | +| `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`); the system-contract deploy in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point 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 | +| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 | @@ -127,8 +127,9 @@ 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`. - 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 refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent); the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. +- The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. + 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index d63deff5a..cafb2f7fd 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -41,7 +41,7 @@ No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a 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. +`apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, and leaves one hook point empty: the pre-block system calls. 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,7 +49,8 @@ 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 are deployed at Satin activation, together with the EIP-7997 factory at `0x4e59…`. +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, 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. @@ -58,7 +59,7 @@ The Oracle forwards a `sendHint` payload to the node's oracle service, and a `ke 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. -History gas, the resource limits, gas detention, system contract deployment and keyless deployment arrive in later changes. +History gas, the resource limits, gas detention 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 index 59c78556f..d5a8e359e 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,7 +1,7 @@ # 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 that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory. ## STRUCTURE - `oracle.rs`: the Oracle's address, code and ABI, and the `sendHint` side effect. @@ -9,7 +9,8 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - `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. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, and the [`SequencerRegistryConfig`] that seeds it. No interceptor. +- `deploy.rs`: the declarative spec, `transact_deploy`, the EIP-7997 factory, and the list of seven predeploys. - `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. @@ -25,6 +26,21 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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. +## 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 an idempotent no-change path (the contract is already deployed with the correct code hash), 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 real-change path, include every account and storage slot the helper touched. +- Present with different code is an error, not an overwrite. + A system address holding foreign bytecode is a broken chain. + +The returned `EvmState` is both the commit and the witness record of that step. + ## 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. @@ -33,10 +49,17 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 call `db.commit(...)` inside a helper that participates in `apply_pre_execution_changes`. + It hides the step from a witness generator. +- 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 overwrite foreign code at a system address. ## 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. +- Add a predeploy: a spec in `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. +- Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list and commits each witness. +- Read the rotated system address, or run `applyPendingChanges`: the pre-block system calls own those. From 69535526e5c9c85040b6e28ae0298bfad7023946 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:44:21 +0800 Subject: [PATCH 011/458] feat(satin): charge history gas for the write records a frame's start makes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A value CALL or CALLCODE writes its sender's account and its recipient's; a CREATE writes the creator's nonce and the created account. The caller pays for all of them at its own opcode, after revm computed the gas it forwards, so the frame's budget carries none of them and its allowance stays free for what the recipient does. What the frame does not keep goes back to the caller when it returns: a failing frame's records, and every record of a frame answered without running at all — an interceptor, the depth guard, the latch, an inspector — while a creation's nonce record survives its creation's failure, as the nonce bump does. The two records made outside any frame are charged where pre-execution makes them: one per applied EIP-7702 authority, which outlives a first frame that fails, and the one the transaction's own frame makes, which does not and is given back by the settlement the way EIP-8037 gives back the state gas of an account that frame would have created. One answer decides both the records and the charge, so they cannot disagree, and holds fifteen transactions to it: the history each pays beyond its body, its logs and its deployed code is exactly the write-record count the layer counted. --- crates/mega-evm/src/evm/execution.rs | 97 ++++++++-- crates/mega-evm/src/evm/instructions.rs | 92 ++++++++- crates/mega-evm/src/limit/frame_limit.rs | 110 +++++++---- crates/mega-evm/src/limit/limit.rs | 160 +++++++++++++-- crates/mega-evm/tests/satin/history_gas.rs | 6 +- crates/mega-evm/tests/satin/pricing-table.md | 14 +- crates/mega-evm/tests/satin/strategic_stop.rs | 6 +- .../tests/satin/synthetic_frame_gas.rs | 6 +- crates/mega-evm/tests/satin/write_records.rs | 183 ++++++++++++++++++ 9 files changed, 589 insertions(+), 85 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9e3149677..d84bfe448 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -40,7 +40,7 @@ use revm::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, InitialAndFloorGas, InstructionResult, InterpreterAction, }, - primitives::{Address, Bytes, CALL_STACK_LIMIT}, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, Inspector, Journal, }; @@ -48,7 +48,8 @@ use crate::{ evm::{history::tx_body_history_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, - ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, MegaInstructions, + write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, + MegaInstructions, }; /// The Satin handler. @@ -101,6 +102,13 @@ where /// 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. fn pre_execution( &self, evm: &mut Self::Evm, @@ -117,12 +125,17 @@ where evm.ctx().journal_mut().checkpoint_revert(checkpoint); return Ok(None); }; - if record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i).exceeded_limit() { + let authorities = record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + if authorities.check.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 })); } + if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, authorities.applied) { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + return Ok(None); + } Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -208,6 +221,18 @@ 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)?; + // 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 top_level = evm.ctx_ref().additional_limit.top_level_write_record_gas(); + let instruction_result = frame_result.instruction_result(); + if top_level > 0 && !instruction_result.is_ok() { + parent_gas.refill_history(top_level); + if instruction_result.is_halt() { + parent_gas.spend_all(); + } + *frame_result.gas_mut().tracker_mut() = *parent_gas; + } let layer = &mut evm.ctx_mut().additional_limit; let history = layer .intrinsic_history_gas() @@ -424,8 +449,15 @@ impl EvmTr for MegaEvm 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(&mut 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 and there is no caller to give anything back to. + if refund > 0 && returned.is_none() { + self.inner.frame_stack.get().interpreter.gas.refill_history(refund); + } + Ok(returned) } } @@ -738,9 +770,9 @@ fn account_nonce( fn record_applied_authorities( ctx: &mut MegaContext, journal_i: usize, -) -> LimitCheck { +) -> AppliedAuthorities { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return LimitCheck::WithinLimit; + return AppliedAuthorities { check: LimitCheck::WithinLimit, applied: 0 }; } let caller = ctx.tx().caller(); let target = ctx.tx().kind().to().copied(); @@ -755,9 +787,50 @@ 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; + let check = + ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); + AppliedAuthorities { check, applied: if check.exceeded_limit() { 0 } else { applied } } +} + +/// What [`record_applied_authorities`] found: the verdict of the limit check, and how many +/// authorities were applied — none, when the check stopped them. +struct AppliedAuthorities { + check: LimitCheck, + applied: 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. +/// +/// 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. +/// `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 top_level_record = match ctx.tx().kind() { + TxKind::Create => true, + TxKind::Call(to) => { + !ctx.tx().value().is_zero() && + to != ctx.tx().caller() && + !ctx.additional_limit.target_is_authority() + } + }; + let Some(top_level) = write_record_history_gas(u64::from(top_level_record)) else { + return false; + }; + let Some(authorities) = write_record_history_gas(applied_authorities) else { return false }; + let Some(cost) = top_level.checked_add(authorities) else { return false }; + if cost > 0 && !gas.record_history_cost(cost) { + return false; + } + ctx.additional_limit.set_top_level_write_record_gas(top_level); + true } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index a51b1774d..600bd18c0 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,8 +1,11 @@ //! 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; @@ -19,6 +22,12 @@ //! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). 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. +//! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. //! @@ -29,11 +38,13 @@ //! the base spec already has it. use revm::{ - bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE, + }, handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{gas_table_spec, host}, + instructions::{contract, gas_table_spec, host}, interpreter::EthInterpreter, interpreter_types::LoopControl, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, @@ -43,7 +54,10 @@ use revm::{ Database, }; -use crate::{history_gas, limit::HistoryBytes, ExternalEnvTypes, LimitCheck, MegaContext}; +use crate::{ + history_gas, limit::HistoryBytes, write_record_history_gas, ExternalEnvTypes, LimitCheck, + MegaContext, +}; use super::MegaInstructions; @@ -61,7 +75,7 @@ pub(crate) fn mega_instructions( 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 wrappers: [(u8, InstructionFn); 11] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -69,6 +83,10 @@ pub(crate) fn mega_instructions( (LOG3, log::<3, DB, ExtEnvs>), (LOG4, log::<4, DB, ExtEnvs>), (SELFDESTRUCT, selfdestruct::), + (CALL, call::), + (CALLCODE, call::), + (CREATE, create::), + (CREATE2, create::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -180,6 +198,66 @@ fn selfdestruct( 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 call the balance cannot fund, a creation the depth refuses — makes no records and is +/// charged nothing. A charge the frame cannot pay is an ordinary out-of-gas. +#[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 }); + if !host.prices_history() { + return result; + } + // An opcode that starts a frame suspends with the frame's input as its action; one that ends + // otherwise — a call the balance cannot fund, an out-of-gas — leaves no such action and makes + // no records. + let Some(InterpreterAction::NewFrame(input)) = interpreter.bytecode.action() else { + return result; + }; + let records = host.additional_limit.frame_start_records(input); + if records.total() == 0 { + return result; + } + let (Some(on_lane), Some(caller)) = ( + write_record_history_gas(records.on_lane), + write_record_history_gas(u64::from(records.caller)), + ) else { + return Err(InstructionResult::OutOfGas); + }; + let Some(cost) = on_lane.checked_add(caller) else { return Err(InstructionResult::OutOfGas) }; + if !interpreter.gas.record_history_cost(cost) { + return Err(InstructionResult::OutOfGas); + } + host.additional_limit.stage_frame_charge(on_lane, caller); + result +} + +/// `CALL` and `CALLCODE`, charging the caller for the records a value transfer writes. +/// +/// `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. `DELEGATECALL` and `STATICCALL` carry no +/// value and write nothing, so they run revm's instruction unwrapped. +fn call( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + charge_frame_start(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::) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 14103a4bc..48245fa7e 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -19,6 +19,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 @@ -41,11 +52,20 @@ pub(crate) struct Lane { } 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, @@ -54,9 +74,29 @@ impl Lane { } } - /// 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) + /// 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) + } } /// What the frame keeps if it succeeds. @@ -147,10 +187,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,6 +199,7 @@ 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); } @@ -240,10 +282,10 @@ mod tests { #[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 +294,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 +318,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 +340,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(); @@ -324,7 +366,7 @@ mod tests { #[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 +381,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"); @@ -361,9 +403,9 @@ mod tests { #[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.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(true, 0); t.drop_caller_record(); t.drop_caller_record(); assert_eq!(t.net(), LimitUsage::ZERO); @@ -377,23 +419,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 8798bbcdd..045e53094 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -50,6 +50,13 @@ pub struct AdditionalLimit { /// The history gas validation charged for the transaction's body, part of /// [`history_gas_spent`](Self::history_gas_spent). intrinsic_history_gas: 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 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, /// The history gas the settled transaction spent. history_gas_spent: u64, } @@ -79,6 +86,8 @@ impl AdditionalLimit { self.sender = Address::ZERO; self.frame_began = false; self.intrinsic_history_gas = 0; + self.top_level_write_record_gas = 0; + self.pending_frame_charge = FrameCharge::NONE; self.history_gas_spent = 0; } @@ -158,6 +167,37 @@ impl AdditionalLimit { self.intrinsic_history_gas = gas; } + /// 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; + } + + /// 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. + /// + /// 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, on_lane: u64, caller: u64) { + self.pending_frame_charge = FrameCharge { on_lane, caller }; + } + /// 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; @@ -278,11 +318,24 @@ impl AdditionalLimit { self.check() } + /// Takes a creation's creator record back: the creation failed before bumping the nonce. + /// + /// The record is gone, so the caller gets its history back when the frame returns: the lane no + /// longer holds a creator's record, and a lane that holds none gives its caller's charge back + /// with the rest. + pub(crate) fn creation_did_not_bump_nonce(&mut self) { + self.tracker.drop_caller_record(); + } + 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, }; + // 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; @@ -294,12 +347,14 @@ impl AdditionalLimit { Some(target), written_outside || transfers_value, budget, + 0, )); if transfers_value && !written_outside { self.tracker.record(WRITE_RECORD); } return; } + let records = self.frame_start_records(input); let inherited = self.tracker.current().is_some_and(|caller| { caller.address == Some(target) && caller.account_recorded }); @@ -308,27 +363,53 @@ 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); + } + if records.on_lane > 0 { + self.tracker.record(WRITE_RECORD.times(records.on_lane)); } } FrameInput::Create(inputs) => { - self.tracker.push(Lane::new(None, true, budget)); - self.tracker.record(WRITE_RECORD); + let records = self.frame_start_records(input); + 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); + } else if records.caller { + self.tracker.record_caller(true, charge.caller); } } FrameInput::Empty => self.push_empty_frame(), } } + /// 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. [`push_lane`](Self::push_lane) makes exactly these records, from + /// this same answer, so the charge and the count cannot disagree. + 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, + } + } + /// 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() { @@ -336,24 +417,31 @@ 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(); - } - /// 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) { + /// + /// 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: &mut FrameResult) -> u64 { self.apply_latch(result); - self.tracker.pop(result.instruction_result().is_ok()); + // 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(); + self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)) } /// Settles the transaction's outermost frame: pops its lane unless the frame already @@ -371,9 +459,45 @@ impl AdditionalLimit { } debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); if self.tracker.depth() == 1 { - self.on_frame_return(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"); } else { self.apply_latch(result); } } } + +/// 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 number of records, whoever keeps them. + pub(crate) const fn total(self) -> u64 { + self.on_lane.saturating_add(self.caller as u64) + } +} + +/// The history gas a caller paid for the records the frame it starts makes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct FrameCharge { + /// 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 { on_lane: 0, caller: 0 }; +} diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index cefc1b6a5..e4496969d 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -75,13 +75,13 @@ fn test_a_reverted_deployment_pays_no_code_deposit_history() { assert!(!reverted.result.is_success(), "the creation reverts"); assert_eq!( deployed.gas.history, - body(deploying(32).len() as u64) + 32 * CPHB, - "the body the init code travels in, and the deployed bytes", + 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", + "the body alone: nothing was deployed, and the account's record went with the failure", ); } diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index b43e0d768..96dcd990c 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -66,14 +66,14 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | Probe | gas used | regular | state | history | |---|---:|---:|---:|---:| | empty call | 42280 | 15000 | 0 | 27280 | -| value transfer to an existing account | 48280 | 21000 | 0 | 27280 | +| value transfer to an existing account | 51800 | 21000 | 0 | 30800 | | self-transfer | 39280 | 12000 | 0 | 27280 | | SSTORE 0 -> 1 | 165826 | 37106 | 97920 | 30800 | | SSTORE 0 -> 1 -> 0 | 51594 | 37212 | 0 | 27280 | -| value CALL to an empty account | 260201 | 49321 | 183600 | 27280 | +| value CALL to an empty account | 267241 | 49321 | 183600 | 34320 | | LOG1 with 32 data bytes | 51746 | 16018 | 0 | 35728 | -| create transaction deploying 0 bytes | 235935 | 24087 | 183600 | 28248 | -| create transaction deploying 32 bytes | 287732 | 24108 | 232560 | 31064 | +| create transaction deploying 0 bytes | 239455 | 24087 | 183600 | 31768 | +| create transaction deploying 32 bytes | 291252 | 24108 | 232560 | 34584 | ## SALT scaling @@ -84,9 +84,9 @@ The same probes again, with the SALT bucket the state charge lands in at `m` tim | SSTORE 0 -> 1 | 1 | 165826 | 37106 | 97920 | 30800 | | SSTORE 0 -> 1 | 2 | 263746 | 37106 | 195840 | 30800 | | SSTORE 0 -> 1 | 8 | 851266 | 37106 | 783360 | 30800 | -| value CALL to an empty account | 1 | 260201 | 49321 | 183600 | 27280 | -| value CALL to an empty account | 2 | 443801 | 49321 | 367200 | 27280 | -| value CALL to an empty account | 8 | 1545401 | 49321 | 1468800 | 27280 | +| value CALL to an empty account | 1 | 267241 | 49321 | 183600 | 34320 | +| value CALL to an empty account | 2 | 450841 | 49321 | 367200 | 34320 | +| value CALL to an empty account | 8 | 1552441 | 49321 | 1468800 | 34320 | ## The execution cap diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index ef8184b8f..811df4854 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -343,8 +343,10 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { ); 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" ); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 2b7468020..90c65bcd3 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -464,7 +464,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_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE; 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); @@ -472,7 +474,7 @@ 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}", ); diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 8bea20109..cbaf80f69 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -9,7 +9,9 @@ //! frame that fails. use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, test_utils::{BytecodeBuilder, MemoryDatabase}, LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, }; @@ -831,3 +833,184 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { assert!(result.result.is_success()); assert_eq!(evm.ctx().additional_limit().usage(), records(2), "CALLEE and CONTRACT2"); } + +/* ---------- 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, +} + +/// 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() +} + +/// 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, + }; + 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( + "a slot rewritten twice", + to_callee(storing(&[(1, 1), (1, 2), (1, 3)])), + plain(), + 0, + 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, + ), + 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, + ), + 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, + ), + 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, + ), + 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), + ] +} + +/// 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. +#[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 outcome = crate::common::execute(case.db, case.tx.clone()); + let usage = outcome.usage; + assert_eq!(usage.write_records, case.records, "{}: the records kept", case.name); + let body = mega_evm::TX_BODY_SIZE + case.tx.0.base.data.len() as u64; + let expected = (body + case.other_bytes + case.records * WRITE_RECORD_SIZE) * CPHB; + assert_eq!(outcome.gas.history, expected, "{}: the history it pays", case.name); + assert_eq!( + usage.data_size, + case.other_bytes + case.records * WRITE_RECORD_SIZE, + "{}: the data size the limit counts is what history prices", + case.name, + ); + } +} From 752d1d794a58fc57396283f997b2e49b4483e672 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:46:05 +0800 Subject: [PATCH 012/458] docs: reflow the module table to satisfy Prettier --- AGENTS.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1164ec6fd..ac9e02ace 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, 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`); the system-contract deploy in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`); the system-contract deploy in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 From 40370b36aa5567c2b61c39d988f6474c4e05951e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:54:30 +0800 Subject: [PATCH 013/458] test: pin the database error as the deploy error's source A failed account load is SystemContractDeployError::Database, and that inner error is what source() returns. Foreign code has no source. --- crates/mega-evm/tests/system/deploy.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index 11bfe1a2d..3365a66df 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -18,7 +18,7 @@ use mega_evm::{ ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, }, - test_utils::MemoryDatabase, + test_utils::{ErrorInjectingDatabase, MemoryDatabase}, HardforkParams, }; use revm::{primitives::KECCAK_EMPTY, DatabaseCommit}; @@ -229,3 +229,20 @@ fn test_registry_config_rejects_a_zero_address() { fn test_the_seeded_system_address_slot_is_the_current_one() { assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::ZERO); } + +/// A failed account load is [`SystemContractDeployError::Database`], and that inner error is +/// the `source` of the deploy error. +#[test] +fn test_a_database_error_is_the_source_of_the_deploy_error() { + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + db.fail_on_account = Some(ORACLE_CONTRACT_ADDRESS); + let err = transact_deploy(&mut db, &oracle_spec()).expect_err("the load fails"); + match &err { + SystemContractDeployError::Database(_) => {} + other => panic!("expected Database, got {other}"), + } + assert!( + core::error::Error::source(&err).is_some(), + "the database error is the source of the deploy error" + ); +} From 4168eebaadde1aa66cafc2cd44884081dfaa5f77 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:54:40 +0800 Subject: [PATCH 014/458] feat(satin): grant a value-transferring call an allowance for its history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: one three-topic event carrying one word, at the cost per history byte, granted to the frame a value-transferring CALL or CALLCODE starts below the transaction's own. It is not gas in any sense. It never enters the frame's Gas, so no settlement can hand it back; only the charge a log makes may draw on it, so it cannot buy computation or a write record; and it lives on the frame's lane, so a frame answered without running neither takes one nor leaves one behind. What it pays for is on no ledger, because no pool of the transaction's gas paid it. The tests pin the boundary it exists for — a transfer() reaching a hook that emits one event, and no more than one — and the three ways it could escape a frame: an interceptor answering in the frame's place, a transaction-level stop unwinding it, and the frame returning to its caller. --- crates/mega-evm/src/evm/history.rs | 32 ++ crates/mega-evm/src/evm/instructions.rs | 23 +- crates/mega-evm/src/limit/frame_limit.rs | 23 + crates/mega-evm/src/limit/limit.rs | 26 +- crates/mega-evm/tests/satin/main.rs | 1 + .../tests/satin/storage_call_stipend.rs | 392 ++++++++++++++++++ 6 files changed, 489 insertions(+), 8 deletions(-) create mode 100644 crates/mega-evm/tests/satin/storage_call_stipend.rs diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index dc6bc856f..f8b8f1c0e 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -46,6 +46,26 @@ 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) } +/// 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 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. @@ -89,6 +109,18 @@ mod tests { 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()); + } + /// A charge is its byte count at the cost per history byte, and a count with no price /// reports none. #[test] diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 600bd18c0..856a98c93 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -102,7 +102,7 @@ pub(crate) fn mega_instructions( /// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the /// staged write back with it. #[inline(always)] -fn commit_after( +fn commit_after( context: Ctx<'_, DB, ExtEnvs>, inner: InstructionFn, ) -> InstructionExecResult { @@ -119,7 +119,7 @@ fn commit_after( } let (check, history) = host.additional_limit.commit_staged_record(); if host.prices_history() { - settle_history(interpreter, history)?; + settle_history::(interpreter, host, history)?; } if check.exceeded_limit() { return Err(stop_frame(interpreter, &check)); @@ -133,16 +133,25 @@ fn commit_after( /// 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( +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) }; - if interpreter.gas.record_history_cost(cost) { + 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) @@ -181,21 +190,21 @@ fn stop_frame( fn sstore( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - commit_after(context, host::sstore) + commit_after::(context, host::sstore) } /// `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. fn selfdestruct( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - commit_after(context, host::selfdestruct) + commit_after::(context, host::selfdestruct) } /// Runs `inner` and charges the frame the history of the write records the frame `inner` starts diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 48245fa7e..36faf69ef 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -49,6 +49,9 @@ pub(crate) struct Lane { 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, + /// 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, } impl Lane { @@ -71,6 +74,7 @@ impl Lane { holds_caller_record: false, creator_record: false, budget, + stipend_remaining: 0, } } @@ -155,6 +159,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); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 045e53094..78442372c 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -3,7 +3,7 @@ use alloy_primitives::Address; use revm::{ handler::FrameResult, - interpreter::{FrameInput, InstructionResult}, + interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; use super::{ @@ -11,6 +11,7 @@ use super::{ record::{HistoryBytes, RecordEffect, StagedRecord}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, }; +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 @@ -181,6 +182,17 @@ impl AdditionalLimit { self.top_level_write_record_gas = gas; } + /// 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 { @@ -371,6 +383,9 @@ impl AdditionalLimit { if records.on_lane > 0 { 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.frame_start_records(input); @@ -469,6 +484,15 @@ impl AdditionalLimit { } } +/// 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 { diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index fcbc1dbed..90f8cdd44 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -19,6 +19,7 @@ mod salt_refund; mod schedule; mod state; mod static_callee; +mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; mod write_records; 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..a9d8e3ef1 --- /dev/null +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -0,0 +1,392 @@ +//! 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. + +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::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + STORAGE_CALL_STIPEND_BYTES, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{ + CALL, CALLCODE, DELEGATECALL, GAS, LOG3, POP, PUSH0, STATICCALL, STOP, +}; + +use crate::common::{call, context, runs_at_measurement_prices}; + +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) +} + +fn run(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + MegaEvm::new(context(db)).execute_transaction(tx).expect("the transaction is valid") +} + +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 = run(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.logs().len(), 1, "the hook emitted its event"); + 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 = run(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"); +} + +/// The allowance pays for history and nothing else: a hook that computes rather than logs runs +/// out of gas at the same 2,300, because no part of the allowance is reachable as gas. +#[test] +fn test_the_allowance_cannot_be_spent_on_computation() { + if runs_at_measurement_prices() { + return; + } + // `JUMPDEST; PUSH0; JUMP`: burns whatever gas it is given. + let burner = Bytes::from_static(&[0x5b, 0x5f, 0x56]); + let sender = + call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append_many([PUSH0, PUSH0]).append(STOP).build(); + let outcome = run(db(sender, burner), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "the caller survives"); + assert_eq!(outcome.gas.history, body(), "the hook kept nothing"); +} + +/// The allowance cannot pay a write record either: a hook that writes a slot has only the 2,300 +/// gas for it, which the slot's own price is far above. +#[test] +fn test_the_allowance_cannot_be_spent_on_a_write_record() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let writer = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let outcome = run(db(sender, writer), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "the caller survives"); + assert_eq!(outcome.usage.write_records, 0, "the hook kept no write"); + assert_eq!(outcome.gas.history, body()); +} + +/* ---------- 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 = run(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 = run(db(without, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + let granted = run(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(); + run(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 = run(with_controls(one_event), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + assert!(one.result.is_success(), "{:?}", one.result); + assert_eq!(one.result.logs().len(), 1, "the receiver still had its allowance"); + assert_eq!(one.gas.history, body() + 2 * record(), "the refusal cost no history"); + + let two = run(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. + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(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 = run(db(sender.clone(), Bytes::new()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + let logging = + run(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"); +} From 76063b0024e61bc12b36a0ae768c502040393766 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 16:59:09 +0800 Subject: [PATCH 015/458] bench(satin): hold the history workloads to the history they draw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The transact benchmark gains a calldata arm — a call carrying four kibibytes, which is four kibibytes of its body's history — and every workload is now checked against what it must draw before it is measured: each pays its body, the logging one pays for the bytes its logs append and the calldata one for the bytes it carries. A workload that stopped drawing what it is there to measure would otherwise still benchmark, and measure the wrong thing. --- crates/mega-evm/benches/transact.rs | 50 +++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index abb22eed3..93c47b6fe 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -8,7 +8,10 @@ //! 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. @@ -21,6 +24,11 @@ //! 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. 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,9 +36,11 @@ 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::{ + constants::COST_PER_HISTORY_BYTE, 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, + ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, + LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ @@ -62,6 +72,9 @@ 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; @@ -233,18 +246,41 @@ 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)), ]; 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 satin = + MegaEvm::new(mega_context(db.clone())).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"); + // 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", + ), + _ => {} } group.bench_function(format!("{workload}/satin"), |b| { b.iter_batched( From 06a9a58740ee96370aae579597973b3bccaf33f3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:03:24 +0800 Subject: [PATCH 016/458] test(satin): port the parked rows history gas owns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stipend rows of the legacy engine's rex4 and rex5 suites, the fee recipients' accounting of its rex6 suite and the exemption rows of the limit tracker's own tests — twenty-eight in all — run in the Satin targets now. The stipend rows become the allowance's, one per rule: which scheme is granted one, what it may and may not pay for, and that neither an interceptor's answer, a frame budget's revert nor a frame's return hands one back. The scheme table is a unit test, because a static frame may not log at all and so has nothing an allowance could buy it. The fee recipients' rows become the transaction body's: the accounts a transaction's fees are credited to are four of the five write records the body carries, so nothing reads them, nothing counts them, and a beneficiary that is one of the fee vaults changes nothing. The exemption rows become the history exemption's, which is the one metering a deposit or the protocol's own transaction is excused from. --- crates/mega-evm/src/limit/limit.rs | 45 ++ crates/mega-evm/tests/_pending/README.md | 19 +- .../_pending/rex4/storage_call_stipend.rs | 687 ------------------ .../tests/_pending/rex5/stipend_accounting.rs | 565 -------------- .../_pending/rex6/fee_reward_accounting.rs | 567 --------------- .../tests/_pending/src/limit/limit.rs | 98 --- crates/mega-evm/tests/satin/history_gas.rs | 78 +- .../tests/satin/storage_call_stipend.rs | 119 +++ 8 files changed, 254 insertions(+), 1924 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/limit.rs diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 78442372c..6f8ba8608 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -525,3 +525,48 @@ impl FrameCharge { /// Nothing charged. const NONE: Self = Self { on_lane: 0, caller: 0 }; } + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{Address, Bytes, U256}; + use revm::interpreter::{CallInput, CallValue}; + + 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, + } + } + + /// 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/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4c4ea6455..248af0b8c 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 | -| 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 | @@ -40,7 +39,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** | **524** | **457** | **67** | **311** | **185** | **28** | +| **Total** | **496** | **433** | **63** | **307** | **161** | **28** | ## Tests ported in place @@ -203,6 +202,18 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the | `src/system/tx.rs` | the system contract interceptors (6) | 6 | `src/system/tx.rs` | | **Total** | | **61** | | +## Tests ported by history gas + +These 28 rows run in a real test target now, adapted to the Satin API and to the history ledger 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 | +|---|---|---:|---| +| `rex4/storage_call_stipend.rs` | history gas (12) | 12 | `crates/mega-evm/src/limit/limit.rs`, `tests/satin/storage_call_stipend.rs` | +| `rex5/stipend_accounting.rs` | history gas (6) | 6 | `tests/satin/storage_call_stipend.rs` | +| `rex6/fee_reward_accounting.rs` | history gas (6) | 6 | `tests/satin/history_gas.rs` | +| `src/limit/limit.rs` | history gas (4) | 4 | `tests/satin/history_exemption.rs` | +| **Total** | | **28** | | + ## 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. @@ -253,7 +264,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `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) | @@ -267,12 +277,10 @@ 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/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) | @@ -283,7 +291,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `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) | 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/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/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/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/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index e4496969d..e5d0c2acb 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -7,7 +7,8 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}, test_utils::{BytecodeBuilder, MemoryDatabase}, - LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, RETURN, REVERT}, @@ -263,3 +264,78 @@ fn test_a_failing_frame_gives_its_history_back() { assert_eq!(kept.gas.history - quiet.gas.history, (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB); assert_eq!(reverted.gas.history, quiet.gas.history, "the reverted frame's log is not paid for"); } + +/* ---------- 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/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index a9d8e3ef1..bb5888f3d 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -390,3 +390,122 @@ fn test_an_unspent_allowance_does_not_return_to_the_caller() { // 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 = run(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.logs().len(), 2, "both hops emitted their event"); + // 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", + ); +} + +/// 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. + 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(200); + + 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 latches nothing"); + 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 = + run(db(sender.clone(), drained_then_reverts), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + let quiet = run(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 = + run(db(sender, event().append(STOP).build()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.logs().len(), 1, "the hook emitted its event"); + assert_eq!(outcome.gas.history, body() + 2 * record()); +} From 39ec36e5b8aeb693d5f8156890b789a4363e1a76 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:06:05 +0800 Subject: [PATCH 017/458] docs(satin): say what history gas charges and who pays none of it The module table, the engine's own description and the contracts of the common execution layer now carry the third ledger: the byte table every site is sized by, where each charge is made and given back, the three kinds of transaction that pay none of it, and the allowance a value-transferring call grants. The legacy engine's storage-gas stipend gets a line of its own in the comparison, because the allowance that replaces it is a different thing: it never enters a frame's gas limit, so there is nothing to burn on return. --- AGENTS.md | 41 +++++++++++++++++++++----------- crates/mega-evm/README.md | 15 +++++++++--- crates/mega-evm/src/constants.rs | 11 ++++++--- crates/mega-evm/src/evm/host.rs | 8 ++++--- 4 files changed, 52 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b691789b..9295eb8e4 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, 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 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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/` | 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 and history allowances (`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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -116,7 +116,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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, 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. + 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. @@ -124,6 +124,16 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. +- 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 charge and the count it pairs with 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, before the frame's budget is forwarded. + What a frame does not keep comes back, at the same price, to whoever paid it. + 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 and binds nothing: history charges the same bytes at a higher rate. +- 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 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`. @@ -132,7 +142,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. +- The legacy engine's gas leakage pitfalls and limit-check protocol describe mechanisms that do not exist here; the contracts below replace them. + 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. ### Contracts of the common execution layer @@ -142,7 +153,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer `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. + 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. + 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. 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. @@ -179,6 +191,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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. `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. ## Test Organization (`crates/mega-evm/tests/`) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index d63deff5a..e7b160f8f 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -27,7 +27,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. -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 with three changes: the entries EIP-8038 repriced go back to their Osaka values, 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. 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. @@ -58,8 +58,17 @@ The Oracle forwards a `sendHint` payload to the node's oracle service, and a `ke 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. -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 charge and the count it pairs with cannot drift apart. +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. +A deposit, a transaction the protocol itself sent and a system call pay no history at all. + +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 resource limits, gas detention, system contract deployment 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 9db7e0493..2437f48b5 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -9,7 +9,7 @@ //! | [`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 | @@ -21,8 +21,8 @@ //! 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. +//! The per-transaction and per-block state-gas limits are further placeholders, which the +//! state-gas limits add when they land. use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; @@ -38,6 +38,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 diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index f3259d784..c99fb59f2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -5,10 +5,12 @@ //! 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. From b7dc0ceef6c9d191e29f7775b54d266f29808e10 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:20:22 +0800 Subject: [PATCH 018/458] test(satin): kill the survivors the history gas mutation gate found Three gaps in what the tests reach, and five places where the code said the same thing twice. The exemption tests deployed nothing, so the schedule an exempt transaction runs was never observed: the program they share now deploys thirty-two bytes, and a test holds the difference a user transaction pays for them against the nothing a deposit pays. A frame answered without running was only ever observed failing, where the charge comes back either way; an inspector answering a value call with a success is the one path where the records were never made and the result still succeeds, and a test pins that its caller pays for none of them. And a transaction whose target is an applied authority was counted but not priced, so the history it pays is now held against a transfer to an account that is not one. The five guards on a zero amount are gone. Every one of them stood in front of an operation that is a no-op at zero - refilling no history, charging no history, recording no records, staging no charge - so each only restated what the operation already does, and nothing could tell the two apart. --- crates/mega-evm/src/evm/execution.rs | 9 +-- crates/mega-evm/src/evm/instructions.rs | 3 - crates/mega-evm/src/limit/limit.rs | 9 +-- .../mega-evm/tests/satin/history_exemption.rs | 81 +++++++++++++++---- crates/mega-evm/tests/satin/write_records.rs | 75 ++++++++++++++++- 5 files changed, 142 insertions(+), 35 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index d84bfe448..55cad95b0 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -224,10 +224,9 @@ where // 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 top_level = evm.ctx_ref().additional_limit.top_level_write_record_gas(); let instruction_result = frame_result.instruction_result(); - if top_level > 0 && !instruction_result.is_ok() { - parent_gas.refill_history(top_level); + 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(); } @@ -454,7 +453,7 @@ impl EvmTr for MegaEvm 0 && returned.is_none() { + if returned.is_none() { self.inner.frame_stack.get().interpreter.gas.refill_history(refund); } Ok(returned) @@ -828,7 +827,7 @@ fn charge_records_made_outside_a_frame( }; let Some(authorities) = write_record_history_gas(applied_authorities) else { return false }; let Some(cost) = top_level.checked_add(authorities) else { return false }; - if cost > 0 && !gas.record_history_cost(cost) { + if !gas.record_history_cost(cost) { return false; } ctx.additional_limit.set_top_level_write_record_gas(top_level); diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 856a98c93..73e63e1a3 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -231,9 +231,6 @@ fn charge_frame_start( return result; }; let records = host.additional_limit.frame_start_records(input); - if records.total() == 0 { - return result; - } let (Some(on_lane), Some(caller)) = ( write_record_history_gas(records.on_lane), write_record_history_gas(u64::from(records.caller)), diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6f8ba8608..933fdbd7e 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -380,9 +380,7 @@ impl AdditionalLimit { if records.caller { self.tracker.record_caller(false, charge.caller); } - if records.on_lane > 0 { - self.tracker.record(WRITE_RECORD.times(records.on_lane)); - } + self.tracker.record(WRITE_RECORD.times(records.on_lane)); if grants_stipend(inputs) { self.tracker.grant_stipend(storage_call_stipend()); } @@ -505,11 +503,6 @@ pub(crate) struct FrameStartRecords { impl FrameStartRecords { /// No record at all. pub(crate) const NONE: Self = Self { on_lane: 0, caller: false }; - - /// The number of records, whoever keeps them. - pub(crate) const fn total(self) -> u64 { - self.on_lane.saturating_add(self.caller as u64) - } } /// The history gas a caller paid for the records the frame it starts makes. diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 35e932f10..8cb26729a 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -18,7 +18,10 @@ use mega_evm::{ test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, MegaEvm, MegaTransaction, }; -use revm::context::TxEnv; +use revm::{ + bytecode::opcode::{CALL, CREATE, LOG0, POP}, + context::TxEnv, +}; use crate::common::{context, runs_at_measurement_prices}; @@ -30,14 +33,20 @@ const PAYEE: Address = address!("0000000000000000000000000000000000400002"); 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 — one of each history site the engine charges. +/// 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(revm::bytecode::opcode::LOG0) + .append(LOG0) // CALL(gas, PAYEE, 1, 0, 0, 0, 0) .push_number(0u64) .push_number(0u64) @@ -46,18 +55,22 @@ fn program() -> Bytes { .push_number(1u64) .push_address(PAYEE) .push_number(1_000_000u64) - .append(revm::bytecode::opcode::CALL) - .append(revm::bytecode::opcode::POP) - // CREATE(0, 0, 0): an empty deployment, which still creates an account + .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) - .push_number(0u64) - .append(revm::bytecode::opcode::CREATE) - .append(revm::bytecode::opcode::POP) + .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; + fn db() -> MemoryDatabase { MemoryDatabase::default() .account_balance(CALLER, U256::from(10u64.pow(18))) @@ -97,16 +110,51 @@ fn test_a_user_transaction_pays_history_for_the_program() { assert!(state > 0, "and for the state it adds"); } -/// A deposit pays no history gas: the bytes it carries were paid for on L1. +/// 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_a_deposit_pays_no_history_gas() { +fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { if runs_at_measurement_prices() { return; } - let mut tx = call_from(CALLER, CONTRACT); + 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"); +} + +/// `tx` as a deposit: no fee, and a source hash a user's transaction could carry. +fn deposit(mut tx: MegaTransaction) -> MegaTransaction { tx.0.deposit.source_hash = B256::repeat_byte(0x11); tx.0.base.gas_price = 0; - let (history, state) = ledgers(tx); + tx +} + +/// 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) = 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"); } @@ -153,10 +201,9 @@ fn test_the_exemption_does_not_outlive_its_transaction() { } let mut evm = MegaEvm::new(context(db())); - let mut deposit = call_from(CALLER, CONTRACT); - deposit.0.deposit.source_hash = B256::repeat_byte(0x11); - deposit.0.base.gas_price = 0; - let exempt = evm.execute_transaction(deposit).expect("the deposit is valid"); + 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. diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index cbaf80f69..0b5b9abcf 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -514,10 +514,35 @@ fn test_applied_authorities_record_once_each() { /// 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)); + + // 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 @@ -1014,3 +1039,49 @@ 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. +#[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, LimitUsage::ZERO, "the answered call wrote nothing"); + assert_eq!(answered_history, body, "so its caller pays for nothing beyond its body"); + assert_eq!(ran_usage, records(2), "the transfer that ran wrote two accounts"); + assert_eq!( + ran_history, + body + 2 * WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE + ); +} From 195914f23ea9fa4be8b13aaffca7500ad4e91eec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:42:24 +0800 Subject: [PATCH 019/458] feat(block): observe pre-block states before commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give MegaBlockExecutor an optional observer and a source enum so each pre-block state — the EIP-2935 call, the EIP-4788 call, and every system-contract deploy — is visible before it is committed. The sequence is the witness a stateless client needs. --- AGENTS.md | 4 +- crates/mega-evm/README.md | 2 +- crates/mega-evm/benches/block.rs | 51 +++++++----- crates/mega-evm/src/block/executor.rs | 88 ++++++++++++++++++-- crates/mega-evm/src/system/AGENTS.md | 3 +- crates/mega-evm/tests/block/common.rs | 24 +++++- crates/mega-evm/tests/block/deploy.rs | 111 +++++++++++++++++++------- 7 files changed, 224 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ac9e02ace..ed9e531f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,7 +95,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, 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`); the system-contract deploy in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the state-gas and write-record block limits | +| `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`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point 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) | @@ -127,7 +127,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`. - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent); the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. + It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index cafb2f7fd..f473b92ef 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -41,7 +41,7 @@ No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a 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` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, and leaves one hook point empty: the pre-block system calls. +`apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, hands each pre-block state (the two EIP calls and the seven deploys) to an optional observer before it commits — that sequence is the witness a stateless client needs — and leaves one hook point empty: the pre-block system calls. 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. diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 62027f068..e249fdf25 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -24,20 +24,21 @@ 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::{ - system::{ - system_contract_specs, transact_deploy, SequencerRegistryConfig, - SYSTEM_CONTRACT_DEPLOY_COUNT, - }, + system::{SequencerRegistryConfig, SYSTEM_CONTRACT_DEPLOY_COUNT}, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, + MegaSpecId, MegaTxEnvelope, PreBlockStateSource, }; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, context::{BlockEnv, CfgEnv}, database::State, + state::EvmState, +}; +use std::{ + hint::black_box, + sync::{Arc, Mutex}, }; -use std::hint::black_box; /// Transactions in the block. const N: u64 = 64; @@ -204,21 +205,35 @@ fn bench_block(c: &mut Criterion) { group.finish(); // The idempotent pre-block path: everything is already deployed, so each of the seven - // specs is a read-only witness entry. Checked once before measurement so a broken deploy - // does not get timed. + // specs is a read-only witness entry. Checked once against the executor's own observer + // before measurement so a broken deploy does not get timed. { let mut state = deployed_state(); - let config = SequencerRegistryConfig::placeholder(); - let mut read_only = 0usize; - for deploy_spec in system_contract_specs(&config) { - let outcome = transact_deploy(&mut state, &deploy_spec).expect("the idempotent check"); - assert_eq!(outcome.len(), 1, "{} is one witness account", deploy_spec.address); - let account = outcome.get(&deploy_spec.address).expect("the account is present"); - assert!(!account.is_touched(), "{} is not touched", deploy_spec.address); - assert!(!account.is_created(), "{} is not created", deploy_spec.address); - read_only += 1; + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); + let mut executor = + MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); + let log = Arc::new(Mutex::new(Vec::new())); + let captured = Arc::clone(&log); + executor.set_pre_block_observer(Some(Box::new( + move |source: PreBlockStateSource, state: &EvmState| { + captured.lock().expect("pre-block observer").push((source, state.clone())); + }, + ))); + executor.apply_pre_execution_changes().expect("the idempotent check"); + let outcomes = log.lock().expect("pre-block observer"); + let deploys: Vec<_> = outcomes + .iter() + .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) + .collect(); + assert_eq!(deploys.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); + for (source, state) in &deploys { + assert_eq!(state.len(), 1, "{source:?} is one witness account"); + let account = state.values().next().expect("the account is present"); + assert!(!account.is_touched(), "{source:?} is not touched"); + assert!(!account.is_created(), "{source:?} is not created"); } - assert_eq!(read_only, SYSTEM_CONTRACT_DEPLOY_COUNT); + assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); + assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); } let mut group = c.benchmark_group("block"); diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 3d9302c80..5a90126b2 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -34,6 +34,17 @@ //! is the compile-time proof that an inspector observes and writes nothing back; the generic route //! is the checked one. //! +//! # The pre-block observer +//! +//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, and every system-contract deploy — +//! produces an [`EvmState`] that this executor commits. alloy-evm 0.36 re-exports revm's +//! `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on [`BlockExecutor`] and no +//! source tag, so this crate names the step ([`PreBlockStateSource`]) and carries an optional +//! [`PreBlockStateObserver`]. Every pre-block state is handed to the observer **before** it is +//! committed, in execution order. The sequence is the witness a stateless client needs: revm +//! drops untouched accounts from the committed transition, so a caller that only saw the +//! database after the commit would miss the read-only deploy entries of a later block. +//! //! # What later mechanisms fill in //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) deploys the @@ -196,6 +207,52 @@ impl From for BlockExecutionError { } } +/// Where a pre-block state change came from. +/// +/// alloy-evm 0.36 re-exports revm's `OnStateHook` (`on_state(&EvmState)`) but has no +/// `set_state_hook` on [`BlockExecutor`] and no source tag, so this crate names the step. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreBlockStateSource { + /// The EIP-2935 history-storage system call. + Eip2935, + /// The EIP-4788 beacon-root system call. + Eip4788, + /// A system-contract or factory deploy at this address. + SystemContract(Address), +} + +/// Receives each pre-block [`EvmState`] before the executor commits it. +/// +/// The sequence is the witness a stateless client needs: every read and write a pre-block step +/// made, tagged with its source, in execution order. Install one with +/// [`MegaBlockExecutor::set_pre_block_observer`]. +pub trait PreBlockStateObserver: Send + 'static { + /// `state` is the witness of this step, not yet committed. + fn on_pre_block_state(&mut self, source: PreBlockStateSource, state: &EvmState); +} + +impl PreBlockStateObserver for F +where + F: FnMut(PreBlockStateSource, &EvmState) + Send + 'static, +{ + fn on_pre_block_state(&mut self, source: PreBlockStateSource, state: &EvmState) { + self(source, state) + } +} + +/// [`Debug`] skip for the optional observer: a trait object is not [`Debug`]. +struct OptionalPreBlockObserver(Option>); + +impl fmt::Debug for OptionalPreBlockObserver { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0.is_some() { + f.write_str("Some(_)") + } else { + f.write_str("None") + } + } +} + /// Executes the transactions of one block on a Satin EVM. #[derive(Debug)] pub struct MegaBlockExecutor { @@ -215,6 +272,8 @@ pub struct MegaBlockExecutor { is_canyon: bool, /// Whether Regolith is active, which decides whether a deposit receipt carries a nonce. is_regolith: bool, + /// Optional observer of each pre-block state, invoked before the state is committed. + pre_block_observer: OptionalPreBlockObserver, } impl MegaBlockExecutor { @@ -242,6 +301,13 @@ impl MegaBlockExecutor { pub const fn gas(&self) -> &BlockGasCounters { &self.limiter.gas } + + /// Installs the observer that receives every pre-block state before it is committed. + /// + /// The sequence is the witness a stateless client needs. `None` turns observation off. + pub fn set_pre_block_observer(&mut self, observer: Option>) { + self.pre_block_observer = OptionalPreBlockObserver(observer); + } } impl MegaBlockExecutor, R, Spec> @@ -281,6 +347,7 @@ where evm, receipts: Vec::new(), limiter: limits.to_block_limiter(), + pre_block_observer: OptionalPreBlockObserver(None), } } } @@ -317,6 +384,14 @@ where self.evm.ctx_mut().db_mut().commit(state); } + /// Hands `state` to the pre-block observer, then commits it. + fn deliver_pre_block(&mut self, source: PreBlockStateSource, state: EvmState) { + if let Some(observer) = self.pre_block_observer.0.as_mut() { + observer.on_pre_block_state(source, &state); + } + self.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. @@ -388,9 +463,10 @@ where /// Runs what a block does before its transactions. /// /// In order: the admission gate, the reset of the block-hash record, the EIP-2935 and - /// EIP-4788 pre-block calls, and the system-contract deploys. Each step's state is committed - /// here rather than inside its helper, so a witness generator sees every step's read and - /// write set. + /// EIP-4788 pre-block calls, and the system-contract deploys. Each step's state is handed to + /// the pre-block observer and then committed here rather than inside its helper, so a + /// witness generator sees every step's read and write set. The sequence the observer + /// receives is the witness a stateless client needs. /// /// 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 @@ -417,7 +493,7 @@ where &mut self.evm, )?; if let Some(ResultAndState { state, .. }) = state { - self.commit(state); + self.deliver_pre_block(PreBlockStateSource::Eip2935, state); } let state = eips::transact_beacon_root_contract_call( @@ -426,7 +502,7 @@ where &mut self.evm, )?; if let Some(ResultAndState { state, .. }) = state { - self.commit(state); + self.deliver_pre_block(PreBlockStateSource::Eip4788, state); } // The EIP-2935 / EIP-4788 calls above do not depend on these predeploys: they target @@ -444,7 +520,7 @@ where .into() } })?; - self.commit(state); + self.deliver_pre_block(PreBlockStateSource::SystemContract(spec.address), state); } // Hook point: the pre-block system calls. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index d5a8e359e..a9dbd1896 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -40,6 +40,7 @@ The contract for a new or modified helper: A system address holding foreign bytecode is a broken chain. The returned `EvmState` is both the commit and the witness record of that step. +The executor hands it to the pre-block observer, then commits: the sequence the observer sees 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. @@ -61,5 +62,5 @@ The returned `EvmState` is both the commit and the witness record of that step. - 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. - Add a predeploy: a spec in `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. -- Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list and commits each witness. +- Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list, delivers each witness to the pre-block observer, and commits. - Read the rotated system address, or run `applyPendingChanges`: the pre-block system calls own those. diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 706736dc7..361992f82 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -13,14 +13,16 @@ use mega_evm::{ test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, - MegaTxEnvelope, + MegaTxEnvelope, PreBlockStateSource, }; use op_alloy_consensus::TxDeposit; use revm::{ context::{BlockEnv, CfgEnv}, database::State, inspector::NoOpInspector, + state::EvmState, }; +use std::sync::{Arc, Mutex}; /// The sender every test transaction comes from. pub(crate) const CALLER: Address = address!("0x2000000000000000000000000000000000000002"); @@ -168,6 +170,26 @@ fn build( MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } +/// Shared log of pre-block states an executor observer records. +pub(crate) type PreBlockLog = Arc>>; + +/// Installs a recording observer on `executor` and returns the log it writes. +pub(crate) fn record_pre_block(executor: &mut TestExecutor<'_>) -> PreBlockLog { + let log = Arc::new(Mutex::new(Vec::new())); + let captured = Arc::clone(&log); + executor.set_pre_block_observer(Some(Box::new( + move |source: PreBlockStateSource, state: &EvmState| { + captured.lock().expect("pre-block observer").push((source, state.clone())); + }, + ))); + log +} + +/// The states the log holds, in execution order. +pub(crate) fn pre_block_states(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { + log.lock().expect("pre-block observer").clone() +} + /// A legacy transaction from [`CALLER`]. pub(crate) fn tx(nonce: u64, to: Address, input: Bytes, gas_limit: u64) -> MegaTxEnvelope { let tx_legacy = TxLegacy { diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index b55ec92d1..6374f2728 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -9,21 +9,21 @@ use mega_evm::{ ADMIN as ADMIN_SLOT, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, }, - system_contract_specs, transact_deploy, SequencerRegistryConfig, 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, - MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, - SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, + SequencerRegistryConfig, 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, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, }, test_utils::MemoryDatabase, - MegaHardfork, MegaHardforkConfig, MegaHardforks, + MegaHardfork, MegaHardforkConfig, MegaHardforks, PreBlockStateSource, }; -use revm::{context::result::ExecutionResult, database::State, Database}; +use revm::{context::result::ExecutionResult, database::State, state::Account, Database}; use crate::common::{ - self, executor, executor_with_spec, recovered, registry_config, tx, unlimited_ctx, ADMIN, - SEQUENCER, + self, executor, executor_with_spec, pre_block_states, record_pre_block, recovered, + registry_config, tx, unlimited_ctx, ADMIN, SEQUENCER, }; fn expected_hashes() -> [(Address, B256); SYSTEM_CONTRACT_DEPLOY_COUNT] { @@ -47,6 +47,30 @@ fn assert_deployed(state: &mut State) { } } +fn deploy_sources() -> [PreBlockStateSource; SYSTEM_CONTRACT_DEPLOY_COUNT] { + expected_hashes().map(|(address, _)| PreBlockStateSource::SystemContract(address)) +} + +fn assert_pre_block_order(outcomes: &[(PreBlockStateSource, revm::state::EvmState)]) { + assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT); + assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); + assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); + for (i, source) in deploy_sources().iter().enumerate() { + assert_eq!(outcomes[2 + i].0, *source); + } +} + +fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryConfig) { + let addr_val = |address: Address| U256::from_be_bytes(address.into_word().0); + let slot = |key: U256| account.storage.get(&key).expect("seeded").present_value; + assert_eq!(slot(CURRENT_SYSTEM_ADDRESS), addr_val(config.initial_system_address)); + assert_eq!(slot(CURRENT_SEQUENCER), addr_val(config.initial_sequencer)); + assert_eq!(slot(ADMIN_SLOT), addr_val(config.initial_admin)); + assert_eq!(slot(INITIAL_SYSTEM_ADDRESS), addr_val(config.initial_system_address)); + assert_eq!(slot(INITIAL_SEQUENCER), addr_val(config.initial_sequencer)); + assert_eq!(slot(INITIAL_FROM_BLOCK), U256::from(config.initial_from_block)); +} + fn assert_registry_seed(state: &mut State, config: &SequencerRegistryConfig) { let addr_val = |address: Address| U256::from_be_bytes(address.into_word().0); assert_eq!( @@ -76,22 +100,46 @@ fn assert_registry_seed(state: &mut State, config: &SequencerReg } /// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the -/// registry's seeded slots. +/// registry's seeded slots. The executor's own observer sees the two EIP calls and then the +/// seven deploy states, in that order. #[test] fn test_the_first_block_deploys_every_system_contract() { let mut state = common::state(); - { + let outcomes = { let mut executor = executor(&mut state, unlimited_ctx()); + let log = record_pre_block(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(executor.gas().execution, 0); + assert_eq!(executor.gas().state, 0); + assert_eq!(executor.gas().history, 0); + pre_block_states(&log) + }; + assert_pre_block_order(&outcomes); + let config = registry_config(); + for (i, (address, hash)) in expected_hashes().into_iter().enumerate() { + let account = outcomes[2 + i] + .1 + .get(&address) + .unwrap_or_else(|| panic!("{address} is in the deploy state")); + assert!(account.is_touched(), "{address} is touched"); + assert!(account.is_created(), "{address} is created"); + assert_eq!(account.info.code_hash, hash, "{address} has the wrong code"); + assert_eq!(account.info.nonce, 1, "{address} is a created contract"); + if address == SEQUENCER_REGISTRY_ADDRESS { + assert_registry_account_seed(account, &config); + } else { + assert!(account.storage.is_empty(), "{address} has no seeded storage"); + } } assert_deployed(&mut state); - assert_registry_seed(&mut state, ®istry_config()); - assert_eq!(registry_config().initial_system_address, MEGA_SYSTEM_ADDRESS); - assert_eq!(registry_config().initial_sequencer, SEQUENCER); - assert_eq!(registry_config().initial_admin, ADMIN); + assert_registry_seed(&mut state, &config); + assert_eq!(config.initial_system_address, MEGA_SYSTEM_ADDRESS); + assert_eq!(config.initial_sequencer, SEQUENCER); + assert_eq!(config.initial_admin, ADMIN); } -/// A second block changes nothing: each deploy is a read-only witness entry. +/// A second block changes nothing in the seven deploys: the executor's own observer reports +/// exactly seven read-only account entries, and the two EIP calls still precede them. #[test] fn test_the_second_block_is_seven_read_only_entries() { let mut state = common::state(); @@ -100,21 +148,24 @@ fn test_the_second_block_is_seven_read_only_entries() { executor.apply_pre_execution_changes().expect("the first block deploys"); } - let specs = system_contract_specs(®istry_config()); - assert_eq!(specs.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); - for spec in &specs { - let outcome = transact_deploy(&mut state, spec).expect("the idempotent check"); - assert_eq!(outcome.len(), 1, "{} is one witness account", spec.address); - let account = outcome.get(&spec.address).unwrap(); - assert!(!account.is_touched(), "{} is not touched", spec.address); - assert!(!account.is_created(), "{} is not created", spec.address); - assert!(account.storage.is_empty(), "{} is not re-seeded", spec.address); - assert_eq!(account.info.code_hash, spec.code_hash); - } - - { + let outcomes = { let mut executor = executor(&mut state, unlimited_ctx()); + let log = record_pre_block(&mut executor); executor.apply_pre_execution_changes().expect("the second block is a no-op"); + assert_eq!(executor.gas().execution, 0); + assert_eq!(executor.gas().state, 0); + assert_eq!(executor.gas().history, 0); + pre_block_states(&log) + }; + assert_pre_block_order(&outcomes); + for (i, (address, hash)) in expected_hashes().into_iter().enumerate() { + let state = &outcomes[2 + i].1; + assert_eq!(state.len(), 1, "{address} is the only account in its witness"); + let account = state.get(&address).unwrap(); + assert!(!account.is_touched(), "{address} is not touched"); + assert!(!account.is_created(), "{address} is not created"); + assert!(account.storage.is_empty(), "{address} is not re-seeded"); + assert_eq!(account.info.code_hash, hash); } assert_deployed(&mut state); assert_registry_seed(&mut state, ®istry_config()); From f119d5b4342801ca8785fd23196ba65b0c290565 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:46:18 +0800 Subject: [PATCH 020/458] test: restore unported deployment rows to pending Rotation, resolution and admin-handoff scenarios belong to the pre-block system calls. Upgrade and per-fork-gate rows are retired because a single-spec engine has neither. The minimum-delay seed stays with this mechanism until it is ported. --- crates/mega-evm/tests/_pending/README.md | 43 +- .../tests/_pending/block_executor/main.rs | 1 + .../block_executor/sequencer_registry.rs | 620 ++++++++++++++++++ .../_pending/src/system/sequencer_registry.rs | 37 ++ 4 files changed, 686 insertions(+), 15 deletions(-) create mode 100644 crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index bf26e6567..abd839462 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -34,13 +34,13 @@ Do not add a `_pending/main.rs`. | 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 | 27 | 15 | 12 | 23 | 4 | 0 | -| system contract deployment | 12 | 5 | 7 | 12 | 0 | 0 | +| the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | +| system contract deployment | 13 | 5 | 8 | 13 | 0 | 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** | **478** | **445** | **33** | **270** | **180** | **28** | +| **Total** | **486** | **452** | **34** | **278** | **180** | **28** | ## Tests ported in place @@ -205,25 +205,25 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by system contract deployment -These 46 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy, so the counts above are lower than the inventory's by exactly these rows. +These 27 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy, 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/sequencer_registry.rs` | system contract deployment (8) | 8 | `tests/block/deploy.rs` | +| `block_executor/sequencer_registry.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | | `mini_rex/oracle.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | | `rex2/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | | `rex4/deployment.rs` | system contract deployment (2) | 2 | `tests/block/deploy.rs` | -| `src/system/control.rs` | system contract deployment (8) | 8 | `tests/system/control.rs`, `tests/system/deploy.rs` | -| `src/system/deploy.rs` | system contract deployment (4) | 4 | `tests/system/deploy.rs` | -| `src/system/keyless_deploy.rs` | system contract deployment (2) | 2 | `tests/system/deploy.rs` | -| `src/system/limit_control.rs` | system contract deployment (5) | 5 | `tests/system/deploy.rs` | -| `src/system/oracle.rs` | system contract deployment (7) | 7 | `tests/system/deploy.rs` | -| `src/system/sequencer_registry.rs` | system contract deployment (8) | 8 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | -| **Total** | | **46** | | +| `src/system/control.rs` | system contract deployment (6) | 6 | `tests/system/control.rs`, `tests/system/deploy.rs` | +| `src/system/deploy.rs` | system contract deployment (1) | 1 | `tests/system/deploy.rs` | +| `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/system/deploy.rs` | +| `src/system/limit_control.rs` | system contract deployment (3) | 3 | `tests/system/deploy.rs` | +| `src/system/oracle.rs` | system contract deployment (4) | 4 | `tests/system/deploy.rs` | +| `src/system/sequencer_registry.rs` | system contract deployment (7) | 7 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | +| **Total** | | **27** | | ## 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. +These 19 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 | @@ -231,7 +231,12 @@ They are not counted above. | `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** | | +| `src/system/control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | +| `src/system/deploy.rs` | system contract deployment (3) | 3 | Satin has no bytecode upgrade path: a system address with different code is an error, not a storage-preserving upgrade; Satin has no bytecode upgrade path: a system address with different code is an error, not a force-created upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version table to pin | +| `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | +| `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | +| `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | +| **Total** | | **19** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -251,6 +256,13 @@ They are not counted above. | `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_respects_30m_floor` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | | `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_updates_and_clears_due_roles` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | | `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_uses_block_gas_limit` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | +| `block_executor/sequencer_registry.rs` | `test_admin_handoff_via_block_executor` | the pre-block system calls | the pre-block system calls own the two-step admin handoff | +| `block_executor/sequencer_registry.rs` | `test_bootstrap_block_resolves_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | +| `block_executor/sequencer_registry.rs` | `test_dual_change_in_same_block` | the pre-block system calls | the pre-block system calls own applying a pending rotation | +| `block_executor/sequencer_registry.rs` | `test_pending_not_yet_due_is_noop` | the pre-block system calls | the pre-block system calls own applying a pending rotation | +| `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | +| `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | +| `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | ## Files @@ -260,6 +272,7 @@ 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` | 7 | keep 7 (the pre-block system calls) | | `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) | @@ -315,4 +328,4 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/sequencer_registry.rs` | 16 | keep 7 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/sequencer_registry.rs` | 17 | keep 8 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | diff --git a/crates/mega-evm/tests/_pending/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs index 3047fceae..693e3735f 100644 --- a/crates/mega-evm/tests/_pending/block_executor/main.rs +++ b/crates/mega-evm/tests/_pending/block_executor/main.rs @@ -2,3 +2,4 @@ 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 new file mode 100644 index 000000000..9723b0c8b --- /dev/null +++ b/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs @@ -0,0 +1,620 @@ +//! 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/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs index 66d4e0ff7..91c1d201a 100644 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -61,6 +61,43 @@ mod tests { ); } + #[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_resolve_rex6_expects_v2_code_hash() { // A V2 registry resolves normally at REX6. From 63a85288af201a0695858b2fff999e4bd17e8466 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:49:42 +0800 Subject: [PATCH 021/458] fix(system): reject a factory with matching code and nonce zero EIP-7997 requires the CREATE2 factory to hold its runtime and a nonzero nonce. Matching code at nonce 0 is now an error of its own; a nonce greater than one is kept. The six MegaETH contracts are not EIP-7997 and still accept matching code regardless of nonce. --- crates/mega-evm/src/block/executor.rs | 12 ++++++ crates/mega-evm/src/system/deploy.rs | 51 ++++++++++++++++++++---- crates/mega-evm/tests/block/deploy.rs | 17 ++++++++ crates/mega-evm/tests/system/deploy.rs | 55 ++++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 5a90126b2..1c70415a3 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -168,6 +168,11 @@ pub enum MegaBlockExecutionError { }, /// Satin is scheduled but the schedule does not carry a [`SequencerRegistryConfig`]. MissingSequencerRegistryConfig, + /// The EIP-7997 factory holds the right runtime but nonce 0. + ZeroFactoryNonce { + /// The factory address. + address: Address, + }, } impl fmt::Display for MegaBlockExecutionError { @@ -195,6 +200,10 @@ impl fmt::Display for MegaBlockExecutionError { Self::MissingSequencerRegistryConfig => { f.write_str("Satin is scheduled but SequencerRegistryConfig is not configured") } + Self::ZeroFactoryNonce { address } => write!( + f, + "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" + ), } } } @@ -519,6 +528,9 @@ where MegaBlockExecutionError::ForeignSystemContractCode { address, expected, found } .into() } + SystemContractDeployError::ZeroFactoryNonce { address } => { + MegaBlockExecutionError::ZeroFactoryNonce { address }.into() + } })?; self.deliver_pre_block(PreBlockStateSource::SystemContract(spec.address), state); } diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs index ca2d3b432..88d06ef91 100644 --- a/crates/mega-evm/src/system/deploy.rs +++ b/crates/mega-evm/src/system/deploy.rs @@ -69,12 +69,19 @@ pub struct SystemContractSpec { /// Flat storage slots to seed `(slot, value)` on a fresh deploy. Empty for every contract /// except the `SequencerRegistry`. pub seed: Vec<(U256, U256)>, + /// When set, matching code with nonce 0 is an error rather than a read-only entry. + /// + /// EIP-7997 requires the factory to hold its runtime **and a nonzero nonce**. The six + /// MegaETH contracts are not EIP-7997, so they leave this unset: matching code is + /// accepted regardless of nonce, because the matching-code path must not rewrite an + /// already-deployed contract. + pub require_nonzero_nonce: bool, } impl SystemContractSpec { - /// A spec with nonce 1 and no seeded storage. + /// A spec with nonce 1, no seeded storage, and no nonce requirement on a matching account. pub fn new(address: Address, code: Bytes, code_hash: B256) -> Self { - Self { address, code, code_hash, nonce: 1, seed: Vec::new() } + Self { address, code, code_hash, nonce: 1, seed: Vec::new(), require_nonzero_nonce: false } } /// Sets the seeded storage slots applied on a fresh deploy. @@ -82,6 +89,12 @@ impl SystemContractSpec { self.seed = seed; self } + + /// Requires a matching existing account to hold a nonzero nonce (EIP-7997). + pub fn require_nonzero_nonce(mut self) -> Self { + self.require_nonzero_nonce = true; + self + } } /// Why [`transact_deploy`] could not produce a witness. @@ -100,6 +113,13 @@ pub enum SystemContractDeployError { /// The hash already in state. found: B256, }, + /// The EIP-7997 factory already holds the right runtime but nonce 0, which the EIP + /// forbids. The matching-code path does not rewrite a nonce, so this cannot be repaired + /// by deploying again. + ZeroFactoryNonce { + /// The factory address. + address: Address, + }, } impl From for SystemContractDeployError { @@ -118,6 +138,12 @@ impl fmt::Display for SystemContractDeployError "system contract at {address} has unexpected code hash {found}, expected {expected}; refusing to overwrite" ) } + Self::ZeroFactoryNonce { address } => { + write!( + f, + "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" + ) + } } } } @@ -128,7 +154,7 @@ impl core::error::Error fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { match self { Self::Database(error) => Some(error), - Self::ForeignCode { .. } => None, + Self::ForeignCode { .. } | Self::ZeroFactoryNonce { .. } => None, } } } @@ -137,7 +163,12 @@ impl core::error::Error /// committed. /// /// - Already deployed with [`SystemContractSpec::code_hash`]: the account as a read-only entry -/// (neither touched nor created, no seeding), so the witness records the read. +/// (neither touched nor created, no seeding), so the witness records the read. A nonce of 7 stays +/// 7. If [`SystemContractSpec::require_nonzero_nonce`] is set (the EIP-7997 factory) and the +/// nonce is 0, this is [`SystemContractDeployError::ZeroFactoryNonce`] instead: the matching-code +/// path does not rewrite a nonce, so a genesis factory with the right code and nonce 0 would +/// otherwise stay invalid forever. The six MegaETH contracts leave that flag unset; they are not +/// EIP-7997, and matching code is accepted regardless of nonce. /// - Absent, or present with empty code: the created account with its bytecode, nonce and every /// seeded slot, all marked. An existing balance is kept. /// - Present with different non-empty code: [`SystemContractDeployError::ForeignCode`]. @@ -145,7 +176,9 @@ impl core::error::Error /// # Errors /// /// [`SystemContractDeployError::Database`] when the account cannot be loaded; -/// [`SystemContractDeployError::ForeignCode`] when the address already holds other bytecode. +/// [`SystemContractDeployError::ForeignCode`] when the address already holds other bytecode; +/// [`SystemContractDeployError::ZeroFactoryNonce`] when the factory holds matching code at +/// nonce 0. pub fn transact_deploy( db: &mut DB, spec: &SystemContractSpec, @@ -161,8 +194,11 @@ pub fn transact_deploy( if let Some(info) = &existing { if info.code_hash == spec.code_hash { + if spec.require_nonzero_nonce && info.nonce == 0 { + return Err(SystemContractDeployError::ZeroFactoryNonce { address: spec.address }); + } // `Account::from` copies the info and leaves status empty: neither touched nor - // created, which is the read-only witness entry. + // created, which is the read-only witness entry. An existing nonce is kept. return Ok(EvmState::from_iter([(spec.address, Account::from(info.clone()))])); } if info.code_hash != KECCAK_EMPTY { @@ -230,7 +266,8 @@ pub fn system_contract_specs( CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE, CREATE2_FACTORY_CODE_HASH, - ), + ) + .require_nonzero_nonce(), ] } diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 6374f2728..979eb51c9 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -192,6 +192,23 @@ fn test_a_pre_existing_factory_with_the_right_code_is_untouched() { assert_eq!(info.balance, U256::from(42), "a matching factory keeps its balance"); } +/// A factory that already holds the right code but nonce 0 fails the block: EIP-7997 requires a +/// nonzero nonce, and the matching-code path will not rewrite it. +#[test] +fn test_a_factory_with_matching_code_and_nonce_zero_fails_the_block() { + let mut db = common::database(); + db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); + db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 0); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, unlimited_ctx()); + let err = executor + .apply_pre_execution_changes() + .expect_err("a zero-nonce factory must fail the block"); + let message = err.to_string(); + assert!(message.contains("nonce 0"), "unexpected error: {message}"); + assert!(message.contains(&CREATE2_FACTORY_ADDRESS.to_string())); +} + /// Foreign code at any of the seven addresses fails the block. #[test] fn test_foreign_code_at_a_system_address_fails_the_block() { diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index 3365a66df..fb42ddfaa 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -99,6 +99,8 @@ fn test_the_spec_list_is_the_seven_predeploys_in_order() { assert_eq!(spec.nonce, 1, "{} starts at nonce 1", spec.address); assert_eq!(keccak256(&spec.code), spec.code_hash); } + assert!(specs[..6].iter().all(|spec| !spec.require_nonzero_nonce)); + assert!(specs[6].require_nonzero_nonce, "EIP-7997 requires a nonzero factory nonce"); assert!(specs[..5].iter().all(|spec| spec.seed.is_empty())); assert!(specs[6].seed.is_empty(), "the factory has no storage"); assert_eq!(specs[5].seed.len(), 6, "the registry seeds the six bootstrap slots"); @@ -185,6 +187,59 @@ fn test_foreign_code_at_a_system_address_is_an_error() { } } +/// Matching factory code at nonce 0 is an error: EIP-7997 requires a nonzero nonce, and the +/// matching-code path does not rewrite one. +#[test] +fn test_matching_factory_code_at_nonce_zero_is_an_error() { + let mut db = MemoryDatabase::default(); + db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); + db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 0); + let factory = &system_contract_specs(&config())[6]; + assert!(factory.require_nonzero_nonce); + + let error = transact_deploy(&mut db, factory).expect_err("nonce 0 is invalid for the factory"); + match error { + SystemContractDeployError::ZeroFactoryNonce { address } => { + assert_eq!(address, CREATE2_FACTORY_ADDRESS); + } + other => panic!("expected ZeroFactoryNonce, got {other}"), + } + assert!(error.to_string().contains("nonce 0")); +} + +/// Matching factory code at nonce 7 is accepted as it is: the helper does not rewrite a valid +/// existing nonce down to 1. +#[test] +fn test_matching_factory_code_keeps_a_nonce_greater_than_one() { + let mut db = MemoryDatabase::default(); + db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); + db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 7); + let factory = &system_contract_specs(&config())[6]; + + let state = transact_deploy(&mut db, factory).expect("nonce 7 is a valid factory"); + let account = state.get(&CREATE2_FACTORY_ADDRESS).unwrap(); + assert!(!account.is_touched()); + assert!(!account.is_created()); + assert_eq!(account.info.nonce, 7); + assert_eq!(account.info.code_hash, CREATE2_FACTORY_CODE_HASH); +} + +/// The six MegaETH contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, +/// not an error. Rewriting the nonce would be a state change the matching-code path exists to +/// avoid. +#[test] +fn test_matching_megaeth_code_at_nonce_zero_is_accepted() { + let mut db = MemoryDatabase::default(); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + db.set_account_nonce(ORACLE_CONTRACT_ADDRESS, 0); + + let state = + transact_deploy(&mut db, &oracle_spec()).expect("MegaETH contracts are not EIP-7997"); + let account = state.get(&ORACLE_CONTRACT_ADDRESS).unwrap(); + assert!(!account.is_touched()); + assert_eq!(account.info.nonce, 0); +} + /// An account that exists with empty code (an EOA that received value) is a fresh deploy: the /// balance is kept and the slots are seeded. #[test] From e6290216376209a0b87fff44f4d73e5445eb5c6c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 17:52:19 +0800 Subject: [PATCH 022/458] fix(system): refuse a used empty-code system account An address with no code but a nonzero nonce is a used account, not a prefunded EOA. The helper now errors instead of resetting the nonce and dropping storage under a created mark. Prefunding with balance alone remains the bootstrap path, which still marks created and clears storage. --- crates/mega-evm/src/block/executor.rs | 14 ++++++++++ crates/mega-evm/src/system/deploy.rs | 36 +++++++++++++++++++++++--- crates/mega-evm/tests/block/deploy.rs | 16 ++++++++++++ crates/mega-evm/tests/system/deploy.rs | 31 +++++++++++++++++++--- 4 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 1c70415a3..93d1acf36 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -173,6 +173,13 @@ pub enum MegaBlockExecutionError { /// The factory address. address: Address, }, + /// A system-contract address has empty code but a used nonce. + UsedEmptyAccount { + /// The system-contract address. + address: Address, + /// The nonce already on the account. + nonce: u64, + }, } impl fmt::Display for MegaBlockExecutionError { @@ -204,6 +211,10 @@ impl fmt::Display for MegaBlockExecutionError { f, "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" ), + Self::UsedEmptyAccount { address, nonce } => write!( + f, + "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" + ), } } } @@ -531,6 +542,9 @@ where SystemContractDeployError::ZeroFactoryNonce { address } => { MegaBlockExecutionError::ZeroFactoryNonce { address }.into() } + SystemContractDeployError::UsedEmptyAccount { address, nonce } => { + MegaBlockExecutionError::UsedEmptyAccount { address, nonce }.into() + } })?; self.deliver_pre_block(PreBlockStateSource::SystemContract(spec.address), state); } diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs index 88d06ef91..9072b35e5 100644 --- a/crates/mega-evm/src/system/deploy.rs +++ b/crates/mega-evm/src/system/deploy.rs @@ -120,6 +120,14 @@ pub enum SystemContractDeployError { /// The factory address. address: Address, }, + /// The address has empty code but a used nonce. Prefunding with balance alone is the + /// bootstrap path; a used account at a system address is not overwritten silently. + UsedEmptyAccount { + /// The system-contract address. + address: Address, + /// The nonce already on the account. + nonce: u64, + }, } impl From for SystemContractDeployError { @@ -144,6 +152,12 @@ impl fmt::Display for SystemContractDeployError "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" ) } + Self::UsedEmptyAccount { address, nonce } => { + write!( + f, + "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" + ) + } } } } @@ -154,7 +168,9 @@ impl core::error::Error fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { match self { Self::Database(error) => Some(error), - Self::ForeignCode { .. } | Self::ZeroFactoryNonce { .. } => None, + Self::ForeignCode { .. } | + Self::ZeroFactoryNonce { .. } | + Self::UsedEmptyAccount { .. } => None, } } } @@ -169,8 +185,12 @@ impl core::error::Error /// path does not rewrite a nonce, so a genesis factory with the right code and nonce 0 would /// otherwise stay invalid forever. The six MegaETH contracts leave that flag unset; they are not /// EIP-7997, and matching code is accepted regardless of nonce. -/// - Absent, or present with empty code: the created account with its bytecode, nonce and every -/// seeded slot, all marked. An existing balance is kept. +/// - Absent, or present with empty code and nonce 0: the created account with its bytecode, nonce +/// and every seeded slot, all marked. An existing balance is kept. Marking the account created +/// clears any storage it had; that is the accepted bootstrap path (prefunding with balance +/// alone). An empty-code account with a nonzero nonce is +/// [`SystemContractDeployError::UsedEmptyAccount`]: a used account at a system address is not +/// overwritten silently. /// - Present with different non-empty code: [`SystemContractDeployError::ForeignCode`]. /// /// # Errors @@ -178,7 +198,9 @@ impl core::error::Error /// [`SystemContractDeployError::Database`] when the account cannot be loaded; /// [`SystemContractDeployError::ForeignCode`] when the address already holds other bytecode; /// [`SystemContractDeployError::ZeroFactoryNonce`] when the factory holds matching code at -/// nonce 0. +/// nonce 0; +/// [`SystemContractDeployError::UsedEmptyAccount`] when the address has empty code and a +/// used nonce. pub fn transact_deploy( db: &mut DB, spec: &SystemContractSpec, @@ -208,6 +230,12 @@ pub fn transact_deploy( found: info.code_hash, }); } + if info.nonce != 0 { + return Err(SystemContractDeployError::UsedEmptyAccount { + address: spec.address, + nonce: info.nonce, + }); + } } let mut info = existing.unwrap_or_default(); diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 979eb51c9..252842abb 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -209,6 +209,22 @@ fn test_a_factory_with_matching_code_and_nonce_zero_fails_the_block() { assert!(message.contains(&CREATE2_FACTORY_ADDRESS.to_string())); } +/// An empty-code account with a used nonce at a system address fails the block rather than +/// being reset to a fresh deploy. +#[test] +fn test_a_used_empty_account_at_a_system_address_fails_the_block() { + let mut db = common::database(); + db.set_account_nonce(ORACLE_CONTRACT_ADDRESS, 42); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, unlimited_ctx()); + let err = executor + .apply_pre_execution_changes() + .expect_err("a used empty account must fail the block"); + let message = err.to_string(); + assert!(message.contains("nonce 42"), "unexpected error: {message}"); + assert!(message.contains(&ORACLE_CONTRACT_ADDRESS.to_string())); +} + /// Foreign code at any of the seven addresses fails the block. #[test] fn test_foreign_code_at_a_system_address_fails_the_block() { diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index fb42ddfaa..6029e1f96 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -240,8 +240,9 @@ fn test_matching_megaeth_code_at_nonce_zero_is_accepted() { assert_eq!(account.info.nonce, 0); } -/// An account that exists with empty code (an EOA that received value) is a fresh deploy: the -/// balance is kept and the slots are seeded. +/// An account that exists with empty code and nonce 0 (an EOA that received value) is a fresh +/// deploy: the balance is kept, the slots are seeded, and marking the account created clears +/// any storage it had. That is the accepted bootstrap path. #[test] fn test_an_empty_account_at_the_address_is_a_fresh_deploy() { let mut db = MemoryDatabase::default(); @@ -253,12 +254,36 @@ fn test_an_empty_account_at_the_address_is_a_fresh_deploy() { .unwrap(); let state = transact_deploy(&mut db, &spec).expect("empty code is a fresh deploy"); let account = state.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); + assert!(account.is_created(), "the bootstrap path marks created, which clears storage"); assert_eq!(account.info.balance, U256::from(1_000)); + assert_eq!(account.info.nonce, 1); assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); assert_eq!(account.storage.len(), 6); } +/// An empty-code account with nonce 42 is a used account, not a prefunded EOA: refusing it +/// avoids resetting the nonce and dropping storage under a `created` mark. +#[test] +fn test_an_empty_account_with_a_used_nonce_is_an_error() { + let mut db = MemoryDatabase::default(); + db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1_000)); + db.set_account_nonce(SEQUENCER_REGISTRY_ADDRESS, 42); + + let spec = system_contract_specs(&config()) + .into_iter() + .find(|spec| spec.address == SEQUENCER_REGISTRY_ADDRESS) + .unwrap(); + let error = transact_deploy(&mut db, &spec).expect_err("a used empty account must fail"); + match error { + SystemContractDeployError::UsedEmptyAccount { address, nonce } => { + assert_eq!(address, SEQUENCER_REGISTRY_ADDRESS); + assert_eq!(nonce, 42); + } + other => panic!("expected UsedEmptyAccount, got {other}"), + } + assert!(error.to_string().contains("nonce 42")); +} + /// Zero addresses in the registry config fail at load, not at the first block. #[test] fn test_registry_config_rejects_a_zero_address() { From 5a826bc4bc06e266505183753c4485752ce55013 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 18:00:26 +0800 Subject: [PATCH 023/458] feat(system): seed the registry minimum rotation delay Fold min_rotation_delay into SequencerRegistryConfig, reject zero at validate, and seed slot 13. A zero delay disables the reaction window the field exists to guarantee, and the contract has no setter, so a fresh registry cannot be repaired later through this helper. The placeholder uses a ten-block delay. --- crates/mega-evm/src/block/chain.rs | 14 ++++-- crates/mega-evm/src/system/deploy.rs | 5 +- .../mega-evm/src/system/sequencer_registry.rs | 21 +++++++- crates/mega-evm/tests/_pending/README.md | 12 ++--- .../_pending/src/system/sequencer_registry.rs | 48 ------------------- crates/mega-evm/tests/block/common.rs | 1 + crates/mega-evm/tests/block/deploy.rs | 7 ++- crates/mega-evm/tests/system/deploy.rs | 18 +++++-- 8 files changed, 59 insertions(+), 67 deletions(-) diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index eefc396fb..d48a87dc4 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -79,9 +79,10 @@ pub fn testnet_hardforks() -> MegaHardforkConfig { /// The schedule an unknown chain runs: every fork up to [`FALLBACK_RUNG`], active at genesis. /// /// Satin requires a [`SequencerRegistryConfig`]. An unknown chain has no published roles, so -/// every role is seeded with [`MEGA_SYSTEM_ADDRESS`] and `_initialFromBlock` is zero. The -/// placeholder only matters when bootstrapping a fresh registry: on a chain whose registry is -/// already deployed, the live roles are read from storage. +/// every role is seeded with [`MEGA_SYSTEM_ADDRESS`], `_initialFromBlock` is zero, and +/// `_minRotationDelay` is [`crate::system::PLACEHOLDER_MIN_ROTATION_DELAY`]. The placeholder +/// only matters when bootstrapping a fresh registry: on a chain whose registry is already +/// deployed, the live roles are read from storage. pub fn all_activated_hardforks() -> MegaHardforkConfig { let mut config = MegaHardforkConfig::new(); for fork in MegaHardfork::VARIANTS { @@ -103,7 +104,10 @@ pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { #[cfg(test)] mod tests { use super::*; - use crate::{system::MEGA_SYSTEM_ADDRESS, MegaHardforks}; + use crate::{ + system::{MEGA_SYSTEM_ADDRESS, PLACEHOLDER_MIN_ROTATION_DELAY}, + MegaHardforks, + }; #[test] fn test_known_chains_have_satin_unscheduled() { @@ -170,6 +174,8 @@ mod tests { assert_eq!(params.initial_sequencer, MEGA_SYSTEM_ADDRESS); assert_eq!(params.initial_admin, MEGA_SYSTEM_ADDRESS); assert_eq!(params.initial_from_block, 0); + assert_eq!(params.min_rotation_delay, PLACEHOLDER_MIN_ROTATION_DELAY); + assert_ne!(params.min_rotation_delay, 0); } /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs index 9072b35e5..115f8c366 100644 --- a/crates/mega-evm/src/system/deploy.rs +++ b/crates/mega-evm/src/system/deploy.rs @@ -18,7 +18,7 @@ use std::vec::Vec; use alloy_primitives::{address, b256, bytes, keccak256, Address, Bytes, B256, U256}; use mega_system_contracts::sequencer_registry::storage_slots::{ ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, - INITIAL_SYSTEM_ADDRESS, + INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, }; use revm::{ primitives::KECCAK_EMPTY, @@ -304,7 +304,7 @@ fn address_to_storage_value(address: Address) -> U256 { U256::from_be_bytes(address.into_word().0) } -/// The six bootstrap slots the `SequencerRegistry` is created with. +/// The seven bootstrap slots the `SequencerRegistry` is created with. fn registry_seed(config: &SequencerRegistryConfig) -> Vec<(U256, U256)> { Vec::from([ (CURRENT_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), @@ -313,5 +313,6 @@ fn registry_seed(config: &SequencerRegistryConfig) -> Vec<(U256, U256)> { (INITIAL_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), (INITIAL_SEQUENCER, address_to_storage_value(config.initial_sequencer)), (INITIAL_FROM_BLOCK, U256::from(config.initial_from_block)), + (MIN_ROTATION_DELAY, U256::from(config.min_rotation_delay)), ]) } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 9cd18ef0f..0608f076f 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -27,10 +27,18 @@ pub use mega_system_contracts::sequencer_registry::LATEST_CODE_HASH as SEQUENCER pub use mega_system_contracts::sequencer_registry::{storage_slots, ISequencerRegistry}; +/// Delay the unknown-chain placeholder seeds, in blocks. +/// +/// A zero delay would disable the reaction window the field exists to guarantee. Ten matches +/// the contract's own tests: long enough that a rotation cannot activate in the same block. +pub const PLACEHOLDER_MIN_ROTATION_DELAY: u64 = 10; + /// Bootstrap configuration for the `SequencerRegistry`, attached to Satin via [`HardforkParams`]. /// /// These values seed the registry's storage on a fresh deploy. After that the live roles are -/// whatever the contract holds; rotating them is a later pre-block system call. +/// whatever the contract holds; rotating them is a later pre-block system call. The contract +/// has no setter for `_minRotationDelay`, so a matching-code registry cannot be repaired later +/// through this helper: the delay must be seeded here, and it must not be zero. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SequencerRegistryConfig { /// Seeded into `_currentSystemAddress` and `_initialSystemAddress`. @@ -41,11 +49,14 @@ pub struct SequencerRegistryConfig { pub initial_admin: Address, /// Seeded into `_initialFromBlock`: the first block at which historical lookups are valid. pub initial_from_block: u64, + /// Seeded into `_minRotationDelay`. Must be nonzero: a zero delay disables the reaction + /// window the field exists to guarantee. + pub min_rotation_delay: u64, } impl SequencerRegistryConfig { /// Placeholder roles for a chain that has none published: [`MEGA_SYSTEM_ADDRESS`] for every - /// address, and block zero. + /// address, block zero, and [`PLACEHOLDER_MIN_ROTATION_DELAY`]. /// /// The unknown-chain fallback schedule uses this so a local chain can start. A real network /// attaches the roles governance chose. @@ -55,6 +66,7 @@ impl SequencerRegistryConfig { initial_sequencer: MEGA_SYSTEM_ADDRESS, initial_admin: MEGA_SYSTEM_ADDRESS, initial_from_block: 0, + min_rotation_delay: PLACEHOLDER_MIN_ROTATION_DELAY, } } } @@ -79,6 +91,11 @@ impl HardforkParams for SequencerRegistryConfig { message: "SequencerRegistryConfig.initial_admin must not be zero".into(), }); } + if self.min_rotation_delay == 0 { + return Err(HardforkParamsError { + message: "SequencerRegistryConfig.min_rotation_delay must not be zero".into(), + }); + } Ok(()) } } diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index abd839462..9dbee52d3 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -35,12 +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 | 34 | 22 | 12 | 30 | 4 | 0 | -| system contract deployment | 13 | 5 | 8 | 13 | 0 | 0 | +| system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **486** | **452** | **34** | **278** | **180** | **28** | +| **Total** | **484** | **452** | **32** | **276** | **180** | **28** | ## Tests ported in place @@ -205,7 +205,7 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by system contract deployment -These 27 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy, 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 and to the single-spec deploy, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -218,8 +218,8 @@ These 27 rows run in a real test target now, adapted to the Satin API and to the | `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/system/deploy.rs` | | `src/system/limit_control.rs` | system contract deployment (3) | 3 | `tests/system/deploy.rs` | | `src/system/oracle.rs` | system contract deployment (4) | 4 | `tests/system/deploy.rs` | -| `src/system/sequencer_registry.rs` | system contract deployment (7) | 7 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | -| **Total** | | **27** | | +| `src/system/sequencer_registry.rs` | system contract deployment (9) | 9 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | +| **Total** | | **29** | | ## Tests retired after the inventory @@ -328,4 +328,4 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/sequencer_registry.rs` | 17 | keep 8 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | 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 91c1d201a..dd9fdae11 100644 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -50,54 +50,6 @@ mod tests { .with_params(test_rex6_config()) } - #[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_resolve_rex6_expects_v2_code_hash() { // A V2 registry resolves normally at REX6. diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 361992f82..cd02342ed 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -81,6 +81,7 @@ pub(crate) fn registry_config() -> SequencerRegistryConfig { initial_sequencer: SEQUENCER, initial_admin: ADMIN, initial_from_block: 1, + min_rotation_delay: 100, } } diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 252842abb..336a0fdfa 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -7,7 +7,7 @@ use mega_evm::{ keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, storage_slots::{ ADMIN as ADMIN_SLOT, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, - INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, + INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, }, SequencerRegistryConfig, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH, CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE, CREATE2_FACTORY_CODE_HASH, @@ -69,6 +69,7 @@ fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryCon assert_eq!(slot(INITIAL_SYSTEM_ADDRESS), addr_val(config.initial_system_address)); assert_eq!(slot(INITIAL_SEQUENCER), addr_val(config.initial_sequencer)); assert_eq!(slot(INITIAL_FROM_BLOCK), U256::from(config.initial_from_block)); + assert_eq!(slot(MIN_ROTATION_DELAY), U256::from(config.min_rotation_delay)); } fn assert_registry_seed(state: &mut State, config: &SequencerRegistryConfig) { @@ -97,6 +98,10 @@ fn assert_registry_seed(state: &mut State, config: &SequencerReg state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_FROM_BLOCK).unwrap(), U256::from(config.initial_from_block) ); + assert_eq!( + state.storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY).unwrap(), + U256::from(config.min_rotation_delay) + ); } /// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index 6029e1f96..80e23196f 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -7,7 +7,7 @@ use mega_evm::{ keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, storage_slots::{ ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, - INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, + INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, }, system_contract_specs, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, SystemContractSpec, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH, @@ -32,6 +32,7 @@ fn config() -> SequencerRegistryConfig { initial_sequencer: SEQUENCER, initial_admin: ADMIN_ADDR, initial_from_block: 7, + min_rotation_delay: 100, } } @@ -103,7 +104,7 @@ fn test_the_spec_list_is_the_seven_predeploys_in_order() { assert!(specs[6].require_nonzero_nonce, "EIP-7997 requires a nonzero factory nonce"); assert!(specs[..5].iter().all(|spec| spec.seed.is_empty())); assert!(specs[6].seed.is_empty(), "the factory has no storage"); - assert_eq!(specs[5].seed.len(), 6, "the registry seeds the six bootstrap slots"); + assert_eq!(specs[5].seed.len(), 7, "the registry seeds the seven bootstrap slots"); } /// A fresh deploy creates the account, installs the code and seeds every slot. @@ -120,7 +121,7 @@ fn test_a_fresh_deploy_creates_the_account_and_seeds_storage() { assert!(account.is_created()); assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); assert_eq!(account.info.nonce, 1); - assert_eq!(account.storage.len(), 6); + assert_eq!(account.storage.len(), 7); assert_eq!( account.storage.get(&CURRENT_SYSTEM_ADDRESS).unwrap().present_value, U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0) @@ -142,6 +143,10 @@ fn test_a_fresh_deploy_creates_the_account_and_seeds_storage() { U256::from_be_bytes(SEQUENCER.into_word().0) ); assert_eq!(account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value, U256::from(7)); + assert_eq!( + account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value, + U256::from(config().min_rotation_delay) + ); db.commit(state); let state = transact_deploy(&mut db, factory).expect("the factory deploys"); @@ -258,7 +263,7 @@ fn test_an_empty_account_at_the_address_is_a_fresh_deploy() { assert_eq!(account.info.balance, U256::from(1_000)); assert_eq!(account.info.nonce, 1); assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(account.storage.len(), 6); + assert_eq!(account.storage.len(), 7); } /// An empty-code account with nonce 42 is a used account, not a prefunded EOA: refusing it @@ -301,6 +306,11 @@ fn test_registry_config_rejects_a_zero_address() { config.initial_admin = Address::ZERO; let err = config.validate().expect_err("zero admin"); assert!(err.message.contains("initial_admin must not be zero")); + + config = self::config(); + config.min_rotation_delay = 0; + let err = config.validate().expect_err("zero min rotation delay"); + assert!(err.message.contains("min_rotation_delay must not be zero")); } /// The seeded current-system-address slot is slot 0, which is the slot a later rotation read From 6cc7ddf6c60a3058408a32ea4f5245e3c668409e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 20:23:27 +0800 Subject: [PATCH 024/458] test(block): pin the placeholder to the unknown-chain fallback hardfork_schedule returns SequencerRegistryConfig::placeholder only for a chain ID it does not know. A known chain ID resolves to its own table and never carries that config. --- crates/mega-evm/src/block/chain.rs | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index d48a87dc4..7af6f1fcf 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -178,6 +178,47 @@ mod tests { assert_ne!(params.min_rotation_delay, 0); } + /// [`SequencerRegistryConfig::placeholder`] is attached only by the unknown-chain fallback. + /// + /// [`hardfork_schedule`] returns it exactly when the chain ID is absent from the activation + /// table. A known chain ID resolves to that chain's own table, which never carries the + /// placeholder. + #[test] + fn test_the_placeholder_is_only_the_unknown_chain_fallback() { + let placeholder = SequencerRegistryConfig::placeholder(); + let fallback = all_activated_hardforks(); + assert_eq!( + fallback.fork_params::(), + Some(&placeholder), + "the unknown-chain fallback is what attaches the placeholder" + ); + + for chain_id in [0_u64, 1, 999_999] { + assert_eq!(chain_activation(chain_id), None, "{chain_id} is not a known chain"); + assert_eq!( + hardfork_schedule(chain_id).fork_params::(), + Some(&placeholder), + "chain {chain_id} reaches the placeholder only by taking the fallback" + ); + } + + for activation in CHAIN_ACTIVATIONS { + let schedule = hardfork_schedule(activation.chain_id); + assert_eq!( + schedule.fork_params::(), + activation.hardforks().fork_params::(), + "chain {} resolves to its own table", + activation.chain_id + ); + assert_ne!( + schedule.fork_params::(), + Some(&placeholder), + "chain {} must not return the placeholder", + activation.chain_id + ); + } + } + /// 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 From d44ecd11e3b5be76b32d6beb38432126a13b144f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 21:40:54 +0800 Subject: [PATCH 025/458] test(block): pin what the executor prints for its pre-block observer --- crates/mega-evm/src/block/executor.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 93d1acf36..e90a2b17a 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -869,4 +869,26 @@ mod tests { executor.evm_mut().set_inspector_enabled(true); assert!(executor.into_evm().is_inspecting()); } + + /// The executor prints whether a pre-block observer is installed. A trait object has no + /// `Debug`, so the observer is reported as a flag rather than dropped: a reader of a node's + /// log can tell a block whose pre-block states were witnessed from one whose were not. + #[test] + fn test_debug_reports_whether_a_pre_block_observer_is_installed() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + 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!(format!("{:?}", executor.pre_block_observer), "None"); + + executor.set_pre_block_observer(Some(Box::new(|_: PreBlockStateSource, _: &EvmState| {}))); + assert_eq!(format!("{:?}", executor.pre_block_observer), "Some(_)"); + + executor.set_pre_block_observer(None); + assert_eq!(format!("{:?}", executor.pre_block_observer), "None"); + } } From 244dca8ad178b066eab4375cd8dcba624fc15c67 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 21:42:06 +0800 Subject: [PATCH 026/458] fix(satin): hand a started frame the reservoir its record charge left revm's CALL, CALLCODE, CREATE and CREATE2 copy the caller's reservoir into the frame's input, and they do it before the wrapper charges the history of the write records the frame's start makes. A returning frame's reservoir is adopted by its caller rather than merged into it, so the frame handed the charge straight back; a frame answered without running handed it back a second time, because its gas is built from the same field and its empty lane refills the whole charge. Above the execution cap, where the reservoir is what pays, a value call and a nested creation appended their write records for free and the interception, depth-guard and latch paths minted gas. The wrapper now writes the post-charge reservoir into the frame's input. Nothing on this branch ran above the cap with a nested frame, which is where this hid: tests/satin/history_reservoir.rs is that regime, and its module documentation states the rule for the mechanisms that follow. The equivalence baseline gains a nested value call with a reservoir, which would have caught this the day it was written. --- crates/mega-evm/src/evm/instructions.rs | 32 ++- crates/mega-evm/tests/satin/equivalence.rs | 58 ++++- .../mega-evm/tests/satin/history_reservoir.rs | 220 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 4 files changed, 307 insertions(+), 4 deletions(-) create mode 100644 crates/mega-evm/tests/satin/history_reservoir.rs diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 73e63e1a3..bc0b763fc 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -26,7 +26,9 @@ //! 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. +//! 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. //! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -47,8 +49,8 @@ use revm::{ instructions::{contract, gas_table_spec, host}, interpreter::EthInterpreter, interpreter_types::LoopControl, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, - InterpreterAction, + FrameInput, Instruction, InstructionContext, InstructionExecResult, InstructionResult, + Interpreter, InterpreterAction, }, primitives::hardfork::SpecId, Database, @@ -214,6 +216,9 @@ fn selfdestruct( /// of what the caller kept rather than out of what the callee gets. An opcode that starts no /// frame — a call the balance cannot fund, a creation the depth refuses — makes no records and is /// charged nothing. A charge the frame cannot pay is an ordinary out-of-gas. +/// +/// 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>, @@ -241,10 +246,31 @@ fn charge_frame_start( if !interpreter.gas.record_history_cost(cost) { return Err(InstructionResult::OutOfGas); } + inherit_reservoir(interpreter); host.additional_limit.stage_frame_charge(on_lane, caller); 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. /// /// `CALLCODE` runs the callee's code in the caller's own account, so the two records of a `CALL` diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 6d37aaff9..073525e8e 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -7,7 +7,10 @@ //! [`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. The six cases at the end are the ones that diverge for a reason of their own — the +//! 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, the `KeylessDeploy` overhead, 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 @@ -28,9 +31,11 @@ use mega_evm::{ satin_gas_params, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; 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, @@ -221,6 +226,57 @@ fn test_value_transfer_matches_op_revm() { assert_same_but_history(&mega, &op); } +/// 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. +#[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] fn test_sstore_matches_op_revm() { if runs_at_measurement_prices() { 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..2120fc3fa --- /dev/null +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -0,0 +1,220 @@ +//! 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, POP, PUSH0, PUSH1, REVERT, STOP}; + +use crate::common::{call, execute, 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::ZERO, "the reverted transfer kept nothing"); + 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::ZERO, "the refused call wrote nothing"); + 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", + ); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 90f8cdd44..60ce07fa6 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -6,6 +6,7 @@ mod db_error; mod equivalence; mod history_exemption; mod history_gas; +mod history_reservoir; mod inspector; mod intrinsic; mod outcome; From 0368e943313f1d08a156944a1a0383521074cefc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 21:46:31 +0800 Subject: [PATCH 027/458] fix(satin): drop the pending frame when its record charge cannot be paid CALL, CALLCODE, CREATE and CREATE2 set the frame's input as the interpreter's action inside revm's instruction, and an interpreter halts on an instruction's error only when no action is pending. So the out-of-gas the frame-start charge returned when the caller could not pay it was swallowed: the pending frame was returned anyway, it started, its lane was pushed and its write records were counted, and nothing had been charged for them. A caller keeps a sixty-fourth of what it holds when it forwards gas, so any caller under roughly 450,000 gas kept less than the two records a value call or a nested creation makes cost, and appended them for free. The wrapper now takes the pending action before it returns, the way the limit stop in the same file already does. --- crates/mega-evm/src/evm/instructions.rs | 26 ++++-- crates/mega-evm/tests/satin/history_gas.rs | 98 +++++++++++++++++++++- 2 files changed, 118 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index bc0b763fc..4c562a2bc 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -28,7 +28,8 @@ //! 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. +//! 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. //! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -215,7 +216,8 @@ fn selfdestruct( /// 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 call the balance cannot fund, a creation the depth refuses — makes no records and is -/// charged nothing. A charge the frame cannot pay is an ordinary out-of-gas. +/// charged nothing. 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`]). /// /// The frame inherits the reservoir the charge left, not the one the caller held before it /// ([`inherit_reservoir`]). @@ -240,17 +242,31 @@ fn charge_frame_start( write_record_history_gas(records.on_lane), write_record_history_gas(u64::from(records.caller)), ) else { - return Err(InstructionResult::OutOfGas); + return Err(abandon_frame(interpreter)); }; - let Some(cost) = on_lane.checked_add(caller) else { return Err(InstructionResult::OutOfGas) }; + let Some(cost) = on_lane.checked_add(caller) else { return Err(abandon_frame(interpreter)) }; if !interpreter.gas.record_history_cost(cost) { - return Err(InstructionResult::OutOfGas); + return Err(abandon_frame(interpreter)); } inherit_reservoir(interpreter); host.additional_limit.stage_frame_charge(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. +#[cold] +#[inline(never)] +fn abandon_frame(interpreter: &mut Interpreter) -> InstructionResult { + let _ = interpreter.take_next_action(); + InstructionResult::OutOfGas +} + /// 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 diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index e5d0c2acb..86e5af4b8 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -11,7 +11,7 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, RETURN, REVERT}, + bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}, context_interface::cfg::GasId, }; @@ -265,6 +265,102 @@ fn test_a_failing_frame_gives_its_history_back() { assert_eq!(reverted.gas.history, quiet.gas.history, "the reverted frame's log is not paid for"); } +/* ---------- 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. +#[test] +fn test_no_gas_limit_buys_a_write_record_for_nothing() { + if runs_at_measurement_prices() { + return; + } + 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] { + let outcome = + execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, limit)); + 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", + ); + } + } +} + /* ---------- the writes every transaction makes ---------- */ /// The transaction body carries the writes every transaction makes whatever it runs: the sender's From d5eb2ffef82a45684acf67a82e4b9572f06142b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 21:51:21 +0800 Subject: [PATCH 028/458] refactor(satin): check a frame's records against the charge made for them The history of the write records a frame's start makes is charged at the opcode, on the input revm's instruction built; the records themselves are counted when the lane is pushed, on the input that survived interception and the keyless rewrite. Those are two answers to the same question, and the comment that said they could not disagree was a claim about today's rewrite being the identity rather than a property of the code. The charge now carries the answer it was computed from, and the count checks its own against it. A rewrite that turns a call into a creation changes which records a frame's start makes; until the mechanism that makes such a rewrite reconciles the charge with them, the divergence trips in every debug build instead of mis-charging the caller and mis-splitting the refund its failure gets back. --- crates/mega-evm/src/evm/instructions.rs | 2 +- crates/mega-evm/src/limit/limit.rs | 103 +++++++++++++++++++++--- 2 files changed, 95 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 4c562a2bc..1da4b8c2d 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -249,7 +249,7 @@ fn charge_frame_start( return Err(abandon_frame(interpreter)); } inherit_reservoir(interpreter); - host.additional_limit.stage_frame_charge(on_lane, caller); + host.additional_limit.stage_frame_charge(records, on_lane, caller); result } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 933fdbd7e..4070b9b40 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -201,13 +201,19 @@ impl AdditionalLimit { /// 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. + /// 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, on_lane: u64, caller: u64) { - self.pending_frame_charge = FrameCharge { on_lane, caller }; + 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 }; } /// Records the history gas the settled transaction spent. @@ -366,7 +372,7 @@ impl AdditionalLimit { } return; } - let records = self.frame_start_records(input); + 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 }); @@ -386,7 +392,7 @@ impl AdditionalLimit { } } FrameInput::Create(inputs) => { - let records = self.frame_start_records(input); + 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 { @@ -399,14 +405,38 @@ impl AdditionalLimit { } } + /// 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, and the count here, on the input that + /// survived interception and the keyless rewrite. They agree because the rewrite is the + /// identity today. The mechanism that makes it rewrite a call into a creation — native + /// keyless deployment — changes which records a frame's start makes, and must reconcile the + /// charge with them; until it does, 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 + } + /// 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. [`push_lane`](Self::push_lane) makes exactly these records, from - /// this same answer, so the charge and the count cannot disagree. + /// 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 { @@ -508,6 +538,9 @@ impl FrameStartRecords { /// 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. @@ -516,15 +549,20 @@ struct FrameCharge { impl FrameCharge { /// Nothing charged. - const NONE: Self = Self { on_lane: 0, caller: 0 }; + const NONE: Self = Self { records: None, on_lane: 0, caller: 0 }; } #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{Address, Bytes, U256}; + use crate::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"); + fn call_inputs(scheme: CallScheme, value: U256) -> CallInputs { CallInputs { input: CallInput::Bytes(Bytes::new()), @@ -542,6 +580,53 @@ mod tests { } } + /// 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 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 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 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. From d2d050c76f80549bb7b9fb4c04e77e3fc06fd890 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 22:01:03 +0800 Subject: [PATCH 029/458] docs(satin): state the byte table's pairing per record, and where it parts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A record's history bytes are its own data size, so the two counts cannot drift apart at a record. Per transaction they are not the same number, and the byte table read as though they were. Two sites part them, both by decision: an Oracle hint's payload is data size the transaction counts and history it does not pay, because the bytes go to the node's oracle service rather than into a block; and the five write records a transaction's body carries are an upper bound, so a transfer whose recipient is the block beneficiary or a fee vault pays a record the body already bound — an over-charge, never an under-charge. The paired corpus gains one case for each, with the number it is expected to pay written out, so the divergence reads as intended rather than as a defect. --- crates/mega-evm/src/limit/mod.rs | 17 ++++- crates/mega-evm/src/limit/record.rs | 4 +- crates/mega-evm/tests/satin/write_records.rs | 75 ++++++++++++++++++-- 3 files changed, 88 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index ca634c68b..cad0b44e6 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -12,9 +12,20 @@ //! # 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, 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. +//! 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. Two sites +//! part them, both 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; +//! - [`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)] diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 2c9c0301f..4979197ee 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -50,7 +50,9 @@ pub(crate) enum RecordEffect { /// 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. +/// 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. diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 0b5b9abcf..82dffd3e0 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -11,7 +11,10 @@ use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + }, test_utils::{BytecodeBuilder, MemoryDatabase}, LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, }; @@ -871,6 +874,11 @@ struct Paired { 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 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 @@ -899,6 +907,8 @@ fn paired_corpus() -> Vec { tx, other_bytes, records, + hint_bytes: 0, + beneficiary: Address::ZERO, }; let to_callee = |code: Bytes| funded().account_code(CALLEE, code); let plain = || call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); @@ -1008,9 +1018,54 @@ fn paired_corpus() -> Vec { 0, ), case("a creation transaction", funded(), create(CALLER, Bytes::new(), GAS_LIMIT), 0, 1), + // The two cases where a transaction's data size and its history part company. Both 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, + ..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 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. @@ -1018,6 +1073,12 @@ fn paired_corpus() -> Vec { /// 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 the last two cases are where a transaction's two totals part: +/// an Oracle hint's payload is data size that is not history, and a transfer to the block +/// beneficiary pays a record the transaction body's five already bound. Both 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() { @@ -1025,7 +1086,13 @@ fn test_every_kept_write_pays_one_record_of_history() { } const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; for case in paired_corpus() { - let outcome = crate::common::execute(case.db, case.tx.clone()); + 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); let body = mega_evm::TX_BODY_SIZE + case.tx.0.base.data.len() as u64; @@ -1033,8 +1100,8 @@ fn test_every_kept_write_pays_one_record_of_history() { assert_eq!(outcome.gas.history, expected, "{}: the history it pays", case.name); assert_eq!( usage.data_size, - case.other_bytes + case.records * WRITE_RECORD_SIZE, - "{}: the data size the limit counts is what history prices", + case.other_bytes + case.records * WRITE_RECORD_SIZE + case.hint_bytes, + "{}: the data size the limit counts", case.name, ); } From 6cf4b6e17bc2c34b97af473591399092ae471ec3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 22:10:17 +0800 Subject: [PATCH 030/458] test(satin): pin how far history gas can fall behind the bytes appended The allowance is drawn before the frame's own gas, 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 them. A contract calling itself records its own account once and nothing after that, so the grant repeats for as long as gas lasts: about 10,000 gas a turn, some twenty thousand turns inside one transaction at the execution cap, around three megabytes of log bytes on no gas ledger. The bytes stay on the data-size lane, so the limits that meter bytes see all of them; what falls behind is the history gas column. Whether the allowance becomes a fallback, or a block's history column becomes a byte count beside its gas figure, belongs with the block-level accounting. The test records the size of the gap so it is a number on the table rather than a rediscovery. --- .../tests/satin/storage_call_stipend.rs | 86 ++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index bb5888f3d..0cec7665f 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -25,7 +25,8 @@ use mega_evm::{ STORAGE_CALL_STIPEND_BYTES, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ - CALL, CALLCODE, DELEGATECALL, GAS, LOG3, POP, PUSH0, STATICCALL, STOP, + ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, POP, + PUSH0, PUSH1, STATICCALL, STOP, }; use crate::common::{call, context, runs_at_measurement_prices}; @@ -429,6 +430,89 @@ fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { ); } +/* ---------- 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, pinned as the known +/// quantity it is. +/// +/// 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 ledger. +/// +/// The bytes are still counted on the data-size lane, so the limits that meter bytes see all of +/// them; what falls behind is the history *gas* column. Whether the allowance becomes a fallback, +/// or a block's history column becomes a byte count beside its gas figure, is a decision for the +/// block-level accounting, not for this mechanism. This test exists so the size of the gap is 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 = run(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, + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + "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", + ); + + let bytes_appended = outcome.usage.data_size; + let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE - TX_BODY_SIZE; + assert_eq!( + bytes_appended - 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] From 43e2ffcb7944932c12d2c61f60a2a24594efc3d7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 22 Sep 2026 22:15:14 +0800 Subject: [PATCH 031/458] docs(satin): say what the frame-start charge does with the pending frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two consequences of 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 post-charge reservoir is written back into it; and the frame is already pending as the interpreter's action, so a caller that cannot pay drops it rather than letting it start unpaid. The byte table's pairing is also stated where it holds — per record — with the two sites where a transaction's two totals part. --- AGENTS.md | 7 +++++-- crates/mega-evm/README.md | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9295eb8e4..25d70bc22 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -125,11 +125,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. - 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 charge and the count it pairs with 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 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, before the frame's budget is forwarded. + 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 two sites, both by decision — an Oracle hint's payload is data size that is never history, 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 and binds nothing: history charges the same bytes at a higher rate. - 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. @@ -155,6 +156,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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. 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. 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index e7b160f8f..000ec934d 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -58,13 +58,17 @@ The Oracle forwards a `sendHint` payload to the node's oracle service, and a `ke 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. -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 charge and the count it pairs with cannot drift apart. +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 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; 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. From 856321ac3ce5eebcb6c943b901725bd1eb04e596 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:16:30 +0800 Subject: [PATCH 032/458] feat(satin): report the history bytes a transaction appends beside the gas it pays A value transfer's history allowance pays for its callee's first event before the callee's gas does, so the history gas column under-reports the bytes appended by exactly what the allowances paid. The allowance keeps paying first; what changes is that the bytes are now reported too. MegaGasUsage and BlockGasCounters carry history_bytes: the body, one write record per kept write, the kept logs and the deposited code. Logs and code ride on the frame lanes, so a frame's failure discards them the way it discards its records. An exempt transaction reports none, as it reports no history gas. No execution result changes. The pinned gap test now reads the gap off the new column. --- crates/mega-evm/src/block/limit.rs | 11 +- crates/mega-evm/src/block/result.rs | 57 ++- crates/mega-evm/src/evm/execution.rs | 29 +- crates/mega-evm/src/evm/mod.rs | 6 +- crates/mega-evm/src/evm/result.rs | 27 +- crates/mega-evm/src/limit/frame_limit.rs | 69 +++ crates/mega-evm/src/limit/limit.rs | 58 ++- crates/mega-evm/tests/block/counters.rs | 72 +++- crates/mega-evm/tests/satin/history_bytes.rs | 406 ++++++++++++++++++ .../mega-evm/tests/satin/history_exemption.rs | 31 ++ crates/mega-evm/tests/satin/history_gas.rs | 5 + crates/mega-evm/tests/satin/main.rs | 1 + .../tests/satin/storage_call_stipend.rs | 25 +- 13 files changed, 744 insertions(+), 53 deletions(-) create mode 100644 crates/mega-evm/tests/satin/history_bytes.rs diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index f7459adad..e66939bff 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -206,7 +206,7 @@ impl BlockLimiter { Self { limits, block_gas_used: 0, - gas: BlockGasCounters { execution: 0, state: 0, history: 0 }, + gas: BlockGasCounters { execution: 0, state: 0, history: 0, history_bytes: 0 }, usage: LimitUsage { data_size: 0, write_records: 0 }, block_tx_size_used: 0, block_da_size_used: 0, @@ -383,6 +383,7 @@ mod tests { 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 }, @@ -429,6 +430,7 @@ mod tests { 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 +442,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); diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index ff18a0936..7c9f06703 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -14,10 +14,11 @@ 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. +/// holds each counter to its own block limit, where it has one. #[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 +27,10 @@ pub struct BlockGasCounters { pub state: u64, /// History gas. pub history: u64, + /// The history bytes the block's transactions appended, whoever paid for them. At the cost per + /// history byte they are worth [`history`](Self::history) plus what the history allowances of + /// value transfers paid, which no gas ledger carries. + 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); } } @@ -342,13 +348,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] @@ -412,12 +433,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/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 55cad95b0..f7c38b095 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -188,11 +188,13 @@ where evm: &mut Self::Evm, ) -> Result { let mut gas = self.op.validate_initial_tx_gas(evm)?; - let history = - if evm.ctx_ref().prices_history() { tx_body_history_gas(evm.ctx_ref()) } else { 0 }; - if history == 0 { + if !evm.ctx_ref().prices_history() { return Ok(gas); } + let bytes = tx_body_history_bytes_of(evm.ctx_ref()); + // 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() @@ -203,7 +205,7 @@ where ); } gas.set_initial_state_gas(gas.initial_state_gas_final() + history); - evm.ctx_mut().additional_limit.set_intrinsic_history_gas(history); + evm.ctx_mut().additional_limit.set_intrinsic_history(history, bytes); Ok(gas) } @@ -212,7 +214,8 @@ where /// (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: what the body was charged, and what the frames - /// charged net of what they gave back. + /// 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, @@ -232,11 +235,13 @@ where } *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(()) } @@ -696,12 +701,9 @@ fn inspect_logs( } } -/// The history gas a transaction's body costs: its envelope and the write records its inclusion -/// makes, its calldata, its authorizations and its access list, at the cost per history byte. -/// -/// A byte count large enough to have no price saturates to `u64::MAX`, which no gas limit covers, -/// so such a transaction is rejected for not covering its own intrinsic gas. -fn tx_body_history_gas( +/// The history bytes a transaction's body appends: its envelope and the write records its +/// inclusion makes, its calldata, its authorizations and its access list. +fn tx_body_history_bytes_of( ctx: &MegaContext, ) -> u64 { let tx = ctx.tx(); @@ -713,13 +715,12 @@ fn tx_body_history_gas( }) }) .unwrap_or_default(); - let bytes = tx_body_history_bytes( + tx_body_history_bytes( tx.input().len() as u64, tx.authorization_list_len() as u64, addresses, slots, - ); - history_gas(bytes).unwrap_or(u64::MAX) + ) } /// Whether executing this transaction creates its caller's account: a deposit-like transaction diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index d8d2f21ee..8f11c4446 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -245,7 +245,11 @@ where ) -> 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, diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 7e75c41b4..35e66f5b0 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -12,6 +12,12 @@ //! 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. use revm::context::result::{ResultAndState, ResultGas}; @@ -54,7 +60,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 +69,13 @@ 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 kept and the code it deposited. + /// + /// 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. A transaction + /// exempt from history gas reports none. + 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 +85,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(), @@ -116,10 +130,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 +144,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); diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 36faf69ef..926d0729d 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 its +//! creations deposit — 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"))] @@ -52,6 +56,10 @@ pub(crate) struct Lane { /// 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 the code its creations deposited. Its write records are + /// history too, and are counted in [`used`](Self::used). + pub(crate) log_and_code_bytes: u64, } impl Lane { @@ -75,6 +83,7 @@ impl Lane { creator_record: false, budget, stipend_remaining: 0, + log_and_code_bytes: 0, } } @@ -127,6 +136,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 { @@ -137,6 +148,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. @@ -149,6 +161,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() @@ -194,6 +212,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) { @@ -253,6 +280,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; } @@ -266,6 +295,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); @@ -385,6 +415,45 @@ 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() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 4070b9b40..3bd6f7fb4 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -9,7 +9,7 @@ use revm::{ use super::{ frame_limit::{FrameLimitTracker, Lane}, record::{HistoryBytes, RecordEffect, StagedRecord}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -51,6 +51,10 @@ pub struct AdditionalLimit { /// 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. @@ -60,6 +64,8 @@ pub struct AdditionalLimit { pending_frame_charge: FrameCharge, /// The history gas the settled transaction spent. history_gas_spent: u64, + /// The history bytes the settled transaction appended. + history_bytes: u64, } impl AdditionalLimit { @@ -87,9 +93,11 @@ impl AdditionalLimit { self.sender = Address::ZERO; self.frame_began = false; self.intrinsic_history_gas = 0; + self.intrinsic_history_bytes = 0; self.top_level_write_record_gas = 0; self.pending_frame_charge = FrameCharge::NONE; self.history_gas_spent = 0; + self.history_bytes = 0; } /* The latch */ @@ -163,9 +171,37 @@ impl AdditionalLimit { self.intrinsic_history_gas } - /// Records the history gas validation charged for the transaction's body. - pub(crate) const fn set_intrinsic_history_gas(&mut self, gas: u64) { + /// 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: its body, + /// one write record per account or storage write it kept, the logs it kept and the code it + /// deposited. + /// + /// Every one of them is priced at the cost per history byte, and + /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of + /// that price. The two part by what the history allowances of its value transfers paid, which + /// no gas ledger carries. A transaction exempt from history gas appended none that anybody + /// priced, and reports none. + 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 @@ -244,6 +280,10 @@ impl AdditionalLimit { }; 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 check = match effect { RecordEffect::None => LimitCheck::WithinLimit, RecordEffect::Record(usage) => { @@ -475,6 +515,10 @@ impl AdditionalLimit { /// 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. /// + /// A creation that ran and succeeded deposited its output as code, which its caller keeps as + /// history bytes of its own: the creation's lane is gone by then, and the code goes wherever + /// the caller's writes go. + /// /// 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"] @@ -484,7 +528,13 @@ impl AdditionalLimit { // opcode, which failed after making it. self.pending_frame_charge = FrameCharge::NONE; let success = result.instruction_result().is_ok(); - self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)) + let Some(lane) = self.tracker.pop(success) else { return 0 }; + if success && lane.records_made { + if let FrameResult::Create(outcome) = &*result { + self.tracker.record_log_and_code_bytes(outcome.output().len() as u64); + } + } + lane.history_refund(success) } /// Settles the transaction's outermost frame: pops its lane unless the frame already diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 73fcfd4fb..0e30bc744 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -4,13 +4,19 @@ 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 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 { @@ -148,4 +154,68 @@ fn test_the_state_and_history_ledgers_refuse_nothing() { bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, "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. +#[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"); + + 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); + assert_eq!(outcome.result.logs().len(), 1, "the receiver emitted its event"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + } + + 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.gas, counters, "the result carries both columns"); } 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..42d4f8499 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -0,0 +1,406 @@ +//! 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_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, LOG_BASE_SIZE, LOG_TOPIC_SIZE, + STORAGE_CALL_STIPEND_BYTES, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, LOG0, POP, PUSH0, PUSH1, RETURN, REVERT}, + interpreter::{ + interpreter::EthInterpreter, CreateInputs, CreateOutcome, Gas, 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", + ); +} + +/// With no allowance anywhere, the bytes a transaction reports are its history gas at the price, +/// at every site that appends history and on every path that takes it back. +#[test] +fn test_without_an_allowance_the_bytes_are_the_history_gas_at_the_price() { + if runs_at_measurement_prices() { + return; + } + type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, u64); + let cases: [Case; 12] = [ + ( + "a body alone", + || callee_running(BytecodeBuilder::default()), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE, + ), + ( + "calldata, a byte a byte", + || callee_running(BytecodeBuilder::default()), + |gas| call_with_data(CALLER, CALLEE, Bytes::from(vec![0xab; 100]), gas), + TX_BODY_SIZE + 100, + ), + ( + "a log", + || callee_running(log(BytecodeBuilder::default(), 2, 50)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE + log_bytes(2, 50), + ), + ( + "a storage write", + || callee_running(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1))), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "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), + TX_BODY_SIZE, + ), + ( + "a transfer that creates its recipient", + funded, + |gas| call(CALLER, FRESH, U256::from(1), gas), + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a creation transaction", + funded, + |gas| create(CALLER, deploying(), gas), + TX_BODY_SIZE + deploying().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, + ), + ( + "a nested creation: the created account, the creator's nonce and the code", + || callee_running(creating(BytecodeBuilder::default(), &deploying())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + DEPLOYED, + ), + ( + "a nested creation that reverts with a word of data: the creator's nonce outlives \ + it, and the data is no code", + || callee_running(creating(BytecodeBuilder::default(), &[PUSH1, 32, PUSH0, REVERT])), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a child that logs and reverts", + || { + callee_running(calling(BytecodeBuilder::default(), CHILD, 0, 1_000_000)) + .account_code(CHILD, log(BytecodeBuilder::default(), 0, 32).revert().build()) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + TX_BODY_SIZE, + ), + ( + "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), + TX_BODY_SIZE, + ), + ( + "every site at once", + || { + 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) + }, + |gas| call_with_data(CALLER, CALLEE, Bytes::from(vec![1; 10]), gas), + // 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, + ), + ]; + + for (name, db, tx, bytes) in cases { + for gas_limit in GAS_LIMITS { + let outcome = execute(db(), tx(gas_limit)); + assert_eq!(outcome.gas.history_bytes, bytes, "{name} at {gas_limit}: the bytes"); + 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); + } + } +} + +/// 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. +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]), + Gas::new(inputs.gas_limit()), + ), + 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; + } + 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_LIMITS[0])) + .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 alone"); + assert_eq!(outcome.gas.history, TX_BODY_SIZE * CPHB); +} + +/* ---------- 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); + } + } +} diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 8cb26729a..d828b2eb9 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -193,6 +193,37 @@ fn test_a_system_call_pays_no_history_gas() { assert!(result.result.gas().state_gas_spent_final() > 0, "the exemption is history's alone"); } +/// 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. +#[test] +fn test_an_exempt_transaction_reports_no_history_bytes() { + if runs_at_measurement_prices() { + return; + } + let gas = |tx: MegaTransaction| { + MegaEvm::new(context(db())).execute_transaction(tx).expect("the transaction is valid").gas + }; + + let paying = gas(call_from(CALLER, CONTRACT)); + assert!(paying.history_bytes > 0); + assert_eq!( + paying.history, + paying.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, + "the control pays for every byte it reports", + ); + + let deposit = gas(deposit(call_from(CALLER, CONTRACT))); + assert_eq!((deposit.history, deposit.history_bytes), (0, 0), "a deposit"); + let system = gas(call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS)); + assert_eq!((system.history, system.history_bytes), (0, 0), "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() { diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 86e5af4b8..8642ea64c 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -357,6 +357,11 @@ fn test_no_gas_limit_buys_a_write_record_for_nothing() { 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", + ); } } } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 60ce07fa6..aad7d739d 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,6 +4,7 @@ mod common; mod contract_size; mod db_error; mod equivalence; +mod history_bytes; mod history_exemption; mod history_gas; mod history_reservoir; diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 0cec7665f..53a753e10 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -461,8 +461,8 @@ fn self_calling_loop() -> Bytes { Bytes::from(code) } -/// How far a transaction's history gas can fall behind the bytes it appended, pinned as the known -/// quantity it is. +/// 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 @@ -470,13 +470,12 @@ fn self_calling_loop() -> Bytes { /// 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 ledger. +/// gas, on no gas ledger. /// -/// The bytes are still counted on the data-size lane, so the limits that meter bytes see all of -/// them; what falls behind is the history *gas* column. Whether the allowance becomes a fallback, -/// or a block's history column becomes a byte count beside its gas figure, is a decision for the -/// block-level accounting, not for this mechanism. This test exists so the size of the gap is a -/// number on record rather than a rediscovery. +/// 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() { @@ -503,11 +502,15 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { 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_appended = outcome.usage.data_size; - let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE - TX_BODY_SIZE; + let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE; assert_eq!( - bytes_appended - bytes_paid_for, + 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", ); From 3df9688b6cef0ca9d7c5fff5ccec3c15b90f0e6e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:19:56 +0800 Subject: [PATCH 033/458] feat(satin): hold a block's state gas to a limit BlockLimits carries block_state_gas_limit, unlimited by default. The block keeps the rule its other post-execution dimensions follow: the transaction that reaches the limit is packed, so the block overshoots by at most one transaction's state gas. What differs is who is refused after it. Only a transaction's execution tells whether it adds state gas, so the limiter checks after execution, and a block that has reached its limit refuses a transaction that adds some with MegaBlockLimitExceededError::StateGasLimit. A transaction that adds none still fits. The check runs again at commit, where a candidate executed against an earlier block state meets the block as it is now. --- crates/mega-evm/src/block/executor.rs | 14 +- crates/mega-evm/src/block/limit.rs | 148 +++++++++++++--- crates/mega-evm/src/block/result.rs | 23 +++ crates/mega-evm/src/constants.rs | 6 +- crates/mega-evm/tests/block/counters.rs | 5 +- crates/mega-evm/tests/block/main.rs | 1 + crates/mega-evm/tests/block/state_gas.rs | 205 +++++++++++++++++++++++ 7 files changed, 372 insertions(+), 30 deletions(-) create mode 100644 crates/mega-evm/tests/block/state_gas.rs diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index e90a2b17a..33c458218 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -696,8 +696,8 @@ where /// /// 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. + /// holds a transaction to is checked once more, its data-availability footprint and the state + /// gas it adds included, and nothing changes before the check passes. pub fn commit_transaction_outcome( &mut self, output: MegaBlockTxResult<::TxType>, @@ -711,6 +711,7 @@ where output.is_deposit, )?; self.check_da_footprint(output.da_footprint)?; + self.limiter.post_execution_check(output.tx_hash, &output.block_usage())?; Ok(self.commit_transaction(output)) } @@ -797,7 +798,7 @@ where .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, @@ -807,7 +808,12 @@ where is_deposit, depositor_nonce, inner: outcome, - }) + }; + // A block that has reached its state gas refuses a transaction that adds some, and only + // its execution tells whether it does. Nothing is committed yet, so the refusal leaves the + // block as it was. + self.limiter.post_execution_check(tx_hash, &result.block_usage())?; + Ok(result) } /// Finishes the block and reports what it counted, on top of what diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index e66939bff..4b362c147 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -10,19 +10,25 @@ //! 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. +//! A limit only known after execution — the execution ledger, the state ledger and the data-size +//! bytes a transaction kept — is accumulated when the transaction commits. 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 +//! reached its limit refuses what comes after it, so the overshoot is bounded by one transaction +//! per dimension: +//! +//! - the execution ledger and the data-size bytes are checked before the *next* transaction starts, +//! and a block that has reached either refuses every later transaction; +//! - the state ledger is checked once the next transaction has executed, and a block that has +//! reached its limit refuses a later transaction only if it adds state gas. One that adds none +//! still fits, and only its own execution can tell which it is. //! //! # 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. +//! Of the three gas ledgers the block counts ([`BlockGasCounters`]), execution and state have a +//! block limit. History has none by design; the history bytes beside it are reported, not +//! limited. The write-record count is accumulated here and enforced by nobody: the write-record +//! limit arrives with the state-growth and KV limits. use alloy_primitives::TxHash; @@ -61,6 +67,9 @@ pub struct BlockLimits { 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 state gas the block's transactions may spend together. The transaction that + /// reaches it is packed; after it, only a transaction that adds no state gas is. + pub block_state_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 @@ -85,6 +94,7 @@ impl BlockLimits { tx_da_size_limit: u64::MAX, block_da_size_limit: u64::MAX, block_execution_gas_limit: u64::MAX, + block_state_gas_limit: u64::MAX, block_txs_data_limit: u64::MAX, tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), } @@ -135,6 +145,12 @@ impl BlockLimits { self } + /// Sets the block's state-gas limit. + pub const fn with_block_state_gas_limit(mut self, limit: u64) -> Self { + self.block_state_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; @@ -229,8 +245,9 @@ impl BlockLimiter { /// /// 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. + /// [`post_execution_check`](Self::post_execution_check) checks what only the transaction's + /// execution reveals, and [`post_execution_update`](Self::post_execution_update) advances the + /// counters once the transaction commits. /// /// # Errors /// @@ -333,13 +350,44 @@ 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.state` is checked after execution, in `post_execution_check`: a block that has + // reached its state gas still admits a transaction that adds none. `self.gas.history` and + // `self.usage.write_records` are accumulated and not checked: history has no block limit, + // and the write-record limit arrives with the state-growth and KV limits. Ok(()) } + /// Whether the executed transaction whose block usage is `usage` may be packed in this block. + /// + /// A block that has reached its state-gas limit refuses a transaction that adds state gas, and + /// only such a transaction: whether one does is known only once it has run. The transaction + /// that reaches the limit is itself packed — the block had not reached it when that + /// transaction came — so the block overshoots its limit by at most one transaction's state + /// gas. Like [`pre_execution_check`](Self::pre_execution_check) it changes nothing. + /// + /// # Errors + /// + /// A [`MegaBlockLimitExceededError::StateGasLimit`] when the block has no state gas left and + /// the transaction adds some, which a builder answers by trying the next transaction. + pub fn post_execution_check( + &self, + tx_hash: TxHash, + usage: &BlockUsage, + ) -> Result<(), BlockExecutionError> { + if usage.gas.state > 0 && self.gas.state >= self.limits.block_state_gas_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::StateGasLimit { + block_used: self.gas.state, + tx_used: usage.gas.state, + limit: self.limits.block_state_gas_limit, + }, + )); + } + Ok(()) + } + /// Adds what one committed transaction used. /// /// Every counter saturates: a block that has already crossed a limit stays crossed, and the @@ -593,21 +641,77 @@ mod tests { 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 history ledger, the history bytes and the write-record count are accumulated, and no + /// check refuses a transaction on them; nor on the state ledger, whose limit is unlimited + /// unless a node sets one. #[test] - fn test_state_history_and_write_records_are_counted_but_not_enforced() { + fn test_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() }, + 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()); + assert!(limiter.post_execution_check(B256::ZERO, &usage).is_ok()); + } + + /// What one committed transaction spent on the state ledger, and nothing else. + fn adds_state(state: u64) -> BlockUsage { + BlockUsage { gas: MegaGasUsage { state, ..Default::default() }, ..Default::default() } + } + + /// The state ledger's block limit: the transaction that reaches it is packed, and after it a + /// transaction is refused only if it adds state gas. + #[test] + fn test_state_gas_limit_packs_the_crossing_transaction_and_skips_the_next_that_adds_state() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); + + // The n-th transaction finds the block below its limit and crosses it: it is packed. + limiter.post_execution_update(&adds_state(900)); + assert!(limiter.post_execution_check(B256::ZERO, &adds_state(300)).is_ok()); + limiter.post_execution_update(&adds_state(300)); + assert_eq!(limiter.gas.state, 1_200, "the block overshoots by that one transaction"); + + // The (n+1)-th adds state gas: refused, with the state dimension's own error. + let err = limiter + .post_execution_check(B256::ZERO, &adds_state(1)) + .expect_err("the block has no state gas left"); + assert!(std::format!("{err}").contains("Block state gas limit reached"), "{err}"); + assert!(std::format!("{err}").contains("block_used=1200"), "{err}"); + assert!(std::format!("{err}").contains("tx_used=1"), "{err}"); + + // One that adds none still fits, before execution and after it. + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); + assert!(limiter.post_execution_check(B256::ZERO, &adds_state(0)).is_ok()); + } + + /// The state-gas limit is an inclusive bound like every other: a block may spend exactly its + /// limit, and the block that has is full. + #[test] + fn test_state_gas_limit_admits_what_exactly_fills_it() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); + limiter.post_execution_update(&adds_state(999)); + assert!(limiter.post_execution_check(B256::ZERO, &adds_state(1)).is_ok()); + + limiter.post_execution_update(&adds_state(1)); + assert!( + limiter.post_execution_check(B256::ZERO, &adds_state(1)).is_err(), + "a block that spent exactly its limit is full" + ); } } diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 7c9f06703..b305130e8 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -145,6 +145,18 @@ pub enum MegaBlockLimitExceededError { /// The block's execution-gas limit. limit: u64, }, + /// The block's transactions have reached their state gas, and this transaction adds more. + /// + /// Only a transaction's own execution tells whether it adds state gas, so this one was + /// executed before it was refused; a transaction that adds none still fits the block. + StateGasLimit { + /// The state gas the block has spent. + block_used: u64, + /// The state gas this transaction would add. + tx_used: u64, + /// The block's state-gas limit. + limit: u64, + }, /// The block's transactions have kept their data-size bytes. TransactionDataLimit { /// The data-size bytes the block has kept. @@ -177,6 +189,7 @@ impl MegaBlockLimitExceededError { pub const fn block_used(&self) -> u64 { match self { Self::ExecutionGasLimit { block_used, .. } | + Self::StateGasLimit { block_used, .. } | Self::TransactionDataLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, @@ -187,6 +200,7 @@ impl MegaBlockLimitExceededError { pub const fn limit(&self) -> u64 { match self { Self::ExecutionGasLimit { limit, .. } | + Self::StateGasLimit { limit, .. } | Self::TransactionDataLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, @@ -200,6 +214,10 @@ impl fmt::Display for MegaBlockLimitExceededError { Self::ExecutionGasLimit { block_used, limit } => { write!(f, "Block execution gas limit reached: block_used={block_used} >= limit={limit}") } + Self::StateGasLimit { block_used, tx_used, limit } => write!( + f, + "Block state gas limit reached: block_used={block_used} >= limit={limit}, tx_used={tx_used}" + ), Self::TransactionDataLimit { block_used, limit } => { write!(f, "Block transactions data limit reached: block_used={block_used} >= limit={limit}") } @@ -402,6 +420,11 @@ mod tests { fn test_block_limit_error_reports_block_usage_and_limit() { let cases = [ (MegaBlockLimitExceededError::ExecutionGasLimit { block_used: 3, limit: 12 }, 3, 12), + ( + MegaBlockLimitExceededError::StateGasLimit { block_used: 6, tx_used: 2, limit: 15 }, + 6, + 15, + ), (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 2437f48b5..114037b9f 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -21,8 +21,10 @@ //! 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 per-transaction and per-block state-gas limits are further placeholders, which the -//! state-gas limits add when they land. +//! The per-transaction state-gas limit is a further placeholder, which the state-gas limits add +//! when they land. The per-block one is +//! [`BlockLimits::block_state_gas_limit`](crate::BlockLimits::block_state_gas_limit), which a node +//! sets and which is unlimited by default; no number for it is fixed here yet. use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 0e30bc744..945df26da 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -127,8 +127,9 @@ fn test_the_execution_limit_packs_the_crossing_transaction_and_skips_the_next() 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. +/// 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. diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 6da67cb95..02c5e66f8 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -12,3 +12,4 @@ mod receipts; mod rules; mod salt; mod schedule; +mod state_gas; 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..1e8261cdd --- /dev/null +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -0,0 +1,205 @@ +//! The block's state-gas limit: the transaction that reaches it is packed, every later one that +//! adds state gas is skipped, and one that adds none still fits. + +use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; +use alloy_evm::{block::BlockExecutor, Evm as _}; +use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, test_utils::BytecodeBuilder, BlockLimits, MegaTxEnvelope, +}; +use revm::{ + bytecode::opcode::{CALLDATALOAD, PUSH0, SSTORE}, + context::BlockEnv, + database::State, + Database, +}; + +use crate::common::{self, executor, CALLER, CHAIN_ID, CONTRACT}; + +/// Two more senders, so candidates of one block can be executed before any of them commits. +const CALLER2: Address = address!("0x2000000000000000000000000000000000000022"); +const CALLER3: Address = address!("0x2000000000000000000000000000000000000033"); + +/// An account with no code: a call to it adds no state gas. +const EMPTY: Address = address!("0x3000000000000000000000000000000000000003"); + +/// Below the execution cap, where the reservoir is empty and state gas spills onto regular gas. +const GAS_LIMIT: u64 = 1_000_000; + +/// 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()); + for caller in [CALLER2, CALLER3] { + db.set_account_balance(caller, U256::from(1_000_000_000_000_000_u64)); + } + State::builder().with_database(db).build() +} + +/// A transaction from `caller` to `to`, carrying `input`. +fn tx_from( + caller: Address, + nonce: u64, + to: Address, + input: Bytes, + gas_limit: u64, +) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 1_000_000, + gas_limit, + to: TxKind::Call(to), + value: U256::ZERO, + input, + }; + let hash = B256::from(U256::from(nonce) + (U256::from_be_slice(caller.as_slice()) << 64)); + Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), hash)), + caller, + ) +} + +/// 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 { + let input = Bytes::from(U256::from(slot).to_be_bytes::<32>()); + tx_from(CALLER, nonce, CONTRACT, input, gas_limit) +} + +/// The state gas a transaction that fills one fresh slot spends, read off a probe block. +fn one_slot() -> u64 { + 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(&writes(0, 1, GAS_LIMIT)).expect("the probe executes"); + let slot = probe.gas().state; + assert!(slot > 0, "a fresh slot draws state gas"); + slot +} + +/// A block with room for one slot and a half: the second slot crosses the limit. +fn limits(slot: u64) -> BlockLimits { + BlockLimits::no_limits().with_block_state_gas_limit(slot + slot / 2) +} + +/// The n-th transaction finds the block below its limit and crosses it: it is packed. The +/// (n+1)-th adds state gas and is skipped with the state dimension's own error, leaving nothing +/// behind. A transaction after it that adds none still fits. +#[test] +fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipped() { + let slot = one_slot(); + let mut state = state(); + let mut executor = executor(&mut state, common::block_ctx(limits(slot))); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&writes(0, 1, GAS_LIMIT)).expect("the block has room"); + executor + .execute_transaction(&writes(1, 2, GAS_LIMIT)) + .expect("the transaction that crosses the limit is still packed"); + assert_eq!(executor.gas().state, 2 * slot, "the block overshoots by that one transaction"); + + let err = executor + .execute_transaction(&writes(2, 3, GAS_LIMIT)) + .expect_err("the next transaction adds state gas"); + assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); + assert_eq!( + executor.evm_mut().db_mut().storage(CONTRACT, U256::from(3)).unwrap(), + U256::ZERO, + "the skipped transaction wrote nothing", + ); + + // The same nonce again, now writing a slot that already holds its value: no state gas. + executor + .execute_transaction(&writes(2, 1, GAS_LIMIT)) + .expect("a transaction that adds no state gas still fits"); + executor + .execute_transaction(&tx_from(CALLER, 3, EMPTY, Bytes::new(), GAS_LIMIT)) + .expect("and so does one that writes nothing at all"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 4); + assert_eq!(result.gas.state, 2 * slot, "the skipped transaction counted nothing"); +} + +/// A builder that executes candidates against the same pre-state and then picks among them gets +/// the same rule at commit: the block's state gas may have been reached while a candidate waited. +#[test] +fn test_the_state_gas_limit_is_checked_again_at_commit() { + let slot = one_slot(); + let mut state = state(); + let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); + let mut executor = executor(&mut state, common::block_ctx(limits)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); + let first = executor.run_transaction(&writes(0, 1, GAS_LIMIT)).expect("the block has room"); + let second = executor + .run_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), GAS_LIMIT)) + .expect("nothing has committed yet"); + let third = executor + .run_transaction(&tx_from(CALLER3, 0, EMPTY, Bytes::new(), GAS_LIMIT)) + .expect("nothing has committed yet"); + assert!(second.gas.state > 0 && third.gas.state == 0); + + executor.commit_transaction_outcome(first).expect("the block has room"); + assert_eq!(executor.gas().state, slot, "the block has spent exactly its limit"); + + let err = executor + .commit_transaction_outcome(second) + .expect_err("the block reached its state gas while this transaction waited"); + assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); + executor.commit_transaction_outcome(third).expect("a transaction that adds none still fits"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); + assert_eq!(result.gas.state, slot); +} + +/// Above the execution cap the reservoir pays the state gas, and the block counts and caps it the +/// same way: the ledger is the state gas spent, whichever pool paid it. +#[test] +fn test_the_state_gas_limit_counts_what_the_reservoir_paid() { + let slot = one_slot(); + 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::block_ctx(limits(slot)), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + for (nonce, slot_index) in [(0, 1), (1, 2)] { + 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("the crossing transaction is packed"); + } + + let err = executor + .execute_transaction(&writes(2, 3, ABOVE_CAP)) + .expect_err("the next transaction adds state gas"); + assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); + executor + .execute_transaction(&writes(2, 1, ABOVE_CAP)) + .expect("a transaction that adds no state gas still fits"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3); + assert_eq!(result.gas.state, 2 * slot); +} From 00fc5807172742d9e859ba58e254e2d33cc47dc8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:22:45 +0800 Subject: [PATCH 034/458] test(satin): pin the compute figure to the gas revm settles The regular ledger is total less state less history, read off the result revm's Gas settled into, and the figure a block counts is that ledger at least the floor. Nothing in the engine counts compute beside Gas, so these tests pin the two properties that follow from it. A floor-bound transaction adds its floor to the block, with history taken out before the floor applies: the fork's block_regular_gas_used carries history, and subtracting it afterwards lands below the floor. An inspector that charges gas between instructions, or hands some back, moves the receipt, the regular ledger and the block figure by the same amount. Both run below and above the execution cap. --- crates/mega-evm/tests/block/counters.rs | 24 +++ crates/mega-evm/tests/satin/compute_gas.rs | 163 +++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 3 files changed, 188 insertions(+) create mode 100644 crates/mega-evm/tests/satin/compute_gas.rs diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 945df26da..a324bbda2 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -220,3 +220,27 @@ fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.gas, counters, "the result carries both columns"); } + +/// 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_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"); + + 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"); +} 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..4bc4b32ec --- /dev/null +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -0,0 +1,163 @@ +//! 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. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockGasCounters, MegaContext, MegaEvm, MegaGasUsage, MegaTransactionOutcome, TX_BODY_SIZE, +}; +use revm::{ + bytecode::opcode::{ADD, POP}, + interpreter::{interpreter::EthInterpreter, Interpreter}, + Inspector, +}; + +use crate::common::{call, call_with_data, context, execute, runs_at_measurement_prices}; + +const CALLER: Address = address!("0000000000000000000000000000000000c00000"); +const CALLEE: Address = address!("0000000000000000000000000000000000c00001"); + +/// 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. +fn assert_ledgers(name: &str, outcome: &MegaTransactionOutcome) { + let gas = &outcome.gas; + 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", &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", &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)); + } + } +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index aad7d739d..70c4a310a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -1,6 +1,7 @@ //! Tests of the Satin engine. mod common; +mod compute_gas; mod contract_size; mod db_error; mod equivalence; From 8ef313e9304fa377f2a66067148e84f941accabc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:24:42 +0800 Subject: [PATCH 035/458] feat(limit): give a child frame 98% of its parent's data-size budget The transaction's own frame gets what the transaction has left, and each child gets 98/100 of what its parent has left, still under a configured frame cap. Crossing the child's budget reverts that frame; crossing the transaction limit still latches the transaction. --- crates/mega-evm/src/limit/limit.rs | 76 +++++++- crates/mega-evm/src/limit/mod.rs | 27 ++- crates/mega-evm/tests/satin/data_size.rs | 162 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/strategic_stop.rs | 16 +- 5 files changed, 266 insertions(+), 16 deletions(-) create mode 100644 crates/mega-evm/tests/satin/data_size.rs diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 4070b9b40..7f9dc439c 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -9,7 +9,8 @@ use revm::{ use super::{ frame_limit::{FrameLimitTracker, Lane}, record::{HistoryBytes, RecordEffect, StagedRecord}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD, }; use crate::storage_call_stipend; @@ -336,6 +337,21 @@ impl AdditionalLimit { self.check() } + /// 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 + /// [`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) + } + /// Takes a creation's creator record back: the creation failed before bumping the nonce. /// /// The record is gone, so the caller gets its history back when the frame returns: the lane no @@ -346,10 +362,7 @@ impl AdditionalLimit { } 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 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)). @@ -512,6 +525,16 @@ impl AdditionalLimit { } } +/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`]. +/// +/// The product is taken in `u128`, so a remaining budget near `u64::MAX` does not wrap. +const fn share_of_remaining(remaining: u64) -> u64 { + let remaining = remaining as u128; + let numerator = FRAME_DATA_SHARE_NUMERATOR as u128; + let denominator = FRAME_DATA_SHARE_DENOMINATOR as u128; + ((remaining * numerator) / denominator) as u64 +} + /// Whether the frame `inputs` starts is granted a history allowance: a value-transferring `CALL` /// or `CALLCODE` below the transaction's own frame. /// @@ -627,6 +650,49 @@ mod tests { limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); } + /// 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. A configured frame cap binds + /// when it is the smaller of the two. + #[test] + fn test_a_child_frame_gets_98_percent_of_what_its_parent_has_left() { + let tx_limit = 10_000; + let mut limit = + AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit)); + limit.tracker.record_tx(LimitUsage { data_size: 310, write_records: 0 }); + + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + assert_eq!(limit.tracker.current().unwrap().budget, tx_limit - 310); + + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); + let child = share_of_remaining(tx_limit - 310); + 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); + } + /// 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. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index cad0b44e6..fd882034a 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -76,6 +76,16 @@ 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. @@ -87,16 +97,21 @@ 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. +/// Limits one transaction's data size. +/// +/// [`tx_data_size_limit`](Self::tx_data_size_limit) stops the transaction. 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. /// -/// The data-size limit replaces them with its own limit and per-frame budget rule. +/// [`frame_data_size_limit`](Self::frame_data_size_limit) is a further cap on every frame's +/// budget. It is unlimited unless a caller sets it. #[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. + /// 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, } @@ -118,7 +133,7 @@ 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 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..ffba37f25 --- /dev/null +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -0,0 +1,162 @@ +//! The data-size limit: the 98% a child frame receives, and what crossing it does. +//! +//! A child frame's budget is 98% of what its parent has left. Crossing that budget reverts the +//! child alone and its parent resumes. Crossing the transaction's own limit stops the transaction +//! through the same latch every other transaction-level limit uses. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::BytecodeBuilder, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, + MegaLimitExceeded, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, +}; +use revm::bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, STOP}; + +use crate::common::{call, context}; + +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; + +/// 98% of `remaining`, the share a child frame is given. +fn share(remaining: u64) -> u64 { + (u128::from(remaining) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / + u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 +} + +/// 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 is not +/// latched. +#[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 result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + ( + result, + evm.ctx().additional_limit().latched().copied(), + evm.ctx().additional_limit().usage(), + ) + }; + + // 32 bytes for the log's address, and the data. Exactly the budget. + let (fits, latched, usage) = run(budget - 32); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(latched, 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, budget + 3 * 40); + + let (over, latched, usage) = run(budget - 31); + assert!(over.result.is_success(), "the callers resume: {:?}", over.result); + assert_eq!(latched, None, "a frame budget does not latch the transaction"); + 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: 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, so the latch stops every caller: the slots they wrote are not kept, and +/// the revert names the transaction limit. +#[test] +fn test_depth_3_transaction_limit_stops_the_transaction() { + const TX_LIMIT: u64 = 8_000; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_LIMIT); + let db = chain(log0(TX_LIMIT)); + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) + .unwrap(); + + assert!(!outcome.result.is_success()); + assert!(!outcome.result.is_halt(), "a data-size stop is a revert: {:?}", outcome.result); + // Nothing was written before the log, so the crossing usage is the log itself: 32 for its + // address and `TX_LIMIT` of data. The revert then drops it; the latch keeps the figure. + let crossed = 32 + TX_LIMIT; + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: TX_LIMIT, + used: crossed, + frame_local: false, + }) + ); + assert_eq!(outcome.usage.data_size, 0, "the revert drops the log that crossed"); + match &outcome.result { + revm::context::result::ExecutionResult::Revert { output, .. } => { + assert_eq!( + output.as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: TX_LIMIT } + .abi_encode() + ); + } + other => panic!("expected the latched revert, got {other:?}"), + } + assert!(!stored(&outcome.state, A) && !stored(&outcome.state, B) && !stored(&outcome.state, C)); + + // The same chain without the log stays inside the limit and keeps every caller's slot. + 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!(stored(&kept.state, A) && stored(&kept.state, B) && stored(&kept.state, C)); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 60ce07fa6..7dcb2bac2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -2,6 +2,7 @@ mod common; mod contract_size; +mod data_size; mod db_error; mod equivalence; mod history_exemption; diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 811df4854..45a18a2b5 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -221,14 +221,19 @@ fn test_stop_bills_only_what_ran() { } code.stop().build() }; + // 100 leaves D's second record (80 bytes) inside both the transaction limit and D's own + // budget, and D's third (120) over the transaction limit. The frame budget is over too; the + // transaction limit is checked first, so the stop is the latch and the code after the call + // does not run. A limit of 80 would revert D on its own budget instead, and the callers + // would resume. 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 mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))); let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, 80); + assert_stopped(&result.result, LimitKind::DataSize, 100); let light = |next: Address| { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) @@ -244,9 +249,9 @@ fn test_stop_bills_only_what_ran() { .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 mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))); let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&light_result.result, LimitKind::DataSize, 80); + assert_stopped(&light_result.result, LimitKind::DataSize, 100); assert_eq!( result.result.gas().tx_gas_used(), light_result.result.gas().tx_gas_used(), @@ -378,7 +383,8 @@ fn test_frame_budget_reverts_the_frame_without_a_latch() { 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)); + // 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)); } From c7a5a929a2605ef2a2bb14a537aba4fe5a6e8fc7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:27:55 +0800 Subject: [PATCH 036/458] test(satin): port the parked rows compute gas owns Twenty-three rows run in tests/satin/compute_gas.rs, rewritten against a compute figure read off the gas revm settles: what the regular ledger counts opcode by opcode (arithmetic, memory, logs, storage, nested and reverted frames, precompiles), what it leaves out (state gas at any bucket price, history, the refund), and the execution cap as the compute budget: work past it is an ordinary out-of-gas with the regular ledger at the cap, and intrinsic gas past it is rejected at validation. Each runs below and above the execution cap. Three rows are retired: one pinned a legacy spec boundary, and two set a compute limit of zero and one, which Satin has no way to configure. --- crates/mega-evm/tests/_pending/README.md | 24 +- .../tests/_pending/compute_gas/claims.rs | 106 -- .../tests/_pending/compute_gas/main.rs | 34 - .../_pending/mini_rex/compute_gas_limit.rs | 904 ------------------ crates/mega-evm/tests/satin/compute_gas.rs | 551 ++++++++++- 5 files changed, 562 insertions(+), 1057 deletions(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5cd2b47b9..e85eba785 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 | -| 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 | @@ -39,7 +38,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** | **456** | **428** | **28** | **272** | **156** | **28** | +| **Total** | **430** | **402** | **28** | **272** | **130** | **28** | ## Tests ported in place @@ -232,13 +231,25 @@ These 29 rows run in a real test target now, adapted to the Satin API and to the | `src/system/sequencer_registry.rs` | system contract deployment (9) | 9 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | | **Total** | | **29** | | +## Tests ported by compute gas + +These 23 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles, 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` | compute gas (2) | 2 | `tests/satin/compute_gas.rs` | +| `compute_gas/main.rs` | compute gas (1) | 1 | `tests/satin/compute_gas.rs` | +| `mini_rex/compute_gas_limit.rs` | compute gas (20) | 20 | `tests/satin/compute_gas.rs` | +| **Total** | | **23** | | + ## Tests retired after the inventory -These 19 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 22 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 | |---|---|---:|---| +| `mini_rex/compute_gas_limit.rs` | compute gas (3) | 3 | it pins that one legacy spec counts compute gas where the spec below it does not. Satin is a single spec and every transaction reports its compute figure, so there is no boundary left for it to pin; Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | | `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 | @@ -247,7 +258,7 @@ They are not counted above. | `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | -| **Total** | | **19** | | +| **Total** | | **22** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -284,12 +295,11 @@ 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` | 7 | keep 7 (the pre-block system calls) | -| `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) | +| `compute_gas/claims.rs` | 6 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 1 (the data-size limit · D33/D48) | | `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/compute_gas_limit.rs` | 2 | 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` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | | `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | diff --git a/crates/mega-evm/tests/_pending/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs index 79285d884..2d03025f3 100644 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -54,112 +54,6 @@ fn intercepted_call(forwarded_gas: u64) -> Bytes { .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() diff --git a/crates/mega-evm/tests/_pending/compute_gas/main.rs b/crates/mega-evm/tests/_pending/compute_gas/main.rs index 970fb979d..3843a4fc8 100644 --- a/crates/mega-evm/tests/_pending/compute_gas/main.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/main.rs @@ -817,37 +817,3 @@ fn render_snapshot() -> String { 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/compute_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs index 59a0a1598..9f004d9c0 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs @@ -83,419 +83,10 @@ fn get_compute_gas_limit_info(result: &ResultAndState) -> Option } } -// ============================================================================ -// 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 @@ -617,505 +208,10 @@ fn test_compute_gas_limit_resets_after_volatile_access_rex1() { ); } -// ============================================================================ -// 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 diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index 4bc4b32ec..cbcc00165 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -10,22 +10,48 @@ //! 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. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_evm::{Evm as _, EvmError, InvalidTxError}; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - constants::{COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockGasCounters, MegaContext, MegaEvm, MegaGasUsage, MegaTransactionOutcome, TX_BODY_SIZE, + 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, POP}, + bytecode::opcode::{ + ADD, CALL, DUP1, GAS, JUMPDEST, JUMPI, LOG0, MLOAD, MSTORE, MUL, POP, PUSH0, PUSH1, PUSH3, + SELFDESTRUCT, SLOAD, SUB, SWAP1, + }, + context::{ + result::{ExecutionResult, HaltReason, InvalidTransaction, OutOfGasError}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, 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}; +use crate::{ + common::{call, call_with_data, context, execute, runs_at_measurement_prices}, + salt::{crowded_account, 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]; @@ -161,3 +187,516 @@ fn test_gas_an_inspector_edits_moves_the_compute_figure_with_the_receipt() { } } } + +/* ---------- 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", &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 log's own price is computation — its static cost, eight gas a byte and the memory it reads — +/// and its bytes are history, on their own ledger. +#[test] +fn test_a_log_is_computed_and_its_bytes_are_history() { + if runs_at_measurement_prices() { + return; + } + let code = || BytecodeBuilder::default().push_number(32_u8).append(PUSH0).append(LOG0).stop(); + // `PUSH1`, `PUSH0`, then `LOG0`: 375, eight a byte, and one word of memory. + assert_eq!(computed_beyond_empty(code().build()), 3 + 2 + 375 + 8 * 32 + 3); + for gas_limit in GAS_LIMITS { + let logged = computes(code().build(), gas_limit); + let quiet = computes(Bytes::new(), gas_limit); + assert_eq!(logged.history - quiet.history, (32 + 32) * COST_PER_HISTORY_BYTE); + } +} + +/// 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 — the cold surcharge and Osaka's price for + // setting a slot, which the schedule keeps beside the state gas; `PUSH0`; a warm `SLOAD`; + // `POP`. + assert_eq!(computed, 3 + 3 + (2_100 + 20_000) + 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 (EIP-3529). + const SSTORE_CLEARS_SCHEDULE: u64 = 4_800; + 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); + outcome.gas + }; + for gas_limit in GAS_LIMITS { + let cleared = writes(0, gas_limit); + let overwritten = writes(2, gas_limit); + assert_eq!(overwritten.gas_used - cleared.gas_used, SSTORE_CLEARS_SCHEDULE); + 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); + crate::salt::run(db, envs, call(CALLER, CALLEE, U256::ZERO, gas_limit)).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); + 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() { + 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_LIMITS[0])).unwrap(); + let second = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, GAS_LIMITS[0])).unwrap(); + assert!(first.result.is_success() && second.result.is_success()); + 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. +#[test] +fn test_below_the_cap_the_gas_limit_is_the_compute_budget() { + let run = |gas_limit: u64| { + execute( + funded().account_code(CALLEE, arithmetic(2_000)), + call(CALLER, CALLEE, U256::ZERO, gas_limit), + ) + }; + 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", &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. +#[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_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 83,328 addresses is 2,400 gas each +/// on top of the call, just past the cap, and one address fewer is admitted. +/// +/// Calldata reaches the cap through its floor first, sixty-four gas a byte against sixteen, and is +/// rejected the same way. +#[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 admitted = execute(funded(), with_addresses(83_327)); + assert!(admitted.result.is_success(), "{:?}", admitted.result); + assert_eq!(admitted.gas.regular, EMPTY_CALL + 2_400 * 83_327); + assert_eq!( + rejection(with_addresses(83_328)), + Some(InvalidTransaction::GasFloorMoreThanGasLimit { + gas_floor: EMPTY_CALL + 2_400 * 83_328, + gas_limit: TX_GAS_LIMIT_CAP, + }), + ); + + let calldata = (TX_GAS_LIMIT_CAP - EMPTY_CALL) / 64 + 1; + let tx = call_with_data( + CALLER, + CALLEE, + Bytes::from(vec![0; calldata as usize]), + TX_GAS_LIMIT_CAP + 400_000_000, + ); + assert_eq!( + rejection(tx), + Some(InvalidTransaction::GasFloorMoreThanGasLimit { + gas_floor: EMPTY_CALL + 64 * calldata, + 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); + 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" + ); + } +} From 0fab0fd5a8c349afb60ef45331601dda81275681 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:29:28 +0800 Subject: [PATCH 037/458] docs(satin): describe the block's accounting and its state-gas limit The module table no longer lists compute gas or the state-gas block limit among what is still to come, the block contracts name the history bytes beside the three ledgers and where the compute figure comes from, and the executor's description says which transactions a reached state-gas limit refuses. The crate README says the same in fewer words. --- AGENTS.md | 17 +++++++++++------ crates/mega-evm/README.md | 9 ++++++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 297b107ad..58743d21a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,10 +94,10 @@ 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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the state-gas and write-record block limits | +| `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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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` with the execution-gas and state-gas block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the write-record block limit | | `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/` | 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 and history allowances (`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 | +| `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 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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 | @@ -135,14 +135,16 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The EIP-7623 calldata floor is still computed and validated and binds nothing: history charges the same bytes at a higher rate. - 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 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`. + A block limit known only after execution packs the transaction that reaches it: the execution-gas limit then refuses every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. 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. + `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until detention and the control contracts' compute-ledger semantics 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 and limit-check protocol describe mechanisms that do not exist here; the contracts below replace them. 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. @@ -193,10 +195,13 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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. - `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. + `history_bytes` counts it all the same — the body, one 40-byte record per kept write, the kept 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. + `gas_used` is the receipt's figure; `BlockGasCounters` sums the three ledgers and the history bytes per block. ## Test Organization (`crates/mega-evm/tests/`) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 0cb10df9e..1c9b00825 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -37,10 +37,12 @@ It is carried as an alloy-evm `PrecompilesMap`, so a node can add or replace an 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. +`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. +Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers and the history bytes they appended. +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. +A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, hands each pre-block state (the two EIP calls and the seven deploys) to an optional observer before it commits — that sequence is the witness a stateless client needs — and leaves one hook point empty: the pre-block system calls. 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. @@ -53,7 +55,7 @@ The six system contracts live at their fixed `0x6342…` addresses and are deplo 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, 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. +`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 the control contracts' compute-ledger semantics 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. @@ -72,6 +74,7 @@ An Oracle hint's payload is data size that is never history, because the bytes g 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 resource limits, gas detention and keyless deployment arrive in later changes. From 7e478b306e6ff1709a6b5b21ae82a5a8ee8488d7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:32:36 +0800 Subject: [PATCH 038/458] test(satin): hold the compute cases above the cap to the reservoir The compute tests ran every case below and above the execution cap and compared the regular ledger across the two, but did not say what the reservoir paid above it. Every run above the cap now also asserts that the reservoir left is the reservoir less the state and history ledgers, the identity the other ledger tests hold their runs to. --- crates/mega-evm/tests/satin/compute_gas.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index cbcc00165..c40da76c1 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -72,9 +72,17 @@ fn arithmetic(count: usize) -> Bytes { } /// 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. -fn assert_ledgers(name: &str, outcome: &MegaTransactionOutcome) { +/// 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, @@ -108,7 +116,7 @@ fn test_a_floor_bound_transaction_counts_its_floor_and_history_comes_out_first() 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", &outcome); + assert_ledgers("floor-bound", gas_limit, &outcome); let gas = outcome.gas; assert_eq!(gas.history, (TX_BODY_SIZE + CALLDATA) * COST_PER_HISTORY_BYTE); @@ -166,7 +174,7 @@ fn test_gas_an_inspector_edits_moves_the_compute_figure_with_the_receipt() { .execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("edited", &outcome); + assert_ledgers("edited", gas_limit, &outcome); outcome.gas }; @@ -195,7 +203,7 @@ 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", &outcome); + assert_ledgers("computes", gas_limit, &outcome); outcome.gas } @@ -488,7 +496,7 @@ fn test_computation_past_the_execution_cap_is_an_ordinary_out_of_gas() { outcome.result ); assert_eq!(outcome.limit_exceeded, None, "no limit of this engine stopped it"); - assert_ledgers("past the cap", &outcome); + 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); From f7faac24039d7e66cf062a49a71044d446718e8e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 07:33:21 +0800 Subject: [PATCH 039/458] test(satin): run the per-transaction compute case above the cap too The case that runs one transaction twice on the same EVM ran below the execution cap only; it now runs at both gas limits, as every other compute case whose outcome the cap does not decide. --- crates/mega-evm/tests/satin/compute_gas.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index c40da76c1..8f41423fb 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -413,12 +413,14 @@ fn test_a_reverted_frame_s_computation_stays_on_the_figure() { /// same, whatever ran before it. #[test] fn test_each_transaction_computes_its_own() { - 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_LIMITS[0])).unwrap(); - let second = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, GAS_LIMITS[0])).unwrap(); - assert!(first.result.is_success() && second.result.is_success()); - assert_eq!(first.gas.regular, second.gas.regular); + 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_eq!(first.gas.regular, second.gas.regular); + } } /// A loop of `iterations` turns, twenty-six gas a turn: `PUSH3 n; JUMPDEST; PUSH1 1; SWAP1; SUB; From 39b98eabb0880ec845b4001402e8edf18d3decb7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:49:06 +0900 Subject: [PATCH 040/458] fix(satin): never refuse a deposit on the block's state gas --- crates/mega-evm/src/block/limit.rs | 53 +++++++++++++++++++++--- crates/mega-evm/src/block/result.rs | 3 +- crates/mega-evm/tests/block/state_gas.rs | 33 +++++++++++++++ 3 files changed, 83 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 4b362c147..3aad3769e 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -23,6 +23,14 @@ //! reached its limit refuses a later transaction only if it adds state gas. One that adds none //! still fits, and only its own execution can tell which it is. //! +//! # 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 a deposit is exempt from both data-availability limits +//! and does not count towards the block's. The state-gas limit is a packing budget for the +//! transactions the builder chooses, so it never refuses a deposit either. A deposit still counts +//! towards the state ledger, so the transactions after it find the room it used. +//! //! # Which dimensions are enforced //! //! Of the three gas ledgers the block counts ([`BlockGasCounters`]), execution and state have a @@ -68,7 +76,8 @@ pub struct BlockLimits { /// The most execution gas the block's transactions may spend together. pub block_execution_gas_limit: u64, /// The most state gas the block's transactions may spend together. The transaction that - /// reaches it is packed; after it, only a transaction that adds no state gas is. + /// reaches it is packed; after it, only a transaction that adds no state gas is, or a deposit, + /// which it never refuses and which counts towards it. pub block_state_gas_limit: u64, /// The most data-size bytes the block's transactions may keep together. pub block_txs_data_limit: u64, @@ -189,7 +198,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 the + /// state-gas limit never refuses. pub is_deposit: bool, } @@ -364,18 +374,24 @@ impl BlockLimiter { /// only such a transaction: whether one does is known only once it has run. The transaction /// that reaches the limit is itself packed — the block had not reached it when that /// transaction came — so the block overshoots its limit by at most one transaction's state - /// gas. Like [`pre_execution_check`](Self::pre_execution_check) it changes nothing. + /// gas, besides what deposits add: a deposit is never refused. Like + /// [`pre_execution_check`](Self::pre_execution_check) it changes nothing. /// /// # Errors /// /// A [`MegaBlockLimitExceededError::StateGasLimit`] when the block has no state gas left and - /// the transaction adds some, which a builder answers by trying the next transaction. + /// the transaction, not a deposit, adds some, which a builder answers by trying the next + /// transaction. pub fn post_execution_check( &self, tx_hash: TxHash, usage: &BlockUsage, ) -> Result<(), BlockExecutionError> { - if usage.gas.state > 0 && self.gas.state >= self.limits.block_state_gas_limit { + // A deposit is not the builder's to refuse; it still counts, in `post_execution_update`. + if !usage.is_deposit && + usage.gas.state > 0 && + self.gas.state >= self.limits.block_state_gas_limit + { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::StateGasLimit { @@ -699,6 +715,33 @@ mod tests { assert!(limiter.post_execution_check(B256::ZERO, &adds_state(0)).is_ok()); } + /// A deposit is never refused by the state-gas 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_state_gas_limit_never_refuses_a_deposit_and_counts_it() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); + let deposit = |state| BlockUsage { is_deposit: true, ..adds_state(state) }; + + // Two deposits cross the limit between them. + for _ in 0..2 { + assert!(limiter.post_execution_check(B256::ZERO, &deposit(600)).is_ok()); + limiter.post_execution_update(&deposit(600)); + } + assert_eq!(limiter.gas.state, 1_200); + + // A third finds the block past its limit and is still admitted. + assert!(limiter.post_execution_check(B256::ZERO, &deposit(600)).is_ok()); + limiter.post_execution_update(&deposit(600)); + assert_eq!(limiter.gas.state, 1_800, "every deposit counts"); + + let err = limiter + .post_execution_check(B256::ZERO, &adds_state(1)) + .expect_err("the deposits used the room an ordinary transaction would need"); + assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); + } + /// The state-gas limit is an inclusive bound like every other: a block may spend exactly its /// limit, and the block that has is full. #[test] diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index b305130e8..e36c3d899 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -148,7 +148,8 @@ pub enum MegaBlockLimitExceededError { /// The block's transactions have reached their state gas, and this transaction adds more. /// /// Only a transaction's own execution tells whether it adds state gas, so this one was - /// executed before it was refused; a transaction that adds none still fits the block. + /// executed before it was refused; a transaction that adds none still fits the block, and a + /// deposit is never refused this way. StateGasLimit { /// The state gas the block has spent. block_used: u64, diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index 1e8261cdd..b1917c89b 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -134,6 +134,39 @@ fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipp assert_eq!(result.gas.state, 2 * slot, "the skipped transaction counted nothing"); } +/// A deposit is not a transaction the builder chose: the block derived from L1 must include it, +/// so the state-gas limit never refuses one, however far past it the block is. It still counts, +/// so an ordinary transaction after the deposits finds the room they used. +#[test] +fn test_a_deposit_is_never_refused_by_the_state_gas_limit() { + let slot = one_slot(); + let mut state = state(); + let mut executor = executor(&mut state, common::block_ctx(limits(slot))); + executor.apply_pre_execution_changes().expect("the block starts"); + + let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); + let deposit = |slot: u64| common::deposit_tx_to(CONTRACT, slot_word(slot), GAS_LIMIT); + + executor.execute_transaction(&deposit(1)).expect("the block has room"); + executor.execute_transaction(&deposit(2)).expect("the deposit that crosses the limit"); + assert_eq!(executor.gas().state, 2 * slot, "two deposits crossed the limit between them"); + + executor + .execute_transaction(&deposit(3)) + .expect("a deposit is included whatever the block's state gas"); + assert_eq!(executor.gas().state, 3 * slot, "and it counts"); + + let err = executor + .execute_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(4), GAS_LIMIT)) + .expect_err("an ordinary transaction that adds state gas finds no room left"); + assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); + assert!(format!("{err}").contains(&format!("block_used={}", 3 * slot)), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3); + assert_eq!(result.gas.state, 3 * slot); +} + /// A builder that executes candidates against the same pre-state and then picks among them gets /// the same rule at commit: the block's state gas may have been reached while a candidate waited. #[test] From 499afcc8572f7d5f3eb00ff31d040d4e0c195542 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:50:00 +0900 Subject: [PATCH 041/458] feat(limit): count the transaction body and deployed code as data size The body is recorded before any frame and kept on a revert and on an out-of-gas before the first frame. Deployed code is counted on the creation's lane before the creation is committed, so a crossing reverts the checkpoint and leaves no code. --- crates/mega-evm/src/evm/context.rs | 8 +- crates/mega-evm/src/evm/execution.rs | 40 +-- crates/mega-evm/src/evm/history.rs | 23 ++ crates/mega-evm/src/limit/limit.rs | 61 +++- crates/mega-evm/tests/block/factory.rs | 5 +- crates/mega-evm/tests/satin/data_size.rs | 297 +++++++++++++++++- .../mega-evm/tests/satin/history_reservoir.rs | 12 +- crates/mega-evm/tests/satin/outcome.rs | 22 +- .../tests/satin/storage_call_stipend.rs | 9 +- crates/mega-evm/tests/satin/strategic_stop.rs | 57 ++-- crates/mega-evm/tests/satin/write_records.rs | 122 +++++-- crates/mega-evm/tests/system/oracle.rs | 46 ++- 12 files changed, 589 insertions(+), 113 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 298b208d2..21a284fc8 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -14,7 +14,10 @@ use revm::{ use crate::{ constants, - evm::schedule::{satin_gas_params, satin_gas_params_history_exempt}, + evm::{ + history::transaction_body_bytes, + schedule::{satin_gas_params, satin_gas_params_history_exempt}, + }, system::{self, MEGA_SYSTEM_ADDRESS}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, @@ -230,6 +233,9 @@ impl MegaContext { self.system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || self.system_originated; self.set_history_exempt(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())); } /// Prepares the context for a system call. Every system-call entry point of diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 55cad95b0..f2dc81bcb 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -18,7 +18,7 @@ use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, - transaction::{AccessListItemTr, TransactionType}, + transaction::TransactionType, ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, context_interface::{ @@ -45,7 +45,7 @@ use revm::{ }; use crate::{ - evm::{history::tx_body_history_bytes, inspector::frame_end_checked}, + evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, @@ -433,6 +433,8 @@ impl EvmTr for MegaEvm( + ctx: &mut MegaContext, + frame: &EthFrame, + mut action: InterpreterAction, +) -> InterpreterAction { + if frame.data.is_create() { + if let InterpreterAction::Return(result) = &mut action { + ctx.additional_limit.on_create_return(result); + } + } + action +} + /// 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. /// @@ -704,22 +723,7 @@ fn inspect_logs( fn tx_body_history_gas( ctx: &MegaContext, ) -> u64 { - let tx = ctx.tx(); - 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(); - let bytes = tx_body_history_bytes( - tx.input().len() as u64, - tx.authorization_list_len() as u64, - addresses, - slots, - ); - history_gas(bytes).unwrap_or(u64::MAX) + history_gas(transaction_body_bytes(ctx.tx())).unwrap_or(u64::MAX) } /// Whether executing this transaction creates its caller's account: a deposit-like transaction diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index f8b8f1c0e..94e1aa4ed 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -16,6 +16,8 @@ //! 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}; + use crate::{ evm::prices::active_satin_prices, limit::{ @@ -66,6 +68,27 @@ 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 7f9dc439c..a903cc7b7 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -3,7 +3,7 @@ use alloy_primitives::Address; use revm::{ handler::FrameResult, - interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, + interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult, InterpreterResult}, }; use super::{ @@ -47,8 +47,12 @@ 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, @@ -87,6 +91,7 @@ impl AdditionalLimit { self.target_is_authority = false; self.sender = Address::ZERO; self.frame_began = false; + self.body_bytes = 0; self.intrinsic_history_gas = 0; self.top_level_write_record_gas = 0; self.pending_frame_charge = FrameCharge::NONE; @@ -275,6 +280,21 @@ impl AdditionalLimit { /* 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. A body that crosses the + /// transaction limit latches it, and the first frame is then answered with the stop. + pub(crate) fn record_tx_body(&mut self, bytes: u64) -> LimitCheck { + self.body_bytes = bytes; + if bytes == 0 { + return LimitCheck::WithinLimit; + } + self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); + self.check() + } + /// Counts the `bytes` of an Oracle hint, the payload a `sendHint` call hands to the node's /// oracle service. /// @@ -337,6 +357,36 @@ impl AdditionalLimit { self.check() } + /// Counts the code a creation is about to deposit, on the creation's own lane, and turns the + /// return into the stop when that crosses a limit. + /// + /// Called from the frame run, on a successful return, before revm's `return_create` commits + /// the creation's journal checkpoint. A rewrite after that commit would leave the code + /// deployed: the checkpoint is already gone, and flipping the frame result does not reopen + /// it. A stop here makes `return_create` revert the checkpoint instead, so the code is not + /// written. 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 return that is already a revert or a halt deposits nothing, and its output is the + /// revert data, not code. Empty code deposits nothing either. + pub(crate) fn on_create_return(&mut self, result: &mut InterpreterResult) { + if !result.result.is_ok() { + return; + } + let bytes = result.output.len() as u64; + if bytes == 0 { + return; + } + debug_assert!(self.tracker.current().is_some(), "a creation returns on its own lane"); + self.tracker.record(LimitUsage { data_size: bytes, write_records: 0 }); + let check = self.check(); + if !check.exceeded_limit() { + return; + } + result.result = InstructionResult::Revert; + result.output = check.revert_data(); + } + /// 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 @@ -506,11 +556,16 @@ impl AdditionalLimit { /// /// 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. + /// records and any latch they set go too, and the halt stays a halt. The body is not one of + /// those records. It is put back after the reset. pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { if !self.frame_began { + let body = self.body_bytes; self.tracker.reset(); self.latched = None; + if body > 0 { + 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"); diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 807119ce3..9f2ee5147 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -138,7 +138,8 @@ fn test_direct_construction_applies_block_context_runtime_limits() { /// 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; + // 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( @@ -167,7 +168,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/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index ffba37f25..85a9d7ac0 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -1,19 +1,30 @@ -//! The data-size limit: the 98% a child frame receives, and what crossing it does. +//! 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 reverts the //! child alone and its parent resumes. Crossing the transaction's own limit stops the transaction //! through the same latch every other transaction-level limit uses. +//! +//! The body is counted before any frame and kept on every path. Deployed code is counted on the +//! creation's lane, one byte per byte, before the creation is committed. use alloy_evm::Evm; -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ - test_utils::BytecodeBuilder, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, - MegaLimitExceeded, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, + MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, REVERT, STOP}, + interpreter::{ + interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, Interpreter, + }, + Database, Inspector, }; -use revm::bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, STOP}; -use crate::common::{call, context}; +use crate::common::{call, call_with_data, context, create}; const CALLER: Address = address!("0000000000000000000000000000000000300000"); const A: Address = address!("0000000000000000000000000000000000300001"); @@ -100,14 +111,17 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { 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, budget + 3 * 40); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + budget + 3 * 40); let (over, latched, usage) = run(budget - 31); assert!(over.result.is_success(), "the callers resume: {:?}", over.result); assert_eq!(latched, None, "a frame budget does not latch the transaction"); 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: 3 * 40, write_records: 3 }); + 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 @@ -124,9 +138,9 @@ fn test_depth_3_transaction_limit_stops_the_transaction() { assert!(!outcome.result.is_success()); assert!(!outcome.result.is_halt(), "a data-size stop is a revert: {:?}", outcome.result); - // Nothing was written before the log, so the crossing usage is the log itself: 32 for its - // address and `TX_LIMIT` of data. The revert then drops it; the latch keeps the figure. - let crossed = 32 + TX_LIMIT; + // Nothing was written before the log, so the crossing usage is the body plus the log: 32 for + // its address and `TX_LIMIT` of data. The revert drops the log; the body stays. + let crossed = mega_evm::TX_BODY_SIZE + 32 + TX_LIMIT; assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { @@ -136,7 +150,11 @@ fn test_depth_3_transaction_limit_stops_the_transaction() { frame_local: false, }) ); - assert_eq!(outcome.usage.data_size, 0, "the revert drops the log that crossed"); + assert_eq!( + outcome.usage.data_size, + mega_evm::TX_BODY_SIZE, + "the revert drops the log and keeps the body" + ); match &outcome.result { revm::context::result::ExecutionResult::Revert { output, .. } => { assert_eq!( @@ -160,3 +178,258 @@ fn test_depth_3_transaction_limit_stops_the_transaction() { assert_eq!(kept.limit_exceeded, None); 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. +#[derive(Clone, Default)] +struct Probe { + steps: u32, + creates: Vec<(InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for Probe { + fn step(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.steps += 1; + } + + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.creates.push((outcome.result.result, outcome.result.output.clone())); + } +} + +/// Init code that returns `size` zero bytes as the deployed contract. +fn constructor_returning(size: u64) -> Bytes { + BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() +} + +/// Init code that reverts with `len` bytes and deploys nothing. +fn reverting_with(len: u8) -> Bytes { + BytecodeBuilder::default().push_number(len).push_number(0_u8).append(REVERT).build() +} + +/// 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"); +} + +/// A body that crosses the transaction limit stops the transaction before its code runs. The +/// body stays counted: it is what crossed. +#[test] +fn test_a_body_over_the_limit_stops_before_any_frame() { + let db = funded().account_code( + A, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + let limit = mega_evm::TX_BODY_SIZE - 1; + let mut evm = MegaEvm::new( + context(db) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), + ) + .with_inspector(Probe::default()); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); + assert_eq!(evm.inspector().steps, 0, "the callee never ran"); + assert_eq!( + evm.ctx().additional_limit().latched().copied(), + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: mega_evm::TX_BODY_SIZE, + frame_local: false, + }) + ); + assert_eq!( + evm.ctx().additional_limit().usage(), + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + ); + assert!( + result.state.get(&A).is_none_or(|account| { + account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) + }), + "the callee's write was never made", + ); +} + +/// 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().latched().copied(), + evm.inspector().clone(), + ) + }; + + for inspect in [false, true] { + let (kept, usage, latched, _) = run(fits, inspect); + assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); + assert_eq!(latched, 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, latched, probe) = run(fits + 1, inspect); + assert!(over.result.is_success(), "the caller resumes: {:?}", over.result); + assert_eq!(latched, None, "a frame budget does not latch the transaction"); + 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() + ); + } + } +} + +/// The output of a reverting creation is revert data, not deployed code, so it is not counted. +#[test] +fn test_a_reverting_creation_does_not_count_its_output() { + let init = reverting_with(40); + let (outcome, _) = run_create(init.clone(), EvmTxRuntimeLimits::no_limits(), false); + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "the revert is the init code's, not a stop"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + init.len() as u64, write_records: 0 }, + ); +} diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 2120fc3fa..b96a6b58d 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -180,7 +180,11 @@ 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::ZERO, "the reverted transfer kept nothing"); + 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, @@ -210,7 +214,11 @@ 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::ZERO, "the refused call wrote nothing"); + 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, diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 41eb0126d..62d34a089 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -59,7 +59,10 @@ fn test_outcome_reports_the_ledgers() { gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * SLOT_STATE_GAS - gas.history, ); - assert_eq!(outcome.usage, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); + 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(); @@ -73,19 +76,26 @@ fn test_outcome_reports_the_ledgers() { /// 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), + 1_000_000, + ); 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. diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 0cec7665f..9c2089865 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -330,7 +330,8 @@ fn test_a_transaction_level_stop_does_not_hand_the_allowance_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. - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(400); + // 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) @@ -495,8 +496,8 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { assert_eq!(outcome.usage.write_records, 1); assert_eq!( outcome.usage.data_size, - WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, - "the record and every event's bytes are counted", + 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, @@ -505,7 +506,7 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { ); let bytes_appended = outcome.usage.data_size; - let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE - TX_BODY_SIZE; + let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE; assert_eq!( bytes_appended - bytes_paid_for, GRANTS * STORAGE_CALL_STIPEND_BYTES, diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 45a18a2b5..e28359ad9 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -99,8 +99,10 @@ const fn create_body_history(init_code_len: u64) -> u64 { (mega_evm::TX_BODY_SIZE + init_code_len) * mega_evm::constants::COST_PER_HISTORY_BYTE } -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 { @@ -146,10 +148,15 @@ impl Inspector, EthInterpreter> for Probe { /// 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; + // A, B, C and D's first write are four records (160 bytes); D's second crosses 180 above + // the body. + let limit = mega_evm::TX_BODY_SIZE + 180; 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(); @@ -165,7 +172,7 @@ fn test_cap_crossed_at_depth_three_stops_the_transaction() { Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, - used: 200, + used: mega_evm::TX_BODY_SIZE + 200, frame_local: false }) ); @@ -201,7 +208,7 @@ fn test_stop_bills_only_what_ran() { 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); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); result.result.gas().tx_gas_used() }; let plain = gas_of(chain(), false); @@ -233,7 +240,7 @@ fn test_stop_bills_only_what_ran() { .account_code(D, writer()); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))); let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, 100); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 100); let light = |next: Address| { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) @@ -251,7 +258,7 @@ fn test_stop_bills_only_what_ran() { .account_code(D, writer()); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))); let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&light_result.result, LimitKind::DataSize, 100); + assert_stopped(&light_result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 100); assert_eq!( result.result.gas().tx_gas_used(), light_result.result.gas().tx_gas_used(), @@ -265,7 +272,7 @@ fn test_stop_bills_only_what_ran() { 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); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); *result.result.gas() }; let small = at(100_000_000); @@ -333,11 +340,15 @@ 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)); assert!(transfer.result.is_success()); @@ -430,7 +441,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); @@ -454,7 +469,7 @@ fn test_the_latch_does_not_outlive_its_transaction() { 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_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 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())); @@ -483,7 +498,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, 119); + 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. @@ -563,7 +578,7 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { 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); + 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); } @@ -585,7 +600,7 @@ 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, 180); + assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); assert_eq!(stopped.gas.history, body_history()); } @@ -595,8 +610,12 @@ fn test_outcome_reports_history_gas() { 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_stopped(&outcome.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); assert!(outcome.limit_exceeded.is_some()); - assert_eq!(outcome.usage, mega_evm::LimitUsage::ZERO, "every lane failed"); + assert_eq!( + outcome.usage, + mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "every lane failed; the body stays" + ); assert!(outcome.result.logs().is_empty()); } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 82dffd3e0..c4edbd884 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -16,12 +16,12 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, test_utils::{BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, + LimitUsage, MegaContext, MegaEvm, StagedRecord, 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, @@ -37,10 +37,25 @@ const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); /// child burned the 63/64 it was forwarded. const GAS_LIMIT: u64 = 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)) @@ -107,7 +122,7 @@ fn test_failed_child_discards_its_transfer_records() { 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); + assert_eq!(usage, body_only()); } /// After a failed transfer the sender can be recorded again by the next one. @@ -168,7 +183,7 @@ fn test_creation_without_funds_records_nothing() { 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!(usage, body_only()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); } @@ -193,7 +208,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), records_only(1)); } /// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty @@ -234,14 +249,14 @@ 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]), records_only(2)); } /* ---------- storage, logs, selfdestruct ---------- */ @@ -253,7 +268,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 { @@ -277,7 +292,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() @@ -314,7 +329,7 @@ fn test_log_counts_its_bytes() { ); 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 }); + assert_eq!(usage, with_extra(body_only(), 32 + 2 * 32 + 10)); } /// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the @@ -326,9 +341,9 @@ 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), + (U256::from(5), CALLEE, body_only()), + (U256::from(5), CALLER, body_only()), + (U256::ZERO, CONTRACT, body_only()), ]; for (balance, beneficiary, expected) in cases { let db = MemoryDatabase::default() @@ -343,15 +358,16 @@ 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)); 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)); assert!(!result.result.is_success()); - assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(usage, with_extra(body_only(), 1)); } /* ---------- the commit happens after the opcode ---------- */ @@ -437,7 +453,7 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { 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 @@ -502,15 +518,24 @@ 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"); + assert_eq!( + usage, + with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), + "a wrong nonce applies nothing, and its tuple is still in the body" + ); 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), + "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 @@ -520,7 +545,7 @@ 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)); + assert_eq!(usage, with_extra(records(1), mega_evm::AUTHORIZATION_SIZE)); // 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 @@ -602,7 +627,7 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { .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 @@ -655,11 +680,13 @@ fn test_authorities_crossing_the_cap_are_not_applied() { .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) .unwrap() }; - let at_the_cap = with_cap(40); + // The body carries the authorization tuple; the applied authority is one record on top. + let tuple = mega_evm::AUTHORIZATION_SIZE; + let at_the_cap = with_cap(TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE); assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); - assert_eq!(at_the_cap.usage, records(1)); + assert_eq!(at_the_cap.usage, with_extra(records(1), tuple)); - let outcome = with_cap(39); + let outcome = with_cap(TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE - 1); assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); assert!(outcome.limit_exceeded.is_some()); let authority = outcome.state.get(&AUTHORITY_1); @@ -667,7 +694,7 @@ fn test_authorities_crossing_the_cap_are_not_applied() { 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); + assert_eq!(outcome.usage, with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE)); } /// A transaction that runs out of gas after its authorities were applied, before its first frame, @@ -702,7 +729,11 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { } let outcome = run_at(succeeds - 1).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), @@ -799,7 +830,12 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { 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), + "the created account, CONTRACT2" + ); } /// A transaction calling its own sender (delegated) counts the sender as recorded from the start. @@ -899,6 +935,16 @@ fn value_call_a_system_contract_refuses() -> Bytes { .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 { @@ -1018,6 +1064,20 @@ fn paired_corpus() -> Vec { 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, + ), // The two cases where a transaction's data size and its history part company. Both are // decisions, stated in the byte table; each is written out here with the number it pays. Paired { @@ -1095,12 +1155,12 @@ fn test_every_kept_write_pays_one_record_of_history() { .expect("the transaction is valid"); let usage = outcome.usage; assert_eq!(usage.write_records, case.records, "{}: the records kept", case.name); - let body = mega_evm::TX_BODY_SIZE + case.tx.0.base.data.len() as u64; + let body = mega_evm::transaction_body_bytes(&case.tx); let expected = (body + case.other_bytes + case.records * WRITE_RECORD_SIZE) * CPHB; assert_eq!(outcome.gas.history, expected, "{}: the history it pays", case.name); assert_eq!( usage.data_size, - case.other_bytes + case.records * WRITE_RECORD_SIZE + case.hint_bytes, + body + case.other_bytes + case.records * WRITE_RECORD_SIZE + case.hint_bytes, "{}: the data size the limit counts", case.name, ); @@ -1144,7 +1204,7 @@ 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, LimitUsage::ZERO, "the answered call wrote nothing"); + 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, records(2), "the transfer that ran wrote two accounts"); assert_eq!( diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 4563c06b0..1c4e285b2 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -25,6 +25,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( @@ -87,14 +97,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 +115,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 +143,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 +175,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 +211,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 +223,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 +243,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,7 +287,7 @@ 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", ); } @@ -287,7 +301,10 @@ fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { #[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 counts it again, and that second copy is + // the byte that crosses. + let counted = top_level_hint(data.len() as u64); + let limit = counted - 1; let (outcome, hints) = run_with_oracle_under( system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), @@ -296,8 +313,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.data_size, - data.len() as u64, + outcome.usage.data_size, counted, "the whole payload is counted: the count is what crossed the limit", ); assert_eq!( @@ -305,7 +321,7 @@ fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, - used: data.len() as u64, + used: counted, frame_local: false, }), ); @@ -324,11 +340,11 @@ 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); } From 7df124b8605fc8c4269f827d9e618122b2b4d1ac Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:50:23 +0900 Subject: [PATCH 042/458] fix(satin): never refuse a deposit on the block's execution gas --- crates/mega-evm/src/block/limit.rs | 49 ++++++++++++++++++++----- crates/mega-evm/src/block/result.rs | 3 +- crates/mega-evm/tests/block/counters.rs | 47 ++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 3aad3769e..97be1bf0b 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -18,7 +18,8 @@ //! per dimension: //! //! - the execution ledger and the data-size bytes are checked before the *next* transaction starts, -//! and a block that has reached either refuses every later transaction; +//! and a block that has reached either refuses every later transaction — a deposit excepted, for +//! the execution ledger; //! - the state ledger is checked once the next transaction has executed, and a block that has //! reached its limit refuses a later transaction only if it adds state gas. One that adds none //! still fits, and only its own execution can tell which it is. @@ -27,9 +28,9 @@ //! //! 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 a deposit is exempt from both data-availability limits -//! and does not count towards the block's. The state-gas limit is a packing budget for the -//! transactions the builder chooses, so it never refuses a deposit either. A deposit still counts -//! towards the state ledger, so the transactions after it find the room it used. +//! and does not count towards the block's. The execution-gas and state-gas limits are packing +//! budgets for the transactions the builder chooses, so neither refuses a deposit either. A +//! deposit still counts towards both ledgers, so the transactions after it find the room it used. //! //! # Which dimensions are enforced //! @@ -73,7 +74,9 @@ pub struct BlockLimits { /// 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. + /// The most execution gas the block's transactions may spend together. The transaction that + /// reaches it is packed; after it, only a deposit is, which it never refuses and which counts + /// towards it. pub block_execution_gas_limit: u64, /// The most state gas the block's transactions may spend together. The transaction that /// reaches it is packed; after it, only a transaction that adds no state gas is, or a deposit, @@ -199,7 +202,7 @@ pub struct BlockUsage { /// The transaction's data-availability footprint, in gas. pub da_footprint: u64, /// Whether the transaction is a deposit, which the data-availability dimensions exempt and the - /// state-gas limit never refuses. + /// execution-gas and state-gas limits never refuse. pub is_deposit: bool, } @@ -253,7 +256,8 @@ impl BlockLimiter { /// Whether `tx` may execute in this block. /// - /// Checks the transaction against its own limits, and against what the block has left. It + /// Checks the transaction against its own limits, and against what the block has left; a + /// deposit is held to neither data-availability limit nor to the execution-gas limit. It /// reads the counters and changes nothing; /// [`post_execution_check`](Self::post_execution_check) checks what only the transaction's /// execution reveals, and [`post_execution_update`](Self::post_execution_update) advances the @@ -339,8 +343,9 @@ impl BlockLimiter { } // 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 { + // is already packed, so what is refused here is the next one. A deposit is not the + // builder's to refuse on the execution ledger; it still counts, in `post_execution_update`. + if !is_deposit && self.gas.execution >= self.limits.block_execution_gas_limit { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::ExecutionGasLimit { @@ -561,6 +566,32 @@ mod tests { assert!(std::format!("{err}").contains("Block execution gas limit reached"), "{err}"); } + /// A deposit is never refused by the execution-gas 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_never_refuses_a_deposit_and_counts_it() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_execution_gas_limit(1_000)); + let deposit = BlockUsage { + gas: MegaGasUsage { regular: 600, ..Default::default() }, + is_deposit: true, + ..Default::default() + }; + + // 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.gas.execution, 1_800, "every deposit counts"); + + let err = limiter + .pre_execution_check(B256::ZERO, 0, 0, 0, false) + .expect_err("the deposits used the room an ordinary transaction would need"); + assert!(std::format!("{err}").contains("block_used=1800"), "{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] diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index e36c3d899..400555d8f 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -138,7 +138,8 @@ 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. + /// The block's transactions have spent their execution gas. A deposit is never refused this + /// way. ExecutionGasLimit { /// The execution gas the block has spent. block_used: u64, diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index a324bbda2..f8fb57cb7 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -127,6 +127,53 @@ fn test_the_execution_limit_packs_the_crossing_transaction_and_skips_the_next() assert_eq!(result.receipts().len(), 1); } +/// A deposit is not a transaction the builder chose: the block derived from L1 must include it, +/// so the execution-gas limit never refuses one, however far past it the block is. It still +/// counts, so an ordinary transaction after the deposits finds the room they used. +#[test] +fn test_a_deposit_is_never_refused_by_the_execution_limit() { + let deposit = || common::deposit_tx_to(RECIPIENT, Bytes::new(), 1_000_000); + + // What one deposit spends on the execution ledger, so two of them cross the limit below. + 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(&deposit()).expect("the probe executes"); + probe.gas().execution + }; + assert!(spent > 0); + + let mut state = state_with_writer(); + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits().with_block_execution_gas_limit(spent + spent / 2), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&deposit()).expect("the block has room"); + executor.execute_transaction(&deposit()).expect("the deposit that crosses the limit"); + assert_eq!(executor.gas().execution, 2 * spent, "two deposits crossed the limit between them"); + + executor + .execute_transaction(&deposit()) + .expect("a deposit is included whatever the block's execution gas"); + assert_eq!(executor.gas().execution, 3 * spent, "and it counts"); + + // Each deposit bumped the sender's nonce, so this one is valid and refused for room alone. + let err = executor + .execute_transaction(&user_tx(3, 1_000_000)) + .expect_err("an ordinary transaction finds no execution gas left"); + assert!(format!("{err}").contains("Block execution gas limit reached"), "{err}"); + assert!(format!("{err}").contains(&format!("block_used={}", 3 * spent)), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3); + assert_eq!(result.gas.execution, 3 * spent); +} + /// 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. From 075a8058ddb2d53eacd089e51f453ec0dd6d25eb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:52:01 +0900 Subject: [PATCH 043/458] fix(satin): hold the trait's commit to the checks the checked commit makes --- crates/mega-evm/src/block/executor.rs | 87 +++++++++++++++++++----- crates/mega-evm/tests/block/state_gas.rs | 28 ++++++++ 2 files changed, 99 insertions(+), 16 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 33c458218..63ac4151a 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -34,6 +34,21 @@ //! 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 +//! 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. +//! +//! Neither path checks the state a candidate executed against. A candidate executed before +//! another commit changed that state is stale whatever the counters say, and executing it again +//! is the builder's responsibility. +//! //! # The pre-block observer //! //! Each pre-block step — the EIP-2935 call, the EIP-4788 call, and every system-contract deploy — @@ -427,6 +442,26 @@ 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, + )?; + self.check_da_footprint(output.da_footprint)?; + self.limiter.post_execution_check(output.tx_hash, &output.block_usage()) + } + /// 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 @@ -580,7 +615,30 @@ 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. + /// + /// Neither commit checks the state `output` executed against: an outcome executed before + /// another commit changed that state is the caller's to execute again. + /// + /// # Panics + /// + /// In a debug build, when the block no longer has room for `output` — a caller that broke the + /// contract, which would otherwise pack the block past a limit. 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"), + ); self.limiter.post_execution_update(&output.block_usage()); let MegaBlockTxResult { tx_type, is_deposit, depositor_nonce, inner, .. } = output; @@ -661,9 +719,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, @@ -694,24 +752,21 @@ 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 everything the block - /// holds a transaction to is checked once more, its data-availability footprint and the state - /// gas it adds 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 and the state gas it adds included — and nothing changes before the check + /// passes. + /// + /// The check covers the block's counters, not the state `output` executed against. A + /// candidate executed before another commit changed that state is stale whatever the counters + /// say, and executing it again is the builder's responsibility. 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.limiter.post_execution_check(output.tx_hash, &output.block_usage())?; + self.check_room(&output)?; Ok(self.commit_transaction(output)) } diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index b1917c89b..bff03ec1f 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -201,6 +201,34 @@ fn test_the_state_gas_limit_is_checked_again_at_commit() { assert_eq!(result.gas.state, slot); } +/// 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 above +/// refuses. The trait's commit makes the same check in a debug build and trips on it. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "an outcome the block no longer has room for")] +fn test_the_trait_commit_trips_on_an_outcome_the_block_has_no_room_for() { + let slot = one_slot(); + let mut state = state(); + let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); + let mut executor = executor(&mut state, common::block_ctx(limits)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); + let first = executor + .execute_transaction_without_commit(&writes(0, 1, GAS_LIMIT)) + .expect("the block has room"); + let second = executor + .execute_transaction_without_commit(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), GAS_LIMIT)) + .expect("nothing has committed yet"); + assert!(second.gas.state > 0); + + BlockExecutor::commit_transaction(&mut executor, first); + assert_eq!(executor.gas().state, slot, "the block has spent exactly its limit"); + BlockExecutor::commit_transaction(&mut executor, second); +} + /// Above the execution cap the reservoir pays the state gas, and the block counts and caps it the /// same way: the ledger is the state gas spent, whichever pool paid it. #[test] From c181ec6b835469fa86ebac0cd9b12cb6a88679ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:54:54 +0900 Subject: [PATCH 044/458] feat(limit): default a block's data-size caps to the production numbers A block that configures nothing holds BLOCK_DATA_LIMIT, and the executor installs TX_DATA_LIMIT on each transaction. no_limits still clears both. A deposit counts towards the block's data size; its data-availability exemption does not extend there. --- crates/mega-evm/src/block/executor.rs | 10 ++++++ crates/mega-evm/src/block/limit.rs | 52 ++++++++++++++++++++++++--- crates/mega-evm/src/constants.rs | 4 +-- crates/mega-evm/tests/block/limits.rs | 29 +++++++++++++++ 4 files changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index e90a2b17a..1e15cc236 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -866,6 +866,16 @@ 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.evm().tx_runtime_limits().tx_data_size_limit, + crate::constants::TX_DATA_LIMIT, + "a default block installs the production 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()); } diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index f7459adad..48dc3caba 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -1,8 +1,10 @@ //! 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. +//! [`BlockLimiter`] is the state one block keeps while it executes. Data size defaults to the +//! production caps — [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) for the block and +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) for each transaction — and every other +//! limit defaults to unlimited. [`BlockLimits::no_limits`] clears the data-size caps too. //! //! # When each limit is checked //! @@ -39,8 +41,9 @@ use crate::{ /// 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 +/// [`Default`] carries the production data-size caps and leaves every other dimension unlimited. +/// [`no_limits`](Self::no_limits) clears the data-size caps too. A node sets the dimensions 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 { @@ -62,15 +65,22 @@ pub struct BlockLimits { /// 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. + /// + /// [`Default`] is [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT). A deposit counts + /// towards it: the data-availability exemption does not extend here. pub block_txs_data_limit: u64, /// The limits every transaction of the block runs under, which the executor installs on the /// EVM. + /// + /// [`Default`] sets the transaction data-size limit to + /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) and leaves the frame cap unlimited, so a + /// frame's budget is the 98% share of what its parent has left. pub tx_runtime_limits: EvmTxRuntimeLimits, } impl Default for BlockLimits { fn default() -> Self { - Self::no_limits() + Self::with_production_data_limits() } } @@ -90,6 +100,20 @@ impl BlockLimits { } } + /// The limits a block runs under when its caller configures nothing else. + /// + /// Every dimension is unlimited except data size: the block holds + /// [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) bytes, and each transaction holds + /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT). The block executor installs the + /// transaction half on the EVM. + pub const fn with_production_data_limits() -> Self { + let mut limits = Self::no_limits(); + limits.block_txs_data_limit = crate::constants::BLOCK_DATA_LIMIT; + limits.tx_runtime_limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT); + limits + } + /// Sets the per-transaction gas limit. pub const fn with_tx_gas_limit(mut self, limit: u64) -> Self { self.tx_gas_limit = limit; @@ -323,6 +347,8 @@ impl BlockLimiter { )); } + // Every committed transaction counts, a deposit included. The transaction that crossed + // is already packed; this refuses the next one. if self.usage.data_size >= self.limits.block_txs_data_limit { return Err(invalid_tx( tx_hash, @@ -372,6 +398,22 @@ mod tests { use super::*; use alloy_primitives::B256; + /// A block that configures nothing holds the production data-size caps and nothing else. + #[test] + fn test_the_default_limits_are_the_production_data_size_caps() { + let limits = BlockLimits::default(); + assert_eq!(limits, BlockLimits::with_production_data_limits()); + assert_eq!(limits.block_txs_data_limit, crate::constants::BLOCK_DATA_LIMIT); + assert_eq!(limits.tx_runtime_limits.tx_data_size_limit, crate::constants::TX_DATA_LIMIT); + assert_eq!(limits.tx_runtime_limits.frame_data_size_limit, u64::MAX); + assert_eq!(limits.tx_gas_limit, u64::MAX); + assert_eq!(limits.block_execution_gas_limit, u64::MAX); + + let unlimited = BlockLimits::no_limits(); + assert_eq!(unlimited.block_txs_data_limit, u64::MAX); + assert_eq!(unlimited.tx_runtime_limits.tx_data_size_limit, u64::MAX); + } + 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) } diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 2437f48b5..f3644b23e 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -13,8 +13,8 @@ //! | [`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) | the block's default transaction limits | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the block's default data-size limit | //! //! 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 diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 2595d497e..0ed52a43e 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -152,6 +152,35 @@ fn test_block_no_state_commit_on_limit_exceeded() { assert!(result.receipts().is_empty()); } +/// A deposit counts towards the block's data size. It is packed when it crosses, and the next +/// transaction is refused. Its data-availability size stays exempt. +#[test] +fn test_a_deposit_counts_towards_the_block_data_size_limit() { + let limit = mega_evm::TX_BODY_SIZE - 1; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(limit)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&common::deposit_tx(Bytes::new(), 100_000)) + .expect("the deposit that crosses the data-size limit is packed"); + assert_eq!(executor.limiter().usage.data_size, mega_evm::TX_BODY_SIZE); + assert_eq!( + executor.limiter().block_da_size_used, + 0, + "the deposit adds no data-availability size" + ); + + let err = executor.execute_transaction(&user_tx(0, 100_000)).expect_err("the block is full"); + assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "the transaction after the crossing never ran"); +} + /// With no size limit configured, a transaction of any size is admitted. #[test] fn test_block_tx_size_limit_default_unlimited() { From 660d00b0e9290928b9d8ebdcd34e55ab980e831d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:57:09 +0900 Subject: [PATCH 045/458] test(limit): pin each data-size site's bytes and the byte that crosses Calldata, a log, a storage write and an account write each record their own count, and one byte over stops on that site. An applied authorization's record is the same, and the oracle hint and deployed code already were. --- crates/mega-evm/tests/satin/data_size.rs | 132 +++++++++++++++++++ crates/mega-evm/tests/satin/write_records.rs | 17 ++- 2 files changed, 146 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 85a9d7ac0..f34191c91 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -433,3 +433,135 @@ fn test_a_reverting_creation_does_not_count_its_output() { LimitUsage { data_size: mega_evm::TX_BODY_SIZE + init.len() as u64, write_records: 0 }, ); } + +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, + }) + ); +} + +/// Calldata is in the body. One byte over that count stops the transaction before the callee +/// runs, so a store the callee would have made is not part of the crossing figure. +#[test] +fn test_calldata_one_byte_over_stops_before_the_callee() { + let data = Bytes::from(vec![0xab; 50]); + let body = mega_evm::TX_BODY_SIZE + data.len() as u64; + let db = || { + funded().account_code( + A, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ) + }; + + let fits = run_at(db(), call_with_data(CALLER, A, data.clone(), GAS_LIMIT), body + 40); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage, LimitUsage { data_size: body + 40, write_records: 1 }); + + let over = run_at(db(), call_with_data(CALLER, A, data, GAS_LIMIT), body - 1); + assert_stopped(&over, body - 1, body); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert!(over.result.logs().is_empty()); + assert!(over.state.get(&A).is_none_or(|account| { + account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) + })); +} + +/// 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. One byte over that stops on the record, +/// 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 fits = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + record + 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 + record + record, write_records: 2 }); + + let over = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + record - 1); + assert_stopped(&over, body + record - 1, body + record); + 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()) + })); +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index c4edbd884..8033e1e49 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -16,7 +16,8 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, test_utils::{BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, StagedRecord, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, StagedRecord, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -686,9 +687,19 @@ fn test_authorities_crossing_the_cap_are_not_applied() { assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); assert_eq!(at_the_cap.usage, with_extra(records(1), tuple)); - let outcome = with_cap(TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE - 1); + let limit = TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE - 1; + let outcome = with_cap(limit); assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); - assert!(outcome.limit_exceeded.is_some()); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + 1, + frame_local: false, + }), + "the authority record is the byte that crosses, and nothing after it is counted" + ); let authority = outcome.state.get(&AUTHORITY_1); assert!( authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), From 4f98c8b849979f67d49fdb33fd4c931963f1c502 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:57:57 +0900 Subject: [PATCH 046/458] test(satin): count the history bytes on the edge paths, below and above the cap --- crates/mega-evm/src/limit/limit.rs | 34 ++ crates/mega-evm/tests/satin/history_bytes.rs | 472 ++++++++++++++++-- .../mega-evm/tests/satin/history_exemption.rs | 54 +- crates/mega-evm/tests/satin/history_gas.rs | 21 +- 4 files changed, 534 insertions(+), 47 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 3bd6f7fb4..d7f3f499e 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -665,6 +665,40 @@ mod tests { ); } + /// A frame answered without running — by the depth guard, the latch, 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. The latch'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 mut result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); + assert_eq!(limit.on_frame_return(&mut 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 mut result = + crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); + limit.on_last_frame_return(&mut 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. diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 42d4f8499..87cc8879c 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -9,17 +9,32 @@ //! 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_primitives::{address, Address, Bytes, U256}; +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, TX_GAS_LIMIT_CAP}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, LOG_BASE_SIZE, LOG_TOPIC_SIZE, - STORAGE_CALL_STIPEND_BYTES, TX_BODY_SIZE, WRITE_RECORD_SIZE, + constants::{COST_PER_HISTORY_BYTE, MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + test_utils::{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, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, LOG0, POP, PUSH0, PUSH1, RETURN, REVERT}, + 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, Gas, InstructionResult, + interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, InterpreterResult, }, Inspector, @@ -114,6 +129,26 @@ fn assert_reservoir_paid(name: &str, gas_limit: u64, outcome: &MegaTransactionOu ); } +/// 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) +} + /// With no allowance anywhere, the bytes a transaction reports are its history gas at the price, /// at every site that appends history and on every path that takes it back. #[test] @@ -207,19 +242,8 @@ fn test_without_an_allowance_the_bytes_are_the_history_gas_at_the_price() { ), ( "every site at once", - || { - 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) - }, - |gas| call_with_data(CALLER, CALLEE, Bytes::from(vec![1; 10]), gas), + every_site, + every_site_called, // 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. @@ -247,6 +271,42 @@ fn test_without_an_allowance_the_bytes_are_the_history_gas_at_the_price() { } } +/// 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] @@ -275,6 +335,10 @@ fn test_a_transaction_that_cannot_pay_its_first_record_reports_its_body_alone() /// 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 { @@ -287,7 +351,7 @@ impl Inspector, EthInterpreter> for AnswersCreations InterpreterResult::new( InstructionResult::Return, Bytes::from(vec![0xfe; 32]), - Gas::new(inputs.gas_limit()), + untouched_create_gas(inputs), ), Some(CHILD), )) @@ -302,16 +366,362 @@ fn test_a_creation_answered_without_running_appends_no_code() { if runs_at_measurement_prices() { return; } - 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_LIMITS[0])) - .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 alone"); - assert_eq!(outcome.gas.history, TX_BODY_SIZE * CPHB); + 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. +fn limited_to(bytes: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) +} + +/// The paths the first table does not take — what the body carries beside calldata, the +/// accounts a `SELFDESTRUCT` and an authorization write, a frame answered without running, a code +/// deposit that fails, a slot written back from another frame — each with its exact byte count +/// and, without an allowance on any of them, the history gas at the price. +#[test] +fn test_the_bytes_on_the_edge_paths_are_the_history_gas_at_the_price() { + if runs_at_measurement_prices() { + return; + } + type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, u64, u64); + let cases: [Case; 19] = [ + ( + "an access list: twenty bytes an address and thirty-two a key", + || callee_running(BytecodeBuilder::default()), + |gas| with_access_list(&[(CALLEE, 2), (PAYEE, 1), (FRESH, 0)], gas), + u64::MAX, + TX_BODY_SIZE + 3 * ACCESS_LIST_ADDRESS_SIZE + 3 * ACCESS_LIST_SLOT_SIZE, + ), + ( + "authorizations: each in the body, and a record for the one authority applied", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(AUTHORITY, 0), (OTHER_AUTHORITY, 7)], gas), + u64::MAX, + TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, + ), + ( + "an authority applied twice is one record", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(AUTHORITY, 0), (AUTHORITY, 1)], gas), + u64::MAX, + TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, + ), + ( + "the sender's own authorization: in the body, and no record beside it", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(CALLER, 1)], gas), + u64::MAX, + TX_BODY_SIZE + AUTHORIZATION_SIZE, + ), + ( + "a SELFDESTRUCT that moves a balance to another account records it", + || funded().account_code(CALLEE, destructs_to(PAYEE)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a SELFDESTRUCT that moves a balance to an account it creates records it", + || funded().account_code(CALLEE, destructs_to(FRESH)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "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), + u64::MAX, + TX_BODY_SIZE, + ), + ( + "a SELFDESTRUCT that moves nothing records nothing", + || funded().account_code(RECEIVER, destructs_to(PAYEE)), + |gas| call(CALLER, RECEIVER, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE, + ), + ( + "a call an interceptor answers runs no frame, and its caller's write is kept", + || { + 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), + u64::MAX, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a value call an interceptor refuses keeps none of the records its caller paid for", + || beside_access_control(asks_access_control(BytecodeBuilder::default(), 1)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE, + ), + ( + "a limit stops the transaction before its first frame: the recipient is not written", + funded, + |gas| call(CALLER, FRESH, U256::from(1), gas), + WRITE_RECORD_SIZE - 1, + TX_BODY_SIZE, + ), + ( + "a limit stops a value call before its frame is built: nothing the transaction wrote \ + is kept", + || { + 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), + 2 * WRITE_RECORD_SIZE - 1, + TX_BODY_SIZE, + ), + ( + "a limit crossed by a child's write: nothing the transaction wrote or logged 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), + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1, + TX_BODY_SIZE, + ), + ( + "a nested creation whose code EIP-3541 refuses: the creator's nonce outlives it, and \ + nothing is deposited", + || callee_running(creating(BytecodeBuilder::default(), &refused_code())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a nested creation whose code is past the size limit: the same", + || callee_running(creating(BytecodeBuilder::default(), &oversized_code())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + u64::MAX, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + ), + ( + "a creation transaction whose code EIP-3541 refuses: its body and init code alone", + funded, + |gas| create(CALLER, refused_code(), gas), + u64::MAX, + TX_BODY_SIZE + refused_code().len() as u64, + ), + ( + "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), + u64::MAX, + TX_BODY_SIZE, + ), + ( + "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), + u64::MAX, + TX_BODY_SIZE, + ), + ( + "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), + u64::MAX, + TX_BODY_SIZE, + ), + ]; + + for (name, db, tx, limit, bytes) in cases { + for gas_limit in GAS_LIMITS { + let outcome = MegaEvm::new(context(db()).with_tx_runtime_limits(limited_to(limit))) + .execute_transaction(tx(gas_limit)) + .expect("the transaction is valid"); + assert_eq!( + outcome.limit_exceeded.is_some(), + limit != u64::MAX, + "{name} at {gas_limit}: {:?}", + outcome.result, + ); + assert_eq!(outcome.gas.history_bytes, bytes, "{name} at {gas_limit}: the bytes"); + 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); + } + } +} + +/// 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 ---------- */ diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index d828b2eb9..ae4a43d35 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -14,6 +14,7 @@ use alloy_evm::Evm; 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, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, MegaEvm, MegaTransaction, @@ -196,27 +197,52 @@ fn test_a_system_call_pays_no_history_gas() { /// 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; } - let gas = |tx: MegaTransaction| { - MegaEvm::new(context(db())).execute_transaction(tx).expect("the transaction is valid").gas - }; + const RESERVOIR: u64 = 100_000_000; + for gas_limit in [GAS_LIMIT, TX_GAS_LIMIT_CAP + RESERVOIR] { + let gas = |mut tx: MegaTransaction| { + tx.0.base.gas_limit = gas_limit; + let gas = MegaEvm::new(context(db())) + .execute_transaction(tx) + .expect("the transaction is valid") + .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", + ); + } + gas + }; - let paying = gas(call_from(CALLER, CONTRACT)); - assert!(paying.history_bytes > 0); - assert_eq!( - paying.history, - paying.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, - "the control pays for every byte it reports", - ); + let paying = gas(call_from(CALLER, CONTRACT)); + 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 = gas(deposit(call_from(CALLER, CONTRACT))); - assert_eq!((deposit.history, deposit.history_bytes), (0, 0), "a deposit"); - let system = gas(call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS)); - assert_eq!((system.history, system.history_bytes), (0, 0), "a system transaction"); + let deposit = gas(deposit(call_from(CALLER, CONTRACT))); + 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 = gas(call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS)); + 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()) diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 8642ea64c..3ce1eca47 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -5,7 +5,7 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}, + 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, @@ -343,15 +343,32 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { /// 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] { + 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, From bf092675f61118a845b7bf1d5d1cbe8b9d1e7598 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:58:53 +0900 Subject: [PATCH 047/458] test(satin): hold every compute outcome to the ledger and reservoir identities --- crates/mega-evm/tests/satin/compute_gas.rs | 27 ++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index 8f41423fb..dbcf3de9b 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -8,7 +8,9 @@ //! 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. +//! 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; @@ -325,6 +327,7 @@ fn test_a_refund_does_not_lower_the_compute_figure() { ); 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 { @@ -348,7 +351,9 @@ fn test_state_gas_stays_off_the_compute_figure_whatever_it_costs() { 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); - crate::salt::run(db, envs, call(CALLER, CALLEE, U256::ZERO, gas_limit)).gas + 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 { @@ -384,6 +389,7 @@ fn with_child(rounds: usize, reverts: bool, gas_limit: u64) -> MegaGasUsage { 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 } @@ -419,6 +425,8 @@ fn test_each_transaction_computes_its_own() { 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); } } @@ -456,13 +464,19 @@ fn past_the_cap() -> Bytes { /// 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| { - execute( + 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); @@ -509,6 +523,8 @@ 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. +/// +/// 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() @@ -523,6 +539,7 @@ fn test_a_nested_call_cannot_compute_past_the_cap() { 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, @@ -562,6 +579,7 @@ fn test_intrinsic_gas_past_the_execution_cap_is_rejected_before_it_runs() { let admitted = execute(funded(), with_addresses(83_327)); 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 + 2_400 * 83_327); assert_eq!( rejection(with_addresses(83_328)), @@ -671,6 +689,7 @@ fn test_a_precompile_in_a_nested_call_is_computed() { .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) From ec5de534bc8819290f1f45f3e560cab30c92eb56 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:00:52 +0900 Subject: [PATCH 048/458] test(satin): admit a transaction whose state gas comes back to zero after the crossing --- crates/mega-evm/tests/block/state_gas.rs | 133 ++++++++++++++++++++++- 1 file changed, 130 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index bff03ec1f..3360ba0d0 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -3,15 +3,19 @@ use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; use alloy_evm::{block::BlockExecutor, Evm as _}; +use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, test_utils::BytecodeBuilder, BlockLimits, MegaTxEnvelope, + constants::TX_GAS_LIMIT_CAP, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, + BlockLimits, MegaContext, MegaEvm, MegaSpecId, MegaTxEnvelope, }; use revm::{ bytecode::opcode::{CALLDATALOAD, PUSH0, SSTORE}, - context::BlockEnv, + context::{BlockEnv, TxEnv}, database::State, - Database, + interpreter::{interpreter::EthInterpreter, Interpreter}, + Database, Inspector, }; use crate::common::{self, executor, CALLER, CHAIN_ID, CONTRACT}; @@ -23,6 +27,12 @@ const CALLER3: Address = address!("0x2000000000000000000000000000000000000033"); /// An account with no code: a call to it adds no state gas. const EMPTY: Address = address!("0x3000000000000000000000000000000000000003"); +/// Runs [`slot_toggler`]. +const TOGGLER: Address = address!("0x1000000000000000000000000000000000000004"); + +/// Runs [`reverting_slot_writer`]. +const REVERTER: Address = address!("0x1000000000000000000000000000000000000005"); + /// Below the execution cap, where the reservoir is empty and state gas spills onto regular gas. const GAS_LIMIT: u64 = 1_000_000; @@ -40,9 +50,39 @@ fn slot_writer() -> Bytes { .build() } +/// Code that fills the slot the first calldata word names and empties it again: the first +/// `SSTORE` charges the slot's state gas, and the second gives it back. +fn slot_toggler() -> Bytes { + BytecodeBuilder::default() + .push_number(1_u8) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .append(PUSH0) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build() +} + +/// Code that fills the slot the first calldata word names and reverts: the frame's failure rolls +/// the slot's state gas back. +fn reverting_slot_writer() -> Bytes { + BytecodeBuilder::default() + .push_number(1_u8) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .revert() + .build() +} + fn state() -> State { let mut db = common::database(); db.set_account_code(CONTRACT, slot_writer()); + db.set_account_code(TOGGLER, slot_toggler()); + db.set_account_code(REVERTER, reverting_slot_writer()); for caller in [CALLER2, CALLER3] { db.set_account_balance(caller, U256::from(1_000_000_000_000_000_u64)); } @@ -201,6 +241,93 @@ fn test_the_state_gas_limit_is_checked_again_at_commit() { assert_eq!(result.gas.state, slot); } +/// Reads the transaction's own frame's state gas after every instruction it runs, and keeps the +/// most it rose above where the frame started. +#[derive(Default)] +struct PeakStateGas { + start: Option, + peak: i64, +} + +impl Inspector for PeakStateGas { + fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + self.start.get_or_insert(interp.gas.state_gas_spent()); + } + + fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + let start = self.start.expect("a step starts before it ends"); + self.peak = self.peak.max(interp.gas.state_gas_spent() - start); + } +} + +/// The state gas a call from [`CALLER2`] to `to` carrying `input` draws partway through, on an EVM +/// of its own: the most its frame's state gas rose while it ran. The transaction ends with none. +fn state_gas_drawn_partway(to: Address, input: Bytes) -> u64 { + let ctx = MegaContext::new(state(), MegaSpecId::SATIN) + .with_block(BlockEnv { gas_limit: GAS_LIMIT, ..Default::default() }) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(PeakStateGas::default()); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER2, + kind: TxKind::Call(to), + data: input, + gas_limit: GAS_LIMIT, + ..Default::default() + })); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert_eq!(outcome.gas.state, 0, "it ends with no state gas"); + u64::try_from(evm.inspector().peak).expect("state gas does not fall below where it started") +} + +/// A transaction whose state gas rises while it runs and comes back to zero before it ends adds +/// none: after the block reached its limit it still fits, whether a write-back gave the slot's +/// state gas back or its frame's failure rolled it back. The limit reads the state gas a +/// transaction ends with, not what it drew on the way. Below the execution cap and above it. +#[test] +fn test_a_transaction_whose_state_gas_comes_back_to_zero_still_fits() { + let slot = one_slot(); + let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); + assert_eq!(state_gas_drawn_partway(TOGGLER, slot_word(7)), slot, "the write-back's"); + assert_eq!(state_gas_drawn_partway(REVERTER, slot_word(8)), slot, "the reverted write's"); + + for gas_limit in [GAS_LIMIT, ABOVE_CAP] { + 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::block_ctx(limits(slot)), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&writes(0, 1, gas_limit)).expect("the block has room"); + executor.execute_transaction(&writes(1, 2, gas_limit)).expect("the crossing is packed"); + assert_eq!(executor.gas().state, 2 * slot, "the block has reached its limit"); + + for (caller, to, slot_index) in [(CALLER2, TOGGLER, 7), (CALLER3, REVERTER, 8)] { + let outcome = executor + .run_transaction(&tx_from(caller, 0, to, slot_word(slot_index), gas_limit)) + .expect("a transaction that ends with no state gas fits"); + assert_eq!(outcome.gas.state, 0, "{to} at {gas_limit}"); + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + outcome.gas.reservoir_remaining, + gas_limit - TX_GAS_LIMIT_CAP - outcome.gas.history, + "{to} at {gas_limit}: what the reservoir paid for the slot came back to it", + ); + } + executor.commit_transaction_outcome(outcome).expect("and it commits"); + } + + let err = executor + .execute_transaction(&writes(2, 3, gas_limit)) + .expect_err("one that ends with state gas is still refused"); + assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 4); + assert_eq!(result.gas.state, 2 * slot); + } +} + /// 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 above From ba7ea1adb4a1922e070cfd1602d764c5c327e8d7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:01:07 +0900 Subject: [PATCH 049/458] test(satin): count the compute-tracking row as ported rather than retired --- crates/mega-evm/tests/_pending/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e85eba785..b3e3cf073 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -233,23 +233,23 @@ These 29 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by compute gas -These 23 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles, so the counts above are lower than the inventory's by exactly these rows. +These 24 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles, 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` | compute gas (2) | 2 | `tests/satin/compute_gas.rs` | | `compute_gas/main.rs` | compute gas (1) | 1 | `tests/satin/compute_gas.rs` | -| `mini_rex/compute_gas_limit.rs` | compute gas (20) | 20 | `tests/satin/compute_gas.rs` | -| **Total** | | **23** | | +| `mini_rex/compute_gas_limit.rs` | compute gas (21) | 21 | `tests/satin/compute_gas.rs` | +| **Total** | | **24** | | ## Tests retired after the inventory -These 22 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 21 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 | |---|---|---:|---| -| `mini_rex/compute_gas_limit.rs` | compute gas (3) | 3 | it pins that one legacy spec counts compute gas where the spec below it does not. Satin is a single spec and every transaction reports its compute figure, so there is no boundary left for it to pin; Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | +| `mini_rex/compute_gas_limit.rs` | compute gas (2) | 2 | Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | | `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 | @@ -258,7 +258,7 @@ They are not counted above. | `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | -| **Total** | | **22** | | +| **Total** | | **21** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism From 9325c3b0fcc410ad0c5680f9e47dfaef8e0c44cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:02:00 +0900 Subject: [PATCH 050/458] docs(satin): say the history byte column counts the bytes the schedule prices --- AGENTS.md | 1 + crates/mega-evm/README.md | 1 + crates/mega-evm/src/block/result.rs | 5 +++++ crates/mega-evm/src/evm/result.rs | 13 +++++++++++-- crates/mega-evm/src/limit/limit.rs | 6 ++++-- 5 files changed, 22 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 58743d21a..2c5bd5a13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,6 +201,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 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. `gas_used` is the receipt's figure; `BlockGasCounters` sums the three ledgers and the history bytes per block. ## Test Organization (`crates/mega-evm/tests/`) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 1c9b00825..b9f01a950 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -75,6 +75,7 @@ An Oracle hint's payload is data size that is never history, because the bytes g 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 byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, and a body counts its five fixed write records even when fewer fee accounts are written. The resource limits, gas detention and keyless deployment arrive in later changes. diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 400555d8f..6de4c366e 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -30,6 +30,11 @@ pub struct BlockGasCounters { /// The history bytes the block's transactions appended, whoever paid for them. At the cost per /// history byte they are worth [`history`](Self::history) plus what the history allowances of /// value transfers paid, which no gas ledger carries. + /// + /// They are the history bytes the schedule prices, not the chain's physical growth: the + /// block's exempt transactions (its deposits, the transactions the protocol sent) add none, + /// and each body counts its five fixed write records even when fewer fee accounts are + /// written. pub history_bytes: u64, } diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 35e66f5b0..0e768f213 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -18,6 +18,10 @@ //! 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, and a body counts +//! its five fixed write records even when fewer fee accounts are written. use revm::context::result::{ResultAndState, ResultGas}; @@ -73,8 +77,13 @@ pub struct MegaGasUsage { /// record per account or storage write it kept, the logs it kept and the code it deposited. /// /// 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. A transaction - /// exempt from history gas reports none. + /// 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, diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d7f3f499e..9971f6938 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -185,8 +185,10 @@ impl AdditionalLimit { /// Every one of them is priced at the cost per history byte, and /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of /// that price. The two part by what the history allowances of its value transfers paid, which - /// no gas ledger carries. A transaction exempt from history gas appended none that anybody - /// priced, and reports none. + /// no gas ledger carries. They are the bytes the schedule prices, not the chain's physical + /// growth: a transaction exempt from history gas appended none that anybody priced, and + /// reports none, and the body counts its fixed write records whichever fee accounts are + /// written. pub const fn history_bytes(&self) -> u64 { self.history_bytes } From 480320111a4868003c99ee32fca59bb52fa8c747 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:02:00 +0900 Subject: [PATCH 051/458] docs(satin): describe the deposit exemption and the two commit paths --- AGENTS.md | 3 +++ crates/mega-evm/README.md | 2 ++ 2 files changed, 5 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 2c5bd5a13..f03e0f261 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,6 +140,9 @@ 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`. A block limit known only after execution packs the transaction that reaches it: the execution-gas limit then refuses every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. + Neither refuses a deposit: both are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards both, so the transactions after it find the room it used. + 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`. + Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. Four of the six system contracts answer calls through their interceptors (`system/`). diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index b9f01a950..aa6e47323 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -43,6 +43,8 @@ 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 and the history bytes they appended. 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. A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. +Neither that cap nor the execution-gas cap refuses a deposit, which the block must include; a deposit still counts towards both. +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` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, hands each pre-block state (the two EIP calls and the seven deploys) to an optional observer before it commits — that sequence is the witness a stateless client needs — and leaves one hook point empty: the pre-block system calls. 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. From ed1127aee97b4c85acae0d454dfd81c281b8c40e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:02:50 +0900 Subject: [PATCH 052/458] fix(limit): report a data-size stop ahead of a rejected record's history 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 it accepts still pays that history, and a charge the frame cannot pay is an out-of-gas. A fresh slot is counted at gas 162,306; keeping it costs the record's 3,520 history gas on top. 62,325 was a prototype figure, not this threshold. --- crates/mega-evm/src/evm/instructions.rs | 10 +- crates/mega-evm/tests/satin/data_size.rs | 112 ++++++++++++++++++++++- 2 files changed, 116 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 1da4b8c2d..9cf750ad8 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -104,6 +104,10 @@ pub(crate) fn mega_instructions( /// 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 data-size check is made before the history charge. 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>, @@ -121,12 +125,12 @@ fn commit_after(interpreter, host, history)?; - } if check.exceeded_limit() { return Err(stop_frame(interpreter, &check)); } + if host.prices_history() { + settle_history::(interpreter, host, history)?; + } result } diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index f34191c91..3687be7fc 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -12,12 +12,13 @@ use alloy_primitives::{address, keccak256, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, - MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, - WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, + MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, REVERT, STOP}, + context::result::{ExecutionResult, HaltReason}, interpreter::{ interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, Interpreter, }, @@ -565,3 +566,108 @@ fn test_an_account_write_one_byte_over_stops_on_the_recipient() { account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) })); } + +/// What one gas limit did with the fresh-slot write. +enum Bound { + /// The gas limit did not cover the intrinsic cost, so the transaction was not included. + Rejected, + /// The write ran out of gas before its record was counted. + OutOfGas, + /// The write completed, and the data-size stop is what the transaction reports. + DataSize, + /// The write completed inside the data-size limit. + Success, +} + +fn fresh_slot() -> Bytes { + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build() +} + +fn bound_at(gas_limit: u64, data_limit: u64) -> Bound { + let db = funded().account_code(A, fresh_slot()); + 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 { .. } => { + assert_eq!(outcome.limit_exceeded, None); + Bound::Success + } + }, + } +} + +/// The smallest gas limit at which the fresh slot's write completes. +fn gas_where_the_write_completes(data_limit: u64) -> u64 { + let mut low = 0_u64; + let mut high = 1_000_000_u64; + assert!( + !matches!(bound_at(high, data_limit), Bound::Rejected | Bound::OutOfGas), + "the high bound must reach the write" + ); + while low + 1 < high { + let middle = low + (high - low) / 2; + if matches!(bound_at(middle, data_limit), Bound::Rejected | Bound::OutOfGas) { + low = middle; + } else { + high = middle; + } + } + high +} + +/// Gas limit at which a top-level fresh `SSTORE` completes and its record is counted. +/// +/// The sweep measures it at the spec's byte prices. Below it the transaction halts out of gas +/// and the record is not counted. The legacy engine quoted 62,325 for a prototype of this +/// boundary; that figure is not this threshold. +const FRESH_SLOT_COUNTED_AT: u64 = 162_306; + +/// A fresh slot's write meets two limits, and the one that binds first is the one reported. +/// +/// The `SSTORE` has to finish before its record exists. Below [`FRESH_SLOT_COUNTED_AT`] that is +/// an out-of-gas, and the record is not counted. At that gas the record is counted: a data-size +/// limit it crosses stops the transaction, and the record's history is not charged because the +/// record is not kept. A limit the record fits costs that history on top — one write record at +/// the cost per history byte — and the write succeeds only once the history is paid. Short of +/// it, the same write halts out of gas. +#[test] +fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { + // The write is 40 bytes on top of the body. One byte under that, the write itself crosses. + let crosses = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE - 1; + let fits = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE; + let counted_at = gas_where_the_write_completes(crosses); + let kept_at = gas_where_the_write_completes(fits); + let record_history = mega_evm::write_record_history_gas(1).expect("one record has a price"); + + assert_eq!(kept_at - counted_at, record_history, "a kept record costs its history and no more"); + assert!(matches!(bound_at(counted_at - 1, crosses), Bound::OutOfGas)); + assert!(matches!(bound_at(counted_at, crosses), Bound::DataSize)); + assert!(matches!(bound_at(kept_at, crosses), Bound::DataSize)); + assert!(matches!(bound_at(counted_at, fits), Bound::OutOfGas)); + assert!(matches!(bound_at(kept_at - 1, fits), Bound::OutOfGas)); + assert!(matches!(bound_at(kept_at, fits), Bound::Success)); + + if crate::common::runs_at_measurement_prices() { + return; + } + assert_eq!(counted_at, FRESH_SLOT_COUNTED_AT); + assert_eq!(record_history, WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE); +} From 1c56aa2c6b76bd22837446bdb43271032c7f98b5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:03:34 +0900 Subject: [PATCH 053/458] test(satin): read the probe's starting state gas lazily --- crates/mega-evm/tests/block/state_gas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index 3360ba0d0..da15d6a83 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -251,7 +251,7 @@ struct PeakStateGas { impl Inspector for PeakStateGas { fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { - self.start.get_or_insert(interp.gas.state_gas_spent()); + self.start.get_or_insert_with(|| interp.gas.state_gas_spent()); } fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { From 6fd075cb97a2840fbe783b3f2cfe1e9fd73ebed5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:02:45 -0700 Subject: [PATCH 054/458] fix(limit): never refuse a deposit on the block's data size The block's data-size limit is a packing budget for the transactions the builder chooses, and a deposit is not chosen. A deposit still counts towards the block's data size, so the transactions after it find the room it used. The per-transaction data-size limit still stops a deposit's own execution, and the deposit is included with the stop as its result. --- crates/mega-evm/src/block/limit.rs | 62 +++++++++++++++++--- crates/mega-evm/tests/block/limits.rs | 81 ++++++++++++++++++++++----- 2 files changed, 121 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 48dc3caba..b9b5e4117 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -16,8 +16,21 @@ //! 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. +//! already done. A block whose counter has crossed refuses every later transaction — a deposit +//! excepted, for the data-size bytes — so the overshoot is bounded by one transaction per +//! dimension, 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 a deposit is exempt from both data-availability limits +//! and does not count towards the block's. The block's data-size limit is a packing budget for the +//! transactions the builder chooses, so it never refuses a deposit either. A deposit still counts +//! towards the block's data size, so the transactions after it find the room it used. +//! +//! The per-transaction data-size limit is not a block limit: it holds a deposit's own execution +//! the way it holds any transaction's, and a deposit that crosses it is included with the stop as +//! its result. //! //! # Which dimensions are enforced //! @@ -66,8 +79,9 @@ pub struct BlockLimits { pub block_execution_gas_limit: u64, /// The most data-size bytes the block's transactions may keep together. /// - /// [`Default`] is [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT). A deposit counts - /// towards it: the data-availability exemption does not extend here. + /// [`Default`] is [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT). The transaction + /// that reaches it is packed; after it, only a deposit is, which it never refuses and which + /// counts towards it. pub block_txs_data_limit: u64, /// The limits every transaction of the block runs under, which the executor installs on the /// EVM. @@ -197,7 +211,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 the + /// block's data-size limit never refuses. pub is_deposit: bool, } @@ -251,7 +266,8 @@ impl BlockLimiter { /// Whether `tx` may execute in this block. /// - /// Checks the transaction against its own limits, and against what the block has left. It + /// Checks the transaction against its own limits, and against what the block has left; a + /// deposit is held to neither data-availability limit nor to the block's data-size limit. It /// reads the counters and changes nothing; /// [`post_execution_update`](Self::post_execution_update) advances them once the /// transaction commits. @@ -347,9 +363,10 @@ impl BlockLimiter { )); } - // Every committed transaction counts, a deposit included. The transaction that crossed - // is already packed; this refuses the next one. - if self.usage.data_size >= self.limits.block_txs_data_limit { + // Every committed transaction counts, a deposit included, in `post_execution_update`. The + // transaction that crossed is already packed, so what is refused here is the next one — + // never a deposit, which is not the builder's to refuse. + if !is_deposit && self.usage.data_size >= self.limits.block_txs_data_limit { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::TransactionDataLimit { @@ -532,6 +549,33 @@ mod tests { assert!(std::format!("{err}").contains("Block execution gas limit reached"), "{err}"); } + /// 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_data_size_limit_never_refuses_a_deposit_and_counts_it() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_txs_data_limit(1_000)); + let deposit = BlockUsage { + usage: LimitUsage { data_size: 600, write_records: 0 }, + is_deposit: true, + ..Default::default() + }; + + // 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"); + + let err = limiter + .pre_execution_check(B256::ZERO, 0, 0, 0, false) + .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 /// what the block has left of it — is admitted, and one unit more is refused. #[test] diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 0ed52a43e..9ca496953 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -4,14 +4,15 @@ 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, + test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, EvmTxRuntimeLimits, LimitCheck, + LimitKind, 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}, + context::{result::ExecutionResult, BlockEnv, ContextTr}, Database as _, }; @@ -152,11 +153,16 @@ fn test_block_no_state_commit_on_limit_exceeded() { assert!(result.receipts().is_empty()); } -/// A deposit counts towards the block's data size. It is packed when it crosses, and the next -/// transaction is refused. Its data-availability size stays exempt. +/// The block's data-size limit never refuses a deposit, and a deposit still counts towards it. +/// +/// Two data-heavy deposits cross the limit between them, a third finds the block past it and is +/// still included, and the ordinary transaction after them is refused on the room they used. The +/// deposits add nothing to the data-availability size. #[test] -fn test_a_deposit_counts_towards_the_block_data_size_limit() { - let limit = mega_evm::TX_BODY_SIZE - 1; +fn test_the_block_data_size_limit_never_refuses_a_deposit() { + const CALLDATA: usize = 1_000; + let per_deposit = mega_evm::TX_BODY_SIZE + CALLDATA as u64; + let limit = per_deposit + per_deposit / 2; let mut state = common::state(); let mut executor = executor( &mut state, @@ -164,21 +170,70 @@ fn test_a_deposit_counts_towards_the_block_data_size_limit() { ); executor.apply_pre_execution_changes().expect("the block starts"); - executor - .execute_transaction(&common::deposit_tx(Bytes::new(), 100_000)) - .expect("the deposit that crosses the data-size limit is packed"); - assert_eq!(executor.limiter().usage.data_size, mega_evm::TX_BODY_SIZE); + for (n, what) in ["the first deposit", "the deposit that crosses", "the deposit past the limit"] + .into_iter() + .enumerate() + { + let deposit = common::deposit_tx(incompressible(CALLDATA), 1_000_000); + let outcome = + executor.run_transaction(&deposit).unwrap_or_else(|err| panic!("{what}: {err}")); + assert!(outcome.inner.result.is_success(), "{what}: {:?}", outcome.inner.result); + assert_eq!(outcome.inner.usage.data_size, per_deposit, "{what}"); + executor.commit_transaction_outcome(outcome).unwrap_or_else(|err| panic!("{what}: {err}")); + assert_eq!(executor.limiter().usage.data_size, per_deposit * (n as u64 + 1), "{what}"); + } + assert!(executor.limiter().usage.data_size > limit, "the deposits crossed the limit"); assert_eq!( executor.limiter().block_da_size_used, 0, - "the deposit adds no data-availability size" + "a deposit adds no data-availability size" ); - let err = executor.execute_transaction(&user_tx(0, 100_000)).expect_err("the block is full"); + let err = executor + .execute_transaction(&user_tx(3, 100_000)) + .expect_err("the deposits used the room an ordinary transaction would need"); assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); + assert!(format!("{err}").contains(&format!("block_used={}", per_deposit * 3)), "{err}"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1, "the transaction after the crossing never ran"); + assert_eq!(result.receipts().len(), 3, "every deposit is packed, and nothing after them"); +} + +/// The per-transaction data-size limit is not a block limit: it stops a deposit's own execution +/// the way it stops any transaction's, and the deposit is included with the stop as its result. +#[test] +fn test_the_transaction_data_size_limit_stops_a_deposit_that_is_still_included() { + let limit = mega_evm::TX_BODY_SIZE + 10; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + )), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + 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::Revert { .. }), + "{:?}", + outcome.inner.result + ); + let stop = outcome.inner.limit_exceeded.expect("the data-size limit stopped the deposit"); + assert!( + matches!( + stop, + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: l, frame_local: false, .. } + if l == limit + ), + "{stop:?}" + ); + executor.commit_transaction_outcome(outcome).expect("the deposit is included"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); + assert!(!result.receipts()[0].status(), "the stopped deposit's receipt reports a failure"); } /// With no size limit configured, a transaction of any size is admitted. From be1e879040fa41c11b1167999a8e92d32820c8ae Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:13:07 -0700 Subject: [PATCH 055/458] fix(limit): report a body's data-size stop ahead of the runtime phase's out-of-gas A body over the limit latches the transaction before it runs, and its first frame is answered with the stop. Pre-execution then applies no authorization and charges no record made outside a frame, and the first frame's input charges nothing for its start, so a gas limit that could not pay those reports the stop that bound first instead of an out-of-gas. The account a deposit-like transaction creates for its caller is still charged: it exists whatever the transaction does. --- crates/mega-evm/src/evm/execution.rs | 73 ++++++++++- crates/mega-evm/src/limit/limit.rs | 10 +- crates/mega-evm/tests/satin/data_size.rs | 140 ++++++++++++++++++++++ crates/mega-evm/tests/system/system_tx.rs | 29 ++++- 4 files changed, 246 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index f2dc81bcb..bf6483cbd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -12,7 +12,7 @@ use op_revm::{ handler::{IsTxError, OpHandler}, OpHaltReason, OpTransactionError, }; -use std::vec::Vec; +use std::{boxed::Box, vec::Vec}; use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ @@ -37,8 +37,9 @@ use revm::{ InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, - InitialAndFloorGas, InstructionResult, InterpreterAction, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInput, CallInputs, + CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, InitialAndFloorGas, + InstructionResult, InterpreterAction, SharedMemory, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, Inspector, Journal, @@ -109,6 +110,13 @@ where /// 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. + /// + /// A transaction whose body crossed the data-size limit is latched before it runs, and its + /// first frame will be answered with the stop. Nothing after the caller's account is applied + /// or charged for it: the authorizations would be taken back, and the records made outside a + /// frame are records the limit rejects. So no charge made for them can run the transaction + /// out of gas, and the stop that bound first is what it reports. The caller's account is + /// charged all the same, because it exists whatever the transaction does. fn pre_execution( &self, evm: &mut Self::Evm, @@ -120,6 +128,9 @@ where evm.ctx().journal_mut().checkpoint_revert(checkpoint); return Ok(None); } + if evm.ctx_ref().additional_limit.latched().is_some() { + return Ok(Some(PreExecutionOutput { eip7702_refund: 0, checkpoint })); + } let gas_before = *gas; let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { evm.ctx().journal_mut().checkpoint_revert(checkpoint); @@ -207,6 +218,26 @@ where Ok(gas) } + /// revm's first frame, unless the transaction is already latched: then a frame input built on + /// what the transaction has left, with nothing charged for the frame's start. + /// + /// A latched transaction's first frame is answered with the stop before revm builds it, so it + /// makes none of the writes revm's EIP-2780 runtime charges price for its start — a value + /// recipient's new account, a created account — and reaches no delegation target. Charging + /// them would only matter to a gas limit that cannot pay them, which would then report an + /// out-of-gas in place of the stop that bound first. The input carries no charged flag, so + /// the stop's settlement gives nothing back that was not charged. + fn first_frame_input( + &mut self, + evm: &mut Self::Evm, + gas: &mut GasTracker, + ) -> Result, Self::Error> { + if evm.ctx_ref().additional_limit.latched().is_none() { + return self.op.first_frame_input(evm, gas); + } + Ok(Some(unbuilt_first_frame(evm.ctx_ref(), 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 @@ -726,6 +757,42 @@ fn tx_body_history_gas( history_gas(transaction_body_bytes(ctx.tx())).unwrap_or(u64::MAX) } +/// The first frame of a latched transaction: the transaction's call or creation on the gas it +/// has left, for the frame the latch answers with the stop. +/// +/// Nothing is loaded and nothing is charged. The frame is never built, so its code is never read. +fn unbuilt_first_frame( + ctx: &MegaContext, + gas: &GasTracker, +) -> FrameInit { + let tx = ctx.tx(); + let frame_input = match tx.kind() { + TxKind::Call(target_address) => FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(tx.input().clone()), + return_memory_offset: 0..0, + gas_limit: gas.remaining(), + reservoir: gas.reservoir(), + bytecode_address: target_address, + known_bytecode: Default::default(), + target_address, + caller: tx.caller(), + value: CallValue::Transfer(tx.value()), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: false, + })), + TxKind::Create => FrameInput::Create(Box::new(CreateInputs::new( + tx.caller(), + CreateScheme::Create, + tx.value(), + tx.input().clone(), + gas.remaining(), + gas.reservoir(), + ))), + }; + FrameInit { depth: 0, memory: SharedMemory::new(), frame_input } +} + /// 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index a903cc7b7..ebed7c57f 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -556,8 +556,14 @@ impl AdditionalLimit { /// /// 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. The body is not one of - /// those records. It is put back after the reset. + /// records go too, and the halt stays a halt. The body is not one of those records. It is put + /// back after the reset. + /// + /// A latch goes with the reset. Only the body's can be set by then: authorities whose records + /// cross the limit are taken back before anything else is charged, and a latched transaction's + /// runtime phase charges nothing but the account a deposit-like transaction creates for its + /// caller. That account exists whatever the transaction does, so a transaction that cannot pay + /// for it is out of gas with or without a stop, and it reports the halt. pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { if !self.frame_began { let body = self.body_bytes; diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 3687be7fc..919cbf729 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -671,3 +671,143 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { assert_eq!(counted_at, FRESH_SLOT_COUNTED_AT); assert_eq!(record_history, WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE); } + +/* ---------- 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 { + use revm::{ + context::{transaction::TransactionType, TxEnv}, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + let authorization = Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: B, nonce: 0 }, + RecoveredAuthority::Valid(AUTHORITY), + )); + alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: alloy_primitives::TxKind::Call(A), + gas_limit, + gas_priority_fee: Some(0), + authorization_list: vec![authorization], + ..Default::default() + })) +} + +/// 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 the stop at every gas limit validation accepts. +/// +/// A gas limit that covers the intrinsic cost and no more cannot pay what the transaction's start +/// costs past it: the account a value transfer or a creation adds, the write record of it, and an +/// authorization's delegation. Without a limit, each of these transactions runs out of gas there, +/// before its first frame. With the body over the limit none of those writes is made — the first +/// frame is answered with the stop — so none is charged, and the transaction reports the stop that +/// bound first. It pays its intrinsic cost and nothing else. +#[test] +fn test_a_body_over_the_limit_is_the_stop_at_the_smallest_valid_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), + ("an authorization", authorizing_call, mega_evm::AUTHORIZATION_SIZE), + ]; + assert_eq!(constructor_returning(1).len(), 12); + for (name, tx, extra) in cases { + let body = mega_evm::TX_BODY_SIZE + extra; + let limit = body - 1; + 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), limit).is_some()), + valid, + "{name}: the limit does not move validation" + ); + + let unlimited = outcome_at(tx(valid), u64::MAX).unwrap(); + assert!( + matches!( + unlimited.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ), + "{name}: without a limit the start runs out of gas, got {:?}", + unlimited.result + ); + + let stopped = outcome_at(tx(valid), limit).unwrap(); + assert_stopped(&stopped, limit, body); + assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + assert_eq!(stopped.result.gas().tx_gas_used(), valid, "{name}: the intrinsic cost only"); + + // A gas limit above the smallest one pays the same: nothing past the intrinsic cost is + // charged, so nothing is burnt either. + let above = outcome_at(tx(valid + 10_000), limit).unwrap(); + assert_stopped(&above, limit, body); + assert_eq!(above.result.gas().tx_gas_used(), valid, "{name}: the stop burns nothing"); + } +} + +/// A creation transaction stopped at the smallest gas limit validation accepts still bumps its +/// sender's nonce, and an authorization its body carried is not applied. +#[test] +fn test_a_stopped_start_bumps_a_creators_nonce_and_applies_no_authorization() { + let init = constructor_returning(1); + let limit = mega_evm::TX_BODY_SIZE + init.len() as u64 - 1; + let valid = smallest_gas_limit(GAS_LIMIT, |gas| { + outcome_at(create(CALLER, init.clone(), gas), limit).is_some() + }); + let stopped = outcome_at(create(CALLER, init, valid), limit).unwrap(); + assert!(stopped.limit_exceeded.is_some(), "{:?}", stopped.result); + assert_eq!(stopped.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); + assert!(stopped + .state + .get(&CALLER.create(0)) + .is_none_or(|account| account.info.is_empty_code_hash() && account.info.nonce == 0)); + + let limit = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE - 1; + let valid = + smallest_gas_limit(GAS_LIMIT, |gas| outcome_at(authorizing_call(gas), limit).is_some()); + let stopped = outcome_at(authorizing_call(valid), limit).unwrap(); + assert!(stopped.limit_exceeded.is_some(), "{:?}", stopped.result); + assert!( + stopped + .state + .get(&AUTHORITY) + .is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "the delegation was not applied" + ); +} diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 2d7a1409f..8b756fdf5 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -11,7 +11,7 @@ use mega_evm::{ SEQUENCER_REGISTRY_ADDRESS, }, test_utils::{op_transaction, MemoryDatabase}, - MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, }; use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; use revm::{ @@ -536,6 +536,33 @@ fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { ); } +/// The account a deposit creates for its caller exists whatever the deposit does, so a stop the +/// deposit's body latched does not waive its charge: a deposit that cannot pay for it is still an +/// out-of-gas halt, and the halt is not a data-size stop. +#[test] +fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_halts() { + let sender = address!("0x00000000000000000000000000000000000f0008"); + let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); + tx.0.base.gas_limit = 30_000; + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE - 1); + + 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 { .. }), + "{:?} is not a halt", + outcome.result, + ); + assert_eq!(outcome.limit_exceeded, None, "the halt 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. #[test] From 9e8515784c43111aed225c78f0ae1c98ddfabaa2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:14:59 -0700 Subject: [PATCH 056/458] test(limit): derive where the data-size stop gives way to out-of-gas A top-level fresh SSTORE is counted at 162,306 gas: the empty call's 42,280, two pushes, the store's 22,100 regular and 97,920 state gas, all read from the schedule in force. Keeping the record costs its 3,520 history on top, so a crossing limit moves the out-of-gas boundary down by that much. At a frame start the caller pays for the records at its opcode, before they are counted, so there the limit does not move the boundary. --- crates/mega-evm/tests/satin/data_size.rs | 128 ++++++++++++++++------- 1 file changed, 93 insertions(+), 35 deletions(-) diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 919cbf729..ff3cb9112 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -19,6 +19,7 @@ use mega_evm::{ use revm::{ bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, REVERT, STOP}, context::result::{ExecutionResult, HaltReason}, + context_interface::cfg::GasId, interpreter::{ interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, Interpreter, }, @@ -567,24 +568,41 @@ fn test_an_account_write_one_byte_over_stops_on_the_recipient() { })); } -/// What one gas limit did with the fresh-slot write. +/// 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 write ran out of gas before its record was counted. + /// The transaction ran out of gas before the write that approaches the limit was counted. OutOfGas, - /// The write completed, and the data-size stop is what the transaction reports. + /// The write was counted, and the data-size stop is what the transaction reports. DataSize, - /// The write completed inside the data-size limit. + /// 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() } -fn bound_at(gas_limit: u64, data_limit: u64) -> Bound { - let db = funded().account_code(A, fresh_slot()); +/// `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. +fn value_call_to_fresh() -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(FRESH) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build() +} + +/// 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, @@ -614,30 +632,30 @@ fn bound_at(gas_limit: u64, data_limit: u64) -> Bound { } } -/// The smallest gas limit at which the fresh slot's write completes. -fn gas_where_the_write_completes(data_limit: u64) -> u64 { - let mut low = 0_u64; - let mut high = 1_000_000_u64; - assert!( - !matches!(bound_at(high, data_limit), Bound::Rejected | Bound::OutOfGas), - "the high bound must reach the write" - ); - while low + 1 < high { - let middle = low + (high - low) / 2; - if matches!(bound_at(middle, data_limit), Bound::Rejected | Bound::OutOfGas) { - low = middle; - } else { - high = middle; - } - } - high +/// 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(1_000_000, |gas| { + !matches!(bound_at(code, gas, data_limit), Bound::Rejected | Bound::OutOfGas) + }) } -/// Gas limit at which a top-level fresh `SSTORE` completes and its record is counted. +/// 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: /// -/// The sweep measures it at the spec's byte prices. Below it the transaction halts out of gas -/// and the record is not counted. The legacy engine quoted 62,325 for a prototype of this -/// boundary; that figure is not this threshold. +/// | 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,100 cold, 19,900 set | 22,100 | +/// | the `SSTORE`'s state gas: a slot's 64 bytes at 1,530 | 97,920 | +/// | **total** | **162,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 = 162_306; /// A fresh slot's write meets two limits, and the one that binds first is the one reported. @@ -650,28 +668,68 @@ const FRESH_SLOT_COUNTED_AT: u64 = 162_306; /// it, the same write halts out of gas. #[test] fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { + let code = fresh_slot(); // The write is 40 bytes on top of the body. One byte under that, the write itself crosses. let crosses = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE - 1; let fits = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE; - let counted_at = gas_where_the_write_completes(crosses); - let kept_at = gas_where_the_write_completes(fits); + let counted_at = gas_where_the_write_is_counted(&code, crosses); + let kept_at = gas_where_the_write_is_counted(&code, fits); let record_history = mega_evm::write_record_history_gas(1).expect("one record has a price"); assert_eq!(kept_at - counted_at, record_history, "a kept record costs its history and no more"); - assert!(matches!(bound_at(counted_at - 1, crosses), Bound::OutOfGas)); - assert!(matches!(bound_at(counted_at, crosses), Bound::DataSize)); - assert!(matches!(bound_at(kept_at, crosses), Bound::DataSize)); - assert!(matches!(bound_at(counted_at, fits), Bound::OutOfGas)); - assert!(matches!(bound_at(kept_at - 1, fits), Bound::OutOfGas)); - assert!(matches!(bound_at(kept_at, fits), Bound::Success)); + assert!(matches!(bound_at(&code, counted_at - 1, crosses), Bound::OutOfGas)); + assert!(matches!(bound_at(&code, counted_at, crosses), Bound::DataSize)); + assert!(matches!(bound_at(&code, kept_at, crosses), Bound::DataSize)); + assert!(matches!(bound_at(&code, counted_at, fits), Bound::OutOfGas)); + assert!(matches!(bound_at(&code, kept_at - 1, fits), Bound::OutOfGas)); + assert!(matches!(bound_at(&code, kept_at, fits), Bound::Success)); + + // The figure is 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. + 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), (22_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); } +/// 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 cross the limit or fit it, and one gas below it is an out-of-gas under either. +#[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: 80 bytes on top of the body. + let records = 2 * WRITE_RECORD_SIZE; + let crosses = mega_evm::TX_BODY_SIZE + records - 1; + let fits = mega_evm::TX_BODY_SIZE + records; + 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)); +} + /* ---------- a body over the limit, at the smallest gas limit validation accepts ---------- */ /// A fresh account nobody has touched. From 6d3f408c99efe29fdc5887c372b5d67e045e4404 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:23:57 -0700 Subject: [PATCH 057/458] test(limit): port the parked rows the data-size limit owns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forty-seven rows run in the Satin targets now. What each kind of transaction keeps — the body, a write record per account or storage write, a log's bytes and deployed code — is one table in `tests/satin/data_size_counts.rs`, with the logs, the SELFDESTRUCT cases and the reset across transactions beside it. The 98% share is measured in slots down to a grandchild and across a sibling, and a body over the limit is stopped before an interceptor or a creation's frame runs. The legacy priority of data size over compute gas at SELFDESTRUCT becomes the site sweep: the stop is reported ahead of the history its record would cost, at a storage write, a log and a SELFDESTRUCT alike. --- crates/mega-evm/src/limit/frame_limit.rs | 20 + crates/mega-evm/src/limit/mod.rs | 2 + crates/mega-evm/tests/_pending/README.md | 35 +- .../tests/_pending/compute_gas/claims.rs | 101 --- .../mini_rex/tx_data_and_kv_update_limit.rs | 646 ------------------ .../tests/_pending/rex4/frame_limits.rs | 278 -------- .../_pending/rex4/intrinsic_limit_bypass.rs | 341 --------- .../_pending/rex5/selfdestruct_beneficiary.rs | 58 -- .../_pending/rex6/beneficiary_detention.rs | 86 --- .../_pending/rex6/frame_local_accounting.rs | 204 ------ .../rex6/self_transfer_account_dedup.rs | 136 ---- .../tests/_pending/src/limit/data_size.rs | 26 - crates/mega-evm/tests/satin/data_size.rs | 254 ++++++- .../mega-evm/tests/satin/data_size_counts.rs | 368 ++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 15 files changed, 646 insertions(+), 1910 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/data_size.rs create mode 100644 crates/mega-evm/tests/satin/data_size_counts.rs diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 36faf69ef..5fd8a5452 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -301,6 +301,26 @@ 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() { diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index fd882034a..376541d68 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -300,6 +300,8 @@ 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 }); } #[test] diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5cd2b47b9..cda76c491 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,7 +29,6 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 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 | @@ -39,7 +38,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** | **456** | **428** | **28** | **272** | **156** | **28** | +| **Total** | **409** | **383** | **26** | **232** | **149** | **28** | ## Tests ported in place @@ -232,6 +231,23 @@ These 29 rows run in a real test target now, adapted to the Satin API and to the | `src/system/sequencer_registry.rs` | system contract deployment (9) | 9 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | | **Total** | | **29** | | +## Tests ported by the data-size limit + +These 47 rows run in a real test target now, adapted to the Satin API and to the byte table and budget rule 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 data-size limit (1) | 1 | `tests/satin/data_size.rs` | +| `mini_rex/tx_data_and_kv_update_limit.rs` | the data-size limit (18) | 18 | `tests/satin/data_size_counts.rs` | +| `rex4/frame_limits.rs` | the data-size limit (10) | 10 | `tests/satin/data_size.rs` | +| `rex4/intrinsic_limit_bypass.rs` | the data-size limit (9) | 9 | `tests/satin/data_size.rs`, `tests/satin/data_size_counts.rs` | +| `rex5/selfdestruct_beneficiary.rs` | the data-size limit (1) | 1 | `tests/satin/data_size_counts.rs` | +| `rex6/beneficiary_detention.rs` | the data-size limit (2) | 2 | `tests/satin/data_size_counts.rs` | +| `rex6/frame_local_accounting.rs` | the data-size limit (3) | 3 | `tests/satin/data_size_counts.rs` | +| `rex6/self_transfer_account_dedup.rs` | the data-size limit (1) | 1 | `tests/satin/data_size_counts.rs` | +| `src/limit/data_size.rs` | the data-size limit (2) | 2 | `crates/mega-evm/src/limit/frame_limit.rs`, `crates/mega-evm/src/limit/mod.rs` | +| **Total** | | **47** | | + ## Tests retired after the inventory These 19 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. @@ -284,7 +300,7 @@ 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` | 7 | keep 7 (the pre-block system calls) | -| `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/claims.rs` | 7 | 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) | | `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) | @@ -293,7 +309,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `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` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | | `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)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 10 | 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` | 36 | 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) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | @@ -302,9 +318,9 @@ 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/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `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/frame_limits.rs` | 10 | 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/intrinsic_limit_bypass.rs` | 4 | undecided 3 (the state-growth and KV limits · D46); 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)) | | `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)) | @@ -319,20 +335,17 @@ Each cell lists `disposition count (mechanism · decision)`. | `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) | -| `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) | +| `rex5/selfdestruct_beneficiary.rs` | 6 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention) | +| `rex6/beneficiary_detention.rs` | 14 | keep 13 (detention · D08); 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/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/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | diff --git a/crates/mega-evm/tests/_pending/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs index 79285d884..279c75eba 100644 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -465,104 +465,3 @@ fn test_first_call_to_the_beneficiary_is_charged_cold_from_minirex() { ); } } - -/// 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/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 fb18534ff..b7090b845 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 @@ -191,451 +191,6 @@ fn gen_log_factory_input(num_topics: u64, data_length: u64) -> Bytes { 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 // ============================================================================ @@ -644,30 +199,6 @@ fn test_nested_creation_revert() { // 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 @@ -925,63 +456,6 @@ fn test_state_revert_when_exceeding_limit() { 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 // ============================================================================ @@ -990,126 +464,6 @@ fn test_limits_reset_across_multiple_transactions() { // 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] diff --git a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs index 83bdcc404..312b558ec 100644 --- a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs +++ b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs @@ -157,143 +157,6 @@ 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. @@ -313,147 +176,6 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { 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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs index b1c0bd78e..ae4f5d75f 100644 --- a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs +++ b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs @@ -95,43 +95,6 @@ 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) // ============================================================================ @@ -162,40 +125,6 @@ fn test_intrinsic_plus_execution_kv_update_overflow() { ); } -// ============================================================================ -// 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) // ============================================================================ @@ -228,126 +157,6 @@ fn test_intrinsic_only_kv_update_overflow() { )); } -// ============================================================================ -// 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 // ============================================================================ @@ -450,153 +259,3 @@ fn test_intrinsic_data_size_overflow_with_inspector_early_return() { "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/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index e45281c84..8d8114ff4 100644 --- a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -335,64 +335,6 @@ fn staticcall_once_parent(target: Address, gas_each: u64) -> Bytes { .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 diff --git a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs index 4b448da87..888ad161c 100644 --- a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs @@ -337,61 +337,6 @@ fn test_rex6_call_to_eip7702_delegator_to_beneficiary_enabled_marks_beneficiary( // 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. @@ -498,37 +443,6 @@ fn test_rex6_selfdestruct_db_error_on_target_surfaces() { 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 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/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/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/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index ff3cb9112..81ad4329f 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -17,7 +17,10 @@ use mega_evm::{ FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, REVERT, STOP}, + bytecode::opcode::{ + CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, + SELFDESTRUCT, STOP, + }, context::result::{ExecutionResult, HaltReason}, context_interface::cfg::GasId, interpreter::{ @@ -658,34 +661,53 @@ fn gas_where_the_write_is_counted(code: &Bytes, data_limit: u64) -> u64 { /// the record is counted, and only for a record the limit keeps. const FRESH_SLOT_COUNTED_AT: u64 = 162_306; -/// A fresh slot's write meets two limits, and the one that binds first is the one reported. +/// A write meets two limits, and the one that binds first is the one reported. /// -/// The `SSTORE` has to finish before its record exists. Below [`FRESH_SLOT_COUNTED_AT`] that is -/// an out-of-gas, and the record is not counted. At that gas the record is counted: a data-size -/// limit it crosses stops the transaction, and the record's history is not charged because the -/// record is not kept. A limit the record fits costs that history on top — one write record at -/// the cost per history byte — and the write succeeds only once the history is paid. Short of -/// it, the same write halts out of gas. +/// 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. #[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), + ("a log of one byte", log0(1), mega_evm::LOG_BASE_SIZE + 1), + ("a SELFDESTRUCT that moves value", selfdestruct, WRITE_RECORD_SIZE), + ]; + for (name, code, 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(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}"); + 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(); - // The write is 40 bytes on top of the body. One byte under that, the write itself crosses. - let crosses = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE - 1; - let fits = mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE; - let counted_at = gas_where_the_write_is_counted(&code, crosses); - let kept_at = gas_where_the_write_is_counted(&code, fits); + 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"); - assert_eq!(kept_at - counted_at, record_history, "a kept record costs its history and no more"); - assert!(matches!(bound_at(&code, counted_at - 1, crosses), Bound::OutOfGas)); - assert!(matches!(bound_at(&code, counted_at, crosses), Bound::DataSize)); - assert!(matches!(bound_at(&code, kept_at, crosses), Bound::DataSize)); - assert!(matches!(bound_at(&code, counted_at, fits), Bound::OutOfGas)); - assert!(matches!(bound_at(&code, kept_at - 1, fits), Bound::OutOfGas)); - assert!(matches!(bound_at(&code, kept_at, fits), Bound::Success)); - - // The figure is 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. let empty_call = MegaEvm::new(context(funded().account_code(A, Bytes::from_static(&[STOP])))) .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) .unwrap(); @@ -869,3 +891,189 @@ fn test_a_stopped_start_bumps_a_creators_nonce_and_applies_no_authorization() { "the delegation was not applied" ); } + +/* ---------- 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 does not latch"); + 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"); + } + } +} + +/// The child that crosses its share reverts with `MegaLimitExceeded` naming the data size and +/// the share it crossed, which is what its caller reads. +#[test] +fn test_a_child_that_crosses_its_share_reverts_with_the_share() { + let returns_revert_data = then_call(BytecodeBuilder::default(), B) + .append(RETURNDATASIZE) + .append_many([PUSH0, PUSH0]) + .append(RETURNDATACOPY) + .append(RETURNDATASIZE) + .append(PUSH0) + .append(RETURN) + .build(); + let db = funded() + .account_code(A, returns_revert_data) + .account_code(B, write_slots(BytecodeBuilder::default(), 99).stop().build()); + let outcome = run_slots(db, room_for(100)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let reverted = MegaLimitExceeded::abi_decode(outcome.result.output().unwrap()).unwrap(); + assert_eq!(reverted.kind, LimitKind::DataSize.as_u8()); + assert_eq!(reverted.limit, 98 * WRITE_RECORD_SIZE); +} + +/// The transaction's own frame gets what the body leaves: with room for 5 slots, 5 are kept and a +/// sixth stops the transaction. Its frame's budget is the transaction's own limit, so the +/// crossing is the transaction's, not a frame-local revert. +#[test] +fn test_the_first_frame_gets_what_the_body_leaves() { + let run = |n| { + run_slots( + funded().account_code(A, write_slots(BytecodeBuilder::default(), n).stop().build()), + room_for(5), + ) + }; + let fits = run(5); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.data_size, room_for(5)); + assert_stopped(&run(6), room_for(5), room_for(6)); +} + +/// 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 stopped before an interceptor could answer the transaction's own +/// call: the stop is the first frame's answer, whatever the frame's target. +#[test] +fn test_a_body_over_the_limit_is_stopped_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 stopped = run_at(funded(), tx(), body - 1); + assert_stopped(&stopped, body - 1, body); + assert_eq!( + stopped.result.output().unwrap(), + &LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: body - 1, + used: body, + frame_local: false, + } + .revert_data(), + ); +} 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..6215c5652 --- /dev/null +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -0,0 +1,368 @@ +//! 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, 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, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, RETURN, SELFDESTRUCT, + SLOAD, SSTORE, STATICCALL, STOP, + }, + context::result::ExecutionResult, +}; + +use crate::common::{call, call_with_data, context, create, execute}; + +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) +} + +/// Init code that returns `size` zero bytes as the deployed contract. +fn constructor_returning(size: u64) -> Bytes { + BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() +} + +/// 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(1), + ), + ( + "a value transfer to an account that does not exist", + funded(), + call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), + records(1), + ), + ( + "a creation deploying 10 bytes", + funded(), + create(CALLER, init.clone(), GAS_LIMIT), + kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 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(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 child that writes a slot back and reverts, under a caller that wrote one", + with_code( + call_to(CALL, LIBRARY, 0).sstore(U256::from(5), U256::from(1)).stop().build(), + ) + .account_code( + LIBRARY, + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO) + .revert() + .build(), + ), + 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(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}"); + } +} + +/// 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 = MegaEvm::new(context(db()).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + )) + .execute_transaction(call_with_data( + CALLER, + CALLEE, + Bytes::from(vec![0xab; calldata]), + GAS_LIMIT, + )) + .unwrap(); + 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/main.rs b/crates/mega-evm/tests/satin/main.rs index 7dcb2bac2..78f8593d2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -3,6 +3,7 @@ mod common; mod contract_size; mod data_size; +mod data_size_counts; mod db_error; mod equivalence; mod history_exemption; From 821201d38132a0061a46648c896dd7a48f69974c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:24:07 -0700 Subject: [PATCH 058/458] style(system): drop the clone the hint test no longer needs --- crates/mega-evm/tests/system/oracle.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 1c4e285b2..ed47149fd 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -307,7 +307,7 @@ fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { let limit = counted - 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), ); From 6bf612eb77e00e03f3dd2580d05bbf600d04871e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:24:36 -0700 Subject: [PATCH 059/458] docs(system): quote MegaETH where clippy reads it as an identifier --- crates/mega-evm/src/system/deploy.rs | 6 +++--- crates/mega-evm/tests/system/deploy.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs index 115f8c366..e3ea8a09e 100644 --- a/crates/mega-evm/src/system/deploy.rs +++ b/crates/mega-evm/src/system/deploy.rs @@ -72,7 +72,7 @@ pub struct SystemContractSpec { /// When set, matching code with nonce 0 is an error rather than a read-only entry. /// /// EIP-7997 requires the factory to hold its runtime **and a nonzero nonce**. The six - /// MegaETH contracts are not EIP-7997, so they leave this unset: matching code is + /// `MegaETH` contracts are not EIP-7997, so they leave this unset: matching code is /// accepted regardless of nonce, because the matching-code path must not rewrite an /// already-deployed contract. pub require_nonzero_nonce: bool, @@ -183,8 +183,8 @@ impl core::error::Error /// 7. If [`SystemContractSpec::require_nonzero_nonce`] is set (the EIP-7997 factory) and the /// nonce is 0, this is [`SystemContractDeployError::ZeroFactoryNonce`] instead: the matching-code /// path does not rewrite a nonce, so a genesis factory with the right code and nonce 0 would -/// otherwise stay invalid forever. The six MegaETH contracts leave that flag unset; they are not -/// EIP-7997, and matching code is accepted regardless of nonce. +/// otherwise stay invalid forever. The six `MegaETH` contracts leave that flag unset; they +/// are not EIP-7997, and matching code is accepted regardless of nonce. /// - Absent, or present with empty code and nonce 0: the created account with its bytecode, nonce /// and every seeded slot, all marked. An existing balance is kept. Marking the account created /// clears any storage it had; that is the accepted bootstrap path (prefunding with balance diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index 80e23196f..66c703c6e 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -229,7 +229,7 @@ fn test_matching_factory_code_keeps_a_nonce_greater_than_one() { assert_eq!(account.info.code_hash, CREATE2_FACTORY_CODE_HASH); } -/// The six MegaETH contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, +/// The six `MegaETH` contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, /// not an error. Rewriting the nonce would be a state change the matching-code path exists to /// avoid. #[test] From cb763db4f93ea9bf3bc6643debe1ba53d863116a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:26:25 -0700 Subject: [PATCH 060/458] bench(limit): time a transaction at the data-size limit and one a byte over it The arm writes 200 fresh slots and emits 200 logs in one frame under a limit equal to what it keeps, and again a byte short of it, where the last log stops the transaction; op-revm runs the same transaction with no limit. Before measuring, the arm is held to the bytes and records it is sized for and to the stop at its last log. --- crates/mega-evm/benches/transact.rs | 92 +++++++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 93c47b6fe..a236f7f18 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -17,6 +17,11 @@ //! 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. +//! - `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`). //! //! 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 @@ -27,8 +32,10 @@ //! //! 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. A workload that stopped drawing what it is here to -//! measure would otherwise still benchmark, and measure the wrong thing. +//! 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; @@ -39,8 +46,9 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, + EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, + MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ @@ -62,6 +70,7 @@ 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"); /// A selector `MegaAccessControl` intercepts, and one it does not. const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; @@ -131,6 +140,30 @@ fn logger_code() -> Bytes { code.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(); @@ -235,6 +268,7 @@ fn bench_transact(c: &mut Criterion) { .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(LIMITED, limited_code()) .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); let cfg = mega_context(db.clone()).cfg().clone(); @@ -303,6 +337,56 @@ 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::no_limits().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 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 = [ From f6ce9c7b04d0518b7ea40600155259496a65669d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:27:50 -0700 Subject: [PATCH 061/458] feat(test-utils): add the neutral configuration for Ethereum fixtures MegaContext::with_neutral_cfg, behind test-utils, takes every configuration field as given and prices no history, so a fixture fork's own schedule, EIP switches, execution cap and code-size limits run on Satin's machinery. neutral_cfg and neutral_precompiles build it for Osaka and Amsterdam. --- crates/mega-evm/src/evm/context.rs | 158 +++++++++++++++++- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/neutral.rs | 178 ++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/neutral.rs | 195 ++++++++++++++++++++++ 5 files changed, 533 insertions(+), 1 deletion(-) create mode 100644 crates/mega-evm/src/test_utils/neutral.rs create mode 100644 crates/mega-evm/tests/satin/neutral.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 298b208d2..63bcc21eb 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -30,7 +30,8 @@ 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 @@ -51,6 +52,9 @@ pub struct MegaContext MegaContext { @@ -78,6 +82,8 @@ impl MegaContext { bucket_multipliers: BucketMultipliers::default(), system_originated: false, prices_history: true, + #[cfg(any(test, feature = "test-utils"))] + neutral: false, } } @@ -87,13 +93,55 @@ impl MegaContext { /// 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`. + /// + /// 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. + /// + /// 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 + } + + /// 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; @@ -251,7 +299,14 @@ impl MegaContext { /// 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() }; @@ -568,4 +623,105 @@ 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 = 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(); + 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(); + 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(); + 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(); + assert!(ctx.prices_history()); + assert_satin_cfg(&ctx); + } + + /// 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(); + assert!(ctx.prices_history()); + } } diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index cd9b7c74e..14c08a369 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -4,6 +4,7 @@ mod bytes; mod database; mod evm; mod inspectors; +mod neutral; mod opcode_gen; mod scenario; @@ -11,5 +12,6 @@ pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; +pub use neutral::*; pub use opcode_gen::*; pub use scenario::*; 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..cbde233e9 --- /dev/null +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -0,0 +1,178 @@ +//! 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 its precompile set +//! ([`neutral_precompiles`]), which the EVM carries rather than the context. +//! +//! 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; +use revm::{ + context::CfgEnv, + context_interface::cfg::GasParams, + precompile::{PrecompileSpecId, Precompiles}, + primitives::eip7954, +}; + +use crate::{EthSpecId, 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. +/// +/// 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)))) +} + +#[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()); + } + + /// 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); + } + + /// 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"); + } + } +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 70c4a310a..24c25034a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -11,6 +11,7 @@ mod history_gas; mod history_reservoir; mod inspector; mod intrinsic; +mod neutral; mod outcome; mod precompile_gas; mod pricing_table; diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs new file mode 100644 index 000000000..d932939e8 --- /dev/null +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -0,0 +1,195 @@ +//! The neutral configuration the execution-spec gate runs Ethereum's fixtures under. +//! +//! Under it, `MegaEvm` must agree with op-revm's `OpEvm` on the same configuration exactly — +//! gas, refund, logs, output and state — where on Satin's own configuration it spends the +//! history ledger more (`equivalence.rs`). Each case runs on Osaka's configuration and on +//! Amsterdam's, and each is one that pays history on Satin's: a priced 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. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{ + neutral_cfg, neutral_precompiles, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, + MemoryDatabase, + }, + EthSpecId, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, +}; +use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG3, POP, PUSH0, PUSH1}, + 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"); +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. +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_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); + *mega.precompiles_mut() = neutral_precompiles(fork).expect("a neutral fork"); + let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); + let mega = + ExecResultAndState::new(outcome.result_and_state.result, outcome.result_and_state.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); + } +} From 56d894d08bcfa9f8c2ecf6112ad1212a07cc9755 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:28:14 -0700 Subject: [PATCH 062/458] docs(limit): describe the data-size limit The limit module, the crate README and AGENTS.md say what the limit counts and when, how a frame's budget is derived, what a crossing does, the order of the check and the history charge, and what a body over the limit waives before the first frame. They also give the defaults a block installs and the block's rule for deposits. --- AGENTS.md | 13 +++++++++--- crates/mega-evm/README.md | 11 +++++++++-- crates/mega-evm/src/limit/mod.rs | 34 ++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 297b107ad..01ddb4939 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -97,7 +97,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 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point 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/` | 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 and history allowances (`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 | +| `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 and history allowances (`frame_limit.rs`), staging, the latch, the transaction body and deployed code 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) | 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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 | @@ -135,7 +135,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The EIP-7623 calldata floor is still computed and validated and binds nothing: history charges the same bytes at a higher rate. - 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 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 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code before the creation is committed, an Oracle hint before it is forwarded. + A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). + A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 for the transactions the builder chooses: the transaction that crosses it is packed and the next one refused, and a deposit is never refused but still counts. + `tests/satin/data_size.rs` derives where the stop gives way to out-of-gas: a top-level fresh `SSTORE` is counted at 162,306 gas, and keeping its record costs its 3,520 history on top. - `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` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. @@ -171,7 +176,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. + 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. 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.** diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 0cb10df9e..5ba5202a4 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -36,7 +36,14 @@ The precompile set is op-revm's Karst set with KZG point evaluation repriced to 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. + +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. +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. +`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB. +The block's data size is a packing budget: the transaction that crosses it is packed and the next one refused, and a deposit is never refused but still counts. `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 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. @@ -73,7 +80,7 @@ An Oracle hint's payload is data size that is never history, because the bytes g 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 resource limits, gas detention and keyless deployment arrive in later changes. +The state-growth and KV limits, gas detention and keyless deployment arrive in later changes. ## Quick start diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 376541d68..6c5170bc8 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -9,6 +9,40 @@ //! 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 its budget reverts alone and its caller resumes; a transaction that crosses its limit +//! is stopped through the latch ([`AdditionalLimit`]). +//! +//! 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; +//! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded. +//! +//! 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. A body over the limit latches the transaction before it runs, and then nothing is +//! charged for what the stop takes back: no authorization is applied, no record made outside a +//! frame is charged, the first frame's start is charged nothing, and the first frame is answered +//! with the stop. The account a deposit-like transaction creates for its caller is charged all the +//! same, because it exists whatever the transaction does. +//! +//! Both limits are unlimited unless a caller sets them. A block executor installs the ones its +//! block limits carry, whose default holds a transaction to +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT). +//! //! # The byte table //! //! The sizes below are what one of those things weighs, and they are the whole byte table of the From b077782244761d2ec8456974b2c73f174a1cab6d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:28:18 -0700 Subject: [PATCH 063/458] docs(system): backtick MegaETH in the deploy doc comments Clippy's doc_markdown lint flagged three bare occurrences. --- crates/mega-evm/src/system/deploy.rs | 6 +++--- crates/mega-evm/tests/system/deploy.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs index 115f8c366..e3ea8a09e 100644 --- a/crates/mega-evm/src/system/deploy.rs +++ b/crates/mega-evm/src/system/deploy.rs @@ -72,7 +72,7 @@ pub struct SystemContractSpec { /// When set, matching code with nonce 0 is an error rather than a read-only entry. /// /// EIP-7997 requires the factory to hold its runtime **and a nonzero nonce**. The six - /// MegaETH contracts are not EIP-7997, so they leave this unset: matching code is + /// `MegaETH` contracts are not EIP-7997, so they leave this unset: matching code is /// accepted regardless of nonce, because the matching-code path must not rewrite an /// already-deployed contract. pub require_nonzero_nonce: bool, @@ -183,8 +183,8 @@ impl core::error::Error /// 7. If [`SystemContractSpec::require_nonzero_nonce`] is set (the EIP-7997 factory) and the /// nonce is 0, this is [`SystemContractDeployError::ZeroFactoryNonce`] instead: the matching-code /// path does not rewrite a nonce, so a genesis factory with the right code and nonce 0 would -/// otherwise stay invalid forever. The six MegaETH contracts leave that flag unset; they are not -/// EIP-7997, and matching code is accepted regardless of nonce. +/// otherwise stay invalid forever. The six `MegaETH` contracts leave that flag unset; they +/// are not EIP-7997, and matching code is accepted regardless of nonce. /// - Absent, or present with empty code and nonce 0: the created account with its bytecode, nonce /// and every seeded slot, all marked. An existing balance is kept. Marking the account created /// clears any storage it had; that is the accepted bootstrap path (prefunding with balance diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs index 80e23196f..66c703c6e 100644 --- a/crates/mega-evm/tests/system/deploy.rs +++ b/crates/mega-evm/tests/system/deploy.rs @@ -229,7 +229,7 @@ fn test_matching_factory_code_keeps_a_nonce_greater_than_one() { assert_eq!(account.info.code_hash, CREATE2_FACTORY_CODE_HASH); } -/// The six MegaETH contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, +/// The six `MegaETH` contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, /// not an error. Rewriting the nonce would be a state change the matching-code path exists to /// avoid. #[test] From 46163e57a0a645c9283f2684d27e2e516aee12fd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:31:16 -0700 Subject: [PATCH 064/458] refactor(limit): put the body back after an early out-of-gas without a zero check --- crates/mega-evm/src/limit/limit.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index ebed7c57f..6d0732256 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -569,9 +569,7 @@ impl AdditionalLimit { let body = self.body_bytes; self.tracker.reset(); self.latched = None; - if body > 0 { - self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); - } + 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"); From 482bf670566235953a955e2a138a5cbf37058447 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:47:03 -0700 Subject: [PATCH 065/458] style(limit): wrap the data-size limit's module docs as rustfmt does --- crates/mega-evm/src/limit/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 6c5170bc8..e222c4dc8 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -23,8 +23,8 @@ //! - 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; +//! - 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; //! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded. From 1037a4c0582a411f2aedb27068dba718a7820a88 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:47:08 -0700 Subject: [PATCH 066/458] style(test): trim the trailing spaces a parked file's Yul listing carried --- .../tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 b7090b845..95b8d0873 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 @@ -93,10 +93,10 @@ const LIBRARY: Address = address!("0000000000000000000000000000000000100002"); /// { /// // 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) @@ -117,7 +117,7 @@ const LIBRARY: Address = address!("0000000000000000000000000000000000100002"); /// default { /// invalid() /// } -/// +/// /// stop() /// } /// ``` From 1fa128ba41fe15e5c13407a3ab42f70bd8fbf07f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:51:55 -0700 Subject: [PATCH 067/458] feat(test-utils): give the neutral EVM the fork's static opcode prices neutralize_evm installs a fixture fork's precompile set and its static opcode prices on a MegaEvm. Amsterdam's static table carries EIP-8038's two-read base for EXTCODESIZE and EXTCODECOPY, which the Osaka-based instruction table does not. The neutral tests now also hold MegaEvm to revm's mainnet EVM on each fork's own spec. --- crates/mega-evm/src/test_utils/neutral.rs | 71 +++- crates/mega-evm/tests/satin/neutral.rs | 181 ++++++++- .../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/tests/bench_fixture.rs | 27 -- .../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/state-test/src/compare.txt | 85 ----- crates/state-test/src/compare_failed.txt | 85 ----- crates/state-test/tests/cli_exit.rs | 101 ----- 22 files changed, 234 insertions(+), 2314 deletions(-) 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 delete mode 100644 crates/mega-state-test/tests/bench_fixture.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 delete mode 100644 crates/state-test/src/compare.txt delete mode 100644 crates/state-test/src/compare_failed.txt delete mode 100644 crates/state-test/tests/cli_exit.rs diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index cbde233e9..0eee59735 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -4,8 +4,9 @@ //! 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 its precompile set -//! ([`neutral_precompiles`]), which the EVM carries rather than the context. +//! 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`]). //! //! 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 @@ -13,15 +14,17 @@ //! 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; +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, }; -use crate::{EthSpecId, MegaSpecId}; +use crate::{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. @@ -68,6 +71,34 @@ pub fn neutral_precompiles(fork: EthSpecId) -> Option { 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 its Osaka base'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)?); + let (_, instructions, evm_precompiles, _) = evm.all_mut(); + *evm_precompiles = precompiles; + *instructions.gas_table_mut() = gas_table; + Some(()) +} + #[cfg(test)] mod tests { use super::*; @@ -175,4 +206,36 @@ mod tests { assert!(out_of_gas(satin_precompiles()), "MegaETH's does not"); } } + + /// Satin's instruction table prices opcodes as its Osaka base does, so Osaka's static prices + /// change nothing; Amsterdam's differ in EIP-8038's two-read base for `EXTCODESIZE` and + /// `EXTCODECOPY` alone. + #[test] + fn test_neutral_gas_tables() { + use revm::bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}; + let mut evm = MegaEvm::new(context(EthSpecId::OSAKA)); + let satin = *evm.all_mut().1.gas_table(); + assert_eq!(neutral_gas_table(EthSpecId::OSAKA), Some(satin)); + + let amsterdam = neutral_gas_table(EthSpecId::AMSTERDAM).expect("a neutral fork"); + let changed: Vec<_> = + (0..=u8::MAX).filter(|&op| amsterdam[op as usize] != satin[op as usize]).collect(); + assert_eq!(changed, vec![EXTCODESIZE, EXTCODECOPY]); + assert_eq!(amsterdam[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::AMSTERDAM)); + assert!(neutralize_evm(&mut evm, EthSpecId::PRAGUE).is_none()); + assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 100); + + assert!(neutralize_evm(&mut evm, EthSpecId::AMSTERDAM).is_some()); + assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 200); + } } diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index d932939e8..05d859a71 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -1,32 +1,41 @@ //! The neutral configuration the execution-spec gate runs Ethereum's fixtures under. //! -//! Under it, `MegaEvm` must agree with op-revm's `OpEvm` on the same configuration exactly — -//! gas, refund, logs, output and state — where on Satin's own configuration it spends the -//! history ledger more (`equivalence.rs`). Each case runs on Osaka's configuration and on -//! Amsterdam's, and each is one that pays history on Satin's: a priced 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. - -use alloy_evm::Evm; +//! 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 alloy_primitives::{address, hex, Address, Bytes, TxKind, U256}; use mega_evm::{ test_utils::{ - neutral_cfg, neutral_precompiles, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, + neutral_cfg, neutralize_evm, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, EthSpecId, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, }; -use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use op_revm::{ + constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + L1BlockInfo, OpEvm, OpHaltReason, OpSpecId, OpTransaction, +}; use revm::{ - bytecode::opcode::{CALL, GAS, LOG3, POP, PUSH0, PUSH1}, + bytecode::opcode::{ADDRESS, CALL, EXTCODESIZE, GAS, LOG1, LOG3, POP, PUSH0, PUSH1, SSTORE}, context::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, inspector::NoOpInspector, state::EvmState, - ExecuteEvm, Journal, + ExecuteEvm, Journal, MainBuilder, MainContext, }; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); @@ -70,7 +79,7 @@ fn run_both(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome .with_chain(zero_fee_l1_block_info()); let mut mega = MegaEvm::new(ctx); - *mega.precompiles_mut() = neutral_precompiles(fork).expect("a neutral fork"); + neutralize_evm(&mut mega, fork).expect("a neutral fork"); let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); let mega = ExecResultAndState::new(outcome.result_and_state.result, outcome.result_and_state.state); @@ -193,3 +202,147 @@ fn test_neutral_nested_value_call_matches_op_revm() { 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. +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_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; + 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); + } + } +} + +/// `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); + } +} + +/// 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 = + revm::precompile::kzg_point_evaluation::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 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-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/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/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/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/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"); -} From 9b0c78408f9d01ce9d9e79042553f812fce79ea3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:54:12 -0700 Subject: [PATCH 068/458] feat(state-test): run the execution-spec fixtures through MegaEvm Both crates rejoin the workspace on the Satin engine. The runner reads the fork's own fixture types and executes one fork's entries in one of two modes: equivalence, a gate on Satin's machinery under the neutral configuration, and satin, a report under Satin's own configuration. Expected exceptions are matched by name, skips mirror the reference runner's, and every equivalence failure must be explained by a registered deviation whose count is pinned (DEVIATIONS.md). The legacy spec mapping, the Rex5 replay-corpus tests and the bench, fill and dump paths that served them are removed. --- Cargo.lock | 120 ++ Cargo.toml | 14 +- crates/mega-state-test/AGENTS.md | 48 +- crates/mega-state-test/Cargo.toml | 33 +- crates/mega-state-test/DEVIATIONS.md | 50 + crates/mega-state-test/README.md | 58 + crates/mega-state-test/src/deviations.rs | 223 +++ crates/mega-state-test/src/exceptions.rs | 178 +++ crates/mega-state-test/src/fork.rs | 101 ++ crates/mega-state-test/src/lib.rs | 32 +- crates/mega-state-test/src/mode.rs | 163 ++ crates/mega-state-test/src/roots.rs | 96 ++ crates/mega-state-test/src/runner.rs | 1849 ++++++---------------- crates/mega-state-test/src/skips.rs | 113 ++ crates/mega-state-test/tests/runner.rs | 364 +++++ crates/state-test/AGENTS.md | 11 +- crates/state-test/Cargo.toml | 10 +- crates/state-test/README.md | 25 +- crates/state-test/src/main.rs | 358 ++--- crates/state-test/tests/cli.rs | 143 ++ 20 files changed, 2348 insertions(+), 1641 deletions(-) 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/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 create mode 100644 crates/mega-state-test/tests/runner.rs create mode 100644 crates/state-test/tests/cli.rs diff --git a/Cargo.lock b/Cargo.lock index d267e10ba..124e95cac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -682,12 +682,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.60.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.60.2", +] + [[package]] name = "anyhow" version = "1.0.103" @@ -1336,6 +1380,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -1344,8 +1389,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]] @@ -2554,6 +2613,12 @@ 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" @@ -2786,6 +2851,21 @@ dependencies = [ "serde_json", ] +[[package]] +name = "mega-state-test" +version = "2.0.0-alpha.1" +dependencies = [ + "alloy-rlp", + "alloy-trie", + "mega-evm", + "revm", + "serde", + "serde_json", + "tempfile", + "thiserror", + "walkdir", +] + [[package]] name = "mega-system-contracts" version = "2.0.0-alpha.1" @@ -2991,6 +3071,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" @@ -3746,6 +3832,7 @@ dependencies = [ "revm-precompile", "revm-primitives", "revm-state", + "revm-statetest-types", ] [[package]] @@ -3929,6 +4016,23 @@ dependencies = [ "serde", ] +[[package]] +name = "revm-statetest-types" +version = "19.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +dependencies = [ + "alloy-eip7928", + "k256", + "revm-context", + "revm-context-interface", + "revm-database", + "revm-primitives", + "revm-state", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -4362,6 +4466,16 @@ 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 = [ + "clap", + "mega-state-test", + "serde_json", + "tempfile", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -4807,6 +4921,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" diff --git a/Cargo.toml b/Cargo.toml index ead272edc..2aedfcc4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,14 @@ [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"] +# The tool crates `bin/mega-evme` and `bin/mega-t8n` 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/mega-state-test", + "crates/state-test", + "crates/system-contracts", +] default-members = ["crates/mega-evm"] exclude = [] @@ -150,6 +155,7 @@ 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 } diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index d58520810..cb8288747 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -1,35 +1,37 @@ # 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). 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 its pinned count; `DEVIATIONS.md` is rendered from it. +- `src/roots.rs`: the post-state root and the logs hash. +- `tests/runner.rs`: the runner on fixtures written in the test, filled from revm's mainnet EVM on the fixture's fork. + +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 matches on fork, failure kind and a path fragment, and pins its count; the gate checks the pins with `--expect-deviations`. +- Skips mirror the reference runner's, so the executed and skipped counts equal the ones `.github/workflows/exec-spec.yml` pins for it. ## 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`, 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 the pinned 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..a42a01862 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,24 @@ 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 = ["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] +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..ca4330691 --- /dev/null +++ b/crates/mega-state-test/DEVIATIONS.md @@ -0,0 +1,50 @@ +# Deviations + + + +The places Satin differs from Ethereum on purpose that the execution-spec gate meets. +In equivalence mode a failure one of them explains is counted against it, and the count is pinned; a failure none of them explains fails the gate. + +## `amsterdam-opcodes-on-osaka` + +2 failed tests on 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.** `state-root-mismatch`, in: + +- `frontier/opcodes/test_all_opcodes.json` +- `stBadOpcode/undefinedOpcodeFirstByte.json` + +## `selfdestruct-burns-on-osaka` + +37 failed tests on 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 post-state and logs Satin does for every one of these fixtures, and the fixtures' own post-state and logs on the Amsterdam spec. +Whether Satin takes EIP-8246 is a decision for its specification, not for this gate. + +**Failures.** `state-root-mismatch`, `logs-mismatch`, in: + +- `amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json` +- `amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json` +- `amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json` +- `amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json` +- `amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json` +- `cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json` +- `cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json` +- `cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json` +- `frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json` +- `ported_static/stCreate2/create2_suicide/create2_suicide.json` +- `ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json` diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md new file mode 100644 index 000000000..4ebfd7147 --- /dev/null +++ b/crates/mega-state-test/README.md @@ -0,0 +1,58 @@ +# 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. + +## 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, history and the access entries it pressed back on purpose, 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. + +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. + +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. +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, and `--trace` runs each test under an EIP-3155 tracer. + +A deviation added or moved updates `src/deviations.rs` 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/deviations.rs b/crates/mega-state-test/src/deviations.rs new file mode 100644 index 000000000..c2a9d996f --- /dev/null +++ b/crates/mega-state-test/src/deviations.rs @@ -0,0 +1,223 @@ +//! The places Satin differs from Ethereum on purpose, and the fixtures 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. +//! +//! An entry explains a failure by where the fixture lives and how it failed, not by the test's +//! name alone, and it pins how many failures it explains on the pinned fixture releases: a new +//! failure of the same shape moves the count and fails the gate as surely as an unattributed one, +//! and so does a fixed one. + +use serde::Serialize; + +use crate::{runner::FailureKind, 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, + /// Path fragments: a failure in a fixture file whose path contains one of them may be this + /// deviation's. + pub paths: &'static [&'static str], + /// The ways a fixture of those paths fails on this rule. + pub kinds: &'static [FailureKind], + /// The forks whose fixtures meet the rule. + pub forks: &'static [Fork], + /// How many failures the entry explains on the pinned fixture releases, per fork. + pub pinned: &'static [(Fork, usize)], +} + +impl Deviation { + /// Whether a failure of `kind`, in the fixture at `path`, of `fork`, is this deviation's. + pub fn explains(&self, fork: Fork, path: &str, kind: FailureKind) -> bool { + let path = path.replace('\\', "/"); + self.forks.contains(&fork) && + self.kinds.contains(&kind) && + self.paths.iter().any(|fragment| path.contains(fragment)) + } + + /// How many failures the entry explains on `fork`'s pinned release. + pub fn pinned(&self, fork: Fork) -> usize { + self.pinned.iter().find(|(f, _)| *f == fork).map_or(0, |(_, count)| *count) + } +} + +/// 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.", + paths: &["frontier/opcodes/test_all_opcodes.json", "stBadOpcode/undefinedOpcodeFirstByte.json"], + kinds: &[FailureKind::StateRootMismatch], + forks: &[Fork::Osaka], + pinned: &[(Fork::Osaka, 2)], +}; + +/// 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 \ + post-state and logs Satin does for every one of these fixtures, and the fixtures' own \ + post-state and logs on the Amsterdam spec. Whether Satin takes EIP-8246 is a decision for its \ + specification, not for this gate.", + paths: &[ + "amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json", + "amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json", + "amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json", + "amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json", + "amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json", + "cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json", + "cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + "cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", + "frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json", + "ported_static/stCreate2/create2_suicide/create2_suicide.json", + "ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json", + ], + kinds: &[FailureKind::StateRootMismatch, FailureKind::LogsMismatch], + forks: &[Fork::Amsterdam], + pinned: &[(Fork::Amsterdam, 37)], +}; + +/// The deviation that explains a failure of `kind` in the fixture at `path`, if one does. +/// +/// Entries are disjoint: no failure is explained by two of them (a test checks it on the +/// registry's own paths), so the first that matches is the one. +pub fn attribute(fork: Fork, path: &str, kind: FailureKind) -> Option<&'static Deviation> { + DEVIATIONS.iter().find(|deviation| deviation.explains(fork, path, kind)) +} + +/// The deviation named `id`. +pub fn by_id(id: &str) -> Option<&'static Deviation> { + DEVIATIONS.iter().find(|deviation| deviation.id == id) +} + +/// 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.\n\ + In equivalence mode a failure one of them explains is counted against it, and the count \ + is pinned; a failure none of them explains fails the gate.\n", + ); + for deviation in DEVIATIONS { + out.push_str(&format!("\n## `{}`\n\n", deviation.id)); + for (fork, count) in deviation.pinned { + out.push_str(&format!("{count} failed tests on the pinned {fork} fixtures.\n\n")); + } + out.push_str(&format!("**Rule.**\n{}\n\n", sentences(deviation.rule))); + out.push_str(&format!("**Reason.**\n{}\n\n", sentences(deviation.reason))); + let kinds: Vec<_> = + deviation.kinds.iter().map(|kind| format!("`{}`", kind.name())).collect(); + out.push_str(&format!("**Failures.** {}, in:\n\n", kinds.join(", "))); + for path in deviation.paths { + out.push_str(&format!("- `{path}`\n")); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + #[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.paths.is_empty() && !deviation.kinds.is_empty(), "{}", deviation.id); + assert!(!deviation.forks.is_empty(), "{}", deviation.id); + for (fork, count) in deviation.pinned { + assert!( + deviation.forks.contains(fork), + "{}: pins a fork it does not cover", + deviation.id + ); + assert!(*count > 0, "{}: a zero pin is a stale entry", deviation.id); + } + for fork in deviation.forks { + assert!( + deviation.pinned(*fork) > 0, + "{}: covers {fork} without a pin", + deviation.id + ); + } + assert_eq!(by_id(deviation.id).map(|d| d.id), Some(deviation.id)); + } + } + + /// No two entries explain the same failure: every entry's own paths, on each fork and kind it + /// covers, are attributed to it and to nothing before it. + #[test] + fn test_entries_are_disjoint() { + for deviation in DEVIATIONS { + for &fork in deviation.forks { + for &kind in deviation.kinds { + for path in deviation.paths { + let path = format!("fixtures/state_tests/{path}/x.json"); + assert_eq!( + attribute(fork, &path, kind).map(|d| d.id), + Some(deviation.id), + "{path} ({fork}, {kind:?})" + ); + let others: Vec<_> = DEVIATIONS + .iter() + .filter(|other| { + other.id != deviation.id && other.explains(fork, &path, kind) + }) + .map(|other| other.id) + .collect(); + assert!(others.is_empty(), "{path}: also explained by {others:?}"); + } + } + } + } + } + + /// `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..70f35b4c5 --- /dev/null +++ b/crates/mega-state-test/src/exceptions.rs @@ -0,0 +1,178 @@ +//! 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. From Amsterdam on that accounting +//! can call `INTRINSIC_GAS_TOO_LOW` a limit revm finds above the intrinsic cost and below the +//! floor, so a floor shortfall satisfies both names; an intrinsic shortfall satisfies only its own. + +use mega_evm::{ + op_revm::OpTransactionError, + revm::context::result::{EVMError, InvalidTransaction}, +}; + +/// The prefix of every transaction exception name. +const PREFIX: &str = "TransactionException."; + +/// The execution-spec exception names `error` satisfies, without the `TransactionException.` +/// prefix; empty for an error no fixture exception describes. +pub fn names(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 { .. } => { + &["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` names. +pub fn check( + expected: &str, + error: &EVMError, +) -> Result<(), Mismatch> { + let EVMError::Transaction(OpTransactionError::Base(invalid)) = error else { + return Err(Mismatch::Unnamed); + }; + let got = names(invalid); + if got.is_empty() { + return Err(Mismatch::Unnamed); + } + let expected = expected.split('|').map(|name| name.trim().strip_prefix(PREFIX).unwrap_or(name)); + let mut expected = expected.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("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( + "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("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("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + let error: EVMError = EVMError::Custom("boom".into()); + assert_eq!( + check("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + let error = EVMError::Transaction(OpTransactionError::MissingEnvelopedTx); + assert_eq!( + check::("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + } + + /// A gas limit below the calldata floor satisfies either name of the one rule; one below the + /// intrinsic cost only its own. + #[test] + fn test_floor_and_intrinsic_shortfalls() { + let floor = + tx_error(InvalidTransaction::GasFloorMoreThanGasLimit { gas_floor: 2, gas_limit: 1 }); + assert_eq!( + check("TransactionException.INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", &floor), + Ok(()) + ); + assert_eq!(check("TransactionException.INTRINSIC_GAS_TOO_LOW", &floor), Ok(())); + let intrinsic = tx_error(InvalidTransaction::CallGasCostMoreThanGasLimit { + initial_gas: 2, + gas_limit: 1, + }); + assert_eq!(check("TransactionException.INTRINSIC_GAS_TOO_LOW", &intrinsic), Ok(())); + assert!( + check("TransactionException.INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", &intrinsic).is_err() + ); + } + + /// 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("TYPE_3_TX_ZERO_BLOBS", &error), Ok(())); + assert!(check("", &error).is_err()); + } +} 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..0af1e7131 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -1,10 +1,34 @@ -//! 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, history and the access entries it pressed back on purpose, 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. #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] -pub mod types; - +pub mod deviations; +pub mod exceptions; +mod fork; +mod mode; +pub mod roots; pub mod runner; +pub mod skips; + +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..140f25147 --- /dev/null +++ b/crates/mega-state-test/src/mode.rs @@ -0,0 +1,163 @@ +//! 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}, + 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`). + /// + /// 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. + 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. + pub fn context( + self, + fork: Fork, + db: DB, + block: BlockEnv, + chain_id: u64, + ) -> MegaContext { + let ctx = MegaContext::new(db, MegaSpecId::SATIN); + let cfg = self.cfg(fork, chain_id); + let ctx = match self { + Self::Equivalence => ctx.with_neutral_cfg(cfg), + 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 { + let mut evm = MegaEvm::new(self.context(fork, db, block, chain_id)); + 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; 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.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..1bd046caa --- /dev/null +++ b/crates/mega-state-test/src/roots.rs @@ -0,0 +1,96 @@ +//! The two roots a state test's expectation is written in: the post-state root and the hash of +//! the logs, computed the way the reference runner computes them. + +use alloy_trie::{root::storage_root_unhashed, HashBuilder, Nibbles, TrieAccount}; +use mega_evm::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 state root over `accounts`: a state test's `hash` field. +/// +/// 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::revm::{ + primitives::{b256, KECCAK_EMPTY}, + state::AccountInfo, + }; + + /// 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..3b45c6e31 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -1,1418 +1,597 @@ -#![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 and, in equivalence mode, +//! the [deviation](crate::deviations::Deviation) that explains it, if one does). +//! [`Report::summary`] counts them, and [`Summary::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; +//! - 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, + CfgEnv, }, - database, - database::State, - database_interface::EmptyDB, + database::{EmptyDB, State}, inspector::{inspectors::TracerEip3155, InspectCommitEvm}, - primitives::{hardfork::SpecId, Bytes, B256}, + primitives::{Bytes, 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::Serialize; +use walkdir::WalkDir; + +use crate::{ + deviations, + exceptions::{self, Mismatch}, + mode::MAX_BLOBS_PER_TX, + roots::{logs_hash, state_root}, + skips::{skip_file, SkipReason}, + types::{Test, TestSuite, TestUnit}, + Fork, Mode, }; -use thiserror::Error; -use walkdir::{DirEntry, WalkDir}; -/// Error that occurs during test execution -#[derive(Debug, Error)] -#[error("Path: {path}\nName: {name}\nError: {kind}")] -pub struct TestError { - pub name: String, +/// 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, +} + +/// 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, - pub kind: TestErrorKind, -} - -/// 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")] + /// 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, +/// A failed test. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Failure { + /// How it failed. + pub kind: FailureKind, + /// 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>, } -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, - }) -} - -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 Failure { + fn new(kind: FailureKind, detail: impl Into) -> Self { + Self { kind, detail: detail.into(), deviation: None } } } -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()), - }), - } -} - -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(()) -} - -/// 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", - } -} - -/// 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, - } -} - -/// 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 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 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() + } + + /// 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 registered deviation's count must equal its pin for `fork` + /// — a deviation that explains fewer failures than it pins is as much a change as one that + /// explains more. + pub fn gate( + &self, + fork: Fork, + expected_executed: Option, + expected_skipped: Option, + check_deviations: bool, + ) -> Vec { + let mut problems = Vec::new(); + if self.file_failures > 0 { + problems.push(format!("{} fixture files could not be read", self.file_failures)); } - } - 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(), - }); + if self.unattributed > 0 { + problems.push(format!("{} failed tests no deviation explains", self.unattributed)); } - } - 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}"); + if let Some(expected) = expected_executed.filter(|&n| n != self.executed) { + problems.push(format!("{} tests executed, {expected} pinned", self.executed)); } - }; - - // 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")) - }), + let skipped = self.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 deviations::DEVIATIONS { + let got = self.deviated.get(deviation.id).copied().unwrap_or(0); + let pinned = deviation.pinned(fork); + if got != pinned { + problems.push(format!( + "deviation {} explains {got} failed tests on {fork}, {pinned} pinned", + deviation.id + )); + } + } + } + problems } } -/// 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 }); +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, } - - // 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 }); } } } + summary } - 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); + /// 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, + }) } - 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. -#[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, +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) + } } -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 +/// 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, files: files.len(), results, file_failures } } -/// 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 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: TestSuite = serde_json::from_str(&json) + .map_err(|error| Failure::new(FailureKind::Fixture, format!("parse: {error}")))?; + 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, &path_str, 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), - }; - - // 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(), - )); - } - - 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 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" - ))) - } - } - } - }; - // 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" - ))); +/// Names the deviation that explains a failure, in equivalence mode. +fn attribute(config: Config, path: &str, outcome: Outcome) -> Outcome { + match outcome { + Outcome::Failed(mut failure) if config.mode == Mode::Equivalence => { + failure.deviation = deviations::attribute(config.fork, path, failure.kind) + .map(|deviation| deviation.id); + Outcome::Failed(failure) } - 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, + 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. +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")) + }) } -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 } +/// 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), } } -#[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 execute_and_check( + config: Config, + unit: &TestUnit, + test: &Test, +) -> Result, Failure> { + let chain_id = chain_id(unit)?; + + // The block is 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. + let mut eth_cfg = CfgEnv::new(); + eth_cfg.chain_id = chain_id; + eth_cfg.set_spec_and_mainnet_gas_params(config.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) { + Ok(tx) => tx, + Err(_) if test.expect_exception.is_some() => { + return Ok(Some(SkipReason::UnbuildableInvalidTransaction)) } - } - - 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) - } -} - -fn run_test_worker(state: TestRunnerState, config: TestRunnerConfig) -> Result<(), TestError> { - loop { - if !config.keep_going && state.n_errors.load(Ordering::SeqCst) > 0 { - return Ok(()); + Err(error) => { + return Err(Failure::new(FailureKind::Fixture, format!("transaction: {error}"))) } + }; + let tx = + OpTx(OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() }); - 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); - } - } - } -} - -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), + 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 { + 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(test, unit.out.as_ref(), &result, &state)?; + Ok(None) } -/// Run all test files in parallel or single-threaded mode +/// 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. /// -/// # 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, - }), - } +/// 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; } - - 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(); - - if n_errors == 0 && n_thread_errors == 0 { - println!("All tests passed!"); - Ok(()) - } 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}"); - } - } - Err(thread_errors.swap_remove(0)) + 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); } } -#[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); - } - 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()); - } - - #[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()); - } - - #[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); +/// Judges an executed entry 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. +fn check( + 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(expected, error) { + Ok(()) => {} + Err(Mismatch::Wrong { got }) => { + return Err(Failure::new( + FailureKind::WrongException, + format!("expected {expected}, rejected as {got:?}: {error:?}"), + )) } - other => panic!("expected GasUsedMismatch, got {other:?}"), - } - } - - #[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"); + Err(Mismatch::Unnamed) => { + return Err(Failure::new( + FailureKind::UnnamedException, + format!("expected {expected}, rejected with {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); - } - other => panic!("expected UnexpectedOutput, got {other:?}"), + }, + (Some(expected), Ok(result)) => { + return Err(Failure::new( + FailureKind::MissingException, + format!("expected {expected}, executed: {}", describe(result)), + )) } - } - - #[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); - } - 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); + if logs_hash != test.logs { + return Err(Failure::new( + FailureKind::LogsMismatch, + format!("logs hash {logs_hash}, expected {}", test.logs), + )); } - - #[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:?}"), - } + let root = state_root(state.cache.trie_account()); + if root != test.hash { + let executed = result.as_ref().map(|r| format!("; {}", describe(r))).unwrap_or_default(); + return Err(Failure::new( + FailureKind::StateRootMismatch, + 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/tests/runner.rs b/crates/mega-state-test/tests/runner.rs new file mode 100644 index 000000000..5cfedeb05 --- /dev/null +++ b/crates/mega-state-test/tests/runner.rs @@ -0,0 +1,364 @@ +//! 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::{ + 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 } +} + +/// 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!(summary.gate(fork, 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. +#[test] +fn test_the_same_fixture_fails_in_satin_mode() { + let dir = tempfile::tempdir().unwrap(); + let unit = unit(&[Fork::Osaka], json!({ "gasLimit": ["0x0f4240"] })); + 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]); + + let report = run(&[path], config(Mode::Satin, Fork::Osaka)); + assert_eq!(failure_kind(outcomes(&report)[0]), Some(FailureKind::StateRootMismatch)); + 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)]); + let summary = report.summary(); + assert_eq!(summary.unattributed, 2); + assert_eq!( + summary.gate(Fork::Osaka, 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, and a fixture failure when it does not. +#[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 others = write( + dir.path(), + "o.json", + json!({ "a_both": both, "b_expected_invalid": expected_invalid, "c_unbuildable": unbuildable }), + ); + + let report = run(&[collision, others], config(Mode::Equivalence, Fork::Osaka)); + let outcomes = outcomes(&report); + assert_eq!(outcomes.len(), 4, "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!(outcomes[3], &Outcome::Skipped { reason: SkipReason::CreateCollisionWithStorage }); + let summary = report.summary(); + assert_eq!((summary.defined, summary.executed, summary.skipped_total()), (4, 2, 2)); + assert_eq!( + summary.gate(Fork::Osaka, Some(2), Some(2), false), + ["1 failed tests no deviation explains"] + ); + assert_eq!( + summary.gate(Fork::Osaka, Some(3), Some(1), false)[1..], + ["2 tests executed, 3 pinned".to_string(), "2 tests skipped, 1 pinned".to_string()] + ); +} + +/// 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!(summary.gate(Fork::Osaka, 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]); +} + +/// In equivalence mode a registered deviation explains a failure of its kind in its files on its +/// fork, and nothing else; Satin mode attributes nothing. +#[test] +fn test_deviations_explain_their_own_failures_only() { + let dir = tempfile::tempdir().unwrap(); + let mut wrong = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + wrong["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let mut wrong_logs = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + wrong_logs["post"]["Osaka"][0]["logs"] = json!(B256::repeat_byte(1)); + let registered = write( + dir.path(), + "frontier/opcodes/test_all_opcodes.json", + json!({ "a_root": wrong.clone(), "b_logs": wrong_logs }), + ); + let elsewhere = write(dir.path(), "frontier/opcodes/other.json", json!({ "a_root": wrong })); + + let report = + run(&[registered.clone(), elsewhere.clone()], config(Mode::Equivalence, Fork::Osaka)); + let deviations: Vec<_> = report + .results + .iter() + .map(|result| match &result.outcome { + Outcome::Failed(failure) => failure.deviation, + _ => panic!("every test fails"), + }) + .collect(); + assert_eq!(deviations, [None, Some("amsterdam-opcodes-on-osaka"), None]); + let summary = report.summary(); + assert_eq!(summary.deviated.get("amsterdam-opcodes-on-osaka"), Some(&1)); + assert_eq!(summary.unattributed, 2); + + let report = run(&[registered, elsewhere], config(Mode::Satin, Fork::Osaka)); + assert_eq!(report.summary().unattributed, 3); +} diff --git a/crates/state-test/AGENTS.md b/crates/state-test/AGENTS.md index d20279268..014893022 100644 --- a/crates/state-test/AGENTS.md +++ b/crates/state-test/AGENTS.md @@ -1,12 +1,13 @@ # 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. +- `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`. +- 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..8a8fdbda7 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,15 @@ 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] +tempfile.workspace = true diff --git a/crates/state-test/README.md b/crates/state-test/README.md index 58ee76f85..96db52850 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -1,18 +1,15 @@ -# 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. - -- **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. - -`--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 +What the two modes are, how a test is 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/main.rs b/crates/state-test/src/main.rs index 65b70acda..6e3a868f4 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -1,270 +1,158 @@ -//! 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. #![cfg_attr(not(test), warn(unused_crate_dependencies))] -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] + +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, Report, Summary}, + Fork, Mode, }; -use std::{path::PathBuf, str::FromStr}; -use mega_evm::MegaSpecId; -use serde_json::json; +/// How many unattributed failures 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")] +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 registered deviation explains exactly as many failed + /// tests as it pins for the fork. #[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(); - } - if self.bench { - return self.run_bench(); +fn main() -> ExitCode { + 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; } - 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)? + let found = find_json_files(path); + if found.is_empty() { + eprintln!("error: no JSON fixtures under {}", path.display()); + return ExitCode::FAILURE; } - 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, + }; + 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 = summary.gate( + cmd.fork, + 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]) + for (kind, count) in &summary.failed { + println!(" failed {:<34} {count}", kind.name()); } - - #[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); - } - - #[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 (id, count) in &summary.deviated { + let pinned = deviations::by_id(id).map_or(0, |d| d.pinned(report.fork)); + println!(" deviated {id:<34} {count} (pinned {pinned})"); + } + 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); } } - - #[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}" - ); + for (path, failure) in &report.file_failures { + println!(" unreadable {path}\n {}", failure.detail); } } diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs new file mode 100644 index 000000000..a5970a3cc --- /dev/null +++ b/crates/state-test/tests/cli.rs @@ -0,0 +1,143 @@ +//! 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. + +use std::{ + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +use serde_json::json; +use state_test::{ + 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 pins a count on the full release; one test explains none. + let output = state_test(&["--fork", "Osaka", "--expect-deviations"], &path); + assert_eq!(output.status.code(), Some(1)); + assert!(stdout(&output).contains("deviation amsterdam-opcodes-on-osaka explains 0")); +} + +#[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"); + } +} From 3a4da5f6e35b18691a680126845ee84cd04f8651 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 10:56:51 -0700 Subject: [PATCH 069/458] ci(exec-spec): gate MegaEvm on the execution-spec fixtures exec-spec-satin.yml downloads the fixture releases the fork's runner names at the pinned tag, runs equivalence mode on the Osaka and Amsterdam entries as a gate with the executed, skipped and deviation counts pinned, and reports Satin mode in the step summary without failing the job. The fork-runner workflow stays as it is. --- .github/workflows/exec-spec-satin.yml | 208 ++++++++++++++++++++++++++ .github/workflows/exec-spec.yml | 4 +- .github/workflows/replay-bench.yml | 9 +- REVIEW.md | 14 +- 4 files changed, 225 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/exec-spec-satin.yml diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml new file mode 100644 index 000000000..768db9153 --- /dev/null +++ b/.github/workflows/exec-spec-satin.yml @@ -0,0 +1,208 @@ +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, whose count is pinned +# there; 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 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. +# Not a required check. + +on: + workflow_dispatch: + pull_request: + 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 + 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: + exec-spec-satin: + name: execution-spec tests on Satin + 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 + # deviation counts in crates/mega-state-test/src/deviations.rs. + OSAKA_EXECUTED: "19465" + OSAKA_SKIPPED: "52" + AMSTERDAM_EXECUTED: "15754" + AMSTERDAM_SKIPPED: "72" + 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" + { + echo "main=$main_url/$main_version/fixtures_develop.tar.gz" + echo "devnet=$devnet_url/$devnet_version/$devnet_tar" + echo "key=eest-state-tests-$main_version-$devnet_version" + } >> "$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 }} + run: | + set -euo pipefail + fetch() { + mkdir -p "fixtures/$1" + curl -fsSL --retry 5 --retry-delay 2 --retry-all-errors "$2" -o "fixtures/$1.tar.gz" + # Only the state tests: the archive's top-level `fixtures/` directory is stripped, as + # the fork's runner strips it. + tar -xzf "fixtures/$1.tar.gz" --strip-components=1 -C "fixtures/$1" fixtures/state_tests + rm "fixtures/$1.tar.gz" + } + fetch main "$MAIN_URL" + fetch devnet "$DEVNET_URL" + + - 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 |" + 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) |"' \ + "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" diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 5493ccd01..f027dcc6f 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: diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml index 808da589e..e66f158da 100644 --- a/.github/workflows/replay-bench.yml +++ b/.github/workflows/replay-bench.yml @@ -104,10 +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. + # Disabled on the satin branch: the corpus under bench/replay/fixtures is + # keyed by the legacy Rex5 spec, and the Satin `state-test` has no `--bench` + # mode; the job returns with a corpus and a bench mode for Satin. (`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 diff --git a/REVIEW.md b/REVIEW.md index d8a3ac1ec..c50c65b76 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -93,10 +93,16 @@ 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 its pinned count, 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. + It runs when the engine, the runner or the lock changes. +- 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 a count that moves 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. ### Instruction counts (CodSpeed) @@ -135,7 +141,7 @@ These checks guard every change to the Satin engine. - `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. + - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the replay corpus, which is keyed by the legacy Rex5 spec, and a bench mode of the state-test tool exist for Satin. ## Dev tools and test infrastructure From 5ff69930d95e8c0cc5c614756274fbe630ee57c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:02:31 -0700 Subject: [PATCH 070/458] test(bench): measure the corpus without building the EVM A scenario is one block: Scenario::evm builds its EVM once and run_on runs every transaction on it, committing each before the next, as a block executor does; run is the two together. The corpus bench builds the EVM in the setup, as transact does, so both families measure per-transaction execution. A test holds one EVM per scenario to what a fresh EVM per transaction gave on every bench scenario. --- crates/mega-evm/benches/corpus.rs | 16 +++- crates/mega-evm/src/test_utils/scenario.rs | 99 ++++++++++++++++++++-- 2 files changed, 102 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/benches/corpus.rs b/crates/mega-evm/benches/corpus.rs index efccc8300..eb440126d 100644 --- a/crates/mega-evm/benches/corpus.rs +++ b/crates/mega-evm/benches/corpus.rs @@ -3,9 +3,13 @@ //! 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. +//! means only that the execution or the pricing of those scenarios moved. +//! +//! 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; @@ -53,7 +57,11 @@ fn bench_corpus(c: &mut Criterion) { 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); + b.iter_batched( + || scenario.evm(scenario.database()), + |mut evm| scenario.run_on(&mut evm), + BatchSize::SmallInput, + ); }); } group.finish(); diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 0aeb64f67..53b08b572 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) } } @@ -467,6 +494,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(200_000))]); + 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() { From db2602fe8b5bd71da3c66efaae9f35ddb745273f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:03:31 -0700 Subject: [PATCH 071/458] docs: describe the execution-spec gate and the ported crates AGENTS.md lists the two state-test crates as members, the commands that run the gate, the neutral configuration in test_utils and a Test Gates section; the root README lists the runner. --- AGENTS.md | 40 ++++++++++++++++++++++++++++++---------- README.md | 3 ++- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f03e0f261..21e22482d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,13 @@ 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 +# 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 +# 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 @@ -56,16 +63,16 @@ 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-state-test` | `crates/mega-state-test` | yes | Execution-spec state-test runner on Satin: the equivalence gate, the report | +| `state-test` | `crates/state-test` | yes | The runner's CLI | +| `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. +The two tool binaries `mega-evme` and `mega-t8n` 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. ### Dependencies on the forks @@ -102,7 +109,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -216,6 +223,16 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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`. +## Test Gates + +`REVIEW.md` lists every check a pull request meets; two of them are this repository's own execution gates. + +- **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`. + Every failure must be explained by a deviation in `crates/mega-state-test/src/deviations.rs`, with its rule, its reason and its pinned count; 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. + ## Version Control `satin` is the integration branch of the new engine; pull requests for Satin target `satin`. @@ -277,6 +294,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 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 fixtures it fails, its pinned count) and regenerates `crates/mega-state-test/DEVIATIONS.md`; a failure that is a bug is fixed, never registered. + A price `MegaETH` sets is not a deviation: the neutral configuration takes it out of equivalence mode, and a new pricing dimension extends the neutral configuration 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. diff --git a/README.md b/README.md index e99cff180..90e6d12e2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,8 @@ A specialized Ethereum Virtual Machine (EVM) implementation tailored for MegaETH | [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 | +| [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 From 7cb6b11c5b7b871732ffec3b3aa44f0dee02f83c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:10:47 -0700 Subject: [PATCH 072/458] fix(limit): hold a creator to its budget with the nonce record a failed creation leaves it --- AGENTS.md | 1 + crates/mega-evm/src/evm/execution.rs | 26 +++--- crates/mega-evm/src/limit/frame_limit.rs | 5 +- crates/mega-evm/src/limit/limit.rs | 27 +++++- crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/tests/satin/data_size.rs | 100 ++++++++++++++++++++++- 6 files changed, 146 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 01ddb4939..640b58e77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,6 +169,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. - **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. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index bf6483cbd..2f51b9226 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -447,8 +447,9 @@ impl EvmTr for MegaEvm( action } -/// 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. Under a latch it is -/// the latter: the child that crossed the limit reverted, and its caller must not resume. +/// A frame runs here for the first time or after a child returned into it. A stop is always the +/// latter. Under a latch, the child that crossed the limit reverted, and its caller must not +/// resume. Without one, the child was a failed creation whose nonce record put its creator over +/// its budget, and the creator reverts alone. #[inline] fn before_frame_run( - ctx: &MegaContext, + ctx: &mut MegaContext, frame: &EthFrame, ) -> Option { - let latched = ctx.additional_limit.latched()?; + let stop = ctx.additional_limit.stop_before_run()?; Some(InterpreterAction::new_return( InstructionResult::Revert, - latched.revert_data(), + stop.revert_data(), frame.interpreter.gas, )) } diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 5fd8a5452..1bbdf1019 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -244,8 +244,9 @@ impl FrameLimitTracker { /// 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. pub(crate) fn pop(&mut self, success: bool) -> Option { let lane = self.lanes.pop()?; if success { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6d0732256..5582c3dff 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -40,6 +40,9 @@ pub struct AdditionalLimit { limits: EvmTxRuntimeLimits, /// The transaction-level stop, once a limit latched one. latched: Option, + /// 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 the transaction's call target is an applied EIP-7702 authority, whose account /// write the transaction's lane already counts. target_is_authority: bool, @@ -88,6 +91,7 @@ impl AdditionalLimit { self.tracker.reset(); self.staged = None; self.latched = None; + self.resume_stop = None; self.target_is_authority = false; self.sender = Address::ZERO; self.frame_began = false; @@ -138,6 +142,14 @@ impl AdditionalLimit { LimitCheck::WithinLimit } + /// The stop the running frame returns instead of running another instruction: the latched + /// one, or the one [`on_frame_return`](Self::on_frame_return) left for a caller its child put + /// over its budget. Taking it clears the latter, which stops one frame. + pub(crate) fn stop_before_run(&mut self) -> Option { + let resume_stop = self.resume_stop.take(); + self.latched.or(resume_stop) + } + /// 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) { @@ -538,6 +550,16 @@ impl AdditionalLimit { /// 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. /// + /// Then the caller is held to its limits with what it now holds, and a crossing is the stop + /// it returns before it runs on ([`stop_before_run`](Self::stop_before_run)): its own + /// frame-local revert for its budget, the latch for the transaction's limit. One return adds + /// to a caller what no check has held it to: the nonce record a failed creation leaves its + /// creator. 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. Any other return leaves the caller + /// within its limits: a failure hands it nothing, and a success hands it no more than the + /// share it gave. + /// /// 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"] @@ -547,7 +569,10 @@ impl AdditionalLimit { // opcode, which failed after making it. self.pending_frame_charge = FrameCharge::NONE; let success = result.instruction_result().is_ok(); - self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)) + let refund = self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)); + let check = self.check(); + self.resume_stop = check.exceeded_limit().then_some(check); + refund } /// Settles the transaction's outermost frame: pops its lane unless the frame already diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index e222c4dc8..b62d6ed40 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -16,7 +16,9 @@ //! 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 its budget reverts alone and its caller resumes; a transaction that crosses its limit -//! is stopped through the latch ([`AdditionalLimit`]). +//! is stopped through the latch ([`AdditionalLimit`]). 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 budget with it before it runs on, and reverts alone if it crossed. //! //! What is counted, and when: //! diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 81ad4329f..b206a8f2d 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -18,8 +18,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, GAS, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, - SELFDESTRUCT, STOP, + CALL, CREATE, CREATE2, GAS, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, + REVERT, SELFDESTRUCT, STOP, }, context::result::{ExecutionResult, HaltReason}, context_interface::cfg::GasId, @@ -1077,3 +1077,99 @@ fn test_a_body_over_the_limit_is_stopped_before_an_interceptor() { .revert_data(), ); } + +/* ---------- 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 does not latch"); + 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", + ); + } + } +} From d43f144d4b61b6608c89b2ee3bd76229f24eab76 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:12:57 -0700 Subject: [PATCH 073/458] fix(limit): count deployed code only when revm would deposit it --- AGENTS.md | 2 +- crates/mega-evm/src/evm/execution.rs | 21 ++++- crates/mega-evm/src/limit/limit.rs | 16 ++-- crates/mega-evm/src/limit/mod.rs | 3 +- crates/mega-evm/tests/satin/data_size.rs | 104 ++++++++++++++++++++++- 5 files changed, 132 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 640b58e77..8633f6b4c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -136,7 +136,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code before the creation is committed, an Oracle hint before it is forwarded. + 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code revm would accept before the creation is committed (code starting with `0xEF` or over the code-size limit fails the creation alone and is not counted), an Oracle hint before it is forwarded. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 for the transactions the builder chooses: the transaction that crosses it is packed and the next one refused, and a deposit is never refused but still counts. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 2f51b9226..3081d9e8a 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -19,7 +19,7 @@ use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, transaction::TransactionType, - ContextError, ContextTr, FrameStack, JournalTr, Transaction, + Cfg, ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, @@ -613,6 +613,10 @@ where /// Counts the bytecode a creation is about to deposit, and turns that return into the stop /// when the bytes cross a limit, before revm commits the creation. +/// +/// Only code `return_create` would deposit is counted ([`deposits`]). Code it refuses fails the +/// creation there, alone, and the chain keeps none of it. Counted, those bytes could cross the +/// transaction's limit and stop every frame above a creation that fails by itself. fn meter_deployed_code( ctx: &mut MegaContext, frame: &EthFrame, @@ -620,12 +624,25 @@ fn meter_deployed_code( ) -> InterpreterAction { if frame.data.is_create() { if let InterpreterAction::Return(result) = &mut action { - ctx.additional_limit.on_create_return(result); + if deposits(ctx.cfg(), &result.output) { + ctx.additional_limit.on_create_return(result); + } } } action } +/// Whether `return_create` deposits `code` a creation returns, as far as the code decides it: +/// no longer than the code-size limit, and not starting with `0xEF` unless EIP-3541 is off, both +/// read from the configuration `return_create` reads. +/// +/// What `return_create` charges for the deposit is not part of it: the count comes before that +/// charge, so a crossing is the stop and not an out-of-gas. `return_create` also gates the two +/// checks on EIP-170 and London, which Satin's base spec, Osaka, enables. +fn deposits(cfg: &impl Cfg, code: &[u8]) -> bool { + code.len() <= cfg.max_code_size() && (cfg.is_eip3541_disabled() || code.first() != Some(&0xEF)) +} + /// 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 5582c3dff..a9dee2b02 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -372,15 +372,17 @@ impl AdditionalLimit { /// Counts the code a creation is about to deposit, on the creation's own lane, and turns the /// return into the stop when that crosses a limit. /// - /// Called from the frame run, on a successful return, before revm's `return_create` commits - /// the creation's journal checkpoint. A rewrite after that commit would leave the code - /// deployed: the checkpoint is already gone, and flipping the frame result does not reopen - /// it. A stop here makes `return_create` revert the checkpoint instead, so the code is not - /// written. 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. + /// Called from the frame run, on a successful return whose code `return_create` would accept, + /// before it charges for the deposit and commits the creation's journal checkpoint. A rewrite + /// after that commit would leave the code deployed: the checkpoint is already gone, and + /// flipping the frame result does not reopen it. A stop here makes `return_create` revert the + /// checkpoint instead, so the code is not written. 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 return that is already a revert or a halt deposits nothing, and its output is the - /// revert data, not code. Empty code deposits nothing either. + /// revert data, not code. Empty code deposits nothing either, and neither does code + /// `return_create` refuses: that fails the creation there, and is never counted. pub(crate) fn on_create_return(&mut self, result: &mut InterpreterResult) { if !result.result.is_ok() { return; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index b62d6ed40..919db8c7b 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -28,7 +28,8 @@ //! - 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; +//! no code behind. Only code revm would deposit counts: code starting with `0xEF` or over the +//! code-size limit fails the creation alone and is not counted; //! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded. //! //! A record is checked against the limits before its history is charged: a record the limit diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index b206a8f2d..6d946ae1f 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -5,12 +5,14 @@ //! through the same latch every other transaction-level limit uses. //! //! The body is counted before any frame and kept on every path. Deployed code is counted on the -//! creation's lane, one byte per byte, before the creation is committed. +//! 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, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, @@ -18,8 +20,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, CREATE2, GAS, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, - REVERT, SELFDESTRUCT, STOP, + CALL, CREATE, CREATE2, GAS, ISZERO, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, + RETURNDATASIZE, REVERT, SELFDESTRUCT, SSTORE, STOP, }, context::result::{ExecutionResult, HaltReason}, context_interface::cfg::GasId, @@ -426,6 +428,102 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { } } +/// 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 crosses the transaction's limit and stops it. +/// +/// `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| { + 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); + 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: counted, and it crosses. + let (stopped, _) = run(&constructor_returning_from(0x00, len.min(max)), inspect); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: mega_evm::TX_BODY_SIZE + at_start + len.min(max), + frame_local: false, + }), + "{case}", + ); + } + } +} + /// The output of a reverting creation is revert data, not deployed code, so it is not counted. #[test] fn test_a_reverting_creation_does_not_count_its_output() { From dc83445ef6e74892842fdaf5ae1b940afcd18aa3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:13:44 -0700 Subject: [PATCH 074/458] test(limit): write the caller's slot before the child that writes back and reverts --- .../mega-evm/tests/satin/data_size_counts.rs | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 6215c5652..739700ca0 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -243,22 +243,6 @@ fn test_what_each_transaction_keeps() { call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), records(1), ), - ( - "a child that writes a slot back and reverts, under a caller that wrote one", - with_code( - call_to(CALL, LIBRARY, 0).sstore(U256::from(5), U256::from(1)).stop().build(), - ) - .account_code( - LIBRARY, - BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::ZERO) - .revert() - .build(), - ), - call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records(1), - ), ( "a SELFDESTRUCT that moves value to an existing account", with_code( @@ -285,6 +269,39 @@ fn test_what_each_transaction_keeps() { } } +/// 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] From 2b287140ea5322ec14c8164afad08fc0e91e44a1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 11:25:18 -0700 Subject: [PATCH 075/458] fix(state-test): skip only named unbuildable transactions, reject duplicate names A transaction the fixture types cannot build is skipped only when the fixture expects the reason it cannot be built: an invalid signature, or a blob or EIP-7702 transaction without a recipient; another expected reason is a wrong exception. A test name that appears twice in a fixture file fails the file instead of one test replacing the other. --- crates/mega-state-test/README.md | 5 +- crates/mega-state-test/src/exceptions.rs | 136 ++++++++++++++++++++++- crates/mega-state-test/src/runner.rs | 60 ++++++++-- crates/mega-state-test/tests/runner.rs | 46 ++++++-- 4 files changed, 224 insertions(+), 23 deletions(-) diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 4ebfd7147..543075abd 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -35,12 +35,13 @@ As the revm fork's reference runner judges it, and more strictly where that runn - 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 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. +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 diff --git a/crates/mega-state-test/src/exceptions.rs b/crates/mega-state-test/src/exceptions.rs index 70f35b4c5..0b434fbc9 100644 --- a/crates/mega-state-test/src/exceptions.rs +++ b/crates/mega-state-test/src/exceptions.rs @@ -20,6 +20,8 @@ use mega_evm::{ revm::context::result::{EVMError, InvalidTransaction}, }; +use crate::types::{TestError, TestUnit}; + /// The prefix of every transaction exception name. const PREFIX: &str = "TransactionException."; @@ -76,12 +78,50 @@ pub fn check( let EVMError::Transaction(OpTransactionError::Base(invalid)) = error else { return Err(Mismatch::Unnamed); }; - let got = names(invalid); + check_names(expected, names(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. +fn check_names(expected: &str, got: &'static [&'static str]) -> Result<(), Mismatch> { if got.is_empty() { return Err(Mismatch::Unnamed); } - let expected = expected.split('|').map(|name| name.trim().strip_prefix(PREFIX).unwrap_or(name)); - let mut expected = expected.peekable(); + 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 { @@ -175,4 +215,94 @@ mod tests { assert_eq!(check("TYPE_3_TX_ZERO_BLOBS", &error), Ok(())); assert!(check("", &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/runner.rs b/crates/mega-state-test/src/runner.rs index 3b45c6e31..0f3f3fd47 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -11,7 +11,10 @@ //! 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; +//! 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. //! @@ -47,7 +50,10 @@ use mega_evm::{ ExecuteCommitEvm, }, }; -use serde::Serialize; +use serde::{ + de::{Error as _, MapAccess, Visitor}, + Deserialize, Deserializer, Serialize, +}; use walkdir::WalkDir; use crate::{ @@ -360,8 +366,9 @@ 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, format!("read: {error}")))?; - let suite: TestSuite = serde_json::from_str(&json) - .map_err(|error| Failure::new(FailureKind::Fixture, format!("parse: {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(); @@ -395,6 +402,35 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> Ok(results) } +/// 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); + +impl<'de> Deserialize<'de> for UniqueNames { + fn deserialize>(deserializer: D) -> Result { + struct Tests; + impl<'de> Visitor<'de> for Tests { + type Value = UniqueNames; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> 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 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))) + } + } + deserializer.deserialize_map(Tests) + } +} + /// Names the deviation that explains a failure, in equivalence mode. fn attribute(config: Config, path: &str, outcome: Outcome) -> Outcome { match outcome { @@ -462,12 +498,18 @@ fn execute_and_check( 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) { - Ok(tx) => tx, - Err(_) if test.expect_exception.is_some() => { - return Ok(Some(SkipReason::UnbuildableInvalidTransaction)) + 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(Some(SkipReason::UnbuildableInvalidTransaction)), + Err(_) => Err(Failure::new( + FailureKind::WrongException, + format!("expected {expected}, the transaction cannot be built: {error}"), + )), + } } - Err(error) => { + (Err(error), None) => { return Err(Failure::new(FailureKind::Fixture, format!("transaction: {error}"))) } }; diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index 5cfedeb05..14117f7ce 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -241,7 +241,8 @@ fn test_an_expected_output_must_be_produced() { /// 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, and a fixture failure when it does not. +/// 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(); @@ -253,31 +254,58 @@ fn test_what_is_counted_and_what_is_skipped() { 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 }), + 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(), 4, "one entry per unit for Osaka, none for Amsterdam"); + 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!(outcomes[3], &Outcome::Skipped { reason: SkipReason::CreateCollisionWithStorage }); + 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()), (4, 2, 2)); + assert_eq!((summary.defined, summary.executed, summary.skipped_total()), (5, 3, 2)); assert_eq!( - summary.gate(Fork::Osaka, Some(2), Some(2), false), - ["1 failed tests no deviation explains"] + summary.gate(Fork::Osaka, Some(3), Some(2), false), + ["2 failed tests no deviation explains"] ); assert_eq!( - summary.gate(Fork::Osaka, Some(3), Some(1), false)[1..], - ["2 tests executed, 3 pinned".to_string(), "2 tests skipped, 1 pinned".to_string()] + summary.gate(Fork::Osaka, 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 ); } From 7fca0d6c478e9c326a84df7713696c7887eb6c42 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:06:54 -0700 Subject: [PATCH 076/458] fix(state-test): list the exact entries each deviation explains A deviation now lists every fixture entry it explains (file, test, 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, which the runner now computes on a logs mismatch too and carries in the failure. A failure is a deviation's only when its entry is listed with those hashes, and the gate requires every listed entry to fail exactly as listed, so a listed entry that passes or fails another way fails the gate. The count is derived from the list. --- .github/workflows/exec-spec-satin.yml | 13 +- AGENTS.md | 4 +- REVIEW.md | 4 +- crates/mega-state-test/AGENTS.md | 8 +- crates/mega-state-test/DEVIATIONS.md | 79 ++- crates/mega-state-test/README.md | 10 +- crates/mega-state-test/src/deviations.rs | 639 +++++++++++++++++++---- crates/mega-state-test/src/runner.rs | 238 ++++++--- crates/mega-state-test/tests/runner.rs | 185 +++++-- crates/state-test/src/main.rs | 56 +- crates/state-test/tests/cli.rs | 12 +- 11 files changed, 994 insertions(+), 254 deletions(-) diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index 768db9153..b89cdcb9a 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -6,8 +6,9 @@ name: Execution-spec tests on Satin # - 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, whose count is pinned -# there; the executed and skipped counts are pinned below. +# 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. # @@ -55,7 +56,7 @@ jobs: # 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 - # deviation counts in crates/mega-state-test/src/deviations.rs. + # entries the deviations in crates/mega-state-test/src/deviations.rs list. OSAKA_EXECUTED: "19465" OSAKA_SKIPPED: "52" AMSTERDAM_EXECUTED: "15754" @@ -162,8 +163,8 @@ jobs: { echo "### Equivalence mode" echo - echo "| Fixtures | Executed | Skipped | Passed | Deviated | Unattributed |" - 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 @@ -171,7 +172,7 @@ jobs: --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) |"' \ + 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 diff --git a/AGENTS.md b/AGENTS.md index 21e22482d..bb2830bc8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -230,7 +230,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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`. - Every failure must be explained by a deviation in `crates/mega-state-test/src/deviations.rs`, with its rule, its reason and its pinned count; the executed and skipped counts are pinned in the workflow and equal the fork runner's. + 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. ## Version Control @@ -295,7 +295,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. - **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 fixtures it fails, its pinned count) and regenerates `crates/mega-state-test/DEVIATIONS.md`; a failure that is a bug is fixed, never registered. + 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 `MegaETH` sets is not a deviation: the neutral configuration takes it out of equivalence mode, and a new pricing dimension extends the neutral configuration rather than the registry. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. diff --git a/REVIEW.md b/REVIEW.md index c50c65b76..fd4a10582 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -97,10 +97,10 @@ These checks guard every change to the Satin engine. 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 its pinned count, and the executed and skipped counts equal the fork runner's pins. + 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. It runs when the engine, the runner or the lock changes. -- 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 a count that moves says which fixtures moved and why. +- 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. diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index cb8288747..2a50a71c2 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -12,7 +12,7 @@ The `state-test` CLI (`crates/state-test`) is a thin front end over this crate. - `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 its pinned count; `DEVIATIONS.md` is rendered from it. +- `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. - `tests/runner.rs`: the runner on fixtures written in the test, filled from revm's mainnet EVM on the fixture's fork. @@ -21,7 +21,7 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty ## KEY PATTERNS - 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 matches on fork, failure kind and a path fragment, and pins its count; the gate checks the pins with `--expect-deviations`. +- 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. ## ANTI-PATTERNS @@ -31,7 +31,7 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty - Do not reach an engine switch from here; the neutral configuration lives in `mega-evm` behind `test-utils`. ## WHERE TO LOOK -- Add or move a deviation: `src/deviations.rs`, then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +- 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 the pinned counts: `.github/workflows/exec-spec-satin.yml`. +- Change the pinned executed and skipped counts: `.github/workflows/exec-spec-satin.yml`. diff --git a/crates/mega-state-test/DEVIATIONS.md b/crates/mega-state-test/DEVIATIONS.md index ca4330691..c43706ef2 100644 --- a/crates/mega-state-test/DEVIATIONS.md +++ b/crates/mega-state-test/DEVIATIONS.md @@ -2,12 +2,12 @@ -The places Satin differs from Ethereum on purpose that the execution-spec gate meets. -In equivalence mode a failure one of them explains is counted against it, and the count is pinned; a failure none of them explains fails the gate. +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 tests on the pinned Osaka fixtures. +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. @@ -17,14 +17,16 @@ 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.** `state-root-mismatch`, in: +**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` -- `stBadOpcode/undefinedOpcodeFirstByte.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` ## `selfdestruct-burns-on-osaka` -37 failed tests on the pinned Amsterdam fixtures. +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. @@ -32,19 +34,56 @@ A contract self-destructed in the transaction that created it is removed as on S **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 post-state and logs Satin does for every one of these fixtures, and the fixtures' own post-state and logs on the Amsterdam spec. +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.** `state-root-mismatch`, `logs-mismatch`, in: - -- `amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json` -- `amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json` -- `amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json` -- `amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json` -- `amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json` -- `cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json` -- `cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json` -- `cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json` -- `frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json` -- `ported_static/stCreate2/create2_suicide/create2_suicide.json` -- `ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json` +**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 index 543075abd..6026cc535 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -54,6 +54,12 @@ 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, and `--trace` runs each test under an EIP-3155 tracer. +`--json-outcome` prints one JSON line per test, a failure's produced hashes included, and `--trace` runs each test under an EIP-3155 tracer. -A deviation added or moved updates `src/deviations.rs` and regenerates [`DEVIATIONS.md`](DEVIATIONS.md) with `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +## 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/deviations.rs b/crates/mega-state-test/src/deviations.rs index c2a9d996f..80f777726 100644 --- a/crates/mega-state-test/src/deviations.rs +++ b/crates/mega-state-test/src/deviations.rs @@ -1,4 +1,4 @@ -//! The places Satin differs from Ethereum on purpose, and the fixtures each one fails. +//! 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 @@ -6,14 +6,23 @@ //! the failures it explains; a failure no entry explains is unattributed, and one unattributed //! failure fails the gate. //! -//! An entry explains a failure by where the fixture lives and how it failed, not by the test's -//! name alone, and it pins how many failures it explains on the pinned fixture releases: a new -//! failure of the same shape moves the count and fails the gate as surely as an unattributed one, -//! and so does a fixed one. +//! 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::{runner::FailureKind, Fork}; +use crate::{ + runner::{Produced, TestId}, + Fork, +}; /// A place Satin differs from Ethereum on purpose. #[derive(Debug, Serialize)] @@ -24,29 +33,60 @@ pub struct Deviation { pub rule: &'static str, /// Why Satin keeps the rule, and why the neutral configuration cannot express Ethereum's. pub reason: &'static str, - /// Path fragments: a failure in a fixture file whose path contains one of them may be this - /// deviation's. - pub paths: &'static [&'static str], - /// The ways a fixture of those paths fails on this rule. - pub kinds: &'static [FailureKind], - /// The forks whose fixtures meet the rule. - pub forks: &'static [Fork], - /// How many failures the entry explains on the pinned fixture releases, per fork. - pub pinned: &'static [(Fork, usize)], + /// 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], +} + +/// 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 { - /// Whether a failure of `kind`, in the fixture at `path`, of `fork`, is this deviation's. - pub fn explains(&self, fork: Fork, path: &str, kind: FailureKind) -> bool { - let path = path.replace('\\', "/"); - self.forks.contains(&fork) && - self.kinds.contains(&kind) && - self.paths.iter().any(|fragment| path.contains(fragment)) + /// The entries the deviation lists for `fork`. + pub fn listed(&self, fork: Fork) -> &'static [Entry] { + if self.fork == fork { + self.entries + } else { + &[] + } + } + + /// 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 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 && { + let path = id.path.replace('\\', "/"); + path.strip_suffix(self.path).is_some_and(|dir| dir.is_empty() || dir.ends_with('/')) + } } +} - /// How many failures the entry explains on `fork`'s pinned release. - pub fn pinned(&self, fork: Fork) -> usize { - self.pinned.iter().find(|(f, _)| *f == fork).map_or(0, |(_, count)| *count) +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) } } @@ -63,10 +103,25 @@ pub const AMSTERDAM_OPCODES_ON_OSAKA: Deviation = Deviation { 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.", - paths: &["frontier/opcodes/test_all_opcodes.json", "stBadOpcode/undefinedOpcodeFirstByte.json"], - kinds: &[FailureKind::StateRootMismatch], - forks: &[Fork::Osaka], - pinned: &[(Fork::Osaka, 2)], + fork: Fork::Osaka, + 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, @@ -81,39 +136,332 @@ pub const SELFDESTRUCT_BURNS_ON_OSAKA: Deviation = Deviation { 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 \ - post-state and logs Satin does for every one of these fixtures, and the fixtures' own \ - post-state and logs on the Amsterdam spec. Whether Satin takes EIP-8246 is a decision for its \ - specification, not for this gate.", - paths: &[ - "amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json", - "amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json", - "amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json", - "amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json", - "amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json", - "cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json", - "cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", - "cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", - "frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json", - "ported_static/stCreate2/create2_suicide/create2_suicide.json", - "ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json", + 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, + 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" + )), + }, ], - kinds: &[FailureKind::StateRootMismatch, FailureKind::LogsMismatch], - forks: &[Fork::Amsterdam], - pinned: &[(Fork::Amsterdam, 37)], }; -/// The deviation that explains a failure of `kind` in the fixture at `path`, if one does. +/// The deviation in `registry` that explains a failure of the entry `id` of `fork`, which +/// produced `produced`, if one does. /// -/// Entries are disjoint: no failure is explained by two of them (a test checks it on the -/// registry's own paths), so the first that matches is the one. -pub fn attribute(fork: Fork, path: &str, kind: FailureKind) -> Option<&'static Deviation> { - DEVIATIONS.iter().find(|deviation| deviation.explains(fork, path, kind)) -} - -/// The deviation named `id`. -pub fn by_id(id: &str) -> Option<&'static Deviation> { - DEVIATIONS.iter().find(|deviation| deviation.id == id) +/// 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. @@ -123,22 +471,45 @@ pub fn render_markdown() -> String { "# Deviations\n\n\ \n\n\ - The places Satin differs from Ethereum on purpose that the execution-spec gate meets.\n\ - In equivalence mode a failure one of them explains is counted against it, and the count \ - is pinned; a failure none of them explains fails the gate.\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)); - for (fork, count) in deviation.pinned { - out.push_str(&format!("{count} failed tests on the pinned {fork} fixtures.\n\n")); - } + 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))); - let kinds: Vec<_> = - deviation.kinds.iter().map(|kind| format!("`{}`", kind.name())).collect(); - out.push_str(&format!("**Failures.** {}, in:\n\n", kinds.join(", "))); - for path in deviation.paths { - out.push_str(&format!("- `{path}`\n")); + 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() + )); } } out @@ -147,63 +518,131 @@ pub fn render_markdown() -> String { #[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.paths.is_empty() && !deviation.kinds.is_empty(), "{}", deviation.id); - assert!(!deviation.forks.is_empty(), "{}", deviation.id); - for (fork, count) in deviation.pinned { + 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!( - deviation.forks.contains(fork), - "{}: pins a fork it does not cover", - deviation.id + 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!(*count > 0, "{}: a zero pin is a stale entry", deviation.id); - } - for fork in deviation.forks { assert!( - deviation.pinned(*fork) > 0, - "{}: covers {fork} without a pin", + matches!( + entry.produced.kind(), + FailureKind::StateRootMismatch | FailureKind::LogsMismatch + ), + "{}: {entry}", deviation.id ); } - assert_eq!(by_id(deviation.id).map(|d| d.id), Some(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); + } } } - /// No two entries explain the same failure: every entry's own paths, on each fork and kind it - /// covers, are attributed to it and to nothing before it. + /// Entries are listed in path, name and index order, each once, and no entry is listed by two + /// deviations. #[test] - fn test_entries_are_disjoint() { + fn test_entries_are_ordered_and_disjoint() { + let mut all = BTreeSet::new(); for deviation in DEVIATIONS { - for &fork in deviation.forks { - for &kind in deviation.kinds { - for path in deviation.paths { - let path = format!("fixtures/state_tests/{path}/x.json"); - assert_eq!( - attribute(fork, &path, kind).map(|d| d.id), - Some(deviation.id), - "{path} ({fork}, {kind:?})" - ); - let others: Vec<_> = DEVIATIONS - .iter() - .filter(|other| { - other.id != deviation.id && other.explains(fork, &path, kind) - }) - .map(|other| other.id) - .collect(); - assert!(others.is_empty(), "{path}: also explained by {others:?}"); + 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() { diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index 0f3f3fd47..f0793462d 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -2,9 +2,10 @@ //! //! [`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 and, in equivalence mode, -//! the [deviation](crate::deviations::Deviation) that explains it, if one does). -//! [`Report::summary`] counts them, and [`Summary::gate`] is what the gate checks. +//! 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 @@ -46,7 +47,7 @@ use mega_evm::{ }, database::{EmptyDB, State}, inspector::{inspectors::TracerEip3155, InspectCommitEvm}, - primitives::{Bytes, KECCAK_EMPTY, U256}, + primitives::{Bytes, B256, KECCAK_EMPTY, U256}, ExecuteCommitEvm, }, }; @@ -57,7 +58,7 @@ use serde::{ use walkdir::WalkDir; use crate::{ - deviations, + deviations::{self, Deviation}, exceptions::{self, Mismatch}, mode::MAX_BLOBS_PER_TX, roots::{logs_hash, state_root}, @@ -79,6 +80,9 @@ pub struct Config { 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. @@ -135,11 +139,50 @@ impl FailureKind { } } +/// 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, + }, +} + +impl Produced { + /// The failure these hashes are. + pub const fn kind(self) -> FailureKind { + match self { + Self::StateRoot(_) => FailureKind::StateRootMismatch, + Self::Logs { .. } => FailureKind::LogsMismatch, + } + } +} + +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}") + } + } + } +} + /// 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. @@ -148,7 +191,16 @@ pub struct Failure { impl Failure { fn new(kind: FailureKind, detail: impl Into) -> Self { - Self { kind, detail: detail.into(), deviation: None } + Self { kind, produced: None, detail: detail.into(), deviation: None } + } + + fn produced(produced: Produced, detail: impl Into) -> Self { + Self { + kind: produced.kind(), + produced: Some(produced), + detail: detail.into(), + deviation: None, + } } } @@ -183,6 +235,9 @@ pub struct Report { 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. @@ -210,6 +265,8 @@ pub struct Summary { 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, @@ -230,48 +287,6 @@ impl Summary { pub fn deviated_total(&self) -> usize { self.deviated.values().sum() } - - /// 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 registered deviation's count must equal its pin for `fork` - /// — a deviation that explains fewer failures than it pins is as much a change as one that - /// explains more. - pub fn gate( - &self, - fork: Fork, - expected_executed: Option, - expected_skipped: Option, - check_deviations: bool, - ) -> Vec { - let mut problems = Vec::new(); - if self.file_failures > 0 { - problems.push(format!("{} fixture files could not be read", self.file_failures)); - } - if self.unattributed > 0 { - problems.push(format!("{} failed tests no deviation explains", self.unattributed)); - } - if let Some(expected) = expected_executed.filter(|&n| n != self.executed) { - problems.push(format!("{} tests executed, {expected} pinned", self.executed)); - } - let skipped = self.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 deviations::DEVIATIONS { - let got = self.deviated.get(deviation.id).copied().unwrap_or(0); - let pinned = deviation.pinned(fork); - if got != pinned { - problems.push(format!( - "deviation {} explains {got} failed tests on {fork}, {pinned} pinned", - deviation.id - )); - } - } - } - problems - } } impl Report { @@ -300,6 +315,9 @@ impl Report { } } } + for unreproduced in self.unreproduced() { + *summary.unreproduced.entry(unreproduced.deviation.id).or_default() += 1; + } summary } @@ -310,6 +328,90 @@ impl Report { _ => 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)); + } + 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 + } +} + +/// An entry a deviation lists that did not fail as listed. +#[derive(Debug)] +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 fmt::Display for TestId { @@ -357,7 +459,14 @@ pub fn run(files: &[PathBuf], config: Config) -> Report { 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, files: files.len(), results, file_failures } + 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 @@ -391,7 +500,7 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> Outcome::Failed(Failure::new(FailureKind::Panic, panic_message(&panic))) }), }; - let outcome = attribute(config, &path_str, outcome); + let outcome = attribute(config, &id, outcome); if config.json_outcome { print_outcome(config, &id, &outcome); } @@ -431,12 +540,13 @@ impl<'de> Deserialize<'de> for UniqueNames { } } -/// Names the deviation that explains a failure, in equivalence mode. -fn attribute(config: Config, path: &str, outcome: Outcome) -> Outcome { +/// 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.fork, path, failure.kind) - .map(|deviation| deviation.id); + failure.deviation = + deviations::attribute(config.deviations, config.fork, id, failure.produced) + .map(|deviation| deviation.id); Outcome::Failed(failure) } outcome => outcome, @@ -561,7 +671,8 @@ fn undo_fee_vault_credit(unit: &TestUnit, state: &mut State, basefee: u /// /// 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. +/// 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( test: &Test, expected_output: Option<&Bytes>, @@ -597,17 +708,20 @@ fn check( } 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::new( - FailureKind::LogsMismatch, - format!("logs hash {logs_hash}, expected {}", 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 + ), )); } - let root = state_root(state.cache.trie_account()); if root != test.hash { - let executed = result.as_ref().map(|r| format!("; {}", describe(r))).unwrap_or_default(); - return Err(Failure::new( - FailureKind::StateRootMismatch, + return Err(Failure::produced( + Produced::StateRoot(root), format!("state root {root}, expected {}{executed}", test.hash), )); } diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index 14117f7ce..aa491e480 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -13,6 +13,7 @@ use mega_evm::revm::{ }; 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, @@ -30,7 +31,7 @@ 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 } + 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 @@ -144,7 +145,7 @@ fn test_a_fixture_ethereum_filled_passes_in_equivalence_mode() { assert_eq!(outcomes(&report), [&Outcome::Passed], "{fork}"); let summary = report.summary(); assert_eq!((summary.defined, summary.executed, summary.passed), (1, 1, 1)); - assert!(summary.gate(fork, Some(1), Some(0), false).is_empty()); + assert!(report.gate(Some(1), Some(0), false).is_empty()); } } @@ -180,12 +181,8 @@ fn test_wrong_roots_fail() { 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)]); - let summary = report.summary(); - assert_eq!(summary.unattributed, 2); - assert_eq!( - summary.gate(Fork::Osaka, None, None, false), - ["2 failed tests no deviation explains"] - ); + 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, @@ -281,12 +278,9 @@ fn test_what_is_counted_and_what_is_skipped() { 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!( - summary.gate(Fork::Osaka, Some(3), Some(2), false), - ["2 failed tests no deviation explains"] - ); - assert_eq!( - summary.gate(Fork::Osaka, Some(4), Some(1), false)[1..], + report.gate(Some(4), Some(1), false)[1..], ["3 tests executed, 4 pinned".to_string(), "2 tests skipped, 1 pinned".to_string()] ); } @@ -319,7 +313,7 @@ fn test_an_unreadable_file_fails_the_gate() { assert_eq!(report.file_failures.len(), 1); let summary = report.summary(); assert_eq!((summary.file_failures, summary.defined), (1, 0)); - assert_eq!(summary.gate(Fork::Osaka, None, None, false), ["1 fixture files could not be read"]); + 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 @@ -356,37 +350,146 @@ fn test_bad_fixture_values_fail_their_own_test() { assert_eq!(kinds, [Some(FailureKind::Fixture), Some(FailureKind::Panic), None]); } -/// In equivalence mode a registered deviation explains a failure of its kind in its files on its -/// fork, and nothing else; Satin mode attributes nothing. -#[test] -fn test_deviations_explain_their_own_failures_only() { - let dir = tempfile::tempdir().unwrap(); - let mut wrong = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); - wrong["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); - let mut wrong_logs = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); - wrong_logs["post"]["Osaka"][0]["logs"] = json!(B256::repeat_byte(1)); - let registered = write( - dir.path(), - "frontier/opcodes/test_all_opcodes.json", - json!({ "a_root": wrong.clone(), "b_logs": wrong_logs }), - ); - let elsewhere = write(dir.path(), "frontier/opcodes/other.json", json!({ "a_root": wrong })); - - let report = - run(&[registered.clone(), elsewhere.clone()], config(Mode::Equivalence, Fork::Osaka)); - let deviations: Vec<_> = report +/// 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() - .map(|result| match &result.outcome { - Outcome::Failed(failure) => failure.deviation, - _ => panic!("every test fails"), + .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(); - assert_eq!(deviations, [None, Some("amsterdam-opcodes-on-osaka"), None]); + Box::leak(Box::new([Deviation { + id: "listed", + rule: "the rule", + reason: "the reason", + fork: Fork::Osaka, + entries: entries.leak(), + }])) +} + +/// 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_eq!(summary.deviated.get("amsterdam-opcodes-on-osaka"), Some(&1)); - assert_eq!(summary.unattributed, 2); + assert!(summary.deviated.is_empty() && summary.unreproduced.is_empty()); +} - let report = run(&[registered, elsewhere], config(Mode::Satin, Fork::Osaka)); - assert_eq!(report.summary().unattributed, 3); +/// 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/state-test/src/main.rs b/crates/state-test/src/main.rs index 6e3a868f4..befe9a898 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -12,11 +12,11 @@ use std::{path::PathBuf, process::ExitCode}; use clap::Parser; use state_test::{ deviations, - runner::{find_json_files, run, Config, Report, Summary}, + runner::{find_json_files, run, Config, Outcome, Report, Summary, TestResult}, Fork, Mode, }; -/// How many unattributed failures the summary lists. +/// How many unattributed failures, and how many unreproduced entries, the summary lists. const LISTED_FAILURES: usize = 50; /// Command-line arguments. @@ -50,8 +50,8 @@ struct Cmd { /// Equivalence mode: fail unless exactly this many tests are skipped. #[arg(long, value_name = "N")] expect_skipped: Option, - /// Equivalence mode: fail unless every registered deviation explains exactly as many failed - /// tests as it pins for the fork. + /// Equivalence mode: fail unless every entry a registered deviation lists for the fork fails + /// exactly as listed, with the hashes listed. #[arg(long)] expect_deviations: bool, } @@ -83,6 +83,7 @@ fn main() -> ExitCode { threads, json_outcome: cmd.json_outcome, trace: cmd.trace, + deviations: deviations::DEVIATIONS, }; let report = run(&files, config); let summary = report.summary(); @@ -100,12 +101,8 @@ fn main() -> ExitCode { match cmd.mode { Mode::Equivalence => { - let problems = summary.gate( - cmd.fork, - cmd.expect_executed, - cmd.expect_skipped, - cmd.expect_deviations, - ); + let problems = + report.gate(cmd.expect_executed, cmd.expect_skipped, cmd.expect_deviations); for problem in &problems { println!("gate: {problem}"); } @@ -140,9 +137,12 @@ fn print_summary(report: &Report, summary: &Summary) { println!(" failed {:<34} {count}", kind.name()); } if report.mode == Mode::Equivalence { - for (id, count) in &summary.deviated { - let pinned = deviations::by_id(id).map_or(0, |d| d.pinned(report.fork)); - println!(" deviated {id:<34} {count} (pinned {pinned})"); + 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) { @@ -151,8 +151,38 @@ fn print_summary(report: &Report, summary: &Summary) { 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); } } + +/// 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 index a5970a3cc..aadc9f52c 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -104,10 +104,18 @@ fn test_a_count_off_its_pin_exits_non_zero() { assert_eq!(output.status.code(), Some(1)); assert!(stdout(&output).contains("gate: 1 tests executed, 2 pinned"), "{}", stdout(&output)); - // Every registered deviation pins a count on the full release; one test explains none. + // 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)); - assert!(stdout(&output).contains("deviation amsterdam-opcodes-on-osaka explains 0")); + 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] From 6d249e7db7097375eef9671da6d7c0ab5563c3e2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:08:12 -0700 Subject: [PATCH 077/458] fix(state-test): accept a floor shortfall as INTRINSIC_GAS_TOO_LOW on Amsterdam only The Amsterdam fixtures label some calldata-floor shortfalls INTRINSIC_GAS_TOO_LOW; the Osaka fixtures never do, so on them each shortfall now satisfies only its own name. The exception check takes the fixture's fork. --- crates/mega-state-test/src/exceptions.rs | 74 ++++++++++++++---------- crates/mega-state-test/src/runner.rs | 7 ++- 2 files changed, 48 insertions(+), 33 deletions(-) diff --git a/crates/mega-state-test/src/exceptions.rs b/crates/mega-state-test/src/exceptions.rs index 0b434fbc9..8a232b9ec 100644 --- a/crates/mega-state-test/src/exceptions.rs +++ b/crates/mega-state-test/src/exceptions.rs @@ -11,32 +11,38 @@ //! 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. From Amsterdam on that accounting +//! 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 a floor shortfall satisfies both names; an intrinsic shortfall satisfies only its own. +//! 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}; +use crate::{ + types::{TestError, TestUnit}, + Fork, +}; /// The prefix of every transaction exception name. const PREFIX: &str = "TransactionException."; -/// The execution-spec exception names `error` satisfies, without the `TransactionException.` -/// prefix; empty for an error no fixture exception describes. -pub fn names(error: &InvalidTransaction) -> &'static [&'static str] { +/// 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 { .. } => { - &["INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", "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"], @@ -70,15 +76,16 @@ pub enum Mismatch { Unnamed, } -/// Whether `error` is one of the exceptions `expected` names. +/// 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(invalid)) + check_names(expected, names(fork, invalid)) } /// The exception names a transaction the fixture types cannot build satisfies: an invalid @@ -141,7 +148,7 @@ mod tests { #[test] fn test_check_accepts_a_named_exception() { let error = tx_error(InvalidTransaction::RejectCallerWithCode); - assert_eq!(check("TransactionException.SENDER_NOT_EOA", &error), Ok(())); + assert_eq!(check(Fork::Osaka, "TransactionException.SENDER_NOT_EOA", &error), Ok(())); } #[test] @@ -151,8 +158,7 @@ mod tests { balance: Box::default(), }); assert_eq!( - check( - "TransactionException.INTRINSIC_GAS_TOO_LOW|TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW|TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", &error ), Ok(()) @@ -163,7 +169,7 @@ mod tests { fn test_check_rejects_the_wrong_reason() { let error = tx_error(InvalidTransaction::NonceTooLow { tx: 0, state: 1 }); assert_eq!( - check("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), Err(Mismatch::Wrong { got: &["NONCE_MISMATCH_TOO_LOW"] }) ); } @@ -172,39 +178,47 @@ mod tests { fn test_check_rejects_an_unnamed_error() { let error = tx_error(InvalidTransaction::Eip7873NotSupported); assert_eq!( - check("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), Err(Mismatch::Unnamed) ); let error: EVMError = EVMError::Custom("boom".into()); assert_eq!( - check("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), Err(Mismatch::Unnamed) ); let error = EVMError::Transaction(OpTransactionError::MissingEnvelopedTx); assert_eq!( - check::("TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + check::(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), Err(Mismatch::Unnamed) ); } - /// A gas limit below the calldata floor satisfies either name of the one rule; one below the - /// intrinsic cost only its own. + /// 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 }); - assert_eq!( - check("TransactionException.INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", &floor), - Ok(()) - ); - assert_eq!(check("TransactionException.INTRINSIC_GAS_TOO_LOW", &floor), Ok(())); let intrinsic = tx_error(InvalidTransaction::CallGasCostMoreThanGasLimit { initial_gas: 2, gas_limit: 1, }); - assert_eq!(check("TransactionException.INTRINSIC_GAS_TOO_LOW", &intrinsic), Ok(())); - assert!( - check("TransactionException.INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", &intrinsic).is_err() + 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"] }) ); } @@ -212,8 +226,8 @@ mod tests { #[test] fn test_check_reads_names_with_or_without_the_prefix() { let error = tx_error(InvalidTransaction::EmptyBlobs); - assert_eq!(check("TYPE_3_TX_ZERO_BLOBS", &error), Ok(())); - assert!(check("", &error).is_err()); + 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 { diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index f0793462d..ffd629b45 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -640,7 +640,7 @@ fn execute_and_check( if let Ok(result) = &result { undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); } - check(test, unit.out.as_ref(), &result, &state)?; + check(config.fork, test, unit.out.as_ref(), &result, &state)?; Ok(None) } @@ -667,20 +667,21 @@ fn undo_fee_vault_credit(unit: &TestUnit, state: &mut State, basefee: u } } -/// Judges an executed entry against its fixture. +/// 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(expected, error) { + (Some(expected), Err(error)) => match exceptions::check(fork, expected, error) { Ok(()) => {} Err(Mismatch::Wrong { got }) => { return Err(Failure::new( From 078c97e57a32f09521038540f235f279b6577981 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:08:50 -0700 Subject: [PATCH 078/458] fix(state-test): run equivalence mode without runtime limits Equivalence mode installs EvmTxRuntimeLimits::no_limits() on its context rather than relying on the engine's default being unlimited, so a limit that becomes a default cannot move the gate's results; the mode test asserts it on the context and on the EVM. --- crates/mega-state-test/README.md | 1 + crates/mega-state-test/src/mode.rs | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 6026cc535..81e541529 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -24,6 +24,7 @@ Equivalence mode is built from test tooling in `mega-evm`, behind its `test-util - `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. diff --git a/crates/mega-state-test/src/mode.rs b/crates/mega-state-test/src/mode.rs index 140f25147..2734db365 100644 --- a/crates/mega-state-test/src/mode.rs +++ b/crates/mega-state-test/src/mode.rs @@ -9,7 +9,7 @@ use mega_evm::{ inspector::NoOpInspector, }, test_utils::{neutral_cfg, neutralize_evm, zero_fee_l1_block_info}, - MegaContext, MegaEvm, MegaSpecId, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, }; use serde::Serialize; @@ -25,7 +25,8 @@ pub const MAX_BLOBS_PER_TX: u64 = 6; 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`). + /// 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. @@ -63,7 +64,8 @@ impl Mode { /// 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. + /// the transaction's L1 cost. Equivalence mode installs no runtime limit, whatever the + /// engine's default is. pub fn context( self, fork: Fork, @@ -74,7 +76,9 @@ impl Mode { let ctx = MegaContext::new(db, MegaSpecId::SATIN); let cfg = self.cfg(fork, chain_id); let ctx = match self { - Self::Equivalence => ctx.with_neutral_cfg(cfg), + 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(); @@ -136,8 +140,9 @@ mod tests { assert!("Equivalence".parse::().is_err()); } - /// Equivalence mode runs the fork's configuration, neutrally; Satin mode runs Satin's. Both - /// keep the fixture's chain id and the blob limit. + /// 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() }; @@ -145,6 +150,9 @@ mod tests { 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() From 077d58acaac80ef7e812806df73cffb77d5bea51 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:09:25 -0700 Subject: [PATCH 079/458] ci(exec-spec): key the fixture cache on the archive URLs The cache key carries a hash of the two archive URLs next to the release versions, so another archive name or host at the same version is a new download rather than the old cache. --- .github/workflows/exec-spec-satin.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index b89cdcb9a..e39dbd81c 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -119,10 +119,15 @@ jobs: 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 cache is keyed on the archives themselves: another name or host at the same + # version is another download. + archives=$(printf '%s\n%s\n' "$main" "$devnet" | sha256sum | cut -c1-16) { - echo "main=$main_url/$main_version/fixtures_develop.tar.gz" - echo "devnet=$devnet_url/$devnet_version/$devnet_tar" - echo "key=eest-state-tests-$main_version-$devnet_version" + echo "main=$main" + echo "devnet=$devnet" + echo "key=eest-state-tests-$main_version-$devnet_version-$archives" } >> "$GITHUB_OUTPUT" - name: Restore the fixtures From ec064896730e6ce8960ebf2bfedcc581a4b692e7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:10:44 -0700 Subject: [PATCH 080/458] ci(exec-spec): report the Satin gate in a job that always runs Pull requests are no longer filtered by path at the trigger: a changes job diffs the merge commit against its base over the push trigger's paths, the gate runs only when one changed, and an execution-spec gate on Satin job always runs and reports the outcome, passing when the gate passed or had nothing to run, so it can be made a required check. --- .github/workflows/exec-spec-satin.yml | 87 ++++++++++++++++++++++++--- REVIEW.md | 4 +- 2 files changed, 79 insertions(+), 12 deletions(-) diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index e39dbd81c..4329a20e5 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -14,20 +14,16 @@ name: Execution-spec tests on Satin # # 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. -# Not a required check. +# +# 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: - 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 push: branches: [satin] paths: @@ -48,8 +44,51 @@ concurrency: 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. A rename lists both of + # its paths, so a file moved out of a covered path counts. + covered='^(Cargo\.lock|Cargo\.toml|rust-toolchain\.toml|\.github/workflows/exec-spec-satin\.yml)$|^crates/(mega-evm|mega-state-test|state-test|system-contracts)/' + if git diff --name-only --no-renames 'HEAD^1' HEAD | grep -qE "$covered"; then + run=true + else + run=false + 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: @@ -212,3 +251,31 @@ jobs: fi done 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/REVIEW.md b/REVIEW.md index fd4a10582..7795de057 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -99,10 +99,10 @@ These checks guard every change to the Satin engine. - `.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. - It runs when the engine, the runner or the lock changes. + 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. - 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. +- Neither workflow is a required check; `execution-spec gate on Satin` is the job a branch rule would require. ### Instruction counts (CodSpeed) From d6c7fab3708391f484dd1c3576e34cdf5d6420b4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:12:10 -0700 Subject: [PATCH 081/458] test(block): hold every block limit to a deposit, at execution and at commit Deposits cross the execution-gas, state-gas and data-size limits, each on its own and all three together, and are included whatever the block's counters say: executed and committed one by one, and executed as candidates and committed through the checked commit and through alloy-evm's. Every deposit counts towards all three, and an ordinary transaction after them is refused before it executes and, as an earlier candidate, at its commit. --- crates/mega-evm/tests/block/deposits.rs | 223 ++++++++++++++++++++++++ crates/mega-evm/tests/block/main.rs | 1 + 2 files changed, 224 insertions(+) create mode 100644 crates/mega-evm/tests/block/deposits.rs diff --git a/crates/mega-evm/tests/block/deposits.rs b/crates/mega-evm/tests/block/deposits.rs new file mode 100644 index 000000000..1a77d83b2 --- /dev/null +++ b/crates/mega-evm/tests/block/deposits.rs @@ -0,0 +1,223 @@ +//! A deposit is never refused by a block's packing budgets. +//! +//! The execution-gas, state-gas and data-size limits of a block budget the transactions its +//! builder chooses. A deposit is not chosen: the block derived from L1 must include it. So none +//! of the three refuses a deposit — not before it executes, not after, and not when an outcome +//! executed earlier is committed through either commit path — and every deposit still counts +//! towards all three, so the ordinary transactions after the deposits find the room they used. + +use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + test_utils::BytecodeBuilder, BlockGasCounters, BlockLimits, LimitUsage, MegaTxEnvelope, +}; +use revm::{ + bytecode::opcode::{CALLDATALOAD, PUSH0, SSTORE}, + database::State, +}; + +use crate::common::{self, executor, CHAIN_ID}; + +/// 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"); + +const GAS_LIMIT: u64 = 1_000_000; + +/// Calldata past the slot word, so each deposit carries data size well beyond its body. +const PADDING: usize = 1_000; + +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)); + 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) +} + +/// A deposit that fills the fresh `slot`: execution gas, state gas and data size, all three. +fn deposit(slot: u64) -> Recovered { + common::deposit_tx_to(WRITER, input(slot), GAS_LIMIT) +} + +/// An ordinary transaction that fills the fresh `slot`, so each of the three limits has +/// something to refuse it on. +fn ordinary(slot: u64) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce: 0, + gas_price: 1_000_000, + gas_limit: GAS_LIMIT, + to: TxKind::Call(WRITER), + value: U256::ZERO, + input: input(slot), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(0x0d), + )), + SENDER, + ) +} + +/// 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 && gas.state > 0 && usage.data_size > 0, "{gas:?} {usage:?}"); + (gas, usage) +} + +/// The block limits the test holds a block to. +#[derive(Clone, Copy, Debug)] +enum Cap { + ExecutionGas, + StateGas, + DataSize, + AllThree, +} + +impl Cap { + /// Limits with room for a deposit and a half on this cap, so the second deposit crosses it. + fn limits(self, gas: &BlockGasCounters, usage: &LimitUsage) -> BlockLimits { + let half_again = |one: u64| one + one / 2; + let limits = BlockLimits::no_limits(); + let execution = limits.with_block_execution_gas_limit(half_again(gas.execution)); + let state = limits.with_block_state_gas_limit(half_again(gas.state)); + let data = limits.with_block_txs_data_limit(half_again(usage.data_size)); + match self { + Self::ExecutionGas => execution, + Self::StateGas => state, + Self::DataSize => data, + Self::AllThree => execution + .with_block_state_gas_limit(half_again(gas.state)) + .with_block_txs_data_limit(half_again(usage.data_size)), + } + } + + /// What the refusal of the ordinary transaction names. With all three limits reached, the + /// execution-gas limit is the first the block checks. + const fn refusal(self) -> &'static str { + match self { + Self::ExecutionGas | Self::AllThree => "Block execution gas limit reached", + Self::StateGas => "Block state gas limit reached", + Self::DataSize => "Block transactions data limit reached", + } + } +} + +/// 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 each block limit and are included all the same, through every route; each one +/// counts towards all three dimensions; 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() { + let (gas, usage) = one_deposit(); + for cap in [Cap::ExecutionGas, Cap::StateGas, Cap::DataSize, Cap::AllThree] { + for route in [Route::OneByOne, Route::CheckedCommit, Route::TraitCommit] { + let name = format!("{cap:?} by {route:?}"); + let limits = cap.limits(&gas, &usage); + 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!( + executor.gas().execution > limits.block_execution_gas_limit || + executor.gas().state > limits.block_state_gas_limit || + 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(cap.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(cap.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/main.rs b/crates/mega-evm/tests/block/main.rs index 02c5e66f8..9263eb4f1 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -4,6 +4,7 @@ mod block_hashes; mod common; mod counters; mod deploy; +mod deposits; mod eips; mod factory; mod inspector; From efa56356b6bf2f31574182efb3254b54c818479d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:12:17 -0700 Subject: [PATCH 082/458] test(satin): hold the history bytes to the data size at every site both count A table over the body, calldata, an access list, authorizations, logs, write records and deployed code, a failed creation, output revm does not deposit, frames answered without running and a stop, below the execution cap and above it: the history bytes a transaction reports are the data size it kept, and an Oracle hint's payload is the one difference between them. --- crates/mega-evm/tests/satin/history_bytes.rs | 304 ++++++++++++++++++- 1 file changed, 303 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index a968c6107..61480c458 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -14,7 +14,10 @@ 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, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + }, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, untouched_create_gas, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, @@ -818,3 +821,302 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { } } } + +/* ---------- 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 case crosses. + Limited(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. The one site they part at is an Oracle hint, whose payload is data +/// size and never history. 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); + let cases: [Case; 23] = [ + ( + "the body", + || callee_running(BytecodeBuilder::default()), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "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, + ), + ( + "a stop at a child's write", + || { + 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::Limited(TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1), + TX_BODY_SIZE, + 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, + ), + ( + "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, + ), + ]; + + for (name, db, tx, run, bytes, hints) in cases { + for gas_limit in GAS_LIMITS { + let limit = match run { + Run::Limited(limit) => limit, + Run::Plain | Run::AnsweringCreations => u64::MAX, + }; + 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(_) => 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.usage.data_size, + bytes + hints * hint, + "{name} at {gas_limit}: the data size is the history bytes and the hints' payloads", + ); + 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); + } + } +} From 33ae4cf769d081072e54683f425f87084ecd30c5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:12:39 -0700 Subject: [PATCH 083/458] docs(satin): say the history bytes are the data size less the hints' payloads --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index c8b7ff9ed..ed7b84005 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -213,6 +213,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 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: 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/`) From 1dec2cd77df05fc5e26f870504d36557101095cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 12:52:29 -0700 Subject: [PATCH 084/458] docs: say equivalence mode takes MegaETH's limits out as well as its prices --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 20ebac2f6..430a43bf6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -238,7 +238,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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`. + - 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. @@ -305,7 +305,7 @@ When the agent is requested to implement a new feature or bug fix, it should con 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 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 `MegaETH` sets is not a deviation: the neutral configuration takes it out of equivalence mode, and a new pricing dimension extends the neutral configuration rather than the registry. + 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. From 4f3cff0fc5d3684b2e05a0d20fae5c33b6389d2c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:23:59 -0700 Subject: [PATCH 085/458] feat(satin): hold a transaction and its frames to a KV limit --- crates/mega-evm/src/limit/frame_limit.rs | 69 ++-- crates/mega-evm/src/limit/limit.rs | 108 +++-- crates/mega-evm/src/limit/mod.rs | 87 +++- crates/mega-evm/tests/satin/common.rs | 38 ++ crates/mega-evm/tests/satin/kv_limit.rs | 499 +++++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 6 files changed, 721 insertions(+), 81 deletions(-) create mode 100644 crates/mega-evm/tests/satin/kv_limit.rs diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 08e21b0fa..9e5ac9c1c 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -18,7 +18,7 @@ use std::vec::Vec; use alloy_primitives::Address; -use super::{LimitUsage, WRITE_RECORD}; +use super::{LimitUsage, UNLIMITED, WRITE_RECORD}; /// One frame's lane. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -51,8 +51,9 @@ 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. - pub(crate) budget: u64, + /// The most the frame may keep: data-size bytes and write records, each `u64::MAX` where the + /// frame has no budget. + pub(crate) budget: LimitUsage, /// 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, @@ -68,7 +69,7 @@ impl Lane { pub(crate) const fn new( address: Option
, account_recorded: bool, - budget: u64, + budget: LimitUsage, history_charge: u64, ) -> Self { Self { @@ -90,7 +91,7 @@ impl Lane { /// 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) } + Self { records_made: false, ..Self::new(None, false, UNLIMITED, history_charge) } } /// The history gas the caller gets back when this frame returns. @@ -117,9 +118,9 @@ impl Lane { 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) + /// What the frame may still keep: the data-size bytes and the write records. + pub(crate) const fn remaining_budget(&self) -> LimitUsage { + self.budget.saturating_sub(self.net()) } } @@ -339,13 +340,13 @@ mod tests { 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::new(Some(ADDR), false, bytes(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_eq!(t.current().unwrap().budget, bytes(7)); assert!(t.pop(true).is_some()); assert_eq!(t.depth(), 0); assert!(t.current().is_none()); @@ -358,7 +359,7 @@ mod tests { 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.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); t.record_caller(true, 0); assert_eq!(t.net(), LimitUsage::ZERO); assert!(!t.current().unwrap().holds_caller_record); @@ -368,11 +369,11 @@ 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, 0)); - t.push(Lane::new(None, true, u64::MAX, 0)); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + t.push(Lane::new(None, true, UNLIMITED, 0)); t.record_caller(true, 0); assert!(t.pop(true).is_some()); - t.push(Lane::new(None, true, u64::MAX, 0)); + t.push(Lane::new(None, true, UNLIMITED, 0)); t.record_caller(true, 0); assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); assert_eq!(t.net(), WRITE_RECORD); @@ -392,19 +393,19 @@ mod tests { assert_eq!(t.net(), bytes(100)); // Frame 1. - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 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.push(Lane::new(None, false, UNLIMITED, 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.push(Lane::new(None, false, UNLIMITED, 0)); t.record(bytes(11)); t.refund(bytes(2)); let before_revert = t.net(); @@ -414,7 +415,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, 0)); + t.push(Lane::new(None, false, UNLIMITED, 0)); t.record(bytes(6)); t.refund(bytes(1)); let before_success = t.net(); @@ -443,9 +444,9 @@ mod tests { 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.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); t.record_log_and_code_bytes(10); - t.push(Lane::new(None, false, u64::MAX, 0)); + t.push(Lane::new(None, false, UNLIMITED, 0)); t.record_log_and_code_bytes(100); assert_eq!(t.log_and_code_bytes(), 115); @@ -453,7 +454,7 @@ mod tests { 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.push(Lane::new(None, false, UNLIMITED, 0)); t.record_log_and_code_bytes(20); t.pop(true); assert_eq!(t.log_and_code_bytes(), 35); @@ -466,7 +467,7 @@ mod tests { 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.push(Lane::new(Some(ADDR), false, UNLIMITED, 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"); @@ -479,7 +480,7 @@ mod tests { #[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.push(Lane::new(None, false, UNLIMITED, 0)); t.record(bytes(10)); t.refund(bytes(100)); assert_eq!(t.net(), LimitUsage::ZERO); @@ -494,16 +495,16 @@ 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, 0)); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); - t.push(Lane::new(None, true, u64::MAX, 0)); + t.push(Lane::new(None, true, UNLIMITED, 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.push(Lane::new(None, true, UNLIMITED, 0)); t.record_caller(true, 0); t.record(WRITE_RECORD); t.pop(false); @@ -516,8 +517,8 @@ mod tests { #[test] fn test_drop_caller_record_rearms_the_caller() { 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.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + t.push(Lane::new(None, true, UNLIMITED, 0)); t.record_caller(true, 0); t.drop_caller_record(); t.drop_caller_record(); @@ -532,23 +533,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, 0)); - t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + t.push(Lane::new(Some(ADDR), true, UNLIMITED, 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.push(Lane::new(Some(other), false, UNLIMITED, 0)); + t.push(Lane::new(Some(other), false, UNLIMITED, 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)); + t.push(Lane::new(Some(ADDR), true, UNLIMITED, 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.push(Lane::new(None, true, UNLIMITED, 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 e92122d2f..2d5e9007a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -129,22 +129,17 @@ impl AdditionalLimit { }) } - /// 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. + /// Checks the limits after the running frame counted something: what the transaction keeps + /// against its limits (latching on a crossing), then what the running frame keeps against its + /// budget. In each, data size comes before the write records. 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((kind, limit, used)) = self.tracker.net().crossing(self.limits.tx_usage_limit()) + { + return self.latch(kind, 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, - }; + if let Some((kind, limit, used)) = lane.net().crossing(lane.budget) { + return LimitCheck::ExceedsLimit { kind, limit, used, frame_local: true }; } } LimitCheck::WithinLimit @@ -377,9 +372,9 @@ impl AdditionalLimit { ) -> 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); + let used = self.tracker.net().saturating_add(records); + if let Some((kind, limit, used)) = used.crossing(self.limits.tx_usage_limit()) { + return self.latch(kind, limit, used); } self.target_is_authority = target_is_authority; self.tracker.record(records); @@ -448,19 +443,27 @@ impl AdditionalLimit { result.output = check.revert_data(); } - /// The data-size budget of the frame about to start. + /// The budget of the frame about to start, in data-size bytes and in write records. /// - /// The transaction's own frame gets what the transaction has left, and never more than - /// [`frame_data_size_limit`](EvmTxRuntimeLimits::frame_data_size_limit). A child gets + /// In each dimension 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), + /// [`frame_kv_update_limit`](EvmTxRuntimeLimits::frame_kv_update_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 { + fn frame_budget(&self) -> LimitUsage { 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), + Some(caller) => { + let remaining = caller.remaining_budget(); + LimitUsage { + data_size: share_of_remaining(remaining.data_size), + write_records: share_of_remaining(remaining.write_records), + } + } + None => self.limits.tx_usage_limit().saturating_sub(self.tracker.net()), }; - forwarded.min(self.limits.frame_data_size_limit) + forwarded.min(self.limits.frame_usage_limit()) } /// Takes a creation's creator record back: the creation failed before bumping the nonce. @@ -818,46 +821,79 @@ mod tests { } /// 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. A configured frame cap binds - /// when it is the smaller of the two. + /// transaction's own frame gets what the transaction has left — in data-size bytes and in + /// write records alike, each from its own limit. #[test] fn test_a_child_frame_gets_98_percent_of_what_its_parent_has_left() { - let tx_limit = 10_000; - let mut limit = - AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit)); + let tx_limit = LimitUsage { data_size: 10_000, write_records: 1_000 }; + let mut limit = AdditionalLimit::new( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(tx_limit.data_size) + .with_tx_kv_update_limit(tx_limit.write_records), + ); limit.tracker.record_tx(LimitUsage { data_size: 310, write_records: 0 }); + let share = |usage: LimitUsage| LimitUsage { + data_size: share_of_remaining(usage.data_size), + write_records: share_of_remaining(usage.write_records), + }; limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.tracker.current().unwrap().budget, tx_limit - 310); + let first = LimitUsage { data_size: 10_000 - 310, write_records: 1_000 }; + 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(tx_limit - 310); + let child = share(first); + assert_eq!(child, LimitUsage { data_size: 9_496, write_records: 980 }); 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); + let grandchild = share(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), + share(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. + /// Each frame cap binds when it is tighter than the share of what the parent has left, in its + /// own dimension and in no other. #[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), + .with_frame_data_size_limit(100) + .with_tx_kv_update_limit(1_000), ); limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.tracker.current().unwrap().budget, 100); + assert_eq!( + limit.tracker.current().unwrap().budget, + LimitUsage { data_size: 100, write_records: 1_000 } + ); limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - assert_eq!(limit.tracker.current().unwrap().budget, 98); + assert_eq!( + limit.tracker.current().unwrap().budget, + LimitUsage { data_size: 98, write_records: 980 } + ); + + let mut limit = AdditionalLimit::new( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(1_000) + .with_frame_kv_update_limit(10), + ); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + assert_eq!( + limit.tracker.current().unwrap().budget, + LimitUsage { data_size: 1_000, write_records: 10 } + ); + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); + assert_eq!( + limit.tracker.current().unwrap().budget, + LimitUsage { data_size: 980, write_records: 9 } + ); } /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 919db8c7b..0ed6ee9b2 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -125,24 +125,28 @@ 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, and the KV limit holds it; it has no +/// tracker of its own. 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 one transaction's data size. +/// Limits one transaction's data size and write records. /// -/// [`tx_data_size_limit`](Self::tx_data_size_limit) stops the transaction. 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) and +/// [`tx_kv_update_limit`](Self::tx_kv_update_limit) stop the transaction. A frame's own budget in +/// each dimension is derived from them: 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. It is unlimited unless a caller sets it. +/// [`frame_data_size_limit`](Self::frame_data_size_limit) and +/// [`frame_kv_update_limit`](Self::frame_kv_update_limit) are a further cap on every frame's +/// budget. Every limit is unlimited unless a caller sets it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EvmTxRuntimeLimits { /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. @@ -150,6 +154,12 @@ pub struct EvmTxRuntimeLimits { /// 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 most write records the transaction may keep: its KV count. Crossing it stops the + /// transaction. + pub tx_kv_update_limit: u64, + /// A cap on every frame's write-record budget, applied after the share of what its parent has + /// left. Crossing it reverts the frame alone. + pub frame_kv_update_limit: u64, } impl Default for EvmTxRuntimeLimits { @@ -161,7 +171,12 @@ impl Default for EvmTxRuntimeLimits { 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 } + Self { + tx_data_size_limit: u64::MAX, + frame_data_size_limit: u64::MAX, + tx_kv_update_limit: u64::MAX, + frame_kv_update_limit: u64::MAX, + } } /// Sets the transaction's data-size limit. @@ -175,16 +190,65 @@ impl EvmTxRuntimeLimits { self.frame_data_size_limit = limit; self } + + /// Sets the transaction's KV limit: the most write records it may keep. + pub const fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { + self.tx_kv_update_limit = limit; + self + } + + /// Caps every frame's write-record budget at `limit`. + pub const fn with_frame_kv_update_limit(mut self, limit: u64) -> Self { + self.frame_kv_update_limit = limit; + self + } + + /// The transaction's limits on what it keeps, one per dimension of [`LimitUsage`]. + pub(crate) const fn tx_usage_limit(&self) -> LimitUsage { + LimitUsage { data_size: self.tx_data_size_limit, write_records: self.tx_kv_update_limit } + } + + /// The caps on every frame's budget, one per dimension of [`LimitUsage`]. + pub(crate) const fn frame_usage_limit(&self) -> LimitUsage { + LimitUsage { + data_size: self.frame_data_size_limit, + write_records: self.frame_kv_update_limit, + } + } } /// One write record. pub(crate) const WRITE_RECORD: LimitUsage = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; +/// A budget with no bound in either dimension. +pub(crate) const UNLIMITED: LimitUsage = + LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; + impl LimitUsage { /// Nothing counted. pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + /// The first dimension in which `self` is over `limit` — data size, then write records — with + /// the limit crossed and the usage that crossed it; `None` when both hold. + pub(crate) const fn crossing(self, limit: Self) -> Option<(LimitKind, u64, u64)> { + if self.data_size > limit.data_size { + return Some((LimitKind::DataSize, limit.data_size, self.data_size)); + } + if self.write_records > limit.write_records { + return Some((LimitKind::KVUpdate, limit.write_records, self.write_records)); + } + None + } + + /// Each counter the smaller of the two. + pub(crate) fn min(self, other: Self) -> Self { + Self { + data_size: self.data_size.min(other.data_size), + write_records: self.write_records.min(other.write_records), + } + } + /// Both counters added, saturating. pub const fn saturating_add(self, other: Self) -> Self { Self { @@ -228,7 +292,8 @@ alloy_sol_types::sol! { 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. + /// Key-value updates: the write records a transaction keeps, one per account or storage + /// write; metered by the KV limit. KVUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 628d68dfb..88d6b0a65 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -48,6 +48,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( diff --git a/crates/mega-evm/tests/satin/kv_limit.rs b/crates/mega-evm/tests/satin/kv_limit.rs new file mode 100644 index 000000000..39959ee95 --- /dev/null +++ b/crates/mega-evm/tests/satin/kv_limit.rs @@ -0,0 +1,499 @@ +//! The KV limit: the write records a transaction keeps, held to a limit of their own. +//! +//! The KV count is the write-record count the common execution layer keeps: 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 part of the transaction body, not records, so a transaction +//! that writes nothing counts none. +//! +//! The limit follows the data-size limit's rules in its own unit. A transaction is held to +//! `tx_kv_update_limit`; its own frame gets what the transaction has left and a child 98% of what +//! its parent has left, under `frame_kv_update_limit`. A frame that crosses its budget reverts +//! alone; a transaction that crosses its limit is stopped with a revert carrying +//! `MegaLimitExceeded(1, limit)`. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaLimitExceeded, + MegaTransaction, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{ + CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, RETURNDATACOPY, RETURNDATASIZE, STOP, +}; + +use crate::common::{authorizing_call, call, call_with_data, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000500000"); +const A: Address = address!("0000000000000000000000000000000000500001"); +const B: Address = address!("0000000000000000000000000000000000500002"); +const C: Address = address!("0000000000000000000000000000000000500003"); +const DELEGATE: Address = address!("00000000000000000000000000000000000de1e5"); +const AUTHORITY_1: Address = address!("00000000000000000000000000000000000a0001"); +const AUTHORITY_2: Address = address!("00000000000000000000000000000000000a0002"); + +/// Enough gas for a few hundred fresh slots and the calls around them. +const GAS_LIMIT: u64 = 100_000_000; + +/// 98% of `remaining`, the share a child frame is given. +fn share(remaining: u64) -> u64 { + remaining * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(A, U256::from(1_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 +} + +/// Code that writes the fresh slots `0..n` and stops. +fn slots(n: u64) -> Bytes { + write_slots(BytecodeBuilder::default(), n).stop().build() +} + +/// Appends a `CALL` to `target` carrying `value` with all the gas, dropping its success flag. +fn then_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) + .append(POP) +} + +/// Code that calls `target` with no value and stops. +fn calls(target: Address) -> Bytes { + then_call(BytecodeBuilder::default(), target, 0).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, 0) + .append(RETURNDATASIZE) + .append_many([PUSH0, PUSH0]) + .append(RETURNDATACOPY) + .append(RETURNDATASIZE) + .append(PUSH0) + .append(RETURN) + .build() +} + +fn run_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)).execute_transaction(tx).unwrap() +} + +/// Runs a call from `CALLER` to `A` over `db` under a KV limit of `limit` and nothing else. +fn run_kv(db: MemoryDatabase, limit: u64) -> MegaTransactionOutcome { + run_under( + db, + call(CALLER, A, U256::ZERO, GAS_LIMIT), + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit), + ) +} + +/// `n` records and the body, with nothing else counted. +const fn records(n: u64) -> LimitUsage { + LimitUsage { data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, write_records: n } +} + +/// The outcome was stopped by the transaction's KV limit `limit`, crossed at `used`: a revert +/// carrying `MegaLimitExceeded(1, limit)`, not a halt. +fn assert_kv_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); + let stop = + LimitCheck::ExceedsLimit { kind: LimitKind::KVUpdate, limit, used, frame_local: false }; + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!(outcome.result.output().unwrap(), &stop.revert_data()); +} + +fn slot_written(outcome: &MegaTransactionOutcome, address: Address, slot: u64) -> bool { + outcome.state.get(&address).is_some_and(|account| { + account.storage.get(&U256::from(slot)).is_some_and(|value| value.is_changed()) + }) +} + +/* ---------- the count ---------- */ + +/// The KV count is the write records kept, by the rules every record follows: a slot counts on +/// its first change and not again, a slot written back counts nothing, writing zero to an empty +/// slot is no change, and the sender is the body's. +#[test] +fn test_the_kv_count_is_the_write_records_kept() { + let cases: [(&str, Bytes, u64); 6] = [ + ("an empty call", Bytes::new(), 0), + ("three fresh slots", slots(3), 3), + ( + "zero written to an empty slot", + BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(), + 0, + ), + ( + "one slot written twice", + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::from(2)) + .stop() + .build(), + 1, + ), + ( + "one slot written and written back", + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO) + .stop() + .build(), + 0, + ), + ( + "a value transfer: the frame's account and the recipient", + { then_call(BytecodeBuilder::default(), B, 1).stop().build() }, + 2, + ), + ]; + for (name, code, kept) in cases { + let outcome = run_kv(funded().account_code(A, code), u64::MAX); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.usage, records(kept), "{name}"); + } + + let transfer = run_under( + funded(), + call(CALLER, B, U256::from(1), GAS_LIMIT), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(transfer.result.is_success()); + assert_eq!(transfer.usage, records(1), "a value transaction records its recipient alone"); +} + +/* ---------- the transaction's limit ---------- */ + +/// A limit equal to the count holds, and one below it stops the transaction at the write that +/// crosses it: a revert naming the KV dimension, with every write taken back. +#[test] +fn test_the_transaction_limit_holds_at_the_count_and_stops_one_above() { + let fits = run_kv(funded().account_code(A, slots(3)), 3); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.limit_exceeded, None); + assert_eq!(fits.usage, records(3)); + + let stopped = run_kv(funded().account_code(A, slots(4)), 3); + assert_kv_stopped(&stopped, 3, 4); + assert_eq!(stopped.usage, records(0), "the stop takes every write back"); + for slot in 0..4 { + assert!(!slot_written(&stopped, A, slot), "slot {slot} is not kept"); + } +} + +/// The transaction's own frame gets the whole transaction limit, so a crossing there is the +/// transaction's and not a frame-local revert: the stop is latched and reported, and it is still +/// a revert, never a halt. +#[test] +fn test_a_crossing_in_the_first_frame_is_the_transactions() { + let outcome = run_kv(funded().account_code(A, slots(101)), 100); + assert_kv_stopped(&outcome, 100, 101); + assert_eq!(outcome.usage, records(0)); +} + +/// A value transaction's recipient is the record its first frame's start makes. A limit it +/// crosses stops the transaction before that frame is built: nothing moves. +#[test] +fn test_a_value_transaction_over_the_limit_moves_nothing() { + let run = |limit| { + run_under( + funded(), + call(CALLER, B, U256::from(7), GAS_LIMIT), + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit), + ) + }; + assert!(run(1).result.is_success()); + let stopped = run(0); + assert_kv_stopped(&stopped, 0, 1); + assert!(stopped.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value moved"); +} + +/// A nested value call records its caller's account and its recipient when it starts, two at +/// once. When the two cross the transaction's limit they stop the transaction, although they also +/// cross the child's own share: the transaction's limit is checked first. +#[test] +fn test_a_frame_start_over_the_transaction_limit_stops_the_transaction() { + let code = then_call(BytecodeBuilder::default(), B, 1).stop().build(); + let library = + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).append(INVALID).build(); + let db = || funded().account_code(A, code.clone()).account_code(B, library.clone()); + + let stopped = run_kv(db(), 1); + assert_kv_stopped(&stopped, 1, 2); + assert!(stopped.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value moved"); + + // Without a limit the child starts, and its halt takes its two start records and its write + // back with it. + let ran = run_kv(db(), u64::MAX); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(ran.usage, records(0)); +} + +/// Data size is checked before the write records: a record that crosses both limits at once is +/// reported as a data-size stop. +#[test] +fn test_a_record_crossing_both_limits_reports_the_data_size() { + let outcome = run_under( + funded().account_code(A, slots(3)), + call(CALLER, A, U256::ZERO, GAS_LIMIT), + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) + .with_tx_kv_update_limit(2), + ); + assert!(!outcome.result.is_success() && !outcome.result.is_halt()); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, + used: TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE, + frame_local: false, + }) + ); +} + +/// A transaction that filled the limit leaves nothing of it to the next one the same EVM runs: +/// each is held to the limit from zero. +#[test] +fn test_each_transaction_is_held_to_the_limit_from_zero() { + let mut evm = MegaEvm::new( + context(funded().account_code(A, slots(3))) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(3)), + ); + for run in 0..2 { + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(outcome.result.is_success(), "run {run}: {:?}", outcome.result); + assert_eq!(outcome.usage, records(3), "run {run}"); + } +} + +/* ---------- the frame budgets ---------- */ + +/// With room for 100 records, 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_records() { + assert_eq!((share(100), share(98), share(80)), (98, 96, 78)); + let stop = || BytecodeBuilder::default().stop().build(); + let parent_of_20 = + || then_call(write_slots(BytecodeBuilder::default(), 20), B, 0).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 record over its share", calls(B), slots(99), stop(), 0), + ("a child that fills what a parent of 20 left", parent_of_20(), slots(78), stop(), 98), + ("a child one record over what a parent of 20 left", parent_of_20(), slots(79), stop(), 20), + ("a grandchild that fills its share", calls(B), calls(C), slots(96), 96), + ("a grandchild one record 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, 0), C, 0).stop().build(), + slots(99), + slots(98), + 98, + ), + ( + "a parent that writes after its child crossed", + then_call(BytecodeBuilder::default(), B, 0) + .sstore(U256::from(500), U256::from(1)) + .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_kv(db, 100); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget does not latch"); + assert_eq!(outcome.usage, records(kept), "{name}"); + } +} + +/// The child that crosses its share reverts with `MegaLimitExceeded` naming the KV dimension and +/// the share it crossed, which is what its caller reads. +#[test] +fn test_a_child_that_crosses_its_share_reverts_with_the_share() { + let db = funded().account_code(A, call_and_return_its_output(B)).account_code(B, slots(99)); + let outcome = run_kv(db, 100); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let reverted = MegaLimitExceeded::abi_decode(outcome.result.output().unwrap()).unwrap(); + assert_eq!(reverted, MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 98 }); +} + +/// The frame cap binds every frame, the transaction's own included, and reverts the frame alone: +/// a top-level frame over the cap reverts without latching the transaction. +#[test] +fn test_the_frame_cap_binds_a_frame_alone() { + let run = |a: Bytes, b: Bytes| { + run_under( + funded().account_code(A, a).account_code(B, b), + call(CALLER, A, U256::ZERO, GAS_LIMIT), + EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(10), + ) + }; + let fits = run(slots(10), Bytes::new()); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage, records(10)); + + let over = run(slots(11), Bytes::new()); + assert!(!over.result.is_success() && !over.result.is_halt(), "{:?}", over.result); + assert_eq!(over.limit_exceeded, None, "a frame cap is not the transaction's limit"); + assert_eq!( + over.result.output().unwrap().as_ref(), + MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 10 }.abi_encode() + ); + + // A child's budget is the share of what its parent has left, under the same cap. + let child = run(call_and_return_its_output(B), slots(10)); + assert!(child.result.is_success(), "{:?}", child.result); + assert_eq!( + MegaLimitExceeded::abi_decode(child.result.output().unwrap()).unwrap(), + MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 9 }, + "the child may keep 98% of ten", + ); +} + +/// A creation too big for its share still bumps its creator's nonce, and the record of that +/// write lands on the creator: the creator is held to its budget with it before it runs on. +/// +/// `A` calls `B`, which may keep 98 records. `B` writes 97 or 98 slots, then creates: the +/// creation's two start records cross its share of what `B` has left, so it is stopped. With one +/// record left, `B` keeps the nonce record at exactly its budget. With none left, the record puts +/// `B` over it: `B` reverts alone, and `A` returns its revert. +#[test] +fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { + let creator = |written| { + write_slots(BytecodeBuilder::default(), written) + .append_many([PUSH0, PUSH0, PUSH0]) + .append(CREATE) + .append(POP) + .append(STOP) + .build() + }; + let run = |written| { + run_kv( + funded() + .account_code(A, call_and_return_its_output(B)) + .account_code(B, creator(written)), + 100, + ) + }; + + let fits = run(97); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.limit_exceeded, None); + assert_eq!(fits.usage, records(98), "97 slots and B's nonce, exactly B's budget"); + assert_eq!(fits.state[&B].info.nonce, 1); + + let over = run(98); + assert!(over.result.is_success(), "A resumes: {:?}", over.result); + assert_eq!(over.limit_exceeded, None, "a frame budget does not latch"); + assert_eq!(over.usage, records(0), "B's slots and nonce went with its revert"); + assert!(over.state.get(&B).is_none_or(|b| b.info.nonce == 0)); + assert_eq!( + over.result.output().unwrap().as_ref(), + MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 98 }.abi_encode(), + ); +} + +/* ---------- records made before the first frame ---------- */ + +/// The records of applied EIP-7702 authorities are made before the first frame. When they cross +/// the limit they are not applied: the limit is enforced before the writes it guards, and the +/// transaction is stopped at its first frame — whatever that frame's target, an intercepted +/// system contract included. Authorities that exist already are records all the same. +#[test] +fn test_authorities_crossing_the_kv_limit_are_not_applied() { + let db = || { + funded() + .account_balance(AUTHORITY_1, U256::from(1)) + .account_balance(AUTHORITY_2, U256::from(1)) + }; + let authorities = [(AUTHORITY_1, 0), (AUTHORITY_2, 0)]; + let run = |to: Address, data: Bytes, limit: u64| { + let mut tx = authorizing_call(CALLER, to, U256::ZERO, GAS_LIMIT, DELEGATE, &authorities); + tx.0.base.data = data; + run_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit)) + }; + let selector = Bytes::from(IMegaLimitControl::remainingComputeGasCall::SELECTOR.to_vec()); + for (to, data) in [(A, Bytes::new()), (LIMIT_CONTROL_ADDRESS, selector)] { + let applied = run(to, data.clone(), 2); + assert!(applied.result.is_success(), "{to}: {:?}", applied.result); + assert_eq!(applied.usage.write_records, 2, "{to}"); + + let stopped = run(to, data, 1); + assert_kv_stopped(&stopped, 1, 2); + assert_eq!(stopped.usage.write_records, 0, "{to}"); + for authority in [AUTHORITY_1, AUTHORITY_2] { + let account = stopped.state.get(&authority); + assert!( + account.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "{to}: {authority} was not delegated: {account:?}" + ); + } + } +} + +/// The records made before the first frame and the ones made in it add up to the limit: two +/// applied authorities leave the first frame room for one slot, and a second one stops it. +#[test] +fn test_authorities_and_execution_add_up_to_the_stop() { + let run = |written| { + let tx = authorizing_call( + CALLER, + A, + U256::ZERO, + GAS_LIMIT, + DELEGATE, + &[(AUTHORITY_1, 0), (AUTHORITY_2, 0)], + ); + run_under( + funded().account_code(A, slots(written)), + tx, + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(3), + ) + }; + let fits = run(1); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 3); + let stopped = run(2); + assert_kv_stopped(&stopped, 3, 4); + assert_eq!(stopped.usage.write_records, 2, "the authorities outlive the first frame's stop"); +} + +/// Calldata is data size and never a record: however much of it a transaction carries, its KV +/// count is what it writes. +#[test] +fn test_calldata_is_not_a_record() { + let outcome = run_under( + funded().account_code(A, slots(1)), + call_with_data(CALLER, A, Bytes::from(vec![0xab; 1_000]), GAS_LIMIT), + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(1), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 1); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6f0879839..a395aa0b1 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -13,6 +13,7 @@ mod history_gas; mod history_reservoir; mod inspector; mod intrinsic; +mod kv_limit; mod neutral; mod outcome; mod precompile_gas; From cb8c8eff6aed15876d8ea2a65573eaf7df77df74 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:25:48 -0700 Subject: [PATCH 086/458] feat(block): hold a block's write records to a KV limit --- crates/mega-evm/src/block/limit.rs | 135 +++++++++++++++++++----- crates/mega-evm/src/block/result.rs | 14 +++ crates/mega-evm/tests/block/deposits.rs | 40 ++++--- 3 files changed, 147 insertions(+), 42 deletions(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index f87af0ab0..36e10af53 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -12,15 +12,16 @@ //! 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, the state ledger and the data-size -//! bytes a transaction kept — is accumulated when the transaction commits. 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 -//! reached its limit refuses what comes after it, so the overshoot is bounded by one transaction -//! per dimension, besides what deposits add: +//! A limit only known after execution — the execution ledger, the state ledger, and the data-size +//! bytes and write records a transaction kept — is accumulated when the transaction commits. 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 reached its limit refuses what comes after it, so the overshoot is bounded by +//! one transaction per dimension, besides what deposits add: //! -//! - the execution ledger and the data-size bytes are checked before the *next* transaction starts, -//! and a block that has reached either refuses every later transaction — a deposit excepted; +//! - the execution ledger, the data-size bytes and the write records are checked before the *next* +//! transaction starts, and a block that has reached any of them refuses every later transaction — +//! a deposit excepted; //! - the state ledger is checked once the next transaction has executed, and a block that has //! reached its limit refuses a later transaction only if it adds state gas — a deposit excepted. //! One that adds none still fits, and only its own execution can tell which it is. @@ -29,21 +30,24 @@ //! //! 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 a deposit is exempt from both data-availability limits -//! and does not count towards the block's. The execution-gas, state-gas and data-size limits are -//! packing budgets for the transactions the builder chooses, so none of them refuses a deposit -//! either. A deposit still counts towards all three, so the transactions after it find the room it +//! and does not count towards the block's. The execution-gas, state-gas, data-size and KV limits +//! are packing budgets for the transactions the builder chooses, so none of them refuses a deposit +//! either. A deposit still counts towards all four, so the transactions after it find the room it //! used. //! -//! The per-transaction data-size limit is not a block limit: it holds a deposit's own execution -//! the way it holds any transaction's, and a deposit that crosses it is included with the stop as -//! its result. +//! The per-transaction limits the block installs on the EVM — data size, write records, state gas +//! — 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`]), execution and state have a //! block limit. History has none by design; the history bytes beside it are reported, not -//! limited. The write-record count is accumulated here and enforced by nobody: the write-record -//! limit arrives with the state-growth and KV limits. +//! limited. The write-record count, which is the block's KV count, has one too: +//! [`BlockLimits::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 whatever its KV limit; the KV limit binds only below that, and is unlimited unless a +//! node sets it. use alloy_primitives::TxHash; @@ -95,6 +99,11 @@ pub struct BlockLimits { /// that reaches it is packed; after it, only a deposit is, which it never refuses and which /// counts towards it. pub block_txs_data_limit: u64, + /// The most write records the block's transactions may keep together: the block's KV count. + /// + /// The transaction that reaches it is packed; after it, only a deposit is, which it never + /// refuses and which counts towards it. + pub block_kv_update_limit: u64, /// The limits every transaction of the block runs under, which the executor installs on the /// EVM. /// @@ -123,6 +132,7 @@ impl BlockLimits { block_execution_gas_limit: u64::MAX, block_state_gas_limit: u64::MAX, block_txs_data_limit: u64::MAX, + block_kv_update_limit: u64::MAX, tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), } } @@ -198,6 +208,12 @@ impl BlockLimits { self } + /// Sets the block's KV limit: the most write records its transactions may keep together. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_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; @@ -286,9 +302,8 @@ impl BlockLimiter { /// Whether `tx` may execute in this block. /// /// Checks the transaction against its own limits, and against what the block has left; a - /// deposit is held to neither data-availability limit, nor to the execution-gas or the - /// data-size limit. It - /// reads the counters and changes nothing; + /// deposit is held to neither data-availability limit, nor to the execution-gas, the data-size + /// or the KV limit. It reads the counters and changes nothing; /// [`post_execution_check`](Self::post_execution_check) checks what only the transaction's /// execution reveals, and [`post_execution_update`](Self::post_execution_update) advances the /// counters once the transaction commits. @@ -398,10 +413,20 @@ impl BlockLimiter { )); } + // The same for the write records, the block's KV count. + if !is_deposit && 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, + }, + )); + } + // `self.gas.state` is checked after execution, in `post_execution_check`: a block that has - // reached its state gas still admits a transaction that adds none. `self.gas.history` and - // `self.usage.write_records` are accumulated and not checked: history has no block limit, - // and the write-record limit arrives with the state-growth and KV limits. + // reached its state gas still admits a transaction that adds none. `self.gas.history` is + // accumulated and not checked: history has no block limit. Ok(()) } @@ -485,10 +510,14 @@ mod tests { assert_eq!(limits.tx_gas_limit, u64::MAX); assert_eq!(limits.block_execution_gas_limit, u64::MAX); assert_eq!(limits.block_state_gas_limit, u64::MAX); + assert_eq!(limits.block_kv_update_limit, u64::MAX); + assert_eq!(limits.tx_runtime_limits.tx_kv_update_limit, u64::MAX); + assert_eq!(limits.tx_runtime_limits.frame_kv_update_limit, u64::MAX); let unlimited = BlockLimits::no_limits(); assert_eq!(unlimited.block_txs_data_limit, u64::MAX); - assert_eq!(unlimited.tx_runtime_limits.tx_data_size_limit, u64::MAX); + assert_eq!(unlimited.block_kv_update_limit, u64::MAX); + assert_eq!(unlimited.tx_runtime_limits, EvmTxRuntimeLimits::no_limits()); } fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { @@ -765,11 +794,11 @@ mod tests { assert_eq!(limiter.available_gas(), 0); } - /// The history ledger, the history bytes and the write-record count are accumulated, and no - /// check refuses a transaction on them; nor on the state ledger, whose limit is unlimited - /// unless a node sets one. + /// The history ledger and the history bytes are accumulated, and no check refuses a + /// transaction on them; nor on the state ledger or the write records, whose limits are + /// unlimited unless a node sets them. #[test] - fn test_history_and_write_records_are_counted_but_not_enforced() { + fn test_history_is_counted_but_not_enforced() { let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); let usage = BlockUsage { gas: MegaGasUsage { @@ -792,6 +821,58 @@ mod tests { assert!(limiter.post_execution_check(B256::ZERO, &usage).is_ok()); } + /// What one committed transaction kept of write records, and nothing else. + fn keeps_records(write_records: u64) -> BlockUsage { + BlockUsage { usage: LimitUsage { data_size: 0, write_records }, ..Default::default() } + } + + /// The block's KV limit is a packing budget like its data size: the transaction that reaches + /// it is packed, the next one is refused before it runs, and the limit is an inclusive bound. + #[test] + fn test_kv_limit_refuses_the_transaction_after_the_crossing() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); + + limiter.post_execution_update(&keeps_records(999)); + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); + + // The crossing transaction had been admitted, and it is packed: the block overshoots. + limiter.post_execution_update(&keeps_records(5)); + assert_eq!(limiter.usage.write_records, 1_004); + let err = limiter + .pre_execution_check(B256::ZERO, 0, 0, 0, false) + .expect_err("the block's write records have reached their limit"); + assert!(std::format!("{err}").contains("Block KV update limit reached"), "{err}"); + assert!(std::format!("{err}").contains("block_used=1004"), "{err}"); + + // A block that kept exactly its limit is full. + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); + limiter.post_execution_update(&keeps_records(1_000)); + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_err()); + } + + /// A deposit is never refused by the block's KV 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_kv_limit_never_refuses_a_deposit_and_counts_it() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); + let deposit = BlockUsage { is_deposit: true, ..keeps_records(600) }; + + 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.write_records, 1_800, "every deposit counts"); + + let err = limiter + .pre_execution_check(B256::ZERO, 0, 0, 0, false) + .expect_err("the deposits used the room an ordinary transaction would need"); + assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); + } + /// What one committed transaction spent on the state ledger, and nothing else. fn adds_state(state: u64) -> BlockUsage { BlockUsage { gas: MegaGasUsage { state, ..Default::default() }, ..Default::default() } diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 6de4c366e..29de02767 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -171,6 +171,14 @@ pub enum MegaBlockLimitExceededError { /// The block's data-size limit. limit: u64, }, + /// The block's transactions have kept their write records, the block's KV count. A deposit is + /// never refused this way. + KVUpdateLimit { + /// The write records the block has kept. + block_used: u64, + /// The block's KV 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. @@ -198,6 +206,7 @@ impl MegaBlockLimitExceededError { Self::ExecutionGasLimit { block_used, .. } | Self::StateGasLimit { block_used, .. } | Self::TransactionDataLimit { block_used, .. } | + Self::KVUpdateLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, } @@ -209,6 +218,7 @@ impl MegaBlockLimitExceededError { Self::ExecutionGasLimit { limit, .. } | Self::StateGasLimit { limit, .. } | Self::TransactionDataLimit { limit, .. } | + Self::KVUpdateLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, } @@ -228,6 +238,9 @@ 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::TransactionEncodeSizeLimit { block_used, tx_used, limit } => write!( f, "Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" @@ -433,6 +446,7 @@ mod tests { 15, ), (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 7, limit: 16 }, 7, 16), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { block_used: 4, diff --git a/crates/mega-evm/tests/block/deposits.rs b/crates/mega-evm/tests/block/deposits.rs index 1a77d83b2..e8cda2ea1 100644 --- a/crates/mega-evm/tests/block/deposits.rs +++ b/crates/mega-evm/tests/block/deposits.rs @@ -1,10 +1,10 @@ //! A deposit is never refused by a block's packing budgets. //! -//! The execution-gas, state-gas and data-size limits of a block budget the transactions its +//! The execution-gas, state-gas, data-size and KV limits of a block budget the transactions its //! builder chooses. A deposit is not chosen: the block derived from L1 must include it. So none -//! of the three refuses a deposit — not before it executes, not after, and not when an outcome +//! of the four refuses a deposit — not before it executes, not after, and not when an outcome //! executed earlier is committed through either commit path — and every deposit still counts -//! towards all three, so the ordinary transactions after the deposits find the room they used. +//! towards all four, so the ordinary transactions after the deposits find the room they used. use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; use alloy_evm::block::BlockExecutor; @@ -51,13 +51,14 @@ fn input(slot: u64) -> Bytes { Bytes::from(input) } -/// A deposit that fills the fresh `slot`: execution gas, state gas and data size, all three. +/// A deposit that fills the fresh `slot`: execution gas, state gas, data size and a write record, +/// all four. fn deposit(slot: u64) -> Recovered { common::deposit_tx_to(WRITER, input(slot), GAS_LIMIT) } -/// An ordinary transaction that fills the fresh `slot`, so each of the three limits has -/// something to refuse it on. +/// An ordinary transaction that fills the fresh `slot`, so each of the four limits has something +/// to refuse it on. fn ordinary(slot: u64) -> Recovered { let tx = TxLegacy { chain_id: Some(CHAIN_ID), @@ -86,6 +87,7 @@ fn one_deposit() -> (BlockGasCounters, LimitUsage) { probe.execute_transaction(&deposit(1)).expect("the probe executes"); let (gas, usage) = (*probe.gas(), probe.limiter().usage); assert!(gas.execution > 0 && gas.state > 0 && usage.data_size > 0, "{gas:?} {usage:?}"); + assert_eq!(usage.write_records, 1, "the slot"); (gas, usage) } @@ -95,34 +97,40 @@ enum Cap { ExecutionGas, StateGas, DataSize, - AllThree, + KvUpdates, + All, } impl Cap { - /// Limits with room for a deposit and a half on this cap, so the second deposit crosses it. + /// Limits with room for a deposit and a half on this cap, so the second deposit crosses it. A + /// deposit keeps one record, so on the write records that is room for one. fn limits(self, gas: &BlockGasCounters, usage: &LimitUsage) -> BlockLimits { let half_again = |one: u64| one + one / 2; let limits = BlockLimits::no_limits(); let execution = limits.with_block_execution_gas_limit(half_again(gas.execution)); let state = limits.with_block_state_gas_limit(half_again(gas.state)); let data = limits.with_block_txs_data_limit(half_again(usage.data_size)); + let kv = limits.with_block_kv_update_limit(half_again(usage.write_records)); match self { Self::ExecutionGas => execution, Self::StateGas => state, Self::DataSize => data, - Self::AllThree => execution + Self::KvUpdates => kv, + Self::All => execution .with_block_state_gas_limit(half_again(gas.state)) - .with_block_txs_data_limit(half_again(usage.data_size)), + .with_block_txs_data_limit(half_again(usage.data_size)) + .with_block_kv_update_limit(half_again(usage.write_records)), } } - /// What the refusal of the ordinary transaction names. With all three limits reached, the + /// What the refusal of the ordinary transaction names. With all four limits reached, the /// execution-gas limit is the first the block checks. const fn refusal(self) -> &'static str { match self { - Self::ExecutionGas | Self::AllThree => "Block execution gas limit reached", + Self::ExecutionGas | Self::All => "Block execution gas limit reached", Self::StateGas => "Block state gas limit reached", Self::DataSize => "Block transactions data limit reached", + Self::KvUpdates => "Block KV update limit reached", } } } @@ -141,12 +149,12 @@ enum Route { } /// Deposits cross each block limit and are included all the same, through every route; each one -/// counts towards all three dimensions; and an ordinary transaction after them is refused — before +/// counts towards all four dimensions; 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() { let (gas, usage) = one_deposit(); - for cap in [Cap::ExecutionGas, Cap::StateGas, Cap::DataSize, Cap::AllThree] { + for cap in [Cap::ExecutionGas, Cap::StateGas, Cap::DataSize, Cap::KvUpdates, Cap::All] { for route in [Route::OneByOne, Route::CheckedCommit, Route::TraitCommit] { let name = format!("{cap:?} by {route:?}"); let limits = cap.limits(&gas, &usage); @@ -196,10 +204,12 @@ fn test_no_block_limit_refuses_a_deposit_and_every_deposit_counts() { 3 * usage.data_size, "{name}: data size counted" ); + assert_eq!(executor.limiter().usage.write_records, 3, "{name}: write records counted"); assert!( executor.gas().execution > limits.block_execution_gas_limit || executor.gas().state > limits.block_state_gas_limit || - executor.limiter().usage.data_size > limits.block_txs_data_limit, + executor.limiter().usage.data_size > limits.block_txs_data_limit || + executor.limiter().usage.write_records > limits.block_kv_update_limit, "{name}: the deposits crossed the limit", ); From 01b8c84f0edacee76ba94e9a840689d3bb975400 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:37:06 -0700 Subject: [PATCH 087/458] feat(satin): hold a transaction's state growth to a state-gas limit --- crates/mega-evm/src/constants.rs | 9 +- crates/mega-evm/src/evm/execution.rs | 91 ++- crates/mega-evm/src/evm/instructions.rs | 65 ++- crates/mega-evm/src/limit/limit.rs | 55 +- crates/mega-evm/src/limit/mod.rs | 27 +- crates/mega-evm/src/limit/state_gas.rs | 129 +++++ crates/mega-evm/tests/satin/main.rs | 1 + .../mega-evm/tests/satin/state_gas_limit.rs | 546 ++++++++++++++++++ 8 files changed, 881 insertions(+), 42 deletions(-) create mode 100644 crates/mega-evm/src/limit/state_gas.rs create mode 100644 crates/mega-evm/tests/satin/state_gas_limit.rs diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index f7e0ca3d3..16b364821 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -21,10 +21,11 @@ //! 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 per-transaction state-gas limit is a further placeholder, which the state-gas limits add -//! when they land. The per-block one is -//! [`BlockLimits::block_state_gas_limit`](crate::BlockLimits::block_state_gas_limit), which a node -//! sets and which is unlimited by default; no number for it is fixed here yet. +//! The state-gas limits are not fixed here either: the per-transaction one is +//! [`EvmTxRuntimeLimits::tx_state_gas_limit`](crate::EvmTxRuntimeLimits::tx_state_gas_limit) and +//! the per-block one +//! [`BlockLimits::block_state_gas_limit`](crate::BlockLimits::block_state_gas_limit). A node sets +//! both, and both are unlimited by default. use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ee477d072..523cc7f79 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -39,7 +39,7 @@ use revm::{ interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, InitialAndFloorGas, - InstructionResult, InterpreterAction, SharedMemory, + InstructionResult, InterpreterAction, InterpreterResult, SharedMemory, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, Inspector, Journal, @@ -136,7 +136,8 @@ where evm.ctx().journal_mut().checkpoint_revert(checkpoint); return Ok(None); }; - let authorities = record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + let authorities = + record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i, gas.state_gas_spent()); if authorities.check.exceeded_limit() { evm.ctx().journal_mut().checkpoint_revert(checkpoint); *gas = gas_before; @@ -229,15 +230,24 @@ where /// them would only matter to a gas limit that cannot pay them, which would then report an /// out-of-gas in place of the stop that bound first. The input carries no charged flag, so /// the stop's settlement gives nothing back that was not charged. + /// + /// Once revm has built the first frame, the state gas the transaction has been charged is all + /// it holds outside its frames: the account a deposit-like transaction creates for its caller, + /// the applied authorities, and the new account EIP-2780 charges the first frame's start for. + /// It is held to the state-gas limit there, and a crossing latches the transaction: the frame + /// is answered with the stop before it runs, and its settlement gives the start's charge back + /// as it does for any first frame that fails. fn first_frame_input( &mut self, evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { - if evm.ctx_ref().additional_limit.latched().is_none() { - return self.op.first_frame_input(evm, gas); + if evm.ctx_ref().additional_limit.latched().is_some() { + return Ok(Some(unbuilt_first_frame(evm.ctx_ref(), gas))); } - Ok(Some(unbuilt_first_frame(evm.ctx_ref(), gas))) + let frame = self.op.first_frame_input(evm, gas)?; + evm.ctx_mut().additional_limit.on_state_gas_before_frames(gas.state_gas_spent()); + Ok(frame) } /// Settles the outermost frame: pops its lane and, when the transaction is latched, turns its @@ -403,11 +413,21 @@ impl EvmTr for MegaEvm Result, ContextDbError> { + // The state gas the caller holds is held outside the frame it starts. The caller is the + // frame on top of the stack, suspended on this frame's input; the transaction's own frame + // has none, and starts on what was charged before it. + if self.inner.frame_stack.index().is_some() { + let held = self.inner.frame_stack.get().interpreter.gas.state_gas_spent(); + self.inner.ctx.additional_limit.note_caller_state_gas(held); + } 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)); @@ -616,10 +636,11 @@ where } } -/// Counts the bytecode a creation is about to deposit, and turns that return into the stop -/// when the bytes cross a limit, before revm commits the creation. +/// Holds the bytecode a creation is about to deposit to the limits, and turns that return into +/// the stop when it crosses one, before revm commits the creation: first the state gas +/// `return_create` will charge for the bytes, then the bytes themselves. /// -/// Only code `return_create` would deposit is counted ([`deposits`]). Code it refuses fails the +/// Only code `return_create` would deposit is held ([`deposits`]). Code it refuses fails the /// creation there, alone, and the chain keeps none of it. Counted, those bytes could cross the /// transaction's limit and stop every frame above a creation that fails by itself. fn meter_deployed_code( @@ -630,6 +651,7 @@ fn meter_deployed_code( if frame.data.is_create() { if let InterpreterAction::Return(result) = &mut action { if deposits(ctx.cfg(), &result.output) { + hold_deposit_state_gas(ctx, frame.interpreter.input.target_address, result); ctx.additional_limit.on_create_return(result); } } @@ -637,6 +659,46 @@ fn meter_deployed_code( action } +/// Holds the state gas `return_create` is about to charge for the code a creation at `address` +/// deposits to the state-gas limit, and turns the return into the stop when it crosses it. +/// +/// A crossing after `return_create` would leave the code deployed: the charge is made inside it, +/// after which it commits the creation's checkpoint. So the charge is priced here, through the +/// same hook and for the same bytes, and held with what the creation already holds. Unlike every +/// other state-gas site, the limit binds here before the charge is made, as the data-size limit +/// does for the same bytes, so a creation that could not have paid for its code is stopped rather +/// than run out of gas. +/// +/// A return that is already a revert or a halt deposits nothing, and a schedule that prices +/// deposited code at no state gas is not asked for a price, as `return_create` does not ask it. +/// A lookup that fails is left to `return_create`, which asks the hook again and fails the same +/// way. +fn hold_deposit_state_gas( + ctx: &mut MegaContext, + address: Address, + result: &mut InterpreterResult, +) { + if !result.result.is_ok() { + return; + } + let bytes = result.output.len(); + if ctx.cfg().gas_params().code_deposit_state_gas(bytes) == 0 { + return; + } + let charge = StateGasCharge::units( + GasId::code_deposit_state_gas(), + StateGasSite::account(address), + bytes as u64, + ); + let Some(cost) = ctx.state_gas_charge(charge) else { return }; + let running = result.gas.state_gas_spent().saturating_add_unsigned(cost); + let check = ctx.additional_limit.check_state_gas(running); + if check.exceeded_limit() { + result.result = InstructionResult::Revert; + result.output = check.revert_data(); + } +} + /// Whether `return_create` deposits `code` a creation returns, as far as the code decides it: /// no longer than the code-size limit, and not starting with `0xEF` unless EIP-3541 is off, both /// read from the configuration `return_create` reads. @@ -852,9 +914,14 @@ fn account_nonce( /// `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. +/// +/// `state_gas` is what the transaction has been charged before its first frame, the authorities' +/// new accounts and delegations included, which the state-gas limit holds before the records are +/// counted. fn record_applied_authorities( ctx: &mut MegaContext, journal_i: usize, + state_gas: i64, ) -> AppliedAuthorities { if ctx.tx().tx_type() != TransactionType::Eip7702 { return AppliedAuthorities { check: LimitCheck::WithinLimit, applied: 0 }; @@ -873,8 +940,12 @@ fn record_applied_authorities( let target_is_authority = target.is_some_and(|target| authorities.binary_search(&target).is_ok()); let applied = authorities.len() as u64; - let check = - ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); + let check = ctx.additional_limit.record_applied_authorities( + caller, + applied, + target_is_authority, + state_gas, + ); AppliedAuthorities { check, applied: if check.exceeded_limit() { 0 } else { applied } } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 9cf750ad8..29c88a79e 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -8,8 +8,10 @@ //! 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, hold the state gas it charged to +//! the state-gas limit, then commit the record; //! 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. //! @@ -17,13 +19,15 @@ //! 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 +//! A state charge or 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 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 +//! The other four run in a wrapper that holds the state gas revm's instruction charged for the +//! account the frame would add to the state-gas limit — a crossing answers the frame with the stop +//! before it is built — and then 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, @@ -105,9 +109,12 @@ pub(crate) fn mega_instructions( /// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the /// staged write back with it. /// -/// The data-size check is made before the history charge. A record the limit rejects is not +/// The state gas the opcode charged is held to the state-gas limit first — `SSTORE` charges a +/// fresh slot's and `SELFDESTRUCT` a new beneficiary's inside revm's instruction — and a crossing +/// stops the frame and discards the record with the write. Then the record is held to the +/// data-size and KV limits, and only then is its history charged. A record a 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. +/// limits accept is charged, and a charge the frame cannot pay is an out-of-gas. #[inline(always)] fn commit_after( context: Ctx<'_, DB, ExtEnvs>, @@ -124,6 +131,11 @@ fn commit_after( commit_after::(context, host::selfdestruct) } -/// Runs `inner` and charges the frame the history of the write records the frame `inner` starts -/// will make. +/// Runs `inner`, holds the state gas it charged to the state-gas limit, and charges the frame the +/// history of the write records the frame `inner` starts will make. +/// +/// revm's instruction charges the caller the state gas of the account the frame would add — a +/// value transfer's new recipient, a created account — before it builds the frame's input. A +/// crossing latches the transaction, and the frame is answered with the stop before it is built, +/// as a frame whose start crosses the data-size limit is: the gas the opcode forwarded and the +/// state gas it charged come back to the caller the way they come back from any frame that +/// reverts, and the caller returns the stop without running on. Such a frame makes no records, so +/// it is charged no history. /// -/// 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 call the balance cannot fund, a creation the depth refuses — makes no records and is -/// charged nothing. 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`]). +/// The history 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 call the balance cannot fund, a creation the depth refuses — makes no +/// records and is charged nothing. 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`]). /// /// The frame inherits the reservoir the charge left, not the one the caller held before it /// ([`inherit_reservoir`]). @@ -232,16 +252,19 @@ fn charge_frame_start( ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - if !host.prices_history() { - return result; - } // An opcode that starts a frame suspends with the frame's input as its action; one that ends // otherwise — a call the balance cannot fund, an out-of-gas — leaves no such action and makes // no records. - let Some(InterpreterAction::NewFrame(input)) = interpreter.bytecode.action() else { - return result; + let records = match interpreter.bytecode.action() { + Some(InterpreterAction::NewFrame(input)) => { + host.additional_limit.frame_start_records(input) + } + _ => return result, }; - let records = host.additional_limit.frame_start_records(input); + let check = host.additional_limit.check_state_gas(interpreter.gas.state_gas_spent()); + if check.exceeded_limit() || !host.prices_history() { + return result; + } let (Some(on_lane), Some(caller)) = ( write_record_history_gas(records.on_lane), write_record_history_gas(u64::from(records.caller)), diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 2d5e9007a..bd9da01a5 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -9,6 +9,7 @@ use revm::{ use super::{ frame_limit::{FrameLimitTracker, Lane}, record::{HistoryBytes, RecordEffect, StagedRecord}, + state_gas::StateGasMeter, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD, WRITE_RECORD_SIZE, }; @@ -74,6 +75,8 @@ pub struct AdditionalLimit { history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, + /// The state gas the transaction holds outside the running frame, for the state-gas limit. + state_gas: StateGasMeter, } impl AdditionalLimit { @@ -108,6 +111,7 @@ impl AdditionalLimit { self.pending_frame_charge = FrameCharge::NONE; self.history_gas_spent = 0; self.history_bytes = 0; + self.state_gas.reset(); } /* The latch */ @@ -359,18 +363,24 @@ 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, from the transaction's `sender`. + /// one of them, from the transaction's `sender`, which has been charged `state_gas` so far. /// - /// 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 limits are checked before the records are made — the state gas the authorities were + /// charged first, then their records: a crossing latches the transaction and records nothing, + /// and the caller takes the authorizations back with the gas they charged, 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, + state_gas: i64, ) -> LimitCheck { self.sender = sender; + let check = self.check_state_gas(state_gas); + if check.exceeded_limit() { + return check; + } let records = WRITE_RECORD.times(authorities); let used = self.tracker.net().saturating_add(records); if let Some((kind, limit, used)) = used.crossing(self.limits.tx_usage_limit()) { @@ -381,6 +391,40 @@ impl AdditionalLimit { LimitCheck::WithinLimit } + /* The state-gas limit */ + + /// Holds the state gas the transaction holds to its limit, the running frame — or, outside + /// any frame, the transaction — holding `running`, and latches the transaction when it is + /// crossed. + /// + /// Called where state gas has just been charged, so a charge the frame could not pay is an + /// out-of-gas whatever the limit: the limit holds what was paid. What a frame refilled, and + /// what a failed frame rolled back, is out of what it holds, so a write taken back gives its + /// room back. + pub(crate) fn check_state_gas(&mut self, running: i64) -> LimitCheck { + debug_assert_eq!(self.state_gas.depth(), self.tracker.depth(), "one entry per lane"); + let used = self.state_gas.held(running); + let limit = self.limits.tx_state_gas_limit; + if used > limit { + return self.latch(LimitKind::StateGrowth, limit, used); + } + LimitCheck::WithinLimit + } + + /// Records the state gas the transaction was charged before its first frame, `spent`, and + /// holds it to the limit. A crossing latches the transaction, and its first frame is answered + /// with the stop before it is built. + pub(crate) fn on_state_gas_before_frames(&mut self, spent: i64) { + self.state_gas.set_before_frames(spent); + self.check_state_gas(spent); + } + + /// Records the state gas `held` by the frame that is starting the next one, which the next + /// frame counts as held outside it. + pub(crate) const fn note_caller_state_gas(&mut self, held: i64) { + self.state_gas.note_caller(held); + } + /* Frame lanes */ /// Pushes the lane of a frame about to start and counts the writes its start makes: @@ -476,6 +520,7 @@ impl AdditionalLimit { } fn push_lane(&mut self, input: &FrameInput, depth: usize) { + self.state_gas.push(); 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 @@ -594,6 +639,7 @@ impl AdditionalLimit { /// 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.state_gas.push(); let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); } @@ -622,6 +668,7 @@ impl AdditionalLimit { self.pending_frame_charge = FrameCharge::NONE; let success = result.instruction_result().is_ok(); let refund = self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)); + self.state_gas.pop(); let check = self.check(); self.resume_stop = check.exceeded_limit().then_some(check); refund diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0ed6ee9b2..3ac0852e5 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -68,6 +68,7 @@ mod frame_limit; #[allow(clippy::module_inception)] mod limit; mod record; +mod state_gas; pub use limit::AdditionalLimit; pub(crate) use record::HistoryBytes; @@ -136,7 +137,7 @@ pub struct LimitUsage { pub write_records: u64, } -/// Limits one transaction's data size and write records. +/// Limits one transaction's data size, write records and state gas. /// /// [`tx_data_size_limit`](Self::tx_data_size_limit) and /// [`tx_kv_update_limit`](Self::tx_kv_update_limit) stop the transaction. A frame's own budget in @@ -146,7 +147,10 @@ pub struct LimitUsage { /// /// [`frame_data_size_limit`](Self::frame_data_size_limit) and /// [`frame_kv_update_limit`](Self::frame_kv_update_limit) are a further cap on every frame's -/// budget. Every limit is unlimited unless a caller sets it. +/// budget. +/// +/// [`tx_state_gas_limit`](Self::tx_state_gas_limit) holds the transaction's state gas and stops +/// the transaction; it has no frame budget. Every limit is unlimited unless a caller sets it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EvmTxRuntimeLimits { /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. @@ -160,6 +164,14 @@ pub struct EvmTxRuntimeLimits { /// A cap on every frame's write-record budget, applied after the share of what its parent has /// left. Crossing it reverts the frame alone. pub frame_kv_update_limit: u64, + /// The most EIP-8037 state gas the transaction may hold, net of what it refilled and of what + /// its failed frames rolled back: the limit on the state it grows. Crossing it stops the + /// transaction. + /// + /// It is a limit on gas, so it counts the state at the price the transaction pays for it: a + /// slot or an account in a crowded SALT bucket costs its bucket's multiple of the schedule's + /// entry, and reaches the limit that many times sooner. + pub tx_state_gas_limit: u64, } impl Default for EvmTxRuntimeLimits { @@ -176,6 +188,7 @@ impl EvmTxRuntimeLimits { frame_data_size_limit: u64::MAX, tx_kv_update_limit: u64::MAX, frame_kv_update_limit: u64::MAX, + tx_state_gas_limit: u64::MAX, } } @@ -203,6 +216,12 @@ impl EvmTxRuntimeLimits { self } + /// Sets the transaction's state-gas limit: the most state gas it may hold. + pub const fn with_tx_state_gas_limit(mut self, limit: u64) -> Self { + self.tx_state_gas_limit = limit; + self + } + /// The transaction's limits on what it keeps, one per dimension of [`LimitUsage`]. pub(crate) const fn tx_usage_limit(&self) -> LimitUsage { LimitUsage { data_size: self.tx_data_size_limit, write_records: self.tx_kv_update_limit } @@ -297,7 +316,9 @@ pub enum LimitKind { KVUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, - /// Net new state; metered by the state-growth and KV limits. + /// Net new state, metered in EIP-8037 state gas by the state-gas limit: the `limit` of its + /// stop is the transaction's state-gas limit, in gas. The legacy engine counted the same + /// dimension in new accounts and slots. StateGrowth, } diff --git a/crates/mega-evm/src/limit/state_gas.rs b/crates/mega-evm/src/limit/state_gas.rs new file mode 100644 index 000000000..c452c7979 --- /dev/null +++ b/crates/mega-evm/src/limit/state_gas.rs @@ -0,0 +1,129 @@ +//! What the state-gas limit counts: the state gas the running transaction holds. +//! +//! EIP-8037 charges state gas for exactly the state a transaction adds — a fresh storage slot, a +//! new account, the bytes of deployed code, a delegation — at the state's own price, scaled by the +//! SALT bucket it lands in. So the state a transaction grows is the state gas it spends, and a +//! limit on that gas is the limit on its growth; nothing counts new accounts and slots beside it. +//! +//! revm keeps state gas on each frame's own gas, net of what the frame refilled, and merges a +//! frame's into its caller's when the frame succeeds; a frame that fails rolls its own back. What +//! the transaction holds at any point is therefore what it was charged before its first frame, +//! plus what every frame on the call stack holds. The first part is fixed once the first frame +//! starts, and every frame below the running one is suspended, so each frame's share of the rest +//! is fixed while it runs: [`StateGasMeter`] keeps, for each frame, what the transaction holds +//! outside it, and the running frame adds what it holds itself. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +/// The state gas the running transaction holds outside the running frame. +/// +/// One entry per frame on the call stack, pushed and popped with the frame's lane. +#[derive(Clone, Debug, Default)] +pub(crate) struct StateGasMeter { + /// The state gas charged before the first frame: the account a deposit-like transaction + /// creates for its caller, the applied EIP-7702 authorities, and the recipient or created + /// account EIP-2780 charges the first frame for. + before_frames: i64, + /// For each frame on the call stack, the state gas the transaction holds outside it: what was + /// charged before the first frame, and what each frame below it held when the frame above it + /// started. + outside: Vec, + /// The state gas the frame starting the next frame holds, until that frame's entry is pushed. + caller: i64, +} + +impl StateGasMeter { + /// Clears the meter for a new transaction, keeping its allocation. + pub(crate) fn reset(&mut self) { + self.before_frames = 0; + self.outside.clear(); + self.caller = 0; + } + + /// Records the state gas charged before the first frame. + pub(crate) const fn set_before_frames(&mut self, spent: i64) { + self.before_frames = spent; + } + + /// Records the state gas the frame starting the next frame holds. + pub(crate) const fn note_caller(&mut self, held: i64) { + self.caller = held; + } + + /// Pushes the entry of a frame about to start: what the transaction holds outside it is what + /// it holds outside its caller plus what its caller holds, or, for the first frame, what was + /// charged before any frame. + /// + /// A frame no caller noted anything for — one an inspector answered before it reached frame + /// init — never runs, so what it is given is never read. + pub(crate) fn push(&mut self) { + let caller = core::mem::take(&mut self.caller); + let outside = match self.outside.last() { + Some(outside) => outside.saturating_add(caller), + None => self.before_frames, + }; + self.outside.push(outside); + } + + /// Pops the entry of the frame that returned. + pub(crate) fn pop(&mut self) { + self.outside.pop(); + } + + /// The state gas the transaction holds while the running frame holds `running`; outside any + /// frame, `running` is all of it. + /// + /// A frame can hold less than nothing — it refilled a slot a caller of its filled — but never + /// by more than its callers hold, so the sum is never below zero. + pub(crate) fn held(&self, running: i64) -> u64 { + let outside = self.outside.last().copied().unwrap_or_default(); + u64::try_from(outside.saturating_add(running)).unwrap_or_default() + } + + /// The number of entries, which is the number of frames on the call stack. + pub(crate) fn depth(&self) -> usize { + self.outside.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Each frame is given what the transaction holds outside it: the state gas charged before + /// the first frame, and what each caller held when it started the next frame. A frame that + /// returned leaves its caller where it was. + #[test] + fn test_each_frame_holds_what_its_callers_held_when_it_started() { + let mut meter = StateGasMeter::default(); + assert_eq!(meter.held(7), 7, "outside any frame, what is charged is all of it"); + + meter.set_before_frames(100); + meter.push(); + assert_eq!(meter.held(0), 100, "the first frame starts on what was charged before it"); + assert_eq!(meter.held(20), 120); + + meter.note_caller(20); + meter.push(); + assert_eq!(meter.held(5), 125, "a child counts its caller's twenty"); + meter.note_caller(5); + meter.push(); + assert_eq!(meter.held(-5), 120, "a grandchild that refilled its caller's fill"); + assert_eq!(meter.depth(), 3); + + meter.pop(); + meter.pop(); + assert_eq!(meter.held(30), 130, "the first frame, holding its child's merged gas"); + + // A frame nobody noted a caller for starts on what its caller's caller left it. + meter.push(); + assert_eq!(meter.held(0), 100); + + meter.reset(); + assert_eq!(meter.depth(), 0); + meter.push(); + assert_eq!(meter.held(0), 0, "a reset forgets what was charged before the frames"); + } +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index a395aa0b1..b7125f964 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -25,6 +25,7 @@ mod salt_failure; mod salt_refund; mod schedule; mod state; +mod state_gas_limit; mod static_callee; mod storage_call_stipend; mod strategic_stop; diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs new file mode 100644 index 000000000..3e67b84bb --- /dev/null +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -0,0 +1,546 @@ +//! The state-gas limit: a transaction's state growth, held to a limit in state gas. +//! +//! EIP-8037 charges state gas for exactly the state a transaction adds, so the limit on its state +//! gas is the limit on its growth. A transaction is held to `tx_state_gas_limit` at every site +//! state gas is charged — a fresh slot, an account a value transfer, a creation or a destruction +//! adds, deployed code, an applied EIP-7702 authority, the first frame's recipient or created +//! account — on what it holds net of refills and of failed frames. A crossing stops the +//! transaction with a revert carrying `MegaLimitExceeded(3, limit)`, wherever on the call stack +//! it happens: there are no frame budgets. +//! +//! The figures are read off the engine rather than written out: each case first runs without a +//! limit, and the state gas it reports is what the limit is set against. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{ + CALL, CREATE, CREATE2, DELEGATECALL, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, REVERT, + SELFDESTRUCT, STOP, +}; + +use crate::common::{authorizing_call, call, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000600000"); +const A: Address = address!("0000000000000000000000000000000000600001"); +const B: Address = address!("0000000000000000000000000000000000600002"); +const C: Address = address!("0000000000000000000000000000000000600003"); +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; +/// Above the execution cap: the reservoir pays every state charge. +const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_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])) +} + +fn run_under(db: MemoryDatabase, tx: MegaTransaction, limit: u64) -> MegaTransactionOutcome { + MegaEvm::new( + context(db) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit)), + ) + .execute_transaction(tx) + .unwrap() +} + +/// The outcome was stopped by the state-gas limit `limit`, crossed at `used`: a revert carrying +/// `MegaLimitExceeded(3, limit)`, never a halt. +fn assert_state_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::StateGrowth, 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 +} + +/// Appends a `CALL` to `target` with all the gas and `value`, dropping its success flag. +fn then_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) + .append(POP) +} + +/// 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() +} + +/// Appends a `CREATE` of `init` carrying no value, or a `CREATE2` with salt zero, dropping the +/// address. +fn then_create(builder: BytecodeBuilder, init: &Bytes, create2: bool) -> BytecodeBuilder { + let builder = builder.mstore(0, init); + // CREATE2 takes a salt below the size, the offset and the value. + let builder = if create2 { builder.push_number(0_u64) } else { builder }; + builder + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(if create2 { CREATE2 } else { CREATE }) + .append(POP) +} + +/// The state gas `tx` holds when it runs without a limit. +fn state_gas_of(db: &MemoryDatabase, tx: &MegaTransaction) -> u64 { + let outcome = run_under(db.clone(), tx.clone(), u64::MAX); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome.gas.state +} + +/// The state gas one fresh slot of `A` costs. +fn one_slot() -> u64 { + let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + state_gas_of(&db, &call(CALLER, A, U256::ZERO, BELOW_CAP)) +} + +/// One case per site state gas is charged at: the transaction, and the state it holds. +fn sites(gas_limit: u64) -> Vec<(&'static str, MemoryDatabase, MegaTransaction)> { + let to_a = |code: BytecodeBuilder| funded().account_code(A, code.stop().build()); + let a = || call(CALLER, A, U256::ZERO, gas_limit); + let deployed = constructor_returning(32); + vec![ + ("a fresh slot", to_a(write_slots(BytecodeBuilder::default(), 0, 1)), a()), + ( + "a value call that creates its recipient", + to_a(then_call(BytecodeBuilder::default(), EMPTY, 1)), + a(), + ), + ( + "a nested creation", + to_a(then_create(BytecodeBuilder::default(), &Bytes::new(), false)), + a(), + ), + ( + "a nested CREATE2 that deposits code", + to_a(then_create(BytecodeBuilder::default(), &deployed, true)), + a(), + ), + ( + "a nested creation that deposits code", + to_a(then_create(BytecodeBuilder::default(), &deployed, false)), + a(), + ), + ( + "a destruction that creates its beneficiary", + to_a(BytecodeBuilder::default().push_address(EMPTY).append(SELFDESTRUCT)), + a(), + ), + ("a value transaction that creates its recipient", funded(), { + call(CALLER, EMPTY, U256::from(1), gas_limit) + }), + ("a creation transaction", funded(), create(CALLER, Bytes::new(), gas_limit)), + ( + "a creation transaction that deposits code", + funded(), + create(CALLER, deployed.clone(), gas_limit), + ), + ( + "an authority the transaction creates", + funded().account_code(A, Bytes::from_static(&[STOP])), + authorizing_call(CALLER, A, U256::ZERO, gas_limit, DELEGATE, &[(AUTHORITY_1, 0)]), + ), + ] +} + +/* ---------- every site ---------- */ + +/// At every site, a limit equal to the state gas a transaction holds lets it through with that +/// state gas, and one below it stops it at the charge that crosses — the last one it makes — with +/// the figure it reports. The stop keeps none of it, below and above the execution cap alike. +#[test] +fn test_every_site_is_held_to_the_limit_at_the_state_gas_it_reports() { + for gas_limit in [BELOW_CAP, ABOVE_CAP] { + for (name, db, tx) in sites(gas_limit) { + let name = format!("{name}, gas limit {gas_limit}"); + let held = state_gas_of(&db, &tx); + assert!(held > 0, "{name}"); + + let fits = run_under(db.clone(), tx.clone(), held); + assert!(fits.result.is_success(), "{name}: {:?}", fits.result); + assert_eq!(fits.limit_exceeded, None, "{name}"); + assert_eq!(fits.gas.state, held, "{name}"); + + let stopped = run_under(db, tx, held - 1); + assert_state_stopped(&name, &stopped, held - 1, held); + assert_eq!(stopped.gas.state, 0, "{name}: the stop keeps none of it"); + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + stopped.gas.reservoir_remaining, + gas_limit - TX_GAS_LIMIT_CAP - stopped.gas.state - stopped.gas.history, + "{name}: the stop hands the reservoir back" + ); + } + } + } +} + +/// A crossing stops the transaction at the charge that crossed: nothing after it runs. Each case +/// crosses at its site and would then burn what its frame has left in a call to a contract that +/// halts; the stop spends none of it. +#[test] +fn test_the_crossing_charge_is_where_the_transaction_stops() { + let deployed = constructor_returning(32); + let cases: [(&str, BytecodeBuilder); 5] = [ + ("a fresh slot", write_slots(BytecodeBuilder::default(), 0, 1)), + ( + "a value call that creates its recipient", + then_call(BytecodeBuilder::default(), EMPTY, 1), + ), + ("a nested creation", then_create(BytecodeBuilder::default(), &Bytes::new(), false)), + ("deployed code", then_create(BytecodeBuilder::default(), &deployed, false)), + ("a nested CREATE2", then_create(BytecodeBuilder::default(), &Bytes::new(), true)), + ]; + for (name, site) in cases { + let db = funded().account_code(A, then_call(site, BURNER, 0).stop().build()); + let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); + let burned = run_under(db.clone(), tx.clone(), u64::MAX); + assert!(burned.gas.regular > BELOW_CAP / 2, "{name}: the burner burns: {:?}", burned.gas); + + let held = burned.gas.state; + let stopped = run_under(db, tx, held - 1); + assert_state_stopped(name, &stopped, held - 1, held); + assert!(stopped.gas.regular < 1_000_000, "{name}: nothing burned: {:?}", stopped.gas); + assert_eq!(stopped.gas.state, 0, "{name}"); + } +} + +/// Deployed code whose state gas crosses the limit is not left deployed, whether the creation is +/// the transaction's own or a nested one: the limit is held before `return_create` commits it. +#[test] +fn test_deployed_code_that_crosses_is_not_left_deployed() { + let deployed = constructor_returning(32); + let nested = funded() + .account_code(A, then_create(BytecodeBuilder::default(), &deployed, false).stop().build()); + let cases = [ + ( + "the transaction's creation", + funded(), + create(CALLER, deployed, BELOW_CAP), + CALLER.create(0), + ), + ("a nested creation", nested, call(CALLER, A, U256::ZERO, BELOW_CAP), A.create(0)), + ]; + for (name, db, tx, created) in cases { + let held = state_gas_of(&db, &tx); + let kept = run_under(db.clone(), tx.clone(), held); + assert_eq!( + kept.state[&created].info.code.as_ref().map(|code| code.original_bytes().len()), + Some(32), + "{name}" + ); + + let stopped = run_under(db, tx, held - 1); + assert_state_stopped(name, &stopped, held - 1, held); + assert!( + stopped.state.get(&created).is_none_or(|account| account.info.is_empty_code_hash()), + "{name}: no code is left at the created address" + ); + } +} + +/// A creation whose init code reverts deposits nothing, whatever its revert data: the limit holds +/// the account the creation would have added and the caller goes on. +#[test] +fn test_a_reverting_creation_is_not_held_for_its_revert_data() { + let reverting = + BytecodeBuilder::default().push_number(32_u8).push_number(0_u8).append(REVERT).build(); + let account = state_gas_of( + &funded().account_code( + A, + then_create(BytecodeBuilder::default(), &Bytes::new(), false).stop().build(), + ), + &call(CALLER, A, U256::ZERO, BELOW_CAP), + ); + let db = funded() + .account_code(A, then_create(BytecodeBuilder::default(), &reverting, false).stop().build()); + let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), account); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.gas.state, 0, "the failed creation's account charge came back"); +} + +/* ---------- one limit for the whole call stack ---------- */ + +/// A child's crossing stops the whole transaction: there is no frame budget to revert it alone. +/// What its callers hold counts: `A`, `B` and `C` each write one slot, and a limit one gas short +/// of three slots is crossed in `C`, with the three slots as the figure. +#[test] +fn test_a_childs_crossing_latches_the_transaction() { + let slot = one_slot(); + let db = funded() + .account_code( + A, + then_call(write_slots(BytecodeBuilder::default(), 0, 1), B, 0).stop().build(), + ) + .account_code( + B, + then_call(write_slots(BytecodeBuilder::default(), 0, 1), C, 0).stop().build(), + ) + .account_code(C, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); + + let fits = run_under(db.clone(), tx.clone(), 3 * slot); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.gas.state, 3 * slot); + + let stopped = run_under(db.clone(), tx.clone(), 3 * slot - 1); + assert_state_stopped("C crosses", &stopped, 3 * slot - 1, 3 * slot); + + let stopped = run_under(db, tx, 2 * slot - 1); + assert_state_stopped("B crosses", &stopped, 2 * slot - 1, 2 * slot); +} + +/// What was charged before the first frame and what the frames charge add up: an authority the +/// transaction creates and a slot its frame writes cross a limit neither crosses alone. +#[test] +fn test_charges_before_the_first_frame_and_in_it_add_up() { + let slot = one_slot(); + let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + let tx = authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]); + let held = state_gas_of(&db, &tx); + let authority = held - slot; + assert!(authority > slot, "an authority costs an account and its delegation"); + + let stopped = run_under(db, tx, held - 1); + assert_state_stopped("the slot after the authority", &stopped, held - 1, held); + assert_eq!( + stopped.state[&AUTHORITY_1].info.nonce, 1, + "the authority fitted, and the stop in the frame does not take it back" + ); + assert_eq!(stopped.gas.state, authority, "the authority's state gas stays with it"); +} + +/* ---------- refills give their room back ---------- */ + +/// The limit holds what the transaction holds net: a slot written back gives its room back, and +/// so do a failed child's writes, a creation that failed, and a slot a delegate writes back +/// before writing another. Each case holds two slots' worth of charges over its run, and fits a +/// limit of one. +#[test] +fn test_what_is_given_back_gives_its_room_back() { + let slot = one_slot(); + let reverting = Bytes::from_static(&[PUSH0, PUSH0, REVERT]); + let restores_then_writes = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::ZERO) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + 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 cases: [(&str, MemoryDatabase); 3] = [ + ( + "a slot written back, then another", + funded().account_code( + A, + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(), + ), + ), + ( + "a child's slot rolled back with its revert, then a slot of the caller's", + funded() + .account_code( + A, + then_call(BytecodeBuilder::default(), B, 0) + .sstore(U256::ZERO, U256::from(1)) + .stop() + .build(), + ) + .account_code( + B, + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, REVERT]) + .build(), + ), + ), + ( + "a delegate that writes its caller's slot back, then another", + funded().account_code(A, delegate_to_b).account_code(B, restores_then_writes), + ), + ]; + for (name, db) in cases { + let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), slot); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}"); + assert_eq!(outcome.gas.state, slot, "{name}"); + } + + // A creation that fails gives its account back to its creator, which then has room for a + // slot under a limit of one account. + let account = state_gas_of( + &funded().account_code( + A, + then_create(BytecodeBuilder::default(), &Bytes::new(), false).stop().build(), + ), + &call(CALLER, A, U256::ZERO, BELOW_CAP), + ); + let db = funded().account_code( + A, + then_create(BytecodeBuilder::default(), &reverting, false) + .sstore(U256::from(9), U256::from(1)) + .stop() + .build(), + ); + let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), account); + assert!(outcome.result.is_success(), "a failed creation: {:?}", outcome.result); + assert_eq!(outcome.gas.state, slot); +} + +/* ---------- SALT ---------- */ + +/// The limit is on state gas, so it counts state at the price SALT sets for it: a slot in a bucket +/// twice the minimum costs two slots of the limit, and a limit of two minimal slots admits two +/// slots in minimal buckets but crosses on the second when the first is in the crowded one. +#[test] +fn test_a_crowded_bucket_reaches_the_limit_sooner() { + use crate::salt::{crowded_slot, minimal_envs, salt_context}; + + let slot = one_slot(); + let db = + || funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 2).stop().build()); + let run = |envs| { + MegaEvm::new(salt_context(db(), envs).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(2 * slot), + )) + .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) + .unwrap() + }; + + let minimal = run(minimal_envs()); + assert!(minimal.result.is_success(), "{:?}", minimal.result); + assert_eq!(minimal.gas.state, 2 * slot); + + let unlimited = + MegaEvm::new(salt_context(db(), crowded_slot(minimal_envs(), A, U256::ZERO, 2))) + .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) + .unwrap(); + assert_eq!(unlimited.gas.state, 3 * slot, "the crowded slot costs two"); + let crowded = run(crowded_slot(minimal_envs(), A, U256::ZERO, 2)); + assert_state_stopped("the second slot after a crowded first", &crowded, 2 * slot, 3 * slot); + + let crowded = run(crowded_slot(minimal_envs(), A, U256::ZERO, 3)); + assert_state_stopped("a first slot three times the price", &crowded, 2 * slot, 3 * slot); +} + +/* ---------- authorities ---------- */ + +/// Authorities whose state gas crosses the limit are not applied: the limit is enforced before +/// the writes it guards, the gas they charged is taken back, and the transaction is stopped at its +/// first frame. The state gas is held before their records are, so a transaction that crosses +/// both limits reports the state gas. +#[test] +fn test_authorities_crossing_the_limit_are_not_applied() { + let db = || funded().account_code(A, Bytes::from_static(&[STOP])); + let tx = || { + authorizing_call( + CALLER, + A, + U256::ZERO, + BELOW_CAP, + DELEGATE, + &[(AUTHORITY_1, 0), (AUTHORITY_2, 0)], + ) + }; + let held = state_gas_of(&db(), &tx()); + let applied = run_under(db(), tx(), held); + assert!(applied.result.is_success()); + assert_eq!(applied.usage.write_records, 2); + + for limits in [ + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(held - 1), + EvmTxRuntimeLimits::no_limits() + .with_tx_state_gas_limit(held - 1) + .with_tx_kv_update_limit(0), + ] { + let stopped = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx()) + .unwrap(); + assert_state_stopped("two authorities", &stopped, held - 1, held); + assert_eq!(stopped.usage.write_records, 0, "no record of them is kept"); + for authority in [AUTHORITY_1, AUTHORITY_2] { + let account = stopped.state.get(&authority); + assert!( + account.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "{authority} was not delegated: {account:?}" + ); + } + } +} + +/* ---------- which limit binds first ---------- */ + +/// A fresh slot is charged its state gas inside `SSTORE`, before its record is counted, so a slot +/// that crosses the state-gas and data-size limits at once is the state-gas limit's stop. +#[test] +fn test_a_slot_crossing_both_limits_reports_the_state_gas() { + let slot = one_slot(); + let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + let outcome = MegaEvm::new( + context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_state_gas_limit(slot - 1) + .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE - 1), + ), + ) + .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) + .unwrap(); + assert_state_stopped("a slot over both", &outcome, slot - 1, slot); +} + +/// Each transaction the same EVM runs is held to the limit from zero. +#[test] +fn test_each_transaction_is_held_to_the_limit_from_zero() { + let slot = one_slot(); + let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 2).stop().build()); + let mut evm = + MegaEvm::new(context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(2 * slot), + )); + for run in 0..2 { + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)).unwrap(); + assert!(outcome.result.is_success(), "run {run}: {:?}", outcome.result); + assert_eq!(outcome.gas.state, 2 * slot, "run {run}"); + } +} From 87756a0534a3c063a4692774020e678ee4662013 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:37:48 -0700 Subject: [PATCH 088/458] test(satin): hold the KV count to the data size across the record corpus --- crates/mega-evm/tests/satin/write_records.rs | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 8033e1e49..662bcb904 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1223,3 +1223,58 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { 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 deployed code and the hint's payload. +/// +/// So a KV limit binds only below the data-size limit's fortieth: at the production data-size +/// caps a transaction keeps at most 327,680 records, whatever its KV limit. +#[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, + "{}: 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"); +} From 8a5d5f7be78444400ffecf8e3aca8245b0064c03 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:39:08 -0700 Subject: [PATCH 089/458] test(satin): hold equivalence mode to no data-size, KV or state-gas limit --- crates/mega-evm/src/limit/mod.rs | 24 +++++++++++++++++++++++ crates/mega-evm/src/test_utils/neutral.rs | 7 +++++++ 2 files changed, 31 insertions(+) diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 3ac0852e5..e78821f04 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -427,6 +427,30 @@ mod tests { 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, and what a bare context runs under. 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, + tx_kv_update_limit, + frame_kv_update_limit, + tx_state_gas_limit, + } = EvmTxRuntimeLimits::no_limits(); + for limit in [ + tx_data_size_limit, + frame_data_size_limit, + tx_kv_update_limit, + frame_kv_update_limit, + tx_state_gas_limit, + ] { + assert_eq!(limit, u64::MAX); + } + assert_eq!(EvmTxRuntimeLimits::default(), EvmTxRuntimeLimits::no_limits()); + } + #[test] fn test_limit_usage_arithmetic_saturates() { let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 0eee59735..39b8386c0 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -8,6 +8,13 @@ //! 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 neither the data-size, the KV nor the state-gas limit binds, at the transaction or +//! at a frame. 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. +//! //! 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 From 011c387f542c58ce19eb394817c6b9e11123cba9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:40:34 -0700 Subject: [PATCH 090/458] bench(satin): run the state-gas and KV limits on the limited workload --- crates/mega-evm/benches/transact.rs | 51 ++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index a236f7f18..5d1ef2b7f 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -22,6 +22,10 @@ //! 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`). +//! - `state_limits`: the same transaction under a state-gas limit and a KV limit equal to exactly +//! the state gas and the write records it keeps, so every fresh slot is held to both as it is +//! written (`satin`); and under a state-gas limit one gas short, so the last slot crosses and the +//! transaction is stopped (`stopped`). Its op-revm baseline is `data_size_limit/op_revm`. //! //! 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 @@ -33,7 +37,9 @@ //! 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 +//! records it is sized for, and stops at its last log one byte short of them; the state-limit one +//! keeps exactly the state gas and records its limits allow, and stops at its last slot one gas +//! 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)] @@ -387,6 +393,49 @@ fn bench_transact(c: &mut Criterion) { ); }); + // The state-limit arms: the same transaction under a state-gas and a KV limit it exactly + // reaches, and under a state-gas limit one gas short of it. + let state_gas = MegaEvm::new(mega_context(db.clone())) + .execute_transaction(OpTx(limited_tx.clone())) + .unwrap() + .gas + .state; + let state_limited = |limit| { + mega_context(db.clone()).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_state_gas_limit(limit) + .with_tx_kv_update_limit(REPEAT), + ) + }; + let at_limit = MegaEvm::new(state_limited(state_gas)) + .execute_transaction(OpTx(limited_tx.clone())) + .unwrap(); + assert!(at_limit.result.is_success(), "state_limits: {:?}", at_limit.result); + assert_eq!(at_limit.gas.state, state_gas, "state_limits: the arm must reach its state gas"); + assert_eq!(at_limit.usage.write_records, REPEAT, "state_limits: and its records"); + let stopped = MegaEvm::new(state_limited(state_gas - 1)) + .execute_transaction(OpTx(limited_tx.clone())) + .unwrap(); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: state_gas - 1, + used: state_gas, + frame_local: false, + }), + "state_limits/stopped: the last slot must be the gas that crosses", + ); + for (arm, limit) in [("satin", state_gas), ("stopped", state_gas - 1)] { + group.bench_function(format!("state_limits/{arm}"), |b| { + b.iter_batched( + || MegaEvm::new(state_limited(limit)), + |mut evm| evm.transact(OpTx(limited_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 = [ From a623e843a14259512e7386d19b81a7b3aea9cfe8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:45:47 -0700 Subject: [PATCH 091/458] test(satin): port the parked rows the state-growth and KV limits own --- crates/mega-evm/tests/_pending/README.md | 41 +- .../_pending/block_executor/block_limits.rs | 131 ---- .../mega-evm/tests/_pending/mini_rex/main.rs | 1 - .../_pending/mini_rex/state_growth_limit.rs | 220 ------ .../mini_rex/tx_data_and_kv_update_limit.rs | 143 ---- .../tests/_pending/rex4/frame_limits.rs | 224 ------ .../_pending/rex4/intrinsic_limit_bypass.rs | 82 --- .../_pending/rex5/eip7702_state_growth.rs | 366 --------- crates/mega-evm/tests/_pending/rex5/main.rs | 1 - .../_pending/rex5/selfdestruct_beneficiary.rs | 146 ---- .../_pending/rex6/beneficiary_detention.rs | 23 - .../rex6/eip7702_authority_accounting.rs | 694 ------------------ .../tests/_pending/src/limit/kv_update.rs | 19 - crates/mega-evm/tests/block/limits.rs | 75 +- crates/mega-evm/tests/satin/kv_limit.rs | 12 +- .../mega-evm/tests/satin/state_gas_limit.rs | 392 +++++++++- 16 files changed, 473 insertions(+), 2097 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/kv_update.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 2c3c2c602..5c0826b69 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,8 +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 | -| detention | 81 | 76 | 5 | 73 | 8 | 0 | -| the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | +| detention | 83 | 78 | 5 | 73 | 10 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | @@ -37,7 +36,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** | **383** | **357** | **26** | **232** | **123** | **28** | +| **Total** | **329** | **304** | **25** | **232** | **90** | **7** | ## Tests ported in place @@ -258,6 +257,24 @@ These 47 rows run in a real test target now, adapted to the Satin API and to the | `src/limit/data_size.rs` | the data-size limit (2) | 2 | `crates/mega-evm/src/limit/frame_limit.rs`, `crates/mega-evm/src/limit/mod.rs` | | **Total** | | **47** | | +## Tests ported by the state-growth and KV limits + +These 54 rows run in a real test target now, adapted to the Satin API: the state growth they pin is held as EIP-8037 state gas by a per-transaction state-gas limit, and the KV updates they count are the write records the common execution layer keeps, held to a KV limit that follows the data-size limit's transaction and frame rules. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `block_executor/block_limits.rs` | the state-growth and KV limits (2) | 2 | `tests/block/limits.rs` | +| `mini_rex/state_growth_limit.rs` | the state-growth and KV limits (4) | 4 | `tests/satin/state_gas_limit.rs` | +| `mini_rex/tx_data_and_kv_update_limit.rs` | the state-growth and KV limits (6) | 6 | `tests/satin/kv_limit.rs` | +| `rex4/frame_limits.rs` | the state-growth and KV limits (9) | 9 | `tests/satin/kv_limit.rs` | +| `rex4/intrinsic_limit_bypass.rs` | the state-growth and KV limits (3) | 3 | `tests/satin/kv_limit.rs` | +| `rex5/eip7702_state_growth.rs` | the state-growth and KV limits (8) | 8 | `tests/satin/state_gas_limit.rs` | +| `rex5/selfdestruct_beneficiary.rs` | the state-growth and KV limits (4) | 4 | `tests/satin/state_gas_limit.rs` | +| `rex6/beneficiary_detention.rs` | the state-growth and KV limits (1) | 1 | `tests/satin/state_gas_limit.rs` | +| `rex6/eip7702_authority_accounting.rs` | the state-growth and KV limits (16) | 16 | `tests/satin/state_gas_limit.rs` | +| `src/limit/kv_update.rs` | the state-growth and KV limits (1) | 1 | `tests/satin/kv_limit.rs` | +| **Total** | | **54** | | + ## Tests retired after the inventory These 21 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. @@ -301,6 +318,8 @@ They are not counted above. | `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | +| `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_beneficiary_triggers_detention` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | +| `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_compute_overflow_skips_authorities` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | ## Files @@ -308,7 +327,6 @@ 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` | 7 | keep 7 (the pre-block system calls) | | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | @@ -318,8 +336,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/compute_gas_limit.rs` | 2 | 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` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | -| `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` | 10 | 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)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | | `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | | `rex2/keyless_deploy.rs` | 36 | 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) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | @@ -328,16 +345,15 @@ 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/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `rex4/frame_limits.rs` | 10 | rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | +| `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | -| `rex4/intrinsic_limit_bypass.rs` | 4 | undecided 3 (the state-growth and KV limits · D46); rewrite 1 (inspector support · D41) | +| `rex4/intrinsic_limit_bypass.rs` | 1 | 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)) | | `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) | @@ -345,10 +361,10 @@ Each cell lists `disposition count (mechanism · decision)`. | `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` | 6 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention) | -| `rex6/beneficiary_detention.rs` | 14 | keep 13 (detention · D08); rewrite 1 (the state-growth and KV limits · D45) | +| `rex5/selfdestruct_beneficiary.rs` | 2 | keep 2 (detention) | +| `rex6/beneficiary_detention.rs` | 13 | keep 13 (detention · D08) | | `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/eip7702_authority_accounting.rs` | 2 | rewrite 2 (detention · 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/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) | @@ -356,6 +372,5 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | | `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · 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 index 824d84eb1..a58dcb8af 100644 --- a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs +++ b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs @@ -108,136 +108,5 @@ fn create_sstore_contract(num_writes: usize) -> Bytes { 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/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs index 0a4e5ed7c..e90c00b83 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -6,5 +6,4 @@ 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/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 index 95b8d0873..f4fce5a89 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 @@ -232,37 +232,6 @@ fn test_data_limit_just_exceed() { 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 @@ -300,122 +269,10 @@ fn test_data_limit_exceed_in_nested_call() { 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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs index 312b558ec..717345d49 100644 --- a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs +++ b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs @@ -180,230 +180,6 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { // 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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs index ae4f5d75f..2a071f929 100644 --- a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs +++ b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs @@ -99,96 +99,14 @@ fn tx_intrinsic_data_size_with_calldata(n: u64) -> u64 { // 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 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 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) // ============================================================================ 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/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 7db9edbf5..0dcc3c499 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -6,7 +6,6 @@ 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; diff --git a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index 8d8114ff4..ebbc3ee73 100644 --- a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -61,105 +61,6 @@ fn transact( // 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 // ============================================================================ @@ -335,50 +236,3 @@ fn staticcall_once_parent(target: Address, gas_each: u64) -> Bytes { .build() } -/// 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/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs index 888ad161c..b09af9d65 100644 --- a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs @@ -337,29 +337,6 @@ fn test_rex6_call_to_eip7702_delegator_to_beneficiary_enabled_marks_beneficiary( // Existing-target SELFDESTRUCT accounting // ============================================================================ -/// 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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs index 00069636d..4261d400c 100644 --- a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs @@ -188,414 +188,6 @@ fn transact_detention( // 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 @@ -642,162 +234,6 @@ fn test_rex6_authority_compute_overflow_skips_authorities() { ); } -/// 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 @@ -849,133 +285,3 @@ fn test_rex6_authority_beneficiary_triggers_detention() { ); } -/// 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/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/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 9ca496953..a8783f287 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -11,7 +11,7 @@ use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, }; use revm::{ - bytecode::opcode::LOG0, + bytecode::opcode::{ADD, DUP1, LOG0, SLOAD, SSTORE}, context::{result::ExecutionResult, BlockEnv, ContextTr}, Database as _, }; @@ -121,6 +121,79 @@ fn test_block_data_limit_exceeded_mid_block() { assert_eq!(result.receipts().len(), 3, "the fourth transaction never ran"); } +/// 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() +} + +/// 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 limit: the transaction that crosses it is packed, however far past the limit +/// it takes the block, and the next one is refused before it runs. +#[test] +fn test_block_custom_kv_update_limit() { + let mut state = state_with_incrementing_contract(50); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_kv_update_limit(1)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&user_tx(0, 10_000_000)).expect("the crossing transaction"); + assert_eq!(executor.limiter().usage.write_records, 50, "the block has crossed its limit"); + + let err = executor + .execute_transaction(&user_tx(1, 10_000_000)) + .expect_err("the block has no write records left"); + assert!(format!("{err}").contains("Block KV update limit reached"), "{err}"); + assert!(format!("{err}").contains("block_used=50"), "{err}"); +} + +/// The same limit mid-block, one record a transaction: the transactions up to the one that +/// reaches the limit are packed, and the block ends there. +#[test] +fn test_block_kv_limit_exceeded_mid_block() { + let mut state = state_with_incrementing_contract(1); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_kv_update_limit(3)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + for nonce in 0..3 { + let tx = user_tx(nonce, 10_000_000); + let gas = executor.execute_transaction(&tx).expect("packed"); + assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); + } + assert!( + executor.execute_transaction(&user_tx(3, 10_000_000)).is_err(), + "the block has no write records left" + ); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3, "the fourth transaction never ran"); + assert_eq!(result.usage.write_records, 3, "the block reports its KV count"); +} + /// A transaction refused before it runs changes nothing: no receipt, and no state. #[test] fn test_block_no_state_commit_on_limit_exceeded() { diff --git a/crates/mega-evm/tests/satin/kv_limit.rs b/crates/mega-evm/tests/satin/kv_limit.rs index 39959ee95..0eff736bb 100644 --- a/crates/mega-evm/tests/satin/kv_limit.rs +++ b/crates/mega-evm/tests/satin/kv_limit.rs @@ -22,7 +22,8 @@ use mega_evm::{ FRAME_DATA_SHARE_NUMERATOR, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ - CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, RETURNDATACOPY, RETURNDATASIZE, STOP, + CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, RETURNDATACOPY, RETURNDATASIZE, + SELFDESTRUCT, STOP, }; use crate::common::{authorizing_call, call, call_with_data, context}; @@ -136,7 +137,7 @@ fn slot_written(outcome: &MegaTransactionOutcome, address: Address, slot: u64) - /// slot is no change, and the sender is the body's. #[test] fn test_the_kv_count_is_the_write_records_kept() { - let cases: [(&str, Bytes, u64); 6] = [ + let cases: [(&str, Bytes, u64); 7] = [ ("an empty call", Bytes::new(), 0), ("three fresh slots", slots(3), 3), ( @@ -164,9 +165,14 @@ fn test_the_kv_count_is_the_write_records_kept() { ), ( "a value transfer: the frame's account and the recipient", - { then_call(BytecodeBuilder::default(), B, 1).stop().build() }, + then_call(BytecodeBuilder::default(), B, 1).stop().build(), 2, ), + ( + "a destruction that moves value: its beneficiary", + BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(), + 1, + ), ]; for (name, code, kept) in cases { let outcome = run_kv(funded().account_code(A, code), u64::MAX); diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index 3e67b84bb..6d918d955 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -466,47 +466,379 @@ fn test_a_crowded_bucket_reaches_the_limit_sooner() { /* ---------- authorities ---------- */ -/// Authorities whose state gas crosses the limit are not applied: the limit is enforced before -/// the writes it guards, the gas they charged is taken back, and the transaction is stopped at its -/// first frame. The state gas is held before their records are, so a transaction that crosses -/// both limits reports the 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_authorities_crossing_the_limit_are_not_applied() { - let db = || funded().account_code(A, Bytes::from_static(&[STOP])); - let tx = || { - authorizing_call( - CALLER, - A, - U256::ZERO, - BELOW_CAP, - DELEGATE, - &[(AUTHORITY_1, 0), (AUTHORITY_2, 0)], - ) +fn test_an_authorization_adds_state_only_when_it_applies() { + 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_under( + db.account_code(A, Bytes::from_static(&[STOP])), + authorizing(A, U256::ZERO, &authorizations), + u64::MAX, + ); + 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"); + } +} + +/// An authority in a crowded bucket costs the bucket's multiple of its new account and its +/// delegation, on the state ledger alone: its record and the data size do not move. +#[test] +fn test_a_crowded_authority_moves_the_state_ledger_alone() { + use crate::salt::{crowded_account, minimal_envs, salt_context}; + let (account, delegation) = account_and_delegation(); + let run = |envs| { + MegaEvm::new(salt_context(funded().account_code(A, Bytes::from_static(&[STOP])), envs)) + .execute_transaction(authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)])) + .unwrap() }; - let held = state_gas_of(&db(), &tx()); - let applied = run_under(db(), tx(), held); - assert!(applied.result.is_success()); - assert_eq!(applied.usage.write_records, 2); + let minimal = run(minimal_envs()); + let crowded = run(crowded_account(minimal_envs(), AUTHORITY_1, 100)); + assert!(minimal.result.is_success() && crowded.result.is_success()); + assert_eq!(minimal.gas.state, account + delegation); + assert_eq!(crowded.gas.state, 100 * (account + delegation)); + assert_eq!(crowded.gas.regular, minimal.gas.regular, "the regular ledger does not move"); + assert_eq!(crowded.usage, minimal.usage, "the record and the data size do not move"); +} + +/// 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() { + 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:?}" + ); + assert!(run(crowded_account(minimal_envs(), AUTHORITY_1, 100), BELOW_CAP).result.is_success()); +} - for limits in [ - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(held - 1), - EvmTxRuntimeLimits::no_limits() - .with_tx_state_gas_limit(held - 1) - .with_tx_kv_update_limit(0), - ] { - let stopped = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) - .execute_transaction(tx()) +/// 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_under( + funded(), + authorizing(AUTHORITY_1, U256::from(1), &[(Some(AUTHORITY_1), 0, 0)]), + u64::MAX, + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, account + delegation); + assert_eq!(outcome.usage.write_records, 1); + + let unauthorized = + run_under(funded(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP), u64::MAX); + assert_eq!(unauthorized.gas.state, account, "the same transfer without it pays the account"); +} + +/// Authorities that cross a limit are not applied, whichever limit it is: the limit is enforced +/// before the writes it guards, the gas they charged is taken back, and the transaction is stopped +/// at its first frame. Their state gas is held first, then their records' data size and KV count, +/// so a transaction that crosses more than one limit reports the first of them. Taking them back +/// forgoes the refund an authority that existed would have earned: two transactions that differ +/// in that alone spend the same gas. +#[test] +fn test_authorities_crossing_any_limit_are_not_applied() { + let (account, delegation) = account_and_delegation(); + 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 held = 2 * (account + delegation); + let body = TX_BODY_SIZE + 2 * mega_evm::AUTHORIZATION_SIZE; + let limits = EvmTxRuntimeLimits::no_limits; + let state_stop = |limit, used| LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit, + used, + frame_local: false, + }; + // (case, database, authorizations, limits, the stop) + type Case = (&'static str, MemoryDatabase, Vec, EvmTxRuntimeLimits, LimitCheck); + let cases: [Case; 6] = [ + ( + "a new authority under no state gas at all", + fresh(), + vec![both[0]], + limits().with_tx_state_gas_limit(0), + state_stop(0, account + delegation), + ), + ( + "two new authorities one gas short", + fresh(), + both.to_vec(), + limits().with_tx_state_gas_limit(held - 1), + state_stop(held - 1, held), + ), + ( + "two new authorities over the state-gas and the KV limit", + fresh(), + both.to_vec(), + limits().with_tx_state_gas_limit(held - 1).with_tx_kv_update_limit(0), + state_stop(held - 1, held), + ), + ( + "two existing authorities over the KV limit", + existing(), + both.to_vec(), + limits().with_tx_kv_update_limit(1), + LimitCheck::ExceedsLimit { + kind: LimitKind::KVUpdate, + limit: 1, + used: 2, + frame_local: false, + }, + ), + ( + "two new authorities over the data-size limit", + fresh(), + both.to_vec(), + limits().with_tx_data_size_limit(body + 2 * WRITE_RECORD_SIZE - 1), + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: body + 2 * WRITE_RECORD_SIZE - 1, + used: body + 2 * WRITE_RECORD_SIZE, + frame_local: false, + }, + ), + ( + "two existing authorities under no state gas at all", + existing(), + both.to_vec(), + limits().with_tx_state_gas_limit(0), + state_stop(0, 2 * delegation), + ), + ]; + for (name, db, authorizations, limits, stop) in cases { + let stopped = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(authorizing(A, U256::ZERO, &authorizations)) .unwrap(); - assert_state_stopped("two authorities", &stopped, held - 1, held); - assert_eq!(stopped.usage.write_records, 0, "no record of them is kept"); + assert!(!stopped.result.is_success() && !stopped.result.is_halt(), "{name}"); + assert_eq!(stopped.limit_exceeded, Some(stop), "{name}"); + assert_eq!(stopped.result.output().unwrap(), &stop.revert_data(), "{name}"); + assert_eq!(stopped.gas.state, 0, "{name}: their state gas was taken back"); + assert_eq!(stopped.usage.write_records, 0, "{name}: no record of them is kept"); for authority in [AUTHORITY_1, AUTHORITY_2] { let account = stopped.state.get(&authority); assert!( account.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), - "{authority} was not delegated: {account:?}" + "{name}: {authority} was not delegated: {account:?}" ); } } + + let spent = |db: MemoryDatabase| { + MegaEvm::new(context(db).with_tx_runtime_limits(limits().with_tx_state_gas_limit(0))) + .execute_transaction(authorizing(A, U256::ZERO, &both)) + .unwrap() + .gas + .gas_used + }; + assert_eq!(spent(existing()), spent(fresh()), "no refund for an authority never applied"); + + let applied = run_under(fresh(), authorizing(A, U256::ZERO, &both), held); + assert!(applied.result.is_success(), "a limit they fit applies them: {:?}", applied.result); + assert_eq!(applied.usage.write_records, 2); +} + +/* ---------- destructions ---------- */ + +/// A `SELFDESTRUCT` grows the state only when the value it moves creates its beneficiary: one new +/// account, which is also one write record. Moving value to an account that exists is a record +/// and no state; moving nothing, or to itself, is neither. +#[test] +fn test_a_destruction_grows_state_only_when_it_creates_its_beneficiary() { + let (account, _) = account_and_delegation(); + let destroys_to = |beneficiary| { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() + }; + let cases: [(&str, MemoryDatabase, u64, u64); 4] = [ + ("value to a new beneficiary", funded().account_code(A, destroys_to(EMPTY)), account, 1), + ("value to a beneficiary that exists", funded().account_code(A, destroys_to(BURNER)), 0, 1), + ( + "nothing to move", + funded().account_balance(A, U256::ZERO).account_code(A, destroys_to(EMPTY)), + 0, + 0, + ), + ("value to itself", funded().account_code(A, destroys_to(A)), 0, 0), + ]; + for (name, db, state_gas, records) in cases { + let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), u64::MAX); + 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"); + } +} + +/* ---------- fresh slots ---------- */ + +/// Three fresh slots fit a limit of three slots' state gas exactly; a fourth crosses it, on the +/// fourth `SSTORE`, and none of the four is kept. +#[test] +fn test_fresh_slots_fit_a_limit_of_their_state_gas_and_one_more_stops() { + let slot = one_slot(); + let run = |slots| { + run_under( + funded() + .account_code(A, write_slots(BytecodeBuilder::default(), 0, slots).stop().build()), + call(CALLER, A, U256::ZERO, BELOW_CAP), + 3 * slot, + ) + }; + let fits = run(3); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.gas.state, 3 * slot); + + let stopped = run(4); + assert_state_stopped("a fourth slot", &stopped, 3 * slot, 4 * slot); + let written = + stopped.state.get(&A).map_or(0, |a| a.storage.values().filter(|v| v.is_changed()).count()); + assert_eq!(written, 0, "none of the slots is kept"); } /* ---------- which limit binds first ---------- */ From 5d40e32fd8ca064484211420ef9ed8ac36038a4d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:47:31 -0700 Subject: [PATCH 092/458] docs(satin): say what the KV and state-gas limits hold and how they stop --- AGENTS.md | 24 +++++++++++---- crates/mega-evm/README.md | 14 +++++++-- crates/mega-evm/src/limit/limit.rs | 4 +-- crates/mega-evm/src/limit/mod.rs | 48 ++++++++++++++++++++++++++---- 4 files changed, 75 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 430a43bf6..e08e9c428 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,9 +102,9 @@ 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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas and data-size block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the write-record block limit | +| `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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | | `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/` | 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 latch, the transaction body and deployed code 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) | detention, the state-growth and KV limits | +| `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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | | `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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 | @@ -149,10 +149,23 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (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 162,306 gas, and keeping its record costs its 3,520 history on top. +- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0) and KV updates (1), counted on the lanes with a transaction limit and frame budgets; compute gas (2), which is the execution cap revm enforces on the regular pool until detention adds its stop; and state growth (3), held as EIP-8037 state gas by a per-transaction limit. +- The KV 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 — by the data-size limit's rules in its own unit: `EvmTxRuntimeLimits::tx_kv_update_limit` stops the transaction, and every frame gets a record budget, what the transaction has left for its own frame and 98% of what its parent has left for a child, under `frame_kv_update_limit`. + 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 data size is checked before the records wherever both cross. + At the production data-size caps a transaction or a block keeps at most 327,680 records, so the KV limits bind only below that; both are unlimited unless a node sets them, and `BlockLimits::block_kv_update_limit` is the block's, a packing budget like its data size. +- The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. + `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). + It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the `CALL`, `CALLCODE`, `CREATE` and `CREATE2` wrappers (the frame they start is answered with the stop, which gives back the gas they forwarded) — and, for deployed code, before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind. + The state gas is checked before the data size and the records wherever both cross. + It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. + It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. - `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`. A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. - None of the three refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all three, so the transactions after it find the room it used. + The KV limit refuses like the data-size one. + None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. 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`. Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. @@ -182,13 +195,14 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + The KV count a node reports is the write-record count, and the KV 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 state-gas limit's entry of what is held outside each frame is pushed and popped with the lane. - **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 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 state gas or records would cross it are taken back before the first frame. 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 51f111c91..795793b43 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -42,7 +42,7 @@ A transaction is held to a data-size limit, and every frame to a budget: the tra 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. 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. -`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB. +`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB of data size. 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. @@ -50,7 +50,7 @@ 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 and the history bytes they appended. 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. A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. -No block cap on execution gas, state gas or data size refuses a deposit, which the block must include; a deposit still counts towards all three. +No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. 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` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, hands each pre-block state (the two EIP calls and the seven deploys) to an optional observer before it commits — that sequence is the witness a stateless client needs — and leaves one hook point empty: the pre-block system calls. @@ -86,7 +86,15 @@ The allowance is not gas: it never enters the frame's `Gas`, only a log's charge 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 byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, and a body counts its five fixed write records even when fewer fee accounts are written. -The state-growth and KV limits, gas detention and keyless deployment arrive in later changes. +The KV and state-gas limits are in place too. +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 the KV limit holds it by the data-size limit's rules: a transaction limit that stops the transaction, and a record budget per frame, 98% of what the 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 whatever its KV limit. +The transaction's KV count is in its outcome's usage and the block's in its result; a block can be held to a KV limit, a packing budget like its data size. +A transaction's state growth is the EIP-8037 state gas it spends, so the state-gas limit is what holds it: `EvmTxRuntimeLimits::tx_state_gas_limit` holds the state gas a transaction holds, net of what it refilled and of what its failed frames rolled back, at every site state gas is charged, and a crossing anywhere on the call stack stops the transaction with `MegaLimitExceeded(3, limit)`. +It is a limit on gas, so a slot or an account in a crowded SALT bucket reaches it sooner. +Every one of these limits is unlimited unless a node sets it. + +Gas detention and keyless deployment arrive in later changes. ## Quick start diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index bd9da01a5..ef7deac1a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -16,8 +16,8 @@ use super::{ 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 state gas the transaction holds outside each frame, 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) diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index e78821f04..336d2304d 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -2,8 +2,8 @@ //! //! 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, the KV limit and the state-gas limit below, and detention for compute gas. //! //! 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 @@ -42,9 +42,47 @@ //! with the stop. The account a deposit-like transaction creates for its caller is charged all the //! same, because it exists whatever the transaction does. //! -//! Both limits are unlimited unless a caller sets them. A block executor installs the ones its -//! block limits carry, whose default holds a transaction to -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT). +//! # The KV limit +//! +//! The KV count is the write-record count the lanes keep: 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. [`EvmTxRuntimeLimits::tx_kv_update_limit`] holds it +//! by the data-size limit's rules in its own unit: the transaction's own frame gets what the +//! transaction has left, a child the same share of what its parent has left, under +//! [`EvmTxRuntimeLimits::frame_kv_update_limit`]; a frame over its budget reverts alone and a +//! transaction over its limit is stopped. Every check holds the data size before the records. +//! +//! A record weighs [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so +//! the KV count never weighs more than the data size, and a KV limit binds only below the +//! data-size limit's fortieth. +//! +//! # The state-gas limit +//! +//! EIP-8037 charges state gas for exactly the state a transaction adds, so the state a transaction +//! grows is the state gas it spends: [`EvmTxRuntimeLimits::tx_state_gas_limit`] holds it, and +//! nothing counts new accounts and slots beside it. What is held is net — what a frame refilled +//! and what a failed frame rolled back is out of it — and is the state gas charged before the +//! first frame plus what every frame on the call stack holds (the `state_gas` module). The limit is +//! per transaction, with no frame budget: a crossing anywhere stops the transaction, reported as +//! [`LimitKind::StateGrowth`] with the limit in gas. +//! +//! The limit holds each charge where it is made, once it is made, so a charge the frame cannot +//! pay is an out-of-gas whatever the limit: the authorities' before the first frame, which are +//! taken back on a crossing; the first frame's recipient or created account, which the first frame +//! is then answered with the stop for; a fresh slot and a destruction's new beneficiary, which +//! stop the frame; and a new account a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` adds, whose frame +//! is answered with the stop. Deployed code is held before `return_create` charges it, as its +//! bytes are, so a crossing leaves no code behind. Wherever the state gas and a record cross +//! together, the state gas is the stop reported. +//! +//! It is a limit on gas, so it counts state at the SALT price: a slot or an account in a bucket +//! `m` times the minimum costs `m` times the schedule's entry, and reaches the limit that many +//! times sooner. +//! +//! Every limit is unlimited unless a caller sets it. A block executor installs the ones its block +//! limits carry, whose default holds a transaction to +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size and to nothing else. //! //! # The byte table //! From 6b637b4cefd658fad74cddaf4d43267dcabfae6c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:48:42 -0700 Subject: [PATCH 093/458] style(test): trim the blank line two parked files were left ending on --- crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs | 1 - .../mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index ebbc3ee73..8caabdd1d 100644 --- a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -235,4 +235,3 @@ fn staticcall_once_parent(target: Address, gas_each: u64) -> Bytes { .append(STOP) .build() } - diff --git a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs index 4261d400c..38317d540 100644 --- a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs @@ -284,4 +284,3 @@ fn test_rex6_authority_beneficiary_triggers_detention() { "REX5 must not detain from an authority (detained5={detained5})", ); } - From d21a7a5503c1e6d86e63a1514e02ac12ed60fd0e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:51:36 -0700 Subject: [PATCH 094/458] feat(access): the set of volatile data a transaction read A bit per kind at its position in MegaAccessControl's VolatileDataAccessType, plus the slot number at bit 12, which the enum does not declare. Ports the four parked rows of the legacy bitmap. --- crates/mega-evm/src/access/mod.rs | 7 +- crates/mega-evm/src/access/volatile.rs | 247 ++++++++++++++++++ crates/mega-evm/src/lib.rs | 1 + crates/mega-evm/tests/_pending/README.md | 14 +- .../tests/_pending/src/access/volatile.rs | 85 ------ 5 files changed, 265 insertions(+), 89 deletions(-) create mode 100644 crates/mega-evm/src/access/volatile.rs delete mode 100644 crates/mega-evm/tests/_pending/src/access/volatile.rs diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 0a46ba7f8..2f7cf283b 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -1,3 +1,8 @@ //! Volatile-data access tracking (block environment, beneficiary, oracle) behind gas detention. //! -//! Empty until gas detention lands. +//! [`VolatileDataAccess`] names the kinds of volatile data a transaction can read. The cap a read +//! sets arrives with gas detention. + +mod volatile; + +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..7cb1d34b5 --- /dev/null +++ b/crates/mega-evm/src/access/volatile.rs @@ -0,0 +1,247 @@ +//! The kinds of volatile data a transaction can read. + +use core::ops::{BitOr, BitOrAssign}; + +use crate::system::VolatileDataAccessType; + +/// 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. +#[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 << 0); + /// 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 difficulty. Satin's base spec answers `DIFFICULTY` with the randomness instead, + /// so no read sets it; the bit keeps its position. + pub const DIFFICULTY: Self = Self(1 << 3); + /// 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); + /// A blob hash. `BLOBHASH` reads the transaction's own blob hashes, which nothing but the + /// transaction decides, so no read sets it; the bit keeps its position. + pub const BLOB_HASH: Self = Self(1 << 9); + /// 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`). + pub const SLOT_NUM: Self = Self(1 << 12); + + /// 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 + } + + /// The bits of the set. An alias of [`bits`](Self::bits). + pub const fn raw(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 + } + + /// How many block-environment kinds the set holds. An alias of + /// [`count_block_env_accessed`](Self::count_block_env_accessed). + pub const fn count_accessed(self) -> usize { + self.count_block_env_accessed() + } + + /// The block-environment kinds of the set. + pub const fn block_env_only(self) -> Self { + Self(self.0 & Self::BLOCK_ENV_MASK) + } + + /// 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.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.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); + assert_eq!(access.count_accessed(), 2); + assert_eq!( + access.block_env_only(), + VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH + ); + assert_eq!(access.raw(), access.bits()); + + 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()); + } + + #[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(), access_type as u8); + assert_eq!(converted.as_u8(), expected_flag.as_u8()); + } + // 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); + } + + /// 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::DIFFICULTY | + VolatileDataAccess::GAS_LIMIT | + VolatileDataAccess::BASE_FEE | + VolatileDataAccess::PREV_RANDAO | + VolatileDataAccess::BLOCK_HASH | + VolatileDataAccess::BLOB_BASE_FEE | + VolatileDataAccess::BLOB_HASH | + VolatileDataAccess::SLOT_NUM; + + assert_eq!(all_block_env.count_block_env_accessed(), 11); + 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); + } + + /// 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/lib.rs b/crates/mega-evm/src/lib.rs index 0e8b96e4d..f00364f84 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -21,6 +21,7 @@ pub mod system; pub mod test_utils; mod types; +pub use access::*; 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 2c3c2c602..4a9f150da 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 | -| detention | 81 | 76 | 5 | 73 | 8 | 0 | +| detention | 77 | 76 | 1 | 69 | 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 | 34 | 22 | 12 | 30 | 4 | 0 | @@ -37,7 +37,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** | **383** | **357** | **26** | **232** | **123** | **28** | +| **Total** | **379** | **357** | **22** | **228** | **123** | **28** | ## Tests ported in place @@ -258,6 +258,15 @@ These 47 rows run in a real test target now, adapted to the Satin API and to the | `src/limit/data_size.rs` | the data-size limit (2) | 2 | `crates/mega-evm/src/limit/frame_limit.rs`, `crates/mega-evm/src/limit/mod.rs` | | **Total** | | **47** | | +## Tests ported by detention + +These 4 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `src/access/volatile.rs` | detention (4) | 4 | `crates/mega-evm/src/access/volatile.rs` | +| **Total** | | **4** | | + ## Tests retired after the inventory These 21 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. @@ -353,7 +362,6 @@ 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/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/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | 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); - } -} From 571db7a745596f37cdbc55a6c0618aa0a72e3bf8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:51:40 -0700 Subject: [PATCH 095/458] feat(constants): the compute caps of gas detention 20,000,000 after a read of the block environment or the beneficiary, and 20,000,000 after a read of the Oracle, both relative to the compute at the read, as on Rex6. --- crates/mega-evm/src/constants.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index f7e0ca3d3..688281141 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -15,6 +15,8 @@ //! | [`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 block's default transaction limits | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the block's default data-size limit | +//! | [`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) | gas detention | +//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | gas detention | //! //! 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 @@ -64,6 +66,16 @@ 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; + #[cfg(test)] mod tests { use super::*; @@ -80,5 +92,7 @@ mod tests { assert_eq!(MAX_INITCODE_SIZE, 1_048_576); assert_eq!(TX_DATA_LIMIT, 13_107_200); assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); + assert_eq!(BLOCK_ENV_ACCESS_COMPUTE_GAS, 20_000_000); + assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, 20_000_000); } } From b5dbd5eee01c329b278cb7b16131e182547ce545 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:53:49 -0700 Subject: [PATCH 096/458] feat(access): gas detention MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A read of volatile data — the block environment, the block beneficiary's account, the Oracle's storage — sets a compute limit: the transaction's compute at the read plus the read's cap. The Host marks the read where it loads the value, and the opcode's wrapper commits it once the opcode completed. The cap is enforced through the frames' gas: every frame that runs keeps no more regular gas than the limit leaves the transaction, and the rest waits in its reservoir, where state and history charges still reach it. The opcode that read, a frame's start and every resume, and a storage write restored to its original value hold the running frame to the limit. A frame's return hands the withheld gas back on success, revert and halt alike. A frame that runs out of gas while gas was withheld from it crossed the cap: it stops the transaction with the revert-class stop (MegaLimitExceeded, kind compute), and the withheld gas goes back to the sender. Compute is the regular gas spent, less the state and history gas that spilled onto it and what a halt burns. While MegaAccessControl's switch is off for a frame, the Host refuses its volatile loads and the frame reverts with VolatileDataAccessDisabled, having paid the opcode's static gas and nothing more. The switch's state is here, with a test-utils helper that sets it; the interceptor steers it once the control contracts' semantics land. System-originated transactions, system calls and the neutral configuration are not detained. --- crates/mega-evm/src/access/detention.rs | 650 ++++++++++++++++++++++++ crates/mega-evm/src/access/mod.rs | 94 +++- crates/mega-evm/src/evm/context.rs | 50 +- crates/mega-evm/src/evm/execution.rs | 72 ++- crates/mega-evm/src/evm/host.rs | 191 +++++-- crates/mega-evm/src/evm/instructions.rs | 242 ++++++++- crates/mega-evm/src/system/control.rs | 15 +- 7 files changed, 1248 insertions(+), 66 deletions(-) create mode 100644 crates/mega-evm/src/access/detention.rs diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs new file mode 100644 index 000000000..46e345496 --- /dev/null +++ b/crates/mega-evm/src/access/detention.rs @@ -0,0 +1,650 @@ +//! The state of gas detention for the running transaction. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::cell::Cell; +use std::vec::Vec; + +use alloy_primitives::{Bytes, U256}; +use revm::interpreter::{Gas, InstructionResult}; + +use super::VolatileDataAccess; +use crate::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, + system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, +}; + +/// What detention keeps of one frame that runs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct DetainedFrame { + /// Regular gas withheld from the frame, which its reservoir holds until the frame returns. + withheld: u64, + /// Regular gas the frame's limit carries that its caller did not pay: a value call's stipend. + minted: u64, + /// The frame's own compute when it suspended on a child: its regular gas spent, less what + /// detention withheld. + 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 gas it forwarded to that child. + contribution: u64, +} + +/// Gas detention for the running transaction: which volatile data it read, the most compute it +/// may reach because of it, and what each frame had withheld to enforce that. +/// +/// 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 its limit less what it has left, less the state and history gas that spilled onto its +/// regular gas, which are not compute. The transaction's compute is its frames' compute: the +/// frame that runs, read off its [`Gas`], and every frame suspended on a child that runs, as it +/// stood when it suspended, less the gas it forwarded. A value call's stipend is gas nobody paid, +/// so a frame's stipend is taken off its compute; once the frame returns, its caller's regular gas +/// spent accounts for it the same way. So the figure follows the regular ledger of the +/// transaction's frames at every moment, before, during and after each child. +/// +/// The one part of the regular ledger that is not compute is what a halt burns: a frame that +/// halts consumes the gas it had left without running anything with it. That gas is taken off the +/// transaction's compute when the frame returns. A frame that ran out of gas has nothing left by +/// then, so what it had when the charge failed counts as spent. +/// +/// # 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. +#[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 and the + /// neutral configuration's are not. + detains: bool, + /// Whether the neutral configuration runs, which detains no transaction. + neutral: bool, + /// 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, + /// What the transaction read. + accessed: VolatileDataAccess, + /// The most compute the transaction may reach, once it read volatile data. + limit: Option, + /// The compute of the frames suspended on a child that runs. + suspended: u64, + /// The stipends of the frames that run or are suspended. + minted: u64, + /// The regular gas the frames that halted burned without running anything with it. + burned: u64, + /// One entry per frame that runs or is suspended, the running one last. + frames: Vec, +} + +impl Detention { + /// Clears the state for a new transaction, keeping its allocation. `detains` is whether the + /// transaction's reads are held to a cap. + pub(crate) fn reset(&mut self, detains: bool) { + self.observed.set(VolatileDataAccess::empty()); + self.refused.set(VolatileDataAccess::empty()); + self.detains = detains && !self.neutral; + self.refusing = false; + #[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.suspended = 0; + self.minted = 0; + self.burned = 0; + self.frames.clear(); + } + + /// Turns detention off for every transaction: the neutral configuration. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) const fn set_neutral(&mut self, neutral: bool) { + self.neutral = neutral; + self.detains &= !neutral; + } + + /// 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. + /// + /// 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() + } + + /// 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 frame at `depth` completed, whose gas is + /// `gas`: the transaction's limit becomes its compute now plus the reads' cap, unless it is + /// already lower, and the frame keeps no more regular gas than the limit leaves 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. + pub(crate) fn commit_reads( + &mut self, + observed: VolatileDataAccess, + gas: &mut Gas, + depth: usize, + forwarded: u64, + ) { + self.accessed |= observed; + let compute = self.compute(gas, depth).saturating_sub(forwarded); + let limit = compute.saturating_add(cap_of(observed)); + self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); + self.cap_frame(gas, depth, 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, or an EIP-7702 authority that is. 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 limit = cap_of(access); + self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); + } + + /// Holds the running frame at `depth` to the limit again, after an opcode that can hand it + /// regular gas back: a storage write restored to its original value refills the state and + /// history gas it spilled onto regular gas, which may have spilled before the limit was set. + #[inline] + pub(crate) fn recap(&mut self, gas: &mut Gas, depth: usize) { + if self.limit.is_some() { + let compute = self.compute(gas, depth); + self.cap_frame(gas, depth, compute); + } + } + + /* 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. `minted` is the stipend its limit carries, which is + /// read the first time only. + /// + /// A frame's first run adds its caller's compute to the transaction's, now that the gas the + /// caller forwarded is known; 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, and the switch is + /// read for it. + #[inline] + pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize, minted: u64) { + self.refusing = self.disabled_from.is_some_and(|from| depth >= from); + if !self.detains { + return; + } + if self.frames.len() == depth { + if let Some(caller) = depth.checked_sub(1).and_then(|i| self.frames.get_mut(i)) { + let forwarded = gas.limit().saturating_sub(minted); + caller.contribution = caller.at_suspension.saturating_sub(forwarded); + self.suspended = self.suspended.saturating_add(caller.contribution); + } + self.frames.push(DetainedFrame { minted, ..Default::default() }); + self.minted = self.minted.saturating_add(minted); + } 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"); + self.recap(gas, depth); + } + + /// 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) { + if !self.detains { + return; + } + if let Some(frame) = self.frames.get_mut(depth) { + frame.at_suspension = regular_spent(gas).saturating_sub(frame.withheld); + } + } + + /// The frame at `depth` returns `result` with `gas`: the gas withheld from it goes back into + /// its regular gas, and the switch turns back on if the frame, or a frame below it, turned it + /// off. When the frame halts, what the halt burns is not compute. + /// + /// Returns the limit, and the compute the transaction had spent, when the frame ran out of + /// gas while detention withheld some of it: the cap bound before the frame's own gas, and the + /// frame must stop the transaction rather than halt. + #[inline] + pub(crate) fn on_frame_end( + &mut self, + result: InstructionResult, + gas: &mut Gas, + depth: usize, + ) -> Option<(u64, u64)> { + if self.disabled_from.is_some_and(|from| from >= depth) { + self.disabled_from = None; + } + if !self.detains { + return None; + } + debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); + let withheld = self.frames.last().map_or(0, |frame| frame.withheld); + let stop = (withheld > 0 && runs_out_of_gas(result)) + .then(|| (self.limit.unwrap_or(u64::MAX), self.compute(gas, depth))); + if let Some(frame) = self.frames.pop() { + self.minted = self.minted.saturating_sub(frame.minted); + } + release(gas, withheld); + if stop.is_none() && result.is_halt() { + // The settlement rolls the spill back into regular gas and burns it all. + let burned = gas.remaining().saturating_add(gas.state_gas_spilled()); + self.burned = self.burned.saturating_add(burned); + } + stop + } + + /* 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. + pub fn disable_access(&mut self, depth: usize) { + if self.disabled_from.is_none_or(|from| depth < from) { + self.disabled_from = Some(depth); + } + self.refusing = self.disabled_from.is_some_and(|from| depth >= from); + } + + /// 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; + self.refusing = false; + 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 frame at `depth` runs with `gas`. + fn compute(&self, gas: &Gas, depth: usize) -> u64 { + let own = self.frames.get(depth).map_or(0, |frame| frame.withheld); + self.suspended + .saturating_add(regular_spent(gas)) + .saturating_sub(own) + .saturating_sub(self.minted) + .saturating_sub(self.burned) + } + + /// Withholds from the frame at `depth` the regular gas it has beyond what the limit leaves + /// the transaction, `compute` being the transaction's compute now. + /// + /// The gas moves into the frame's reservoir. A regular charge cannot draw on the reservoir, + /// so the frame cannot compute with it; a state or history charge draws on the reservoir + /// first, so the frame can still pay for what it writes and appends, which is not compute. + fn cap_frame(&mut self, gas: &mut Gas, depth: usize, compute: u64) { + let Some(limit) = self.limit else { return }; + let allowance = limit.saturating_sub(compute); + let excess = gas.remaining().saturating_sub(allowance); + if excess == 0 { + return; + } + let Some(frame) = self.frames.get_mut(depth) else { return }; + gas.set_remaining(gas.remaining() - excess); + gas.set_reservoir(gas.reservoir().saturating_add(excess)); + frame.withheld = frame.withheld.saturating_add(excess); + } +} + +/// 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 cap a read of `access` sets: the lowest of the caps of the kinds it holds. +fn cap_of(access: VolatileDataAccess) -> u64 { + let mut cap = u64::MAX; + if access.has_block_env_access() || access.has_beneficiary_balance_access() { + cap = cap.min(BLOCK_ENV_ACCESS_COMPUTE_GAS); + } + if access.has_oracle_access() { + cap = cap.min(ORACLE_ACCESS_COMPUTE_GAS); + } + cap +} + +/// The regular gas a frame spent: its limit, less what it has left, 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()) +} + +/// Whether `result` is running out of gas: a charge the frame could not pay. Running into the +/// memory limit is not, nor is a precompile's out-of-gas, which no frame that runs returns. +const fn runs_out_of_gas(result: InstructionResult) -> bool { + matches!( + result, + InstructionResult::OutOfGas | + InstructionResult::MemoryOOG | + InstructionResult::InvalidOperandOOG | + InstructionResult::ReentrancySentryOOG + ) +} + +/// Hands `withheld` back to the regular gas of the frame whose final gas is `gas`, as if it had +/// never been withheld. +/// +/// Withheld gas sits in the reservoir, where the frame's state and history charges may have drawn +/// on it. What is left of it goes back to regular gas; what was drawn is counted as having +/// spilled onto regular gas, which is where those charges would have come from had nothing been +/// withheld. The frame's result then settles exactly as it would have without detention: a +/// success or a revert gives the caller the unspent regular gas, a halt burns it, and the +/// reservoir returns to what the caller handed down. +#[inline] +pub(crate) fn release(gas: &mut Gas, withheld: u64) { + if withheld == 0 { + return; + } + let back = withheld.min(gas.reservoir()); + gas.set_reservoir(gas.reservoir() - back); + gas.set_remaining(gas.remaining().saturating_add(back)); + gas.add_state_gas_spilled(withheld - back); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 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); + detention + } + + /// The cap of a read is the lowest of the caps of the kinds it holds; both caps are the + /// same today, so every kind sets the same one. + #[test] + fn test_the_cap_of_a_read_is_its_kinds_lowest() { + assert_eq!(cap_of(VolatileDataAccess::TIMESTAMP), BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(cap_of(VolatileDataAccess::SLOT_NUM), BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(cap_of(VolatileDataAccess::BENEFICIARY_BALANCE), BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(cap_of(VolatileDataAccess::ORACLE), ORACLE_ACCESS_COMPUTE_GAS); + assert_eq!( + cap_of(VolatileDataAccess::ORACLE | VolatileDataAccess::TIMESTAMP), + BLOCK_ENV_ACCESS_COMPUTE_GAS.min(ORACLE_ACCESS_COMPUTE_GAS) + ); + assert_eq!(cap_of(VolatileDataAccess::empty()), u64::MAX); + } + + /// A read caps the frame at its compute then plus the cap: the regular gas beyond it moves + /// into the reservoir, and the frame returns it on release. + #[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, 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.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(frame.reservoir(), 7 + 100_000_000 - 1_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(detention.accessed(), VolatileDataAccess::TIMESTAMP); + + assert_eq!(detention.on_frame_end(InstructionResult::Stop, &mut frame, 0), None); + assert_eq!((frame.remaining(), frame.reservoir()), (100_000_000 - 1_000, 7)); + assert_eq!(frame.state_gas_spilled(), 0); + } + + /// 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, 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.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000); + } + + /// What a state charge drew from the withheld gas counts as spilled once released: that is + /// where it would have come from, and a revert gives it back to regular gas as a spill. + #[test] + fn test_release_counts_what_state_drew_as_spilled() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + let withheld = 100_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS; + assert!(frame.record_state_cost(withheld + 10)); + assert_eq!(frame.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 10); + + detention.on_frame_end(InstructionResult::Revert, &mut frame, 0); + assert_eq!(frame.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 10); + assert_eq!(frame.reservoir(), 0); + assert_eq!(frame.state_gas_spilled(), withheld + 10); + frame.rollback_state_gas(); + assert_eq!(frame.remaining(), 100_000_000, "a revert gives all of it back"); + } + + /// Out of gas with gas withheld is the cap binding; out of gas without is the frame's own. + #[test] + fn test_out_of_gas_is_the_cap_only_with_gas_withheld() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + frame.spend_all(); + let stop = detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0); + assert_eq!(stop, Some((BLOCK_ENV_ACCESS_COMPUTE_GAS, BLOCK_ENV_ACCESS_COMPUTE_GAS))); + + let mut detention = detaining(); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert_eq!(frame.remaining(), 1_000_000, "nothing to withhold"); + assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + + for result in [InstructionResult::MemoryLimitOOG, InstructionResult::InvalidFEOpcode] { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert_eq!(detention.on_frame_end(result, &mut frame, 0), None, "{result:?}"); + } + } + + /// 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(); + let mut caller = gas(100_000, 0); + detention.on_frame_run(&mut caller, 0, 0); + assert!(caller.record_regular_cost(9_000 + 60_000)); + detention.on_frame_suspend(&caller, 0); + + let mut child = gas(60_000 + 2_300, 0); + detention.on_frame_run(&mut child, 1, 2_300); + assert_eq!(detention.compute(&child, 1), 9_000 - 2_300); + assert!(child.record_regular_cost(4_000)); + assert_eq!(detention.compute(&child, 1), 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, 0); + assert_eq!(detention.compute(&caller, 0), 9_000 + 4_000 - 2_300); + assert_eq!((detention.suspended, detention.minted), (0, 0)); + } + + /// 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. + #[test] + fn test_what_a_halt_burns_is_not_compute() { + let mut detention = detaining(); + let mut caller = gas(1_000_000, 0); + detention.on_frame_run(&mut caller, 0, 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, 0); + assert!(child.record_regular_cost(1_000)); + assert!(child.record_state_cost(3_000)); + assert_eq!(detention.on_frame_end(InstructionResult::InvalidFEOpcode, &mut child, 1), None); + + // The caller's regular gas spent now holds everything it forwarded. + detention.on_frame_run(&mut caller, 0, 0); + assert_eq!(detention.compute(&caller, 0), 1_000); + assert_eq!(detention.burned, 500_000 - 1_000); + } + + /// 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, 0); + detention.on_frame_suspend(&frame, 0); + let mut child = gas(100_000, 0); + detention.on_frame_run(&mut child, 1, 0); + detention.disable_access(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::TIMESTAMP)); + assert_eq!(detention.take_refused(), Some(VolatileDataAccess::TIMESTAMP)); + + 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, 0); + assert!(!detention.is_refusing()); + + detention.disable_access(0); + assert!(detention.enable_access(0), "the frame that switched it off switches it on"); + assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); + } + + /// A transaction that is not detained records nothing and caps nothing. + #[test] + fn test_an_exempt_transaction_is_not_detained() { + let mut detention = Detention::default(); + detention.reset(false); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0, 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()); + } +} diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 2f7cf283b..37d51bd07 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -1,8 +1,96 @@ -//! 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. //! -//! [`VolatileDataAccess`] names the kinds of volatile data a transaction can read. The cap a read -//! sets arrives with gas detention. +//! `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`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) | +//! | 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, and an applied EIP-7702 authority that is | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) | +//! | the Oracle's storage | `SLOAD` in the Oracle's own frame | [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS) | +//! +//! `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: they are the +//! protocol maintaining its own state, the Oracle's included. +//! +//! # 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, and neither is what a halting +//! frame burns ([`Detention`]). 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. Every frame +//! that runs keeps no more regular gas than the limit leaves the transaction; the rest is +//! *withheld* — moved into the frame's reservoir — until the frame returns. Three points hold +//! this, and between them no frame can compute past the limit: +//! +//! - **the read**: the opcode that read volatile data withholds from its own frame, right after the +//! Host's load, 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 caps 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, so the frame is held to the limit again. +//! +//! A frame that runs out of regular gas while detention withheld some of it has crossed the cap, +//! not its own gas: detention holds the frame to less than it was given, so the charge that +//! failed was one the cap refused. The frame then stops the transaction the way every +//! transaction-level limit does — it reverts with `MegaLimitExceeded` (kind: compute), the +//! transaction is latched, no caller resumes, and the transaction settles like an EIP-8037 revert +//! (see [`AdditionalLimit`](crate::AdditionalLimit)). What the frame had left of its allowance when +//! the charge failed is spent; the withheld gas is not, and goes back to the sender. A frame +//! detention withheld nothing from runs out of its own gas, and halts: a child forwarded less +//! than the limit leaves the transaction halts on its own, and its caller resumes. +//! +//! State and history charges are not held back. They draw on the reservoir first, where the +//! withheld gas sits, so a detained frame pays for what it writes and appends as it would have. +//! +//! # Withheld gas does not leak +//! +//! Withheld gas is regular gas the frame was given and must neither be lost nor escape the cap. +//! A frame's end hands it back into the frame's regular gas before the result settles, as if it +//! had never been withheld ([`release`](detention::release)), on every path: +//! +//! - **a frame answered without running** — an interceptor's answer, the latch, the depth guard, an +//! inspector — never runs, so nothing is withheld from it; the answer carries the forwarded gas +//! back to its caller, and the caller is held to the limit when it resumes; +//! - **the transaction-level stop** returns the stopped frame's withheld gas with the revert, and +//! every caller's with its own, so the sender gets back what nobody spent; +//! - **the frame's return** releases on success, revert and halt alike: a success or a revert hands +//! the unspent gas to the caller, which is held to the limit as it resumes, and a halt burns it +//! as it would have burned it undetained. +//! +//! # 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 `SLOTNUM` +//! refusal names access type 12, which the contract's `VolatileDataAccessType` does not declare. +mod detention; mod volatile; +pub use detention::{volatile_data_access_disabled_revert_data, Detention}; pub use volatile::VolatileDataAccess; diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 5ab13d9e5..461fc89b5 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -19,8 +19,9 @@ use crate::{ schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, system::{self, MEGA_SYSTEM_ADDRESS}, - AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, + AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, Detention, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, + VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -38,15 +39,18 @@ 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`]) 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`]) and the SALT bucket multipliers that transaction has priced state +/// gas with ([`BucketMultipliers`]). #[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, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, @@ -81,6 +85,7 @@ impl MegaContext { cfg, external_envs, additional_limit: AdditionalLimit::default(), + detention: Detention::default(), block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), system_originated: false, @@ -105,6 +110,7 @@ impl MegaContext { #[cfg(any(test, feature = "test-utils"))] { self.neutral = false; + self.detention.set_neutral(false); } self } @@ -124,6 +130,7 @@ impl MegaContext { /// 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. + /// - No transaction is detained: a read of volatile data caps nothing. /// /// 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 @@ -134,6 +141,7 @@ impl MegaContext { self.cfg = cfg; self.neutral = true; self.prices_history = false; + self.detention.set_neutral(true); self } @@ -216,6 +224,25 @@ impl MegaContext { &mut self.additional_limit } + /// 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: the contract's interceptor steers the + /// switch once the control contracts' semantics land. + #[cfg(any(test, feature = "test-utils"))] + 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 /// its bucket in minimum buckets, never below one. /// @@ -284,6 +311,20 @@ impl MegaContext { // 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. + self.detention.reset(!self.system_originated); + 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); + } } /// Prepares the context for a system call. Every system-call entry point of @@ -295,6 +336,7 @@ impl MegaContext { self.on_new_tx(); self.system_originated = true; self.set_history_exempt(true); + self.detention.reset(false); } /// Records whether the running transaction is exempt from history gas, and installs the diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ee477d072..36fe2df97 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -46,11 +46,13 @@ use revm::{ }; use crate::{ - evm::{history::transaction_body_bytes, inspector::frame_end_checked}, + evm::{ + history::transaction_body_bytes, inspector::frame_end_checked, instructions::minted_gas, + }, history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, - write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, - MegaInstructions, + write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, + MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, }; /// The Satin handler. @@ -455,6 +457,9 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm bool { /// latter. Under a latch, the child that crossed the limit reverted, and its caller must not /// resume. Without one, the child was a failed creation whose nonce record put its creator over /// its budget, and the creator reverts alone. +/// +/// 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 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: &mut MegaContext, - frame: &EthFrame, + frame: &mut EthFrame, ) -> Option { + // The transaction's own frame is given what the transaction has left, stipend or not. + let minted = if frame.depth == 0 { + 0 + } else { + minted_gas(&frame.input, ctx.gas_params().call_stipend()) + }; + ctx.detention.on_frame_run(&mut frame.interpreter.gas, frame.depth, minted); let stop = ctx.additional_limit.stop_before_run()?; Some(InterpreterAction::new_return( InstructionResult::Revert, @@ -669,6 +688,40 @@ fn before_frame_run( )) } +/// 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 gets the regular gas +/// detention withheld from it back into its result. +/// +/// A frame that ran out of gas while detention withheld some of it crossed the compute limit +/// rather than its own gas: its halt becomes the transaction-level stop, a revert carrying +/// `MegaLimitExceeded` (kind: compute), and the transaction is latched, so no caller resumes. +/// The withheld gas goes back with the revert, to the caller and in the end to the sender. +#[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(); + let Some((limit, compute)) = + ctx.detention.on_frame_end(instruction_result, result.gas_mut(), frame.depth) + else { + return; + }; + let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, limit, compute); + let result = result.interpreter_result_mut(); + result.result = InstructionResult::Revert; + result.output = stop.revert_data(); + } + Err(_) => {} + } +} + /// 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. @@ -875,7 +928,14 @@ fn record_applied_authorities( let applied = authorities.len() as u64; let check = ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); - AppliedAuthorities { check, applied: if check.exceeded_limit() { 0 } else { applied } } + if check.exceeded_limit() { + return AppliedAuthorities { check, applied: 0 }; + } + // 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); + } + AppliedAuthorities { check, applied } } /// What [`record_applied_authorities`] found: the verdict of the limit check, and how many diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index c99fb59f2..a7258208a 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -15,6 +15,21 @@ //! `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. +//! //! # One hook prices every state charge //! //! [`state_gas_price`](revm::context_interface::Host::state_gas_price) is the one place an @@ -45,29 +60,23 @@ 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}, + primitives::{Address, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256}, state::{Account, EvmStorageSlot}, Database, Journal, }; -use crate::{ExternalEnvTypes, MegaContext, StagedRecord}; +use crate::{ + system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, 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; fn effective_gas_price(&self) -> U256; fn caller(&self) -> Address; @@ -75,28 +84,122 @@ impl revm::context_interface::Host 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 difficulty(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::DIFFICULTY) { + return Default::default(); + } + self.inner.difficulty() + } + + #[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, marking a read of the Oracle's storage. + #[inline] + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + let oracle = address == ORACLE_CONTRACT_ADDRESS; + if oracle && self.detention.refuses(VolatileDataAccess::ORACLE) { + return Err(LoadError::ColdLoadSkipped); + } + let load = self.inner.sload_skip_cold_load(address, key, skip_cold_load)?; + if oracle { + self.detention.observe(VolatileDataAccess::ORACLE); + } + Ok(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. @@ -143,6 +246,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) @@ -185,7 +291,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, @@ -193,7 +301,15 @@ 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, @@ -204,6 +320,19 @@ impl revm::context_interface::Host } } +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 + } +} + /// 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 @@ -316,7 +445,7 @@ impl JournalInspectTr for Journal { #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{address, keccak256}; + use alloy_primitives::{address, keccak256, Bytes}; use core::cell::Cell; use revm::{ context::JournalTr, diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 9cf750ad8..0336eacc0 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -31,6 +31,20 @@ //! 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 +//! caps the frame at 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. +//! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. //! @@ -42,15 +56,19 @@ use revm::{ bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE, + BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, CREATE, CREATE2, + DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, LOG0, LOG1, + LOG2, LOG3, LOG4, NUMBER, SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, + TIMESTAMP, }, + context_interface::Host, handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{contract, gas_table_spec, host}, + instructions::{block_info, contract, gas_table_spec, host}, interpreter::EthInterpreter, interpreter_types::LoopControl, - FrameInput, Instruction, InstructionContext, InstructionExecResult, InstructionResult, + FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, InterpreterAction, }, primitives::hardfork::SpecId, @@ -58,8 +76,8 @@ use revm::{ }; use crate::{ - history_gas, limit::HistoryBytes, write_record_history_gas, ExternalEnvTypes, LimitCheck, - MegaContext, + history_gas, limit::HistoryBytes, volatile_data_access_disabled_revert_data, + write_record_history_gas, ExternalEnvTypes, LimitCheck, MegaContext, VolatileDataAccess, }; use super::MegaInstructions; @@ -70,15 +88,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. 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); 11] = [ + let wrappers: [(u8, InstructionFn); 28] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -88,8 +107,25 @@ pub(crate) fn mega_instructions( (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::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -193,11 +229,21 @@ fn stop_frame( 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 capped again. + host.detention.recap(&mut interpreter.gas, interpreter.input.depth); + result } /// `LOG0`..`LOG4`, committing the log's bytes. @@ -207,11 +253,12 @@ fn 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 @@ -291,15 +338,25 @@ fn inherit_reservoir(interpreter: &mut Interpreter) { } } -/// `CALL` and `CALLCODE`, charging the caller for the records a value transfer writes. +/// `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. `DELEGATECALL` and `STATICCALL` carry no -/// value and write nothing, so they run revm's instruction unwrapped. +/// — the sender's and the recipient's — are one here. fn call( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - charge_frame_start(context, contract::call::) + 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 @@ -310,6 +367,159 @@ fn create( 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 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 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, + }; + let depth = interpreter.input.depth; + host.detention.commit_reads(observed, &mut interpreter.gas, depth, forwarded); + // A frame the opcode is about to start inherits the reservoir the cap moved gas into. + inherit_reservoir(interpreter); + 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 forwarded to the frame `input` starts: the frame's limit, +/// less a value call's stipend, which the caller does not pay. +fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { + match input { + FrameInput::Call(inputs) => { + inputs.gas_limit.saturating_sub(minted_gas(input, call_stipend)) + } + FrameInput::Create(inputs) => inputs.gas_limit(), + FrameInput::Empty => 0, + } +} + +/// The regular gas the frame `input` starts is given beyond what its caller paid: the stipend of +/// a call that transfers value. +pub(crate) fn minted_gas(input: &FrameInput, call_stipend: u64) -> u64 { + match input { + FrameInput::Call(inputs) if inputs.transfers_value() => call_stipend, + _ => 0, + } +} + +/// Defines an opcode that reads a block-environment field, as revm's instruction in +/// [`read_volatile`]. +macro_rules! block_env_read { + ($($name:ident => $inner:path, $opcode:literal;)*) => {$( + #[doc = concat!("`", $opcode, "`, committing the read of the field.")] + fn $name( + context: Ctx<'_, DB, ExtEnvs>, + ) -> InstructionExecResult { + read_volatile(context, $inner) + } + )*}; +} + +block_env_read! { + coinbase => block_info::coinbase, "COINBASE"; + timestamp => block_info::timestamp, "TIMESTAMP"; + number => block_info::block_number, "NUMBER"; + difficulty => block_info::difficulty, "PREVRANDAO"; + gaslimit => block_info::gaslimit, "GASLIMIT"; + basefee => block_info::basefee, "BASEFEE"; + blobbasefee => block_info::blob_basefee, "BLOBBASEFEE"; + slotnum => block_info::slot_num_enabled, "SLOTNUM"; + blockhash => host::blockhash, "BLOCKHASH"; +} + +/// Defines an opcode that loads an account or a slot, as revm's instruction in +/// [`read_volatile`]. +macro_rules! state_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) + } + )*}; +} + +state_read! { + 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"; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 21043b806..8eb2f8acc 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -45,12 +45,15 @@ pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = /// /// # 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. +/// The switch is gas detention's: [`Detention`](crate::Detention) holds it, the Host consults it +/// before every volatile load, and a refused read reverts its frame with +/// `VolatileDataAccessDisabled`. The interceptor does not steer it yet — that is the control +/// contracts' semantics, which land on their own. 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 switch holds +/// when no call steered it. `DisabledByParent()`, the answer to a frame that re-enables what a +/// frame above it disabled, is what [`Detention::enable_access`](crate::Detention::enable_access) +/// refuses. /// /// All three take no value: they read or steer execution, and the contract holds no balance. pub(crate) fn intercept( From 24cd72db4316f459fdb4cdc79e04ebf77a24c833 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:55:56 -0700 Subject: [PATCH 097/458] test(access): pin gas detention Every volatile read caps the transaction from where it read, below and above the execution cap: the stop spends exactly the limit and the intrinsic gas on the regular ledger, keeps no state and no log, and no caller resumes. Pins the relative cap, the most restrictive limit, a child's read capping its caller, a real out-of-gas that still halts, a failed load that caps nothing, a refused read that pays its static gas alone, the three paths withheld gas could leak through, and the state and history gas that are not compute; and, in a block, the stop's failed receipt and a fresh cap for every transaction. --- crates/mega-evm/tests/block/detention.rs | 81 ++ crates/mega-evm/tests/block/main.rs | 1 + crates/mega-evm/tests/satin/detention.rs | 1064 ++++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 4 files changed, 1147 insertions(+) create mode 100644 crates/mega-evm/tests/block/detention.rs create mode 100644 crates/mega-evm/tests/satin/detention.rs diff --git a/crates/mega-evm/tests/block/detention.rs b/crates/mega-evm/tests/block/detention.rs new file mode 100644 index 000000000..b1dbd70e9 --- /dev/null +++ b/crates/mega-evm/tests/block/detention.rs @@ -0,0 +1,81 @@ +//! 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, unlimited_ctx, 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; + let mut executor = executor_with_env(&mut state, unlimited_ctx(), env); + 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/main.rs b/crates/mega-evm/tests/block/main.rs index 9263eb4f1..691936f39 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -5,6 +5,7 @@ mod common; mod counters; mod deploy; mod deposits; +mod detention; mod eips; mod factory; mod inspector; diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs new file mode 100644 index 000000000..93b8be7f3 --- /dev/null +++ b/crates/mega-evm/tests/satin/detention.rs @@ -0,0 +1,1064 @@ +//! 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 exactly its limit +//! and its intrinsic gas on the regular ledger: the allowance it had left when the charge failed +//! is spent, and the gas detention withheld is not. +//! +//! 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}, + 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, LimitCheck, LimitKind, MegaContext, MegaEvm, + MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, VolatileDataAccess, +}; +use revm::{ + bytecode::opcode::*, + context::{result::ExecutionResult, BlockEnv, TxEnv}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000d00000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000d00001"); +const CHILD: Address = address!("0000000000000000000000000000000000d00002"); +const DELEGATOR: Address = address!("0000000000000000000000000000000000d00003"); +const BENEFICIARY: Address = address!("0000000000000000000000000000000000bef000"); + +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]; + +/// Rounds of [`work`] spent before a read: 5,283,600 of compute. +const WORK: u32 = 1_700; + +/// The compute one round of [`work`] spends once its memory is expanded. +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. +fn copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(0x8000_u16).append_many([PUSH0, PUSH0, MCOPY]) +} + +fn block() -> BlockEnv { + BlockEnv { + number: U256::from(300), + beneficiary: BENEFICIARY, + timestamp: U256::from(1_700_000_000), + gas_limit: 10_000_000_000, + prevrandao: Some(B256::repeat_byte(7)), + slot_num: 9, + ..Default::default() + } +} + +fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +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. +struct Run { + outcome: MegaTransactionOutcome, + limit: Option, + accessed: VolatileDataAccess, +} + +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() } +} + +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. +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. +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. +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. +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. +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`. +fn stop_data(limit: u64) -> Bytes { + MegaLimitExceeded { kind: LimitKind::ComputeGas.as_u8(), limit }.abi_encode().into() +} + +/// Asserts the transaction was stopped by detention, having spent exactly its limit. +fn assert_stopped(run: &Run, intrinsic: 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:?}"), + } + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false + }) + ); + assert_eq!( + run.outcome.gas.regular, + intrinsic + limit, + "the transaction computed up to 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 +} + +/* ---------- 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, and the kind it +/// records. +struct Read { + name: &'static str, + code: Append, + db: fn(MemoryDatabase) -> MemoryDatabase, + access: VolatileDataAccess, +} + +fn no_setup(db: MemoryDatabase) -> MemoryDatabase { + db +} + +fn op(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { + code.append(opcode).append(POP) +} + +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, + }, + Read { + name: "TIMESTAMP", + code: |c| op(c, TIMESTAMP), + db: no_setup, + access: VolatileDataAccess::TIMESTAMP, + }, + Read { + name: "COINBASE", + code: |c| op(c, COINBASE), + db: no_setup, + access: VolatileDataAccess::COINBASE, + }, + Read { + name: "PREVRANDAO", + code: |c| op(c, DIFFICULTY), + db: no_setup, + access: VolatileDataAccess::PREV_RANDAO, + }, + Read { + name: "GASLIMIT", + code: |c| op(c, GASLIMIT), + db: no_setup, + access: VolatileDataAccess::GAS_LIMIT, + }, + Read { + name: "BASEFEE", + code: |c| op(c, BASEFEE), + db: no_setup, + access: VolatileDataAccess::BASE_FEE, + }, + Read { + name: "BLOBBASEFEE", + code: |c| op(c, BLOBBASEFEE), + db: no_setup, + access: VolatileDataAccess::BLOB_BASE_FEE, + }, + Read { + name: "SLOTNUM", + code: |c| op(c, SLOTNUM), + db: no_setup, + access: VolatileDataAccess::SLOT_NUM, + }, + Read { + name: "BLOCKHASH", + code: |c| c.push_number(299_u16).append(BLOCKHASH).append(POP), + db: no_setup, + access: VolatileDataAccess::BLOCK_NUMBER | VolatileDataAccess::BLOCK_HASH, + }, + Read { + name: "BALANCE", + code: |c| on_beneficiary(c, BALANCE), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + Read { + name: "EXTCODESIZE", + code: |c| on_beneficiary(c, EXTCODESIZE), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + Read { + name: "EXTCODEHASH", + code: |c| on_beneficiary(c, EXTCODEHASH), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + 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, + }, + Read { + name: "CALL", + code: |c| call(c, CALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + Read { + name: "CALLCODE", + code: |c| call(c, CALLCODE, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + Read { + name: "DELEGATECALL", + code: |c| call(c, DELEGATECALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + Read { + name: "STATICCALL", + code: |c| call(c, STATICCALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + }, + 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, + }, + 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, + }, + 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, + }, + ] +} + +/// Gives `address` the `0xef0100 || to` designator an applied EIP-7702 authorization leaves. +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 more compute than the cap, then reads, then computes forever, and it stops having spent +/// exactly its compute at the read plus the cap. +#[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)); + let limit = assert_stopped(&run, intrinsic); + 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); + } + } +} + +/// The cap is relative: a transaction that spent more than the cap before it read may still +/// spend the cap after. +#[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 limit = assert_stopped(&run, intrinsic(gas_limit)); + assert!(limit - CAP > u64::from(before) * WORK_ROUND, "{limit}"); + assert!(limit - CAP > CAP); + } +} + +/// 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, recipient or applied EIP-7702 authority is the beneficiary is +/// detained from its first instruction: its limit is the cap. +#[test] +fn test_a_transaction_touching_the_beneficiary_is_detained_from_the_start() { + use revm::{ + context::transaction::TransactionType, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let spinner = spin(BytecodeBuilder::default()); + + // The sender. + let db = MemoryDatabase::default().account_code(CONTRACT, spinner.clone()); + let run_sender = execute(db, tx(BENEFICIARY, CONTRACT, gas_limit)); + // A sender's intrinsic gas is the same whoever it is. + assert_eq!(assert_stopped(&run_sender, intrinsic), CAP, "the sender"); + + // The recipient. + let db = MemoryDatabase::default().account_code(BENEFICIARY, spinner.clone()); + let run_recipient = execute(db, tx(CALLER, BENEFICIARY, gas_limit)); + assert_eq!(assert_stopped(&run_recipient, intrinsic), CAP, "the recipient"); + + // An applied authority. + let authorization = Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: CHILD, nonce: 0 }, + RecoveredAuthority::Valid(BENEFICIARY), + )); + let authorizing = 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() + })); + let db = MemoryDatabase::default().account_code(CONTRACT, spinner); + let run_authority = execute(db, authorizing); + assert_eq!(run_authority.limit, Some(CAP), "the authority"); + assert!(matches!(run_authority.outcome.result, ExecutionResult::Revert { .. })); + assert_eq!(run_authority.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + } +} + +/// 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()); +} + +/* ---------- 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)); + let limit = assert_stopped(&run, intrinsic); + assert!(limit < CAP + 100_000, "the first read set the limit: {limit}"); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE); + } + } +} + +/// 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 code = + burn(op(BytecodeBuilder::default(), TIMESTAMP), u32::try_from(rounds).unwrap() + 1) + .stop() + .build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert_stopped(&run, intrinsic(gas_limit)); + } +} + +/* ---------- 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)); + let limit = assert_stopped(&run, intrinsic); + assert!(limit < CAP + 100_000, "the child read near the start: {limit}"); + } +} + +/// When a child crosses the cap, no caller resumes: the caller's code after the call — a write +/// and a log — never runs, and every frame returns the stop. +#[test] +fn test_no_caller_resumes_after_the_stop() { + 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 limit = assert_stopped(&run, intrinsic); + 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 did not resume"); + } +} + +/// 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)); + assert_stopped(&run, intrinsic(*gas_limit)); + 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()); + } +} + +/* ---------- 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 new account, 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(); + // 9,000 for the transfer and 25,000 for the new account do not fit in 30,000. + let child = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(BENEFICIARY) + .append_many([PUSH0, CALL, STOP]) + .build(); + for (callee, gas) in [(ORACLE_CONTRACT_ADDRESS, 2_000_u32), (CHILD, 30_000)] { + 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}"); + } + } +} + +/* ---------- refused reads ---------- */ + +/// Records every call's result and the gas it spent, and every opcode that ran. +#[derive(Default)] +struct Calls { + calls: Vec, + opcodes: Vec, +} + +struct CallRecord { + target: Address, + result: InstructionResult, + output: Bytes, + spent: u64, +} + +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()); + } + + 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(), + }); + } +} + +/// 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_NUMBER, + ), + ( + "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(), + 3 + 2 + 2 + 3 + 100, + 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 of a `SLOTNUM` names access type 12, one past the contract's enum; the others name +/// their enum variant. +#[test] +fn test_the_refusal_names_the_access_type() { + use mega_evm::system::{IMegaAccessControl, VolatileDataAccessType}; + assert_eq!( + volatile_data_access_disabled_revert_data(VolatileDataAccess::ORACLE), + Bytes::from( + IMegaAccessControl::VolatileDataAccessDisabled { + accessType: VolatileDataAccessType::Oracle + } + .abi_encode() + ) + ); + let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); + assert_eq!(&slot_num[..4], IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR.as_slice()); + assert_eq!(U256::from_be_slice(&slot_num[4..]), U256::from(12)); +} + +/// 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, and what it hears from `remainingComputeGas()` is no more +/// than the limit leaves it. +#[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), + ); + assert_stopped(&run, intrinsic); + + // The answer, read without the loop. + 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(32_u8) + .push_number(0_u8) + .append(RETURN) + .build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + let answer = U256::from_be_slice(run.outcome.result.output().unwrap()); + assert!(answer < U256::from(CAP), "the call was forwarded from the capped frame: {answer}"); + } +} + +/// 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 writes more state gas than the cap and still completes. +#[test] +fn test_state_and_history_gas_are_not_compute() { + // 300 fresh slots: 29,376,000 of state gas and 1,056,000 of history, 6,630,000 of compute. + let mut code = op(BytecodeBuilder::default(), TIMESTAMP); + for slot in 1..=300_u64 { + code = code.sstore(U256::from(slot), U256::from(1)); + } + let code = code.stop().build(); + 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); + assert!(run.outcome.gas.state > CAP, "{}", run.outcome.gas.state); + assert!(run.outcome.gas.regular < CAP); + } +} + +/// 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 limit = assert_stopped(&run, intrinsic(gas_limit)); + // Two pushes and a fresh slot's 22,100 of regular gas, a hundred times, then TIMESTAMP. + assert_eq!(limit - CAP, 100 * (3 + 3 + 22_100) + 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), + ); + assert_stopped(&run, intrinsic(BELOW)); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6f0879839..3b38900ea 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -6,6 +6,7 @@ mod contract_size; mod data_size; mod data_size_counts; mod db_error; +mod detention; mod equivalence; mod history_bytes; mod history_exemption; From 7a00afc4bb76b674111d8c71929fa2539739d4c9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 13:59:33 -0700 Subject: [PATCH 098/458] fix(access): a frame whose writes spent the withheld gas runs out of its own gas Undetained, a frame that runs out of gas would have had min(withheld, reservoir) more regular gas. Only while that is above zero can the cap be what the failed charge crossed; once the frame's state and history charges drew the reservoir dry, it ran out where it would have without detention, and it halts. --- crates/mega-evm/src/access/detention.rs | 22 ++++++++++++++++--- crates/mega-evm/src/access/mod.rs | 10 +++++---- crates/mega-evm/src/evm/execution.rs | 8 +++---- crates/mega-evm/tests/satin/detention.rs | 27 ++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 46e345496..b54315f71 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -297,8 +297,14 @@ impl Detention { /// off. When the frame halts, what the halt burns is not compute. /// /// Returns the limit, and the compute the transaction had spent, when the frame ran out of - /// gas while detention withheld some of it: the cap bound before the frame's own gas, and the - /// frame must stop the transaction rather than halt. + /// gas while detention still held back some of what it withheld: the cap bound before the + /// frame's own gas, and the frame must stop the transaction rather than halt. + /// + /// Without detention the frame would have had `min(withheld, reservoir)` more regular gas when + /// it ran out ([`release`]). While that is above zero the charge that failed may have been one + /// the cap refused, and the cap is the tighter of the two bounds, so it is the one reported. + /// Once the frame's state and history charges have drawn the reservoir dry, the withheld gas + /// is spent and the frame ran out exactly where it would have undetained: its own gas. #[inline] pub(crate) fn on_frame_end( &mut self, @@ -314,7 +320,8 @@ impl Detention { } debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); let withheld = self.frames.last().map_or(0, |frame| frame.withheld); - let stop = (withheld > 0 && runs_out_of_gas(result)) + let held_back = withheld.min(gas.reservoir()); + let stop = (held_back > 0 && runs_out_of_gas(result)) .then(|| (self.limit.unwrap_or(u64::MAX), self.compute(gas, depth))); if let Some(frame) = self.frames.pop() { self.minted = self.minted.saturating_sub(frame.minted); @@ -551,6 +558,15 @@ mod tests { assert_eq!(frame.remaining(), 1_000_000, "nothing to withhold"); assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + // Withheld gas the frame's writes drew dry is spent: the frame ran out of its own gas. + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(frame.record_state_cost(frame.reservoir())); + frame.spend_all(); + assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + for result in [InstructionResult::MemoryLimitOOG, InstructionResult::InvalidFEOpcode] { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 37d51bd07..324943933 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -52,15 +52,17 @@ //! - **a storage write restored to its original value**: it refills state and history gas that //! spilled onto regular gas, possibly before the read, so the frame is held to the limit again. //! -//! A frame that runs out of regular gas while detention withheld some of it has crossed the cap, -//! not its own gas: detention holds the frame to less than it was given, so the charge that -//! failed was one the cap refused. The frame then stops the transaction the way every +//! A frame that runs out of regular gas while detention still holds back some of what it withheld +//! has crossed the cap, not its own gas: undetained, the frame would have had that gas to charge +//! against, so the cap is the tighter bound. The frame then stops the transaction the way every //! transaction-level limit does — it reverts with `MegaLimitExceeded` (kind: compute), the //! transaction is latched, no caller resumes, and the transaction settles like an EIP-8037 revert //! (see [`AdditionalLimit`](crate::AdditionalLimit)). What the frame had left of its allowance when //! the charge failed is spent; the withheld gas is not, and goes back to the sender. A frame //! detention withheld nothing from runs out of its own gas, and halts: a child forwarded less -//! than the limit leaves the transaction halts on its own, and its caller resumes. +//! than the limit leaves the transaction halts on its own, and its caller resumes. So does a frame +//! whose state and history charges drew the withheld gas dry: it ran out where it would have +//! undetained. //! //! State and history charges are not held back. They draw on the reservoir first, where the //! withheld gas sits, so a detained frame pays for what it writes and appends as it would have. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 36fe2df97..069b213af 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -692,10 +692,10 @@ fn before_frame_run( /// for the child's start to add to the transaction's; a frame that returns gets the regular gas /// detention withheld from it back into its result. /// -/// A frame that ran out of gas while detention withheld some of it crossed the compute limit -/// rather than its own gas: its halt becomes the transaction-level stop, a revert carrying -/// `MegaLimitExceeded` (kind: compute), and the transaction is latched, so no caller resumes. -/// The withheld gas goes back with the revert, to the caller and in the end to the sender. +/// A frame that ran out of gas while detention still held back some of what it withheld crossed +/// the compute limit rather than its own gas: its halt becomes the transaction-level stop, a revert +/// carrying `MegaLimitExceeded` (kind: compute), and the transaction is latched, so no caller +/// resumes. The withheld gas goes back with the revert, to the caller and in the end to the sender. #[inline] fn after_frame_run( ctx: &mut MegaContext, diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 93b8be7f3..d90380f56 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -680,6 +680,33 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { } } +/// 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, a thousand fresh slots — 22,100,000 of compute — +/// cross it and stop the transaction. Without that room 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 mut code = op(BytecodeBuilder::default(), TIMESTAMP); + for slot in 1..=1_000_u64 { + code = code.sstore(U256::from(slot), U256::from(1)); + } + let code = code.stop().build(); + + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + tx(CALLER, CONTRACT, ABOVE), + ); + assert_stopped(&run, intrinsic(ABOVE)); + + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, BELOW), + ); + 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(), BELOW, "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: From a26116861a95276099bcd181f7230b2002908aa2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:04:42 -0700 Subject: [PATCH 099/458] test(access): port the parked rows detention owns 77 rows: the kinds a read records and the ones that record nothing, the limit a first read sets, detention starting afresh for every transaction, reads down the call stack and in a reverted frame, the Oracle's storage read directly, through a static call and not through a delegate call, a hint, the system address's exemption, the beneficiary's own frame, and the refusals that follow what the Host loads while stack underflows and database failures keep their own outcome. Five emptied pending files deleted. --- crates/mega-evm/tests/_pending/README.md | 44 +- .../mini_rex/access_beneficiary_balance.rs | 410 ------------ .../mini_rex/block_env_access_tracking.rs | 271 -------- .../_pending/mini_rex/block_env_gas_limit.rs | 474 -------------- .../_pending/mini_rex/compute_gas_limit.rs | 257 -------- .../tests/_pending/mini_rex/oracle.rs | 285 --------- crates/mega-evm/tests/_pending/rex/oracle.rs | 141 ----- .../tests/_pending/rex3/oracle_gas_limit.rs | 237 ------- .../tests/_pending/rex3/system_address.rs | 164 ----- .../tests/_pending/rex4/access_control.rs | 107 ---- .../_pending/rex4/beneficiary_detention.rs | 421 ------------- .../tests/_pending/rex4/gas_detention.rs | 84 --- .../_pending/rex5/selfdestruct_beneficiary.rs | 102 --- .../_pending/rex6/beneficiary_detention.rs | 509 --------------- .../tests/_pending/src/limit/compute_gas.rs | 28 - crates/mega-evm/tests/satin/detention.rs | 92 +-- crates/mega-evm/tests/satin/main.rs | 1 + .../mega-evm/tests/satin/volatile_access.rs | 596 ++++++++++++++++++ 18 files changed, 675 insertions(+), 3548 deletions(-) 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/compute_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex/oracle.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/system_address.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/compute_gas.rs create mode 100644 crates/mega-evm/tests/satin/volatile_access.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4a9f150da..c2f4f48ae 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 | -| detention | 77 | 76 | 1 | 69 | 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 | 34 | 22 | 12 | 30 | 4 | 0 | @@ -37,7 +36,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** | **379** | **357** | **22** | **228** | **123** | **28** | +| **Total** | **302** | **281** | **21** | **159** | **115** | **28** | ## Tests ported in place @@ -260,12 +259,26 @@ These 47 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by detention -These 4 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. +These 81 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, 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/access_beneficiary_balance.rs` | detention (9) | 9 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `mini_rex/block_env_access_tracking.rs` | detention (3) | 3 | `tests/satin/volatile_access.rs` | +| `mini_rex/block_env_gas_limit.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `mini_rex/compute_gas_limit.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `mini_rex/oracle.rs` | detention (5) | 5 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex/oracle.rs` | detention (3) | 3 | `tests/satin/volatile_access.rs` | +| `rex3/oracle_gas_limit.rs` | detention (7) | 7 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex3/system_address.rs` | detention (2) | 2 | `tests/satin/volatile_access.rs` | +| `rex4/access_control.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex4/beneficiary_detention.rs` | detention (12) | 12 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex4/gas_detention.rs` | detention (3) | 3 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex5/selfdestruct_beneficiary.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex6/beneficiary_detention.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `src/access/volatile.rs` | detention (4) | 4 | `crates/mega-evm/src/access/volatile.rs` | -| **Total** | | **4** | | +| `src/limit/compute_gas.rs` | detention (1) | 1 | `tests/satin/detention.rs` | +| **Total** | | **81** | | ## Tests retired after the inventory @@ -321,24 +334,20 @@ 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` | 7 | keep 7 (the pre-block system calls) | | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | -| `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` | 2 | rewrite 2 (detention · D48) | +| `mini_rex/access_beneficiary_balance.rs` | 1 | rewrite 1 (revert-class aborts · D48) | +| `mini_rex/block_env_gas_limit.rs` | 3 | rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `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` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | +| `mini_rex/oracle.rs` | 7 | rewrite 3 (revert-class aborts · D48); keep 4 (the oracle and control contracts) | | `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` | 10 | 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` | 36 | 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) | | `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) | +| `rex3/oracle_gas_limit.rs` | 1 | rewrite 1 (revert-class aborts · D48) | +| `rex4/access_control.rs` | 46 | keep 46 (the oracle and control contracts) | +| `rex4/beneficiary_detention.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | | `rex4/frame_limits.rs` | 10 | 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/gas_detention.rs` | 2 | rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 4 | undecided 3 (the state-growth and KV limits · D46); 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)) | @@ -354,8 +363,8 @@ Each cell lists `disposition count (mechanism · decision)`. | `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` | 6 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention) | -| `rex6/beneficiary_detention.rs` | 14 | keep 13 (detention · D08); rewrite 1 (the state-growth and KV limits · D45) | +| `rex5/selfdestruct_beneficiary.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)) | +| `rex6/beneficiary_detention.rs` | 1 | 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) | @@ -363,7 +372,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `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/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | | `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | 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 index cc3ee8854..6d6250f1c 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs @@ -87,416 +87,6 @@ fn assert_beneficiary_detection( } } -/// 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. 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 index fbb69594b..5ddbd3ab9 100644 --- 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 @@ -82,372 +82,6 @@ fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool ) } -#[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 @@ -503,68 +137,6 @@ fn test_nested_call_block_env_access_child_oog() { ); } -#[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 @@ -626,52 +198,6 @@ fn test_parent_block_env_access_oog_after_nested_call() { ); } -#[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 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 9f004d9c0..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs +++ /dev/null @@ -1,257 +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, - } -} - -// ============================================================================ -// TRANSACTION RESET TESTS -// ============================================================================ - -/// 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 - ); -} - -// ============================================================================ -// EDGE CASE TESTS -// ============================================================================ - -#[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/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs index 50cdba332..4b4005c2c 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -139,106 +139,6 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { ); } -/// 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() { @@ -461,122 +361,6 @@ fn test_oracle_sload_determinism_between_oracle_env_and_state() { 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 @@ -676,72 +460,3 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { ); } -/// 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/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/rex3/oracle_gas_limit.rs b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs index 327f491c8..f0f7c3d3d 100644 --- a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs @@ -89,58 +89,6 @@ fn build_oracle_sload_code() -> Bytes { // 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] @@ -175,192 +123,7 @@ fn test_rex3_oracle_access_still_enforces_20m_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 index 976f8ab06..d683d9635 100644 --- a/crates/mega-evm/tests/_pending/rex4/access_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/access_control.rs @@ -430,32 +430,6 @@ fn test_nested_call_volatile_access_reverts() { // 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 // ============================================================================ @@ -1131,87 +1105,6 @@ fn test_inspector_sees_system_contract_call() { // 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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs index 5944b95e9..727792b2f 100644 --- a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs @@ -202,187 +202,26 @@ fn append_callcode(builder: BytecodeBuilder, target: Address, gas: u64) -> Bytec // 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 // ============================================================================ @@ -391,38 +230,6 @@ fn test_caller_is_beneficiary_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 // ============================================================================ @@ -431,184 +238,18 @@ fn test_recipient_is_beneficiary_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 // ============================================================================ @@ -685,65 +326,3 @@ fn test_detention_plus_intrinsic_data_size_overflow() { // 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/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs index 463179592..5da01d617 100644 --- a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs @@ -104,32 +104,6 @@ fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool // 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] @@ -154,36 +128,6 @@ fn test_rex4_volatile_access_post_access_cap_enforced() { ); } -/// 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 @@ -237,31 +181,3 @@ fn test_rex4_non_binding_detention_reports_normal_compute_limit() { ); } -/// 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/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index 8d8114ff4..132185c26 100644 --- a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -213,108 +213,6 @@ fn append_call_and_return_child_data( .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 // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs index 888ad161c..26fd31117 100644 --- a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs @@ -159,180 +159,10 @@ fn decode_volatile_data_access_disabled( // 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 // ============================================================================ @@ -364,349 +194,10 @@ fn test_rex6_selfdestruct_to_empty_target_still_records_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: 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/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/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index d90380f56..b83d549a0 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -28,33 +28,33 @@ use revm::{ Database, Inspector, }; -const CALLER: Address = address!("0000000000000000000000000000000000d00000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000d00001"); -const CHILD: Address = address!("0000000000000000000000000000000000d00002"); -const DELEGATOR: Address = address!("0000000000000000000000000000000000d00003"); -const BENEFICIARY: Address = address!("0000000000000000000000000000000000bef000"); +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"); -const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; +pub(crate) const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; /// Below the execution cap: no reservoir. -const BELOW: u64 = 100_000_000; +pub(crate) 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]; +pub(crate) const ABOVE: u64 = TX_GAS_LIMIT_CAP + 100_000_000; +pub(crate) const TIERS: [u64; 2] = [BELOW, ABOVE]; /// Rounds of [`work`] spent before a read: 5,283,600 of compute. -const WORK: u32 = 1_700; +pub(crate) const WORK: u32 = 1_700; /// The compute one round of [`work`] spends once its memory is expanded. -const WORK_ROUND: u64 = 3_108; +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. -fn copy(code: BytecodeBuilder) -> BytecodeBuilder { +pub(crate) fn copy(code: BytecodeBuilder) -> BytecodeBuilder { code.push_number(0x8000_u16).append_many([PUSH0, PUSH0, MCOPY]) } -fn block() -> BlockEnv { +pub(crate) fn block() -> BlockEnv { BlockEnv { number: U256::from(300), beneficiary: BENEFICIARY, @@ -66,22 +66,22 @@ fn block() -> BlockEnv { } } -fn context(db: DB) -> MegaContext { +pub(crate) fn context(db: DB) -> MegaContext { MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) } -fn tx(caller: Address, to: Address, gas_limit: u64) -> MegaTransaction { +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. -struct Run { - outcome: MegaTransactionOutcome, - limit: Option, - accessed: VolatileDataAccess, +pub(crate) struct Run { + pub(crate) outcome: MegaTransactionOutcome, + pub(crate) limit: Option, + pub(crate) accessed: VolatileDataAccess, } -fn run_on(evm: &mut MegaEvm, tx: MegaTransaction) -> Run +pub(crate) fn run_on(evm: &mut MegaEvm, tx: MegaTransaction) -> Run where INSP: Inspector, EthInterpreter>, { @@ -90,26 +90,26 @@ where Run { outcome, limit: detention.compute_limit(), accessed: detention.accessed() } } -fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { +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. -fn intrinsic(gas_limit: u64) -> u64 { +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. -fn spin(code: BytecodeBuilder) -> Bytes { +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. -fn work(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { +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)) @@ -120,7 +120,7 @@ fn work(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { } /// Appends `rounds` rounds of a counting loop, twenty-six gas a round. -fn burn(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { +pub(crate) fn burn(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { let code = code.push_number(rounds); let dest = code.len() as u32; code.append(JUMPDEST) @@ -131,19 +131,19 @@ fn burn(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { } /// Appends a call of `scheme` to `to` forwarding all gas, dropping its status. -fn call(code: BytecodeBuilder, scheme: u8, to: Address) -> BytecodeBuilder { +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`. -fn stop_data(limit: u64) -> Bytes { +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 spent exactly its limit. -fn assert_stopped(run: &Run, intrinsic: u64) -> u64 { +pub(crate) fn assert_stopped(run: &Run, intrinsic: 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)), @@ -186,11 +186,11 @@ fn no_setup(db: MemoryDatabase) -> MemoryDatabase { db } -fn op(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { +pub(crate) fn op(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { code.append(opcode).append(POP) } -fn on_beneficiary(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { +pub(crate) fn on_beneficiary(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { code.push_address(BENEFICIARY).append(opcode).append(POP) } @@ -339,7 +339,11 @@ fn reads() -> Vec { } /// Gives `address` the `0xef0100 || to` designator an applied EIP-7702 authorization leaves. -fn with_delegation(mut db: MemoryDatabase, address: Address, to: Address) -> MemoryDatabase { +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(); @@ -375,7 +379,7 @@ fn test_every_volatile_read_caps_the_transaction_from_where_it_read() { } /// The cap is relative: a transaction that spent more than the cap before it read may still -/// spend the cap after. +/// 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; @@ -388,6 +392,14 @@ fn test_the_cap_counts_from_a_spend_larger_than_itself() { let limit = assert_stopped(&run, intrinsic(gas_limit)); 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"); } } @@ -761,16 +773,16 @@ fn test_a_failed_load_caps_nothing() { /// Records every call's result and the gas it spent, and every opcode that ran. #[derive(Default)] -struct Calls { - calls: Vec, - opcodes: Vec, +pub(crate) struct Calls { + pub(crate) calls: Vec, + pub(crate) opcodes: Vec, } -struct CallRecord { - target: Address, - result: InstructionResult, - output: Bytes, - spent: u64, +pub(crate) struct CallRecord { + pub(crate) target: Address, + pub(crate) result: InstructionResult, + pub(crate) output: Bytes, + pub(crate) spent: u64, } impl Inspector, EthInterpreter> for Calls { diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 3b38900ea..61409ae98 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -29,4 +29,5 @@ mod static_callee; mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; +mod volatile_access; mod write_records; 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..fa9669842 --- /dev/null +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -0,0 +1,596 @@ +//! 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; +use mega_evm::{ + constants::ORACLE_ACCESS_COMPUTE_GAS, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{op_transaction, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, + VolatileDataAccess, +}; +use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult, state::Bytecode}; + +use crate::detention::{ + assert_stopped, call, context, execute, intrinsic, on_beneficiary, op, run_on, spin, tx, + with_delegation, work, Calls, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, DELEGATOR, + TIERS, +}; + +/// 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 ---------- */ + +/// Every block-environment opcode records its own kind; the transaction's and the chain's own +/// fields, and a contract's own balance, record nothing. +#[test] +fn test_the_block_environment_opcodes_record_their_kind_and_nothing_else_does() { + let reads: [(u8, VolatileDataAccess); 9] = [ + (NUMBER, VolatileDataAccess::BLOCK_NUMBER), + (TIMESTAMP, VolatileDataAccess::TIMESTAMP), + (COINBASE, VolatileDataAccess::COINBASE), + (DIFFICULTY, VolatileDataAccess::PREV_RANDAO), + (GASLIMIT, VolatileDataAccess::GAS_LIMIT), + (BASEFEE, VolatileDataAccess::BASE_FEE), + (BLOBBASEFEE, VolatileDataAccess::BLOB_BASE_FEE), + (SLOTNUM, VolatileDataAccess::SLOT_NUM), + (PUSH0, VolatileDataAccess::empty()), + ]; + for (opcode, access) in reads { + 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, access, "{opcode:#04x}"); + assert_eq!(run.accessed.count_block_env_accessed(), usize::from(!access.is_empty())); + } + 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}"); + } +} + +/// A transaction that reads several kinds records all of them, and the first read's limit, the +/// lowest, is the one that holds. +#[test] +fn test_several_reads_record_every_kind_and_the_first_limit_holds() { + for gas_limit in TIERS { + let code = op(BytecodeBuilder::default(), NUMBER); + let code = op(work(code, 300), TIMESTAMP); + let code = op(work(code, 300), BASEFEE); + let code = work(code, 300).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.accessed, + VolatileDataAccess::BLOCK_NUMBER | + VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::BASE_FEE + ); + assert_eq!(run.accessed.count_block_env_accessed(), 3); + assert_eq!(run.limit, Some(2 + CAP), "NUMBER, the first read, set the limit"); + } +} + +/// 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); +} + +/// A read that stays within the cap costs what it ran: the gas detention withheld goes back +/// when the transaction ends, below and above the execution cap. +#[test] +fn test_a_read_within_the_cap_bills_what_ran() { + for gas_limit in TIERS { + for opcode in [TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE] { + // The read, a word stored, a short loop, and the word returned. + let code = BytecodeBuilder::default().append(opcode).push_number(0_u8).append(MSTORE); + let code = work(code, 10).push_number(32_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(), "{opcode:#04x}"); + assert!(run.limit.is_some(), "{opcode:#04x}"); + let used = run.outcome.result.gas().tx_gas_used(); + assert!(used < 100_000, "{opcode:#04x}: {used}, not the gas it was given"); + } + let code = BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).stop().build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success()); + assert!(run.outcome.result.gas().tx_gas_used() < 100_000); + } +} + +/* ---------- 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), + ); + let limit = assert_stopped(&run, intrinsic(gas_limit)); + 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); + } +} + +/// A caller that already read keeps its own limit through a child that reads again. +#[test] +fn test_a_childs_second_read_leaves_the_callers_limit() { + let child = op(BytecodeBuilder::default(), NUMBER).stop().build(); + let parent = work(op(BytecodeBuilder::default(), TIMESTAMP), 300); + let parent = call(parent, CALL, CHILD).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()); + assert_eq!(run.limit, Some(2 + CAP), "TIMESTAMP, the caller's first opcode, set it"); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOCK_NUMBER); + } +} + +/// 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)); + let limit = assert_stopped(&run, intrinsic(gas_limit)); + 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::no_limits().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, 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()) + }; + + let run = execute(db(), tx(CALLER, ORACLE_CONTRACT_ADDRESS, gas_limit)); + assert_eq!( + assert_stopped(&run, intrinsic), + 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_stopped(&run, intrinsic); + 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()); + + 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_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!( + matches!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "{:?}", + run.outcome.result + ); +} + +/* ---------- 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), + ); + assert_eq!(assert_stopped(&run, intrinsic(gas_limit)), 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 (2,600), POP and GAS. + assert_eq!(consumed, U256::from(17 + 2_600 + 2 + 2)); +} From 27c579a3453ea7850551729fd7dfeac0f8cdee8b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:06:33 -0700 Subject: [PATCH 100/458] test(satin): the neutral configuration detains nothing A program reading the block environment and the beneficiary records no read and sets no compute limit under the neutral configuration, and still matches Ethereum. --- crates/mega-evm/tests/satin/neutral.rs | 38 ++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index 05d859a71..ff41ef0a7 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -21,14 +21,17 @@ use mega_evm::{ neutral_cfg, neutralize_evm, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, - EthSpecId, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + EthSpecId, 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, CALL, EXTCODESIZE, GAS, LOG1, LOG3, POP, PUSH0, PUSH1, SSTORE}, + bytecode::opcode::{ + ADDRESS, BALANCE, CALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, PUSH1, SSTORE, + TIMESTAMP, + }, context::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, @@ -284,6 +287,37 @@ fn test_neutral_programs_match_ethereum() { } } +/// The neutral configuration detains nothing: 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_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] From 6c4abd4065d5f1db72a00d284dc06adf911c0878 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:08:35 -0700 Subject: [PATCH 101/458] bench(access): volatile reads and plain storage reads volatile_reads: 200 rounds of TIMESTAMP, NUMBER and the beneficiary's BALANCE, then 200 Oracle SLOADs in a call, checked before measurement to mark every kind and detain. storage_reads: 200 SLOADs nothing volatile holds, the read wrapper's cost on the hottest opcode it wraps. --- crates/mega-evm/benches/transact.rs | 77 ++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index a236f7f18..cf9665cae 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -17,6 +17,12 @@ //! 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. +//! - `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. //! - `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 @@ -44,17 +50,19 @@ use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + system::{ + IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, + }, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, - MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + MegaSpecId, TestExternalEnvs, VolatileDataAccess, LOG_BASE_SIZE, LOG_TOPIC_SIZE, + MIN_BUCKET_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, + ADDRESS, BALANCE, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, + MSTORE, NUMBER, POP, PUSH0, PUSH1, SLOAD, SSTORE, STATICCALL, STOP, SUB, SWAP1, TIMESTAMP, }, context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, inspector::NoOpInspector, @@ -71,6 +79,11 @@ const SALT_CALLER: Address = address!("0x000000000000000000000000000000000010000 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"); + +/// 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; @@ -140,6 +153,35 @@ 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() +} + +/// 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 { @@ -269,6 +311,9 @@ fn bench_transact(c: &mut Criterion) { .account_code(INTERCEPTED, system_caller_code(IS_DISABLED)) .account_code(MISSING, system_caller_code(UNKNOWN_SELECTOR)) .account_code(LIMITED, limited_code()) + .account_code(READER, reader_code()) + .account_code(VOLATILE, volatile_code()) + .account_code(ORACLE_CONTRACT_ADDRESS, reader_code()) .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); let cfg = mega_context(db.clone()).cfg().clone(); @@ -283,13 +328,31 @@ fn bench_transact(c: &mut Criterion) { ("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)), + ("storage_reads", call_tx(READER, Bytes::new(), 30_000_000)), + ("volatile_reads", call_tx(VOLATILE, 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())).execute_transaction(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); + // Only the volatile workload reads what detention caps, and it must read every kind it is + // here to measure. + let detention = evm.ctx().detention(); + 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; From 320eaa82d66f6441c557f0739ae19c1727f3a6e4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:10:25 -0700 Subject: [PATCH 102/458] docs(access): describe gas detention MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md gains a Gas detention section — what is volatile, where a read is marked, the cap, withheld gas as the enforcement point, the stop, the three leakage paths and refused reads — the module table rows it fills, and a contract of the common layer: a per-frame gas adjustment is released where the frame ends. The crate README and the limit module say where detention lives and how it stops a transaction. --- AGENTS.md | 65 +++++++++++++++++++++++++------- crates/mega-evm/README.md | 13 ++++++- crates/mega-evm/src/limit/mod.rs | 5 +++ 3 files changed, 67 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 430a43bf6..adfa13d0b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,17 +99,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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas and data-size block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the write-record block limit | -| `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/` | 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 latch, the transaction body and deployed code 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) | 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `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 (detention's hooks included), 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, the volatile-read marks and refusals and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas and data-size block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`), the write-record block limit | +| `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/` | 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 latch, the transaction body and deployed code 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) | the state-growth and KV limits | +| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit, the gas withheld per frame and its release, the compute figure across frames, and the volatile-access switch with its refusals (`detention.rs`) | the control contracts steering the switch | +| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (steering the detention switch, the 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, detention caps) | 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -122,7 +122,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `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, the block-hash read the Host records and the state-gas price the Host scales. +- `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. @@ -149,6 +149,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (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 162,306 gas, and keeping its record costs its 3,520 history on top. +- 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 20,000,000 (see Gas detention below). + Crossing the cap stops the transaction through the latch, with `MegaLimitExceeded` of kind compute. - `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`. A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. @@ -159,11 +161,42 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. 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 the control contracts' compute-ledger semantics 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. + `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until the control contracts' semantics fill them in — steering detention's switch and answering with the compute ledger — 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 and limit-check protocol describe mechanisms that do not exist here; the contracts below replace them. +- The legacy engine's limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. + Its gas leakage pitfalls apply to one mechanism here, detention, which adjusts a frame's gas; how it handles them is below. 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 and an applied EIP-7702 authority that is; 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, a system call and the neutral configuration are not detained. +- **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 spent, read off `Gas`: state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. + A read sets a limit — the transaction's compute at the read plus `BLOCK_ENV_ACCESS_COMPUTE_GAS` or `ORACLE_ACCESS_COMPUTE_GAS`, 20,000,000 each — and the limit only goes down, so the most restrictive read binds. + The transaction's compute is the running frame's regular gas spent plus every suspended caller's, less the gas each forwarded, less value-call stipends: the regular ledger at every moment. +- **The enforcement point: withheld gas.** + The interpreter stops a frame on one condition only, running out of regular gas, so every frame that runs keeps no more regular gas than the limit leaves the transaction; the rest moves into its reservoir, where state and history charges still reach it and regular charges cannot. + The frame is held to the limit at the read (the wrapper), at its start and at every resume (`before_frame_run`), and after an `SSTORE` that restored a slot and so refilled regular gas. + At the frame's end (`after_frame_run`, before revm settles the result) the withheld gas is released: what is left of it goes back to regular gas and what state and history drew from it counts as spilled, which maps the result onto exactly what it would have been undetained. +- **The stop.** + A frame that runs out of gas while detention still holds back some of what it withheld (withheld gas left in its reservoir) crossed the cap, not its own gas: the result becomes the latch's revert, `MegaLimitExceeded(2, limit)`, and the withheld gas goes back to the sender with it. + A frame detention withheld nothing from, or whose writes drew the withheld gas dry, ran out of its own gas and halts. +- **The three leakage paths.** + A frame answered without running (an interceptor, the latch, the depth guard, an inspector) has nothing withheld and hands its forwarded gas back, and the caller is held to the limit as it resumes. + The transaction-level stop releases every frame's withheld gas on the way up, so the sender gets back what nobody spent. + A frame's return releases on success, revert and halt alike: a halt burns the released gas as it would have burned it undetained. +- **Refused reads.** + `MegaAccessControl` can switch volatile-data access off for a frame and every frame below it (the state is `Detention`'s; the interceptor steers it once the control contracts' semantics land, and `MegaContext::with_volatile_access_disabled_from` is the test helper). + 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; `SLOTNUM` names access type 12, which the contract's enum does not declare. + ### Contracts of the common execution layer Every later mechanism plugs into these; a change to one comes back to this layer. @@ -176,6 +209,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. - **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. @@ -194,6 +228,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. 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. +- **A per-frame gas adjustment is released where the frame ends.** + Detention withholds regular gas into a frame's reservoir; `after_frame_run` releases it on every path, before revm settles the result, and a frame that never ran has nothing to release. + A later mechanism that adjusts a frame's gas settles it at the same point, and a result an opcode already built (a limit's stop) holds the frame's gas as it stood, so nothing is withheld after it. - **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.** diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 51f111c91..97a0e460a 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -64,7 +64,7 @@ The six system contracts live at their fixed `0x6342…` addresses and are deplo 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, 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 the control contracts' compute-ledger semantics fill them in. +`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 the control contracts' semantics fill them in: steering gas detention's switch, and answering with the compute ledger. 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. @@ -86,7 +86,16 @@ The allowance is not gas: it never enters the frame's `Gas`, only a log's charge 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 byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, and a body counts its five fixed write records even when fewer fee accounts are written. -The state-growth and KV limits, gas detention and keyless deployment arrive in later changes. +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 Host marks the read where it loads the value, and the most restrictive read binds. +Every frame keeps no more regular gas than the limit leaves the transaction; the rest waits in its reservoir, where state and history charges still reach it, and goes back into the frame's regular gas when the frame returns. +A frame that runs out of gas while gas is still withheld from it crossed the cap: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, and the sender gets back everything withheld. +A frame that runs out of its own gas still halts. +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 protocol's own transactions, the system calls and the execution-spec gate's neutral configuration are not detained. + +The state-growth and KV limits and keyless deployment arrive in later changes. ## Quick start diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 919db8c7b..24b293da9 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -5,6 +5,11 @@ //! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension (the data-size limit, //! detention, the state-growth and KV limits) fill these in. //! +//! 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. It stops a transaction through the same latch ([`AdditionalLimit::latch`]), with the +//! compute the transaction may reach as the limit. +//! //! 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. From 1c048bb615bb366d796730af086797facc22fb75 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:12:05 -0700 Subject: [PATCH 103/458] style(test): drop the blank line four parked files ended with after the port --- crates/mega-evm/tests/_pending/mini_rex/oracle.rs | 1 - crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs | 1 - crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs | 1 - crates/mega-evm/tests/_pending/rex4/gas_detention.rs | 1 - 4 files changed, 4 deletions(-) diff --git a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs index 4b4005c2c..b71b162d6 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -459,4 +459,3 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { gas_used ); } - diff --git a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs index f0f7c3d3d..c9c6e66a5 100644 --- a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs @@ -126,4 +126,3 @@ fn test_rex3_oracle_access_still_enforces_20m_limit() { // ============================================================================= // Rex3: Additional oracle SLOAD detention tests // ============================================================================= - diff --git a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs index 727792b2f..827ee74a4 100644 --- a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs @@ -325,4 +325,3 @@ fn test_detention_plus_intrinsic_data_size_overflow() { // TEST 12: Detention + execution data limit — detained compute gas does not // interfere with data size enforcement // ============================================================================ - diff --git a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs index 5da01d617..49bfec00e 100644 --- a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs @@ -180,4 +180,3 @@ fn test_rex4_non_binding_detention_reports_normal_compute_limit() { "Should resolve as normal compute-limit failure, not volatile-data OOG" ); } - From c200aa51556cb756bb67a0acba5f66036231758d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:31:23 -0700 Subject: [PATCH 104/458] docs(satin): say where the state gas a frame's caller holds is kept --- crates/mega-evm/src/evm/execution.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 523cc7f79..09cccedd8 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -414,8 +414,9 @@ impl EvmTr for MegaEvm Date: Wed, 23 Sep 2026 14:49:23 -0700 Subject: [PATCH 105/458] refactor(access): drop the detention state no execution reads set_neutral no longer recomputes detains, which every transaction's reset recomputes; the switch's disable and enable no longer set the running frame's refusal, which the frame reads when it resumes after the call that steered the switch; disable keeps the shallower depth through min; the block number's bit is written without a shift. The Host delegates difficulty again: since the merge DIFFICULTY reads the randomness, which is what is marked. --- crates/mega-evm/src/access/detention.rs | 19 ++++++++++++------- crates/mega-evm/src/access/volatile.rs | 2 +- crates/mega-evm/src/evm/host.rs | 10 ++-------- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index b54315f71..47392fe0d 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -112,11 +112,11 @@ impl Detention { self.frames.clear(); } - /// Turns detention off for every transaction: the neutral configuration. + /// Turns detention off for every transaction from the next one on: the neutral + /// configuration. #[cfg(any(test, feature = "test-utils"))] pub(crate) const fn set_neutral(&mut self, neutral: bool) { self.neutral = neutral; - self.detains &= !neutral; } /// Starts every transaction with volatile-data access switched off from `depth` down, as if @@ -339,11 +339,10 @@ impl Detention { /// 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) { - if self.disabled_from.is_none_or(|from| depth < from) { - self.disabled_from = Some(depth); - } - self.refusing = self.disabled_from.is_some_and(|from| depth >= from); + self.disabled_from = Some(self.disabled_from.map_or(depth, |from| from.min(depth))); } /// Switches volatile-data access back on for the frame at `depth`, and reports whether it @@ -353,7 +352,6 @@ impl Detention { Some(from) if depth > from => false, _ => { self.disabled_from = None; - self.refusing = false; true } } @@ -630,7 +628,11 @@ mod tests { detention.on_frame_suspend(&frame, 0); let mut child = gas(100_000, 0); detention.on_frame_run(&mut child, 1, 0); + 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, 0); assert!(detention.is_refusing()); assert!(!detention.is_access_disabled(0)); assert!(detention.is_access_disabled(1) && detention.is_access_disabled(2)); @@ -646,7 +648,10 @@ mod tests { assert!(!detention.is_refusing()); detention.disable_access(0); + detention.on_frame_run(&mut frame, 0, 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, 0); assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); } diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs index 7cb1d34b5..372eb2389 100644 --- a/crates/mega-evm/src/access/volatile.rs +++ b/crates/mega-evm/src/access/volatile.rs @@ -15,7 +15,7 @@ pub struct VolatileDataAccess(u16); impl VolatileDataAccess { /// The block number (`NUMBER`, and the `BLOCKHASH` that compares against it). - pub const BLOCK_NUMBER: Self = Self(1 << 0); + pub const BLOCK_NUMBER: Self = Self(1); /// The block timestamp (`TIMESTAMP`). pub const TIMESTAMP: Self = Self(1 << 1); /// The block beneficiary's address (`COINBASE`). diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index a7258208a..f13cf3764 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -78,6 +78,8 @@ impl revm::context_interface::Host delegate! { to self.inner { 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; @@ -113,14 +115,6 @@ impl revm::context_interface::Host self.inner.gas_limit() } - #[inline] - fn difficulty(&self) -> U256 { - if !self.read_block_env(VolatileDataAccess::DIFFICULTY) { - return Default::default(); - } - self.inner.difficulty() - } - #[inline] fn prevrandao(&self) -> Option { if !self.read_block_env(VolatileDataAccess::PREV_RANDAO) { From 4139e55953b41b41808e9bbf980af5e0adf22235 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 14:49:23 -0700 Subject: [PATCH 106/458] test(access): pin the values reads answer with, stipends, and an inspector's own reads Every block-environment read answers with the block's field. A value call's stipend is not compute, and a transaction carrying value gives its own frame none. A tracer reading the timestamp through the Host neither detains the transaction nor has its reads refused as the transaction's. A user's transaction is detained and a system transaction is not. --- crates/mega-evm/tests/satin/detention.rs | 143 +++++++++++++++++- .../mega-evm/tests/satin/volatile_access.rs | 2 + 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index b83d549a0..4ff7e570e 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -22,6 +22,7 @@ use mega_evm::{ use revm::{ bytecode::opcode::*, context::{result::ExecutionResult, BlockEnv, TxEnv}, + context_interface::block::BlobExcessGasAndPrice, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult, Interpreter, }, @@ -60,7 +61,12 @@ pub(crate) fn block() -> BlockEnv { 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() } @@ -79,6 +85,7 @@ 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 @@ -87,7 +94,12 @@ where { 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() } + Run { + outcome, + limit: detention.compute_limit(), + accessed: detention.accessed(), + detains: detention.detains(), + } } pub(crate) fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { @@ -505,6 +517,61 @@ fn test_blobhash_is_not_volatile() { 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 @@ -575,6 +642,48 @@ 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 exactly the limit, 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, POP, 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)); + assert_stopped(&run, intrinsic(gas_limit)); + + 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)); + assert_eq!(limit, CAP + 2, "TIMESTAMP was the first opcode"); + } +} + +/// 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 @@ -769,6 +878,38 @@ fn test_a_failed_load_caps_nothing() { } } +/// 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, and every opcode that ran. diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index fa9669842..fcfe78350 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -360,11 +360,13 @@ fn test_the_system_address_is_not_detained() { }); 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, From 3b5783aa590c9b069b01e15ece63e5cd54b70991 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:24:45 -0700 Subject: [PATCH 107/458] test(satin): read history prices off the engine where tests wrote them out --- crates/mega-evm/tests/block/counters.rs | 6 ++++- crates/mega-evm/tests/block/rules.rs | 27 ++++++++++++------- crates/mega-evm/tests/satin/intrinsic.rs | 10 ++++--- crates/mega-evm/tests/satin/strategic_stop.rs | 10 +++---- .../tests/satin/synthetic_frame_gas.rs | 8 +++--- crates/mega-evm/tests/satin/write_records.rs | 15 ++++++++++- 6 files changed, 51 insertions(+), 25 deletions(-) diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index f8fb57cb7..21ad511bb 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -197,9 +197,13 @@ fn test_the_state_and_history_ledgers_refuse_nothing() { 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, - bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, + 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"); diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index 98aba7f75..b0567977c 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -173,22 +173,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 what the transaction has to pay under the Satin gas table — its intrinsic charge and - // its body's history — and below the footprint the scalar yields, so the block's gas limit - // still fits the transaction's gas. - const GAS_LIMIT: u64 = 2_200_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"); diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index a1c2e3149..468610bc3 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -47,12 +47,14 @@ const EMPTY_CALL: u64 = 15_000; /// 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. +/// 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. -const fn body_history(bytes: u64) -> u64 { - (TX_BODY_SIZE + bytes) * HISTORY_PER_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. diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index e28359ad9..90fcc1b03 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -89,14 +89,14 @@ fn run( } /// The history gas an empty transaction body costs, which every transaction here pays before its -/// first frame and keeps whatever that frame does. -const fn body_history() -> u64 { - mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE +/// 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. -const fn create_body_history(init_code_len: u64) -> u64 { - (mega_evm::TX_BODY_SIZE + init_code_len) * mega_evm::constants::COST_PER_HISTORY_BYTE +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") } /// A transaction limit that leaves `execution_bytes` above the body. diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 90c65bcd3..4e3a9c0f8 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -47,9 +47,9 @@ 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. -const fn body_history(calldata_len: u64) -> u64 { - (mega_evm::TX_BODY_SIZE + calldata_len) * mega_evm::constants::COST_PER_HISTORY_BYTE +/// 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 { @@ -466,7 +466,7 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { // else, and the refusal is answered before a frame runs, so what the dispatched call spends // 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_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE; + 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); diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 662bcb904..8a6d91c18 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -127,10 +127,23 @@ fn test_failed_child_discards_its_transfer_records() { } /// 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)); From 47252bec31869543818a5424e6f00afd9f390304 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:31:57 -0700 Subject: [PATCH 108/458] refactor(access): take a caller's contribution off its child's whole gas limit The child's limit carries a value call's stipend, so subtracting the limit takes the stipend off the caller's contribution; tracking the stipend beside it subtracted it twice and added it back once. Only the read a call makes itself still needs the stipend split out of the gas it forwards. --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 81 +++++++++++-------------- crates/mega-evm/src/evm/execution.rs | 12 +--- crates/mega-evm/src/evm/instructions.rs | 18 ++---- 4 files changed, 43 insertions(+), 70 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index adfa13d0b..d100a940e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -181,7 +181,7 @@ Detention caps how much a transaction may still compute once it read such data ( - **The cap.** Compute is the regular gas spent, read off `Gas`: state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. A read sets a limit — the transaction's compute at the read plus `BLOCK_ENV_ACCESS_COMPUTE_GAS` or `ORACLE_ACCESS_COMPUTE_GAS`, 20,000,000 each — and the limit only goes down, so the most restrictive read binds. - The transaction's compute is the running frame's regular gas spent plus every suspended caller's, less the gas each forwarded, less value-call stipends: the regular ledger at every moment. + 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: the regular ledger at every moment. - **The enforcement point: withheld gas.** The interpreter stops a frame on one condition only, running out of regular gas, so every frame that runs keeps no more regular gas than the limit leaves the transaction; the rest moves into its reservoir, where state and history charges still reach it and regular charges cannot. The frame is held to the limit at the read (the wrapper), at its start and at every resume (`before_frame_run`), and after an `SSTORE` that restored a slot and so refilled regular gas. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 47392fe0d..8d821a7b8 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -19,13 +19,11 @@ use crate::{ struct DetainedFrame { /// Regular gas withheld from the frame, which its reservoir holds until the frame returns. withheld: u64, - /// Regular gas the frame's limit carries that its caller did not pay: a value call's stipend. - minted: u64, /// The frame's own compute when it suspended on a child: its regular gas spent, less what /// detention withheld. 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 gas it forwarded to that child. + /// [`at_suspension`](Self::at_suspension) less the child's gas limit. contribution: u64, } @@ -40,10 +38,10 @@ struct DetainedFrame { /// is its limit less what it has left, less the state and history gas that spilled onto its /// regular gas, which are not compute. The transaction's compute is its frames' compute: the /// frame that runs, read off its [`Gas`], and every frame suspended on a child that runs, as it -/// stood when it suspended, less the gas it forwarded. A value call's stipend is gas nobody paid, -/// so a frame's stipend is taken off its compute; once the frame returns, its caller's regular gas -/// spent accounts for it the same way. So the figure follows the regular ledger of the -/// transaction's frames at every moment, before, during and after each child. +/// 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. /// /// The one part of the regular ledger that is not compute is what a halt burns: a frame that /// halts consumes the gas it had left without running anything with it. That gas is taken off the @@ -80,8 +78,6 @@ pub struct Detention { limit: Option, /// The compute of the frames suspended on a child that runs. suspended: u64, - /// The stipends of the frames that run or are suspended. - minted: u64, /// The regular gas the frames that halted burned without running anything with it. burned: u64, /// One entry per frame that runs or is suspended, the running one last. @@ -107,7 +103,6 @@ impl Detention { self.accessed = VolatileDataAccess::empty(); self.limit = None; self.suspended = 0; - self.minted = 0; self.burned = 0; self.frames.clear(); } @@ -251,27 +246,24 @@ impl Detention { /* 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. `minted` is the stipend its limit carries, which is - /// read the first time only. + /// after a child returned into it. /// - /// A frame's first run adds its caller's compute to the transaction's, now that the gas the - /// caller forwarded is known; 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, and the switch is - /// read for it. + /// 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, what an interceptor charged it, 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, and the switch is read for it. #[inline] - pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize, minted: u64) { + pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) { self.refusing = self.disabled_from.is_some_and(|from| depth >= from); if !self.detains { return; } if self.frames.len() == depth { if let Some(caller) = depth.checked_sub(1).and_then(|i| self.frames.get_mut(i)) { - let forwarded = gas.limit().saturating_sub(minted); - caller.contribution = caller.at_suspension.saturating_sub(forwarded); + caller.contribution = caller.at_suspension.saturating_sub(gas.limit()); self.suspended = self.suspended.saturating_add(caller.contribution); } - self.frames.push(DetainedFrame { minted, ..Default::default() }); - self.minted = self.minted.saturating_add(minted); + 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; @@ -323,9 +315,7 @@ impl Detention { let held_back = withheld.min(gas.reservoir()); let stop = (held_back > 0 && runs_out_of_gas(result)) .then(|| (self.limit.unwrap_or(u64::MAX), self.compute(gas, depth))); - if let Some(frame) = self.frames.pop() { - self.minted = self.minted.saturating_sub(frame.minted); - } + self.frames.pop(); release(gas, withheld); if stop.is_none() && result.is_halt() { // The settlement rolls the spill back into regular gas and burns it all. @@ -370,7 +360,6 @@ impl Detention { self.suspended .saturating_add(regular_spent(gas)) .saturating_sub(own) - .saturating_sub(self.minted) .saturating_sub(self.burned) } @@ -491,7 +480,7 @@ mod tests { 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, 0); + detention.on_frame_run(&mut frame, 0); assert!(frame.record_regular_cost(1_000)); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); @@ -510,7 +499,7 @@ mod tests { 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, 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); @@ -524,7 +513,7 @@ mod tests { fn test_release_counts_what_state_drew_as_spilled() { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); let withheld = 100_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS; assert!(frame.record_state_cost(withheld + 10)); @@ -543,7 +532,7 @@ mod tests { fn test_out_of_gas_is_the_cap_only_with_gas_withheld() { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); frame.spend_all(); let stop = detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0); @@ -551,7 +540,7 @@ mod tests { let mut detention = detaining(); let mut frame = gas(1_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); assert_eq!(frame.remaining(), 1_000_000, "nothing to withhold"); assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); @@ -559,7 +548,7 @@ mod tests { // Withheld gas the frame's writes drew dry is spent: the frame ran out of its own gas. let mut detention = detaining(); let mut frame = gas(100_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); assert!(frame.record_state_cost(frame.reservoir())); frame.spend_all(); @@ -568,7 +557,7 @@ mod tests { for result in [InstructionResult::MemoryLimitOOG, InstructionResult::InvalidFEOpcode] { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); assert_eq!(detention.on_frame_end(result, &mut frame, 0), None, "{result:?}"); } @@ -580,21 +569,21 @@ mod tests { fn test_compute_spans_frames() { let mut detention = detaining(); let mut caller = gas(100_000, 0); - detention.on_frame_run(&mut caller, 0, 0); + detention.on_frame_run(&mut caller, 0); assert!(caller.record_regular_cost(9_000 + 60_000)); detention.on_frame_suspend(&caller, 0); let mut child = gas(60_000 + 2_300, 0); - detention.on_frame_run(&mut child, 1, 2_300); + detention.on_frame_run(&mut child, 1); assert_eq!(detention.compute(&child, 1), 9_000 - 2_300); assert!(child.record_regular_cost(4_000)); assert_eq!(detention.compute(&child, 1), 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, 0); + detention.on_frame_run(&mut caller, 0); assert_eq!(detention.compute(&caller, 0), 9_000 + 4_000 - 2_300); - assert_eq!((detention.suspended, detention.minted), (0, 0)); + assert_eq!(detention.suspended, 0); } /// What a halting child burns is not compute: its caller's compute after it returns is what @@ -603,17 +592,17 @@ mod tests { fn test_what_a_halt_burns_is_not_compute() { let mut detention = detaining(); let mut caller = gas(1_000_000, 0); - detention.on_frame_run(&mut caller, 0, 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, 0); + detention.on_frame_run(&mut child, 1); assert!(child.record_regular_cost(1_000)); assert!(child.record_state_cost(3_000)); assert_eq!(detention.on_frame_end(InstructionResult::InvalidFEOpcode, &mut child, 1), None); // The caller's regular gas spent now holds everything it forwarded. - detention.on_frame_run(&mut caller, 0, 0); + detention.on_frame_run(&mut caller, 0); assert_eq!(detention.compute(&caller, 0), 1_000); assert_eq!(detention.burned, 500_000 - 1_000); } @@ -624,15 +613,15 @@ mod tests { 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, 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, 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, 0); + 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)); @@ -644,14 +633,14 @@ mod tests { 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, 0); + detention.on_frame_run(&mut frame, 0); assert!(!detention.is_refusing()); detention.disable_access(0); - detention.on_frame_run(&mut frame, 0, 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, 0); + detention.on_frame_run(&mut frame, 0); assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); } @@ -661,7 +650,7 @@ mod tests { let mut detention = Detention::default(); detention.reset(false); let mut frame = gas(100_000_000, 0); - detention.on_frame_run(&mut frame, 0, 0); + detention.on_frame_run(&mut frame, 0); detention.observe(VolatileDataAccess::TIMESTAMP); assert!(!detention.has_reads()); detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 069b213af..69a4aafac 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -46,9 +46,7 @@ use revm::{ }; use crate::{ - evm::{ - history::transaction_body_bytes, inspector::frame_end_checked, instructions::minted_gas, - }, + evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, @@ -673,13 +671,7 @@ fn before_frame_run( ctx: &mut MegaContext, frame: &mut EthFrame, ) -> Option { - // The transaction's own frame is given what the transaction has left, stipend or not. - let minted = if frame.depth == 0 { - 0 - } else { - minted_gas(&frame.input, ctx.gas_params().call_stipend()) - }; - ctx.detention.on_frame_run(&mut frame.interpreter.gas, frame.depth, minted); + 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, diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 0336eacc0..b8a2e42f3 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -452,27 +452,19 @@ fn refuse( result } -/// The regular gas the running frame forwarded to the frame `input` starts: the frame's limit, -/// less a value call's stipend, which the caller does not pay. +/// 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) => { - inputs.gas_limit.saturating_sub(minted_gas(input, call_stipend)) + 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, } } -/// The regular gas the frame `input` starts is given beyond what its caller paid: the stipend of -/// a call that transfers value. -pub(crate) fn minted_gas(input: &FrameInput, call_stipend: u64) -> u64 { - match input { - FrameInput::Call(inputs) if inputs.transfers_value() => call_stipend, - _ => 0, - } -} - /// Defines an opcode that reads a block-environment field, as revm's instruction in /// [`read_volatile`]. macro_rules! block_env_read { From 25a40597d85f8b6d634ef935cb0360b04455f4f7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:31:57 -0700 Subject: [PATCH 109/458] test(access): pin the limit a call's read sets, and a union of overlapping reads A plain call to the beneficiary and one carrying value set exact limits: the compute the caller paid at the call, the forwarded gas less the stipend. A union keeps the kinds both sides hold. --- crates/mega-evm/src/access/volatile.rs | 13 ++++++++++++ crates/mega-evm/tests/satin/detention.rs | 26 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs index 372eb2389..eb50e387d 100644 --- a/crates/mega-evm/src/access/volatile.rs +++ b/crates/mega-evm/src/access/volatile.rs @@ -233,6 +233,19 @@ mod tests { assert_eq!(all_block_env.block_env_only(), all_block_env); } + /// 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() { diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 4ff7e570e..39c4ac56b 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -674,6 +674,32 @@ fn test_a_stipend_is_not_compute() { } } +/// 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 + 9_000), + ] { + 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() From ebd37fcfb31e146508dfaca776a807fbd40f7a64 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:38:22 -0700 Subject: [PATCH 110/458] fix(satin): hold deployed code only where return_create charges its state gas --- AGENTS.md | 4 +- crates/mega-evm/src/evm/execution.rs | 114 ++++-- crates/mega-evm/src/limit/limit.rs | 17 +- crates/mega-evm/src/limit/mod.rs | 9 +- crates/mega-evm/tests/satin/data_size.rs | 17 +- crates/mega-evm/tests/satin/deposit_charge.rs | 341 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 7 files changed, 446 insertions(+), 57 deletions(-) create mode 100644 crates/mega-evm/tests/satin/deposit_charge.rs diff --git a/AGENTS.md b/AGENTS.md index e08e9c428..9946620b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -144,7 +144,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code revm would accept before the creation is committed (code starting with `0xEF` or over the code-size limit fails the creation alone and is not counted), an Oracle hint before it is forwarded. + 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code revm would deposit before the creation is committed (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 before it is forwarded. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (see the block executor below). @@ -157,7 +157,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the `CALL`, `CALLCODE`, `CREATE` and `CREATE2` wrappers (the frame they start is answered with the stop, which gives back the gas they forwarded) — and, for deployed code, before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the `CALL`, `CALLCODE`, `CREATE` and `CREATE2` wrappers (the frame they start is answered with the stop, which gives back the gas they forwarded) — and, for deployed code, just before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind; both hold the deposit only once `return_create` is sure to make that charge, so a creation that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 09cccedd8..0d886c8a3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -641,8 +641,9 @@ where /// the stop when it crosses one, before revm commits the creation: first the state gas /// `return_create` will charge for the bytes, then the bytes themselves. /// -/// Only code `return_create` would deposit is held ([`deposits`]). Code it refuses fails the -/// creation there, alone, and the chain keeps none of it. Counted, those bytes could cross the +/// Only a deposit `return_create` would make its state charge for is held +/// ([`deposit_state_gas`]). A creation that fails before that charge fails there, alone, and the +/// chain keeps none of its code: counted, those bytes and their state gas could cross the /// transaction's limit and stop every frame above a creation that fails by itself. fn meter_deployed_code( ctx: &mut MegaContext, @@ -651,8 +652,9 @@ fn meter_deployed_code( ) -> InterpreterAction { if frame.data.is_create() { if let InterpreterAction::Return(result) = &mut action { - if deposits(ctx.cfg(), &result.output) { - hold_deposit_state_gas(ctx, frame.interpreter.input.target_address, result); + let address = frame.interpreter.input.target_address; + if let Some(state_gas) = deposit_state_gas(ctx, address, result) { + hold_deposit_state_gas(ctx, result, state_gas); ctx.additional_limit.on_create_return(result); } } @@ -660,39 +662,23 @@ fn meter_deployed_code( action } -/// Holds the state gas `return_create` is about to charge for the code a creation at `address` -/// deposits to the state-gas limit, and turns the return into the stop when it crosses it. +/// Holds the `state_gas` `return_create` is about to charge for the code a creation deposits to +/// the state-gas limit, with what the creation already holds, and turns the return into the stop +/// when it crosses it. /// /// A crossing after `return_create` would leave the code deployed: the charge is made inside it, -/// after which it commits the creation's checkpoint. So the charge is priced here, through the -/// same hook and for the same bytes, and held with what the creation already holds. Unlike every -/// other state-gas site, the limit binds here before the charge is made, as the data-size limit -/// does for the same bytes, so a creation that could not have paid for its code is stopped rather -/// than run out of gas. -/// -/// A return that is already a revert or a halt deposits nothing, and a schedule that prices -/// deposited code at no state gas is not asked for a price, as `return_create` does not ask it. -/// A lookup that fails is left to `return_create`, which asks the hook again and fails the same -/// way. +/// after which it commits the creation's checkpoint. So the limit binds here, just before the +/// charge, and only once [`deposit_state_gas`] found that `return_create` will make it: a charge +/// the creation cannot pay is an out-of-gas whatever the limit, as it is at every other site. fn hold_deposit_state_gas( ctx: &mut MegaContext, - address: Address, result: &mut InterpreterResult, + state_gas: u64, ) { - if !result.result.is_ok() { - return; - } - let bytes = result.output.len(); - if ctx.cfg().gas_params().code_deposit_state_gas(bytes) == 0 { + if state_gas == 0 { return; } - let charge = StateGasCharge::units( - GasId::code_deposit_state_gas(), - StateGasSite::account(address), - bytes as u64, - ); - let Some(cost) = ctx.state_gas_charge(charge) else { return }; - let running = result.gas.state_gas_spent().saturating_add_unsigned(cost); + let running = result.gas.state_gas_spent().saturating_add_unsigned(state_gas); let check = ctx.additional_limit.check_state_gas(running); if check.exceeded_limit() { result.result = InstructionResult::Revert; @@ -700,15 +686,69 @@ fn hold_deposit_state_gas( } } -/// Whether `return_create` deposits `code` a creation returns, as far as the code decides it: -/// no longer than the code-size limit, and not starting with `0xEF` unless EIP-3541 is off, both -/// read from the configuration `return_create` reads. +/// The state gas `return_create` charges for the code a creation at `address` returns, when it +/// reaches that charge and the creation can pay it — zero when it charges none; `None` when it +/// fails the creation at that charge or before it. +/// +/// It retraces revm's `return_create` (`crates/handler/src/frame.rs`), step by step and on a copy +/// of the frame's gas, up to and including the state charge: +/// +/// 1. a return that is not a success deposits nothing: `if !interpreter_result.result.is_ok()`; +/// 2. code over the code-size limit fails the creation: `interpreter_result.output.len() > +/// max_code_size`; +/// 3. so does code starting with `0xEF`, unless EIP-3541 is off: `!is_eip3541_disabled && +/// interpreter_result.output.first() == Some(&0xEF)`; +/// 4. the regular deposit cost, `gas_params.code_deposit_cost(len)`, is charged, and a frame that +/// cannot pay it runs out of gas; +/// 5. under EIP-8037, so is the regular cost of hashing the code, `gas_params.keccak256_cost(len)`; +/// 6. under EIP-8037, when the schedule prices deposited code (`code_deposit_state_gas(len) > 0`), +/// the state gas is priced through the hook — a lookup that fails fails the creation — and +/// recorded as `record_state_cost` records it, the reservoir first and then regular gas, and a +/// frame that cannot pay it runs out of gas. +/// +/// Only a creation that passes all six is held, so every out-of-gas `return_create` would report +/// is still reported, and the hook is asked for a price only where `return_create` asks it: a +/// lookup that fails here fails there the same way. What `return_create` charges after the state +/// gas — the deposited code's history — is a charge like the history after any other state +/// charge, which the limit holds before. /// -/// What `return_create` charges for the deposit is not part of it: the count comes before that -/// charge, so a crossing is the stop and not an out-of-gas. `return_create` also gates the two -/// checks on EIP-170 and London, which Satin's base spec, Osaka, enables. -fn deposits(cfg: &impl Cfg, code: &[u8]) -> bool { - code.len() <= cfg.max_code_size() && (cfg.is_eip3541_disabled() || code.first() != Some(&0xEF)) +/// `return_create` also gates steps 2, 3 and 4's out-of-gas on EIP-170, London and Homestead, +/// which Satin's base spec, Osaka, enables. +fn deposit_state_gas( + ctx: &mut MegaContext, + address: Address, + result: &InterpreterResult, +) -> Option { + let code = &result.output; + let len = code.len(); + let cfg = ctx.cfg(); + if !result.result.is_ok() || + len > cfg.max_code_size() || + (!cfg.is_eip3541_disabled() && code.first() == Some(&0xEF)) + { + return None; + } + let mut gas = result.gas; + let gas_params = cfg.gas_params(); + if !gas.record_regular_cost(gas_params.code_deposit_cost(len)) { + return None; + } + if !cfg.is_amsterdam_eip8037_enabled() { + return Some(0); + } + if !gas.record_regular_cost(gas_params.keccak256_cost(len)) { + return None; + } + if gas_params.code_deposit_state_gas(len) == 0 { + return Some(0); + } + let charge = StateGasCharge::units( + GasId::code_deposit_state_gas(), + StateGasSite::account(address), + len as u64, + ); + let cost = ctx.state_gas_charge(charge)?; + gas.record_state_cost(cost).then_some(cost) } /// The action of a frame about to run: the stop it returns without running an instruction, when diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index ef7deac1a..eb6d72819 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -453,17 +453,18 @@ impl AdditionalLimit { /// Counts the code a creation is about to deposit, on the creation's own lane, and turns the /// return into the stop when that crosses a limit. /// - /// Called from the frame run, on a successful return whose code `return_create` would accept, - /// before it charges for the deposit and commits the creation's journal checkpoint. A rewrite - /// after that commit would leave the code deployed: the checkpoint is already gone, and - /// flipping the frame result does not reopen it. A stop here makes `return_create` revert the - /// checkpoint instead, so the code is not written. 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. + /// Called from the frame run, on a return `return_create` would deposit — a success whose code + /// it accepts, from a frame that can pay what it charges for the deposit — before it makes + /// those charges and commits the creation's journal checkpoint. A rewrite after that commit + /// would leave the code deployed: the checkpoint is already gone, and flipping the frame + /// result does not reopen it. A stop here makes `return_create` revert the checkpoint instead, + /// so the code is not written. 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 return that is already a revert or a halt deposits nothing, and its output is the /// revert data, not code. Empty code deposits nothing either, and neither does code - /// `return_create` refuses: that fails the creation there, and is never counted. + /// `return_create` refuses or a creation that cannot pay for its deposit: those fail the + /// creation there, and are never counted. /// /// 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: diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 336d2304d..233fd8a4c 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -29,7 +29,8 @@ //! 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 fails the creation alone and is not counted; +//! 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. //! //! A record is checked against the limits before its history is charged: a record the limit @@ -72,8 +73,10 @@ //! taken back on a crossing; the first frame's recipient or created account, which the first frame //! is then answered with the stop for; a fresh slot and a destruction's new beneficiary, which //! stop the frame; and a new account a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` adds, whose frame -//! is answered with the stop. Deployed code is held before `return_create` charges it, as its -//! bytes are, so a crossing leaves no code behind. Wherever the state gas and a record cross +//! is answered with the stop. Deployed code is held just before `return_create` charges it, as its +//! bytes are, so a crossing leaves no code behind — and only once `return_create` is sure to make +//! the charge: a creation that cannot pay the regular costs it charges first, or the state gas +//! itself, runs out of gas there whatever the limit. Wherever the state gas and a record cross //! together, the state gas is the stop reported. //! //! It is a limit on gas, so it counts state at the SALT price: a slot or an account in a bucket diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 6d946ae1f..bb64c943a 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -12,7 +12,7 @@ use alloy_evm::Evm; use alloy_primitives::{address, keccak256, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ - constants::MAX_CONTRACT_SIZE, + 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, @@ -458,7 +458,9 @@ fn factory_noting_failure(init: &Bytes) -> Bytes { /// 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 crosses the transaction's limit and stops it. +/// deposit, with the gas to pay for them, crosses the transaction's limit and stops it: 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 @@ -473,12 +475,12 @@ fn test_code_return_create_refuses_is_not_counted() { ("0xEF first", 0xEF, 21, InstructionResult::CreateContractStartingWithEF), ("over the code-size limit", 0x00, max + 1, InstructionResult::CreateContractSizeLimit), ]; - let run = |init: &Bytes, inspect: bool| { + 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(); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); (outcome, evm.inspector().clone()) }; let failure_noted = |outcome: &MegaTransactionOutcome| { @@ -488,7 +490,7 @@ fn test_code_return_create_refuses_is_not_counted() { 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); + 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"); @@ -508,8 +510,9 @@ fn test_code_return_create_refuses_is_not_counted() { assert_eq!(probe.creates[0].0, refusal, "{case}: revm's own refusal"); } - // The same length, deployable: counted, and it crosses. - let (stopped, _) = run(&constructor_returning_from(0x00, len.min(max)), inspect); + // The same length, deployable and paid for: counted, and it crosses. + let deployable = constructor_returning_from(0x00, len.min(max)); + let (stopped, _) = run(&deployable, inspect, TX_GAS_LIMIT_CAP + 2_000_000_000); assert_eq!( stopped.limit_exceeded, Some(LimitCheck::ExceedsLimit { 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..689dfef86 --- /dev/null +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -0,0 +1,341 @@ +//! Deployed code is held to the limits only where `return_create` charges its state gas. +//! +//! `return_create` charges a creation's deposit in this order: the regular deposit cost, the +//! regular cost of hashing the code under EIP-8037, then the code's state gas — the reservoir +//! first, then regular gas — and last the code's history. A creation that cannot pay one of them +//! runs out of gas there, alone, and the chain keeps none of its code. The state-gas limit and the +//! data-size limit both hold the deposit before `return_create` commits it, and only once the +//! state gas is paid: a creation that cannot pay a charge up to it runs out of gas whatever the +//! limit, and its caller goes on. The history after it is held like a record's history after the +//! state gas of its slot: the limit comes first. +//! +//! Each case finds its boundary on the engine: the least gas `A` can call the creator `B` with for +//! `return_create` to charge the code's state gas — or, without EIP-8037, to deposit the code — +//! when no limit is set. The creation then has no regular gas left after it, so it is exactly +//! enough. With that gas a limit the deposit crosses stops the creation; one gas short the +//! creation runs out of gas, under the limit exactly as without it. +//! +//! Which charge the creation runs out of gas on follows from where the gas comes from. Above the +//! execution cap the reservoir pays the code's state gas and history, so the last regular charge +//! is the hash. Below it there is no reservoir, and the state gas is paid out of regular gas after +//! the hash. 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. + +use alloy_primitives::{address, Address, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{neutral_cfg, neutralize_evm, BytecodeBuilder, MemoryDatabase}, + EthSpecId, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, + MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, MLOAD, MSTORE, POP, PUSH0, RETURN, RETURNDATASIZE, SSTORE}, + context_interface::cfg::GasId, + inspector::NoOpInspector, + interpreter::{interpreter::EthInterpreter, CreateInputs, CreateOutcome}, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000a00000"); +/// Calls `B` with a chosen gas, keeps what `B` answers in slot 1, then writes slot 0. +const A: Address = address!("0000000000000000000000000000000000a00001"); +/// Creates the code with everything it has, and answers with the size of what the creation +/// returned: a stop's revert data, or nothing. +const B: Address = address!("0000000000000000000000000000000000a00002"); + +/// The bytes the creation deploys. +const CODE_LEN: u16 = 1_024; + +/// Below the execution cap: there is no reservoir, and every state charge is paid out of regular +/// gas. +const BELOW_CAP: u64 = 10_000_000; +/// Above the execution cap: the reservoir pays every state and history charge. +const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 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)] +enum Setup { + /// Satin's own configuration, with this gas limit. + Satin(u64), + /// The neutral configuration of Osaka, which has no EIP-8037 and charges the regular deposit + /// cost. + NeutralOsaka, +} + +/// `A` calling `B` with `gas`. +/// +/// The creation's init code touches memory far out before it returns the code, which costs it a +/// few thousand gas: `B` keeps a sixty-fourth of what it forwards, and that has to be enough for +/// it to answer however little the creation gives back. +fn world(gas: u64) -> MemoryDatabase { + let init = BytecodeBuilder::default() + .push_number(0x8000_u16) + .append(MLOAD) + .append(POP) + .push_number(CODE_LEN) + .push_number(0_u8) + .append(RETURN) + .build(); + 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(RETURNDATASIZE) + .append(PUSH0) + .append(MSTORE) + .push_number(32_u8) + .append(PUSH0) + .append(RETURN) + .build(); + let caller = BytecodeBuilder::default() + .push_number(32_u8) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(gas) + .append(CALL) + .append(POP) + .append(PUSH0) + .append(MLOAD) + .push_number(1_u8) + .append(SSTORE) + .sstore(U256::ZERO, U256::from(1)) + .stop() + .build(); + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, caller) + .account_code(B, creator) +} + +fn evm( + setup: Setup, + gas: u64, + limits: EvmTxRuntimeLimits, +) -> MegaEvm { + let ctx = context(world(gas)); + match setup { + Setup::Satin(_) => MegaEvm::new(ctx.with_tx_runtime_limits(limits)), + Setup::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 + } + } +} + +const fn gas_limit(setup: Setup) -> u64 { + match setup { + Setup::Satin(gas_limit) => gas_limit, + Setup::NeutralOsaka => BELOW_CAP, + } +} + +/// Runs the transaction with `A` calling `B` with `gas`, under `limits`. +fn run(setup: Setup, gas: u64, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + evm(setup, gas, limits) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit(setup))) + .expect("the transaction is valid") +} + +/// Whether the creation's code is at its address. +fn deployed(outcome: &MegaTransactionOutcome) -> bool { + outcome.state.get(&B.create(0)).is_some_and(|account| !account.info.is_empty_code_hash()) +} + +/// The size of what `B`'s creation returned, as `A` kept it. +fn creation_answer(outcome: &MegaTransactionOutcome) -> U256 { + outcome.state[&A].storage.get(&U256::from(1)).map(|slot| slot.present_value).unwrap_or_default() +} + +/// The creation's frame once `return_create` is done with it. +#[derive(Clone, Copy, Debug, Default)] +struct CreationEnd { + /// 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, +} + +impl CreationEnd { + /// Whether `return_create` got as far as the charge the limits hold the deposit before: the + /// code's state gas, or, without EIP-8037, the deposit itself. + const fn reached(&self) -> bool { + self.deposited || self.charged_state_gas + } +} + +impl Inspector, EthInterpreter> for CreationEnd { + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let gas = outcome.result.gas; + *self = Self { + deposited: outcome.result.is_ok(), + charged_state_gas: gas.state_gas_spent() > 0, + remaining: gas.remaining(), + }; + } +} + +/// How the creation ends when `A` calls `B` with `gas` and no limit is set. +fn creation_end(setup: Setup, gas: u64) -> CreationEnd { + let mut evm = + evm(setup, gas, EvmTxRuntimeLimits::no_limits()).with_inspector(CreationEnd::default()); + evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit(setup))).unwrap(); + *evm.inspector() +} + +/// The least gas `A` can call `B` with for `return_create` to reach the charge the limits hold the +/// deposit before, with no limit set; and the unlimited outcome one gas short of it. +/// +/// At the boundary the creation has no regular gas left after that charge, so it is exactly +/// enough; one gas short the creation runs out of gas and deploys nothing. +fn boundary(setup: Setup) -> (u64, MegaTransactionOutcome) { + let (mut short, mut enough) = (0, 5_000_000); + assert!( + !creation_end(setup, short).reached() && creation_end(setup, enough).reached(), + "{setup:?}: the search brackets the boundary" + ); + while enough - short > 1 { + let middle = short + (enough - short) / 2; + if creation_end(setup, middle).reached() { + enough = middle; + } else { + short = middle; + } + } + let end = creation_end(setup, enough); + assert_eq!(end.remaining, 0, "{setup:?}: exactly enough: {end:?}"); + + let outcome = run(setup, short, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "{setup:?}: {:?}", outcome.result); + assert!(!deployed(&outcome), "{setup:?}: one gas short, the creation runs out of gas"); + assert_eq!(creation_answer(&outcome), U256::ZERO, "{setup:?}: an out-of-gas returns nothing"); + (enough, outcome) +} + +/// The state gas the creation holds once its code's state gas is charged: the created account +/// and the code. +fn creation_state_gas() -> u64 { + crate::salt::entry(GasId::create_state_gas()) + + u64::from(CODE_LEN) * crate::salt::entry(GasId::code_deposit_state_gas()) +} + +/// Under a state-gas limit one gas short of what the creation holds with its code, the creation +/// that reaches the charge is stopped, and the one that cannot runs out of gas as it does without +/// the limit: the transaction succeeds with no code deployed and the same gas. +fn assert_state_gas_limit_stands_aside(setup: Setup) { + let (enough, short) = boundary(setup); + let creation = creation_state_gas(); + assert!(short.gas.state > 0 && short.gas.state < creation, "{setup:?}: the slot alone fits"); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(creation - 1); + + let stopped = run(setup, enough, limits); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: creation - 1, + used: creation, + frame_local: false, + }; + assert_eq!(stopped.limit_exceeded, Some(stop), "{setup:?}: exactly enough, the check fires"); + assert!(!deployed(&stopped), "{setup:?}"); + + let ran_out = run(setup, enough - 1, limits); + assert!(ran_out.result.is_success(), "{setup:?}: {:?}", ran_out.result); + assert_eq!(ran_out.limit_exceeded, None, "{setup:?}: one gas short, it stands aside"); + assert!(!deployed(&ran_out), "{setup:?}"); + assert_eq!(creation_answer(&ran_out), U256::ZERO, "{setup:?}: the creation ran out of gas"); + assert_eq!(ran_out.gas, short.gas, "{setup:?}: as without the limit"); +} + +/// Under a frame cap the creation's code crosses, the creation that reaches the charge is stopped +/// alone — it answers with the stop's revert data — and the one that cannot runs out of gas as it +/// does without the cap. +fn assert_data_size_limit_stands_aside(setup: Setup) { + let (enough, short) = boundary(setup); + 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(setup, enough, limits); + assert!(stopped.result.is_success(), "{setup:?}: {:?}", stopped.result); + assert_eq!( + creation_answer(&stopped), + U256::from(stop.revert_data().len()), + "{setup:?}: exactly enough, the check fires and the creation reverts with the stop", + ); + assert!(!deployed(&stopped), "{setup:?}"); + + let ran_out = run(setup, enough - 1, limits); + assert!(ran_out.result.is_success(), "{setup:?}: {:?}", ran_out.result); + assert_eq!(creation_answer(&ran_out), U256::ZERO, "{setup:?}: one gas short, it stands aside"); + assert!(!deployed(&ran_out), "{setup:?}"); + assert_eq!(ran_out.gas, short.gas, "{setup:?}: as without the limit"); + assert_eq!(ran_out.usage, short.usage, "{setup:?}: and it keeps what it keeps without it"); +} + +/// Above the execution cap the reservoir pays the code's state gas: a creation that cannot pay +/// the hash of its code runs out of gas on it, whatever the state-gas limit. +#[test] +fn test_a_creation_that_cannot_pay_the_hash_runs_out_of_gas_under_the_state_gas_limit() { + let setup = Setup::Satin(ABOVE_CAP); + let (enough, _) = boundary(setup); + assert!( + deployed(&run(setup, enough, EvmTxRuntimeLimits::no_limits())), + "the hash is the last charge the frame's own gas pays" + ); + assert_state_gas_limit_stands_aside(setup); +} + +/// Below the execution cap the code's state gas is paid out of regular gas: a creation that can +/// pay the hash of its code but not its state gas runs out of gas on the state gas, whatever the +/// state-gas limit. +/// +/// With exactly enough for the state gas the check fires, although without a limit the creation +/// would then run out of gas on the code's history: that is charged after the state gas, as a +/// record's history is after its slot's, and the limit holds what was charged before it. +#[test] +fn test_a_creation_that_cannot_pay_its_state_gas_runs_out_of_gas_under_the_state_gas_limit() { + let setup = Setup::Satin(BELOW_CAP); + let (enough, _) = boundary(setup); + let end = creation_end(setup, enough); + assert!(end.charged_state_gas && !end.deposited, "the history is what it cannot pay: {end:?}"); + assert_state_gas_limit_stands_aside(setup); +} + +/// The data-size limit counts deployed code behind the same check: a creation that cannot pay the +/// hash of its code, or its state gas, runs out of gas whatever the limit. +#[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(Setup::Satin(ABOVE_CAP)); + assert_data_size_limit_stands_aside(Setup::Satin(BELOW_CAP)); +} + +/// Without EIP-8037 the deposit's only charge is the regular deposit cost: a creation that cannot +/// pay it runs out of gas whatever the data-size limit. +#[test] +fn test_a_creation_that_cannot_pay_the_deposit_cost_runs_out_of_gas_under_the_data_size_limit() { + let end = creation_end(Setup::NeutralOsaka, boundary(Setup::NeutralOsaka).0); + assert!(end.deposited && !end.charged_state_gas, "no state gas without EIP-8037: {end:?}"); + assert_data_size_limit_stands_aside(Setup::NeutralOsaka); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index b7125f964..a19a47930 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -6,6 +6,7 @@ mod contract_size; mod data_size; mod data_size_counts; mod db_error; +mod deposit_charge; mod equivalence; mod history_bytes; mod history_exemption; From 8090c2baa253c4d72c9cd45dc9d23bd25d40b9a1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:45:53 -0700 Subject: [PATCH 111/458] fix(satin): hold a frame's upfront state gas once revm has decided the frame --- AGENTS.md | 5 +- crates/mega-evm/src/evm/execution.rs | 152 ++++++++++++- crates/mega-evm/src/evm/instructions.rs | 41 ++-- crates/mega-evm/src/limit/limit.rs | 2 +- crates/mega-evm/src/limit/mod.rs | 19 +- .../mega-evm/tests/satin/state_gas_limit.rs | 214 +++++++++++++++++- 6 files changed, 392 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9946620b5..ea0371d47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -157,8 +157,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the `CALL`, `CALLCODE`, `CREATE` and `CREATE2` wrappers (the frame they start is answered with the stop, which gives back the gas they forwarded) — and, for deployed code, just before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind; both hold the deposit only once `return_create` is sure to make that charge, so a creation that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas whatever the limit. - The state gas is checked before the data size and the records wherever both cross. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame revm refuses — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, just before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind; both hold the deposit only once `return_create` is sure to make that charge, so a creation that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas whatever the limit. + The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. @@ -203,6 +203,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 state gas or records would cross it are taken back before the first frame. + The one exception is the state gas an opcode charges upfront for the account the frame it starts adds: revm gives it back for a frame it refuses, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts. 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 0d886c8a3..da61ced87 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -403,7 +403,10 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm { ctx.additional_limit.set_frame_address(address); + hold_upfront_state_gas(ctx, None); Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } - Err(result) => { + Err(mut result) => { if let Some((creator, nonce)) = creator { if account_nonce(ctx, creator) == nonce { ctx.additional_limit.creation_did_not_bump_nonce(); } } + hold_upfront_state_gas(ctx, Some(&mut result)); Ok(ItemOrResult::Result(result)) } } @@ -563,7 +569,8 @@ 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 is held to the state-gas limit as revm's own is ([`hold_upfront_state_gas`]). #[inline] fn inspect_frame_init( &mut self, @@ -578,6 +585,7 @@ where output = answer; } ctx.additional_limit.push_empty_frame(); + hold_upfront_state_gas(ctx, Some(&mut output)); frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } @@ -813,6 +821,40 @@ impl MegaEvm { } } +/// Holds the state gas the caller was charged upfront for the frame that is starting — the new +/// account a value `CALL` adds, a creation's account — to the state-gas limit, once revm has +/// decided the frame. `answer` is the frame's result when it was answered without running; a +/// frame revm built has none yet. +/// +/// revm's `CALL`, `CREATE` and `CREATE2` make that charge before anything knows whether the frame +/// can start, and a frame that adds no account gives it back when its answer returns +/// ([`FrameResult::refundable_state_gas_charge`]): a value call its caller cannot fund, a call past +/// the call-stack limit, an answer that fails. Such a charge is never held. A charge that stands — +/// the frame is built, or answered with a success, as a value call to an account with no code is +/// — is held, and a crossing latches the transaction: a built frame returns the stop before its +/// first instruction, and an answer is rewritten to it here, so an inspector sees the answer the +/// caller gets. The writes the frame's start made go with the frames the stop reverts. A built +/// frame that later fails gives the charge back too, but by then it has started, and a crossing +/// inside a frame that later fails is a crossing. +/// +/// The frame's own entry is on top by now, and holds what its caller held, the charge included; +/// the frame itself holds nothing yet. Every other charge was held where it was made, so only the +/// upfront one can cross here. +fn hold_upfront_state_gas( + ctx: &mut MegaContext, + answer: Option<&mut FrameResult>, +) { + let Some(answer) = answer else { + ctx.additional_limit.check_state_gas(0); + return; + }; + if answer.refundable_state_gas_charge().is_none() && + ctx.additional_limit.check_state_gas(0).exceeded_limit() + { + ctx.additional_limit.apply_latch(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( @@ -1031,3 +1073,103 @@ fn charge_records_made_outside_a_frame( ctx.additional_limit.set_top_level_write_record_gas(top_level); true } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaLimitExceeded, MegaSpecId, + }; + use alloy_primitives::{address, U256}; + use alloy_sol_types::SolError; + + const CALLER: Address = address!("00000000000000000000000000000000000e0001"); + const TARGET: Address = address!("00000000000000000000000000000000000e0002"); + + /// A `CALL` from `caller` to `target` of `value` wei, which its opcode charged a new account + /// for when `charged`. + fn call(caller: Address, target: Address, value: u64, charged: bool) -> 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, + value: CallValue::Transfer(U256::from(value)), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: charged, + })) + } + + /// A `CALL` of one wei to `TARGET`, which its opcode charged a new account for. + fn value_call() -> FrameInput { + call(CALLER, TARGET, 1, true) + } + + /// A `CREATE` its opcode charged the created account for. + 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 under a state-gas limit of 99, with the transaction's own frame on the call stack + /// holding 100 — the upfront charge of the frame it starts — and the entry of that frame + /// pushed. + fn starting_a_frame_charged_100() -> MegaContext { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(99)); + let _ = ctx.additional_limit.on_frame_init(&call(CALLER, CALLER, 0, false), 0); + ctx.additional_limit.note_caller_state_gas(100); + ctx.additional_limit.push_empty_frame(); + ctx + } + + /// A frame revm refuses — past the call-stack limit, which no transaction reaches under the + /// execution cap — gives its caller's upfront charge back, so the charge is not held, for a + /// call and a creation alike; the answer stays what it was. + #[test] + fn test_a_refused_frame_is_not_held_for_its_upfront_charge() { + for input in [value_call(), creation()] { + let mut ctx = starting_a_frame_charged_100(); + let mut refused = + synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); + assert!(refused.refundable_state_gas_charge().is_some(), "{input:?}"); + hold_upfront_state_gas(&mut ctx, Some(&mut refused)); + assert_eq!(ctx.additional_limit.latched(), None, "{input:?}"); + assert_eq!(refused.instruction_result(), InstructionResult::CallTooDeep); + } + } + + /// A charge that stands is held: a frame revm built latches the transaction, and a success + /// answer carrying the charge latches it and is rewritten to the stop. + #[test] + fn test_a_charge_that_stands_is_held() { + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 99, + used: 100, + frame_local: false, + }; + let mut ctx = starting_a_frame_charged_100(); + hold_upfront_state_gas(&mut ctx, None); + assert_eq!(ctx.additional_limit.latched(), Some(&stop), "a built frame"); + + let mut ctx = starting_a_frame_charged_100(); + let mut answered = + synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); + hold_upfront_state_gas(&mut ctx, Some(&mut answered)); + assert_eq!(ctx.additional_limit.latched(), Some(&stop), "a success answer"); + assert_eq!(answered.instruction_result(), InstructionResult::Revert); + assert_eq!( + answered.interpreter_result().output, + Bytes::from(MegaLimitExceeded { kind: 3, limit: 99 }.abi_encode()), + ); + } +} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 29c88a79e..58c764b68 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -24,16 +24,17 @@ //! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). 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 holds the state gas revm's instruction charged for the -//! account the frame would add to the state-gas limit — a crossing answers the frame with the stop -//! before it is built — and then 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 +//! 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. +//! interpreter halts on an instruction's error only when no frame is pending. The state gas revm's +//! instruction charged for the account the frame would add is held to the state-gas limit later, +//! once revm has decided the frame: revm refuses some frames after the charge — a value call its +//! caller cannot fund, one past the call-stack limit — and gives the charge back. //! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -226,22 +227,21 @@ fn selfdestruct( commit_after::(context, host::selfdestruct) } -/// Runs `inner`, holds the state gas it charged to the state-gas limit, and charges the frame the -/// history of the write records the frame `inner` starts will make. +/// Runs `inner` and charges the frame the history of the write records the frame `inner` starts +/// will make. /// -/// revm's instruction charges the caller the state gas of the account the frame would add — a -/// value transfer's new recipient, a created account — before it builds the frame's input. A -/// crossing latches the transaction, and the frame is answered with the stop before it is built, -/// as a frame whose start crosses the data-size limit is: the gas the opcode forwarded and the -/// state gas it charged come back to the caller the way they come back from any frame that -/// reverts, and the caller returns the stop without running on. Such a frame makes no records, so -/// it is charged no history. +/// 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. A frame revm refuses once it has it — a value call the caller cannot fund, +/// one past the call-stack limit — makes no records either, 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`]). /// -/// The history 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 call the balance cannot fund, a creation the depth refuses — makes no -/// records and is charged nothing. 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. That charge is held to the state-gas +/// limit when revm has decided the frame, not here: a frame revm refuses gives it back, and a +/// limit that held it would stop the transaction for an account nobody adds. /// /// The frame inherits the reservoir the charge left, not the one the caller held before it /// ([`inherit_reservoir`]). @@ -261,8 +261,7 @@ fn charge_frame_start( } _ => return result, }; - let check = host.additional_limit.check_state_gas(interpreter.gas.state_gas_spent()); - if check.exceeded_limit() || !host.prices_history() { + if !host.prices_history() { return result; } let (Some(on_lane), Some(caller)) = ( diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index eb6d72819..71476940e 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -159,7 +159,7 @@ impl AdditionalLimit { /// 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) { + pub(crate) 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() { diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 233fd8a4c..2b98f2464 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -72,12 +72,19 @@ //! pay is an out-of-gas whatever the limit: the authorities' before the first frame, which are //! taken back on a crossing; the first frame's recipient or created account, which the first frame //! is then answered with the stop for; a fresh slot and a destruction's new beneficiary, which -//! stop the frame; and a new account a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` adds, whose frame -//! is answered with the stop. Deployed code is held just before `return_create` charges it, as its -//! bytes are, so a crossing leaves no code behind — and only once `return_create` is sure to make -//! the charge: a creation that cannot pay the regular costs it charges first, or the state gas -//! itself, runs out of gas there whatever the limit. Wherever the state gas and a record cross -//! together, the state gas is the stop reported. +//! stop the frame; and a new account a `CALL`, `CREATE` or `CREATE2` adds, which its opcode is +//! charged for upfront and the limit holds once revm has decided the frame. A frame revm refuses — +//! a value call its caller cannot fund, one past the call-stack limit — gives that charge back and +//! is never held for it; a frame revm builds, or answers with a success, returns the stop. +//! +//! Deployed code is held just before `return_create` charges it, as its bytes are, so a crossing +//! leaves no code behind — and only once `return_create` is sure to make the charge: a creation +//! that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas +//! there whatever the limit. +//! +//! Wherever the state gas and a record cross together at one site, the state gas is the stop +//! reported. At a frame start the records are held before revm builds the frame, and a frame they +//! stop adds no account, so its upfront state gas is given back rather than held. //! //! It is a limit on gas, so it counts state at the SALT price: a slot or an account in a bucket //! `m` times the minimum costs `m` times the schedule's entry, and reaches the limit that many diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index 6d918d955..b82dfe4df 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -11,16 +11,20 @@ //! The figures are read off the engine rather than written out: each case first runs without a //! limit, and the state gas it reports is what the limit is set against. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - TX_BODY_SIZE, WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaTransaction, + MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{ - CALL, CREATE, CREATE2, DELEGATECALL, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, REVERT, - SELFDESTRUCT, STOP, +use revm::{ + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, + REVERT, SELFDESTRUCT, STOP, + }, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult}, + Database, Inspector, }; use crate::common::{authorizing_call, call, context, create}; @@ -289,6 +293,204 @@ fn test_a_reverting_creation_is_not_held_for_its_revert_data() { assert_eq!(outcome.gas.state, 0, "the failed creation's account charge came back"); } +/* ---------- a frame's upfront charge, held once revm has decided the frame ---------- */ + +/// The state gas one account a creation or a value transfer adds costs. +fn one_account() -> u64 { + state_gas_of( + &funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()), + &call(CALLER, A, U256::ZERO, BELOW_CAP), + ) +} + +/// Appends a `CALL` or `CALLCODE` to `target` with all the gas and `value`, dropping its success +/// flag. +fn then_call_with( + builder: BytecodeBuilder, + opcode: u8, + target: Address, + value: u64, +) -> BytecodeBuilder { + builder + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(target) + .append(GAS) + .append(opcode) + .append(POP) +} + +/// Appends a `CREATE`, or a `CREATE2` with salt zero, of empty init code carrying `value`, +/// dropping the address. +fn then_create_with(builder: BytecodeBuilder, create2: bool, value: u64) -> BytecodeBuilder { + let builder = if create2 { builder.push_number(0_u64) } else { builder }; + builder + .push_number(0_u64) + .push_number(0_u64) + .push_number(value) + .append(if create2 { CREATE2 } else { CREATE }) + .append(POP) +} + +/// A frame revm refuses once its caller's opcode charged the state gas of the account it would add +/// gives the charge back, and adds nothing: the limit does not hold it. Each case writes a fresh +/// slot after the refused frame and runs under limits the refused charge would cross — what the +/// transaction ends up holding, and one account less one gas — and succeeds exactly as it does +/// without a limit. +/// +/// Only the value `CALL` its caller cannot fund reaches revm with the charge made: its opcode +/// charges the new account before the balance is known, and revm refuses the frame when it moves +/// the value. The other cases pin that nothing is held where nothing is charged: `CALLCODE` moves +/// value within its caller's own account and never adds one, and under EIP-8037 `CREATE` and +/// `CREATE2` refuse a creation their caller cannot fund before they charge it, and charge only a +/// destination with nothing at it, which cannot collide. A frame past the call-stack limit is +/// refused with the charge made too; no transaction reaches that depth under the execution cap, +/// and the unit tests of the frame lifecycle pin it. +#[test] +fn test_a_frame_revm_refuses_is_not_held_for_its_upfront_charge() { + let account = one_account(); + let empty_init = Bytes::new(); + let taken = |address: Address| funded().account_nonce(address, 1); + let cases: [(&str, MemoryDatabase, BytecodeBuilder); 6] = [ + ( + "a CALL its caller cannot fund", + funded(), + then_call_with(BytecodeBuilder::default(), CALL, EMPTY, 2_000), + ), + ( + "a CALLCODE its caller cannot fund", + funded(), + then_call_with(BytecodeBuilder::default(), CALLCODE, EMPTY, 2_000), + ), + ( + "a CREATE its caller cannot fund", + funded(), + then_create_with(BytecodeBuilder::default(), false, 2_000), + ), + ( + "a CREATE2 its caller cannot fund", + funded(), + then_create_with(BytecodeBuilder::default(), true, 2_000), + ), + ( + "a CREATE whose address is taken", + taken(A.create(0)), + then_create_with(BytecodeBuilder::default(), false, 0), + ), + ( + "a CREATE2 whose address is taken", + taken(A.create2_from_code(B256::ZERO, &empty_init)), + then_create_with(BytecodeBuilder::default(), true, 0), + ), + ]; + for (name, db, site) in cases { + let db = db.account_code(A, write_slots(site, 0, 1).stop().build()); + let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); + let free = run_under(db.clone(), tx.clone(), u64::MAX); + assert!(free.result.is_success(), "{name}: {:?}", free.result); + assert_eq!(free.gas.state, one_slot(), "{name}: the slot alone"); + + for limit in [free.gas.state, account - 1] { + let limited = run_under(db.clone(), tx.clone(), limit); + assert!(limited.result.is_success(), "{name}, limit {limit}: {:?}", limited.result); + assert_eq!(limited.limit_exceeded, None, "{name}, limit {limit}"); + assert_eq!(limited.gas, free.gas, "{name}, limit {limit}: as without the limit"); + assert!( + limited.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero()), + "{name}, limit {limit}: nothing moved" + ); + } + } +} + +/// The result of each call to [`EMPTY`] an inspector saw end. +#[derive(Default)] +struct CallsToEmpty(Vec<(InstructionResult, Bytes)>); + +impl Inspector, EthInterpreter> for CallsToEmpty { + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == EMPTY { + self.0.push((outcome.result.result, outcome.result.output.clone())); + } + } +} + +/// A frame revm decides to run, or answers with a success, adds the account its caller's opcode +/// was charged for, so the charge is held, and a crossing latches the transaction — one case per +/// opcode family. A value call to an account with no code is answered by revm without running and +/// rewritten to the stop at once, so an inspector sees the answer the caller gets. The stop keeps +/// none of what the frame's start wrote: no value moved, no account created, and the history of +/// its records given back. +#[test] +fn test_a_frame_revm_decides_is_held_for_its_upfront_charge() { + let account = one_account(); + let body = mega_evm::history_gas(TX_BODY_SIZE).expect("a body has a price"); + let cases: [(&str, BytecodeBuilder); 3] = [ + ( + "a value CALL that creates its recipient", + then_call(BytecodeBuilder::default(), EMPTY, 1), + ), + ("a CREATE", then_create_with(BytecodeBuilder::default(), false, 0)), + ("a CREATE2", then_create_with(BytecodeBuilder::default(), true, 0)), + ]; + for (name, site) in cases { + let db = funded().account_code(A, site.stop().build()); + let stopped = run_under(db.clone(), call(CALLER, A, U256::ZERO, BELOW_CAP), account - 1); + assert_state_stopped(name, &stopped, account - 1, account); + assert_eq!(stopped.gas.state, 0, "{name}"); + assert_eq!(stopped.gas.history, body, "{name}: the records' history came back"); + assert!(stopped.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); + assert!(stopped.state.get(&A.create(0)).is_none_or(|account| !account.is_created())); + } + + let db = + funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), + )) + .with_inspector(CallsToEmpty::default()); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)).unwrap(); + let stop = outcome.limit_exceeded.expect("the call is stopped"); + assert_eq!(evm.inspector().0, [(InstructionResult::Revert, stop.revert_data())]); +} + +/// The records a frame's start makes are held before revm builds the frame, and its upfront state +/// gas after revm has decided it. A value call whose records cross the data-size limit is answered +/// with that stop, adds no account, and gives its upfront charge back: the state-gas limit that +/// charge would have crossed is not. +#[test] +fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { + let account = one_account(); + let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE - 1; + let db = + funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()); + let outcome = MegaEvm::new( + context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_state_gas_limit(account - 1) + .with_tx_data_size_limit(limit), + ), + ) + .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) + .unwrap(); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + 1, + frame_local: false, + }), + "the caller's account and the recipient's, over the limit by one byte", + ); + assert_eq!(outcome.gas.state, 0); +} + /* ---------- one limit for the whole call stack ---------- */ /// A child's crossing stops the whole transaction: there is no frame budget to revert it alone. From 479fafd29a8afb7b184818f55fb2e0b44b884f99 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:47:00 -0700 Subject: [PATCH 112/458] refactor(satin): make an empty frame input unreachable where a lane is pushed --- crates/mega-evm/src/limit/limit.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 71476940e..34c0f3416 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -574,7 +574,11 @@ impl AdditionalLimit { 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. The state-gas entry pushed above is the lane's, one per lane. + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), } } From d167abc24d314a6b9a8f19ceb41b931f5f4c241a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:47:18 -0700 Subject: [PATCH 113/458] docs(block): name the KV limit among those no deposit is refused by --- crates/mega-evm/src/block/limit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 36e10af53..b63c4e4f8 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -247,7 +247,7 @@ pub struct BlockUsage { /// The transaction's data-availability footprint, in gas. pub da_footprint: u64, /// Whether the transaction is a deposit, which the data-availability dimensions exempt and the - /// execution-gas, state-gas and data-size limits never refuse. + /// execution-gas, state-gas, data-size and KV limits never refuse. pub is_deposit: bool, } From ff47aac622ea8a960a992400b27447f6706fe606 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:56:51 -0700 Subject: [PATCH 114/458] feat(satin): hold the protocol's own transactions to no per-transaction limit --- AGENTS.md | 4 + crates/mega-evm/README.md | 2 + crates/mega-evm/src/evm/context.rs | 49 ++-- crates/mega-evm/src/limit/limit.rs | 174 ++++++++++++-- crates/mega-evm/src/limit/mod.rs | 13 +- crates/mega-evm/src/system/tx.rs | 5 +- crates/mega-evm/tests/block/eips.rs | 24 +- .../mega-evm/tests/satin/limit_exemption.rs | 214 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 9 files changed, 445 insertions(+), 41 deletions(-) create mode 100644 crates/mega-evm/tests/satin/limit_exemption.rs diff --git a/AGENTS.md b/AGENTS.md index ea0371d47..3b545fa90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,6 +161,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. +- 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 EIP-2935 and EIP-4788 pre-block calls among them — run under the sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. + 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 them, a system transaction being promoted to a deposit. + A user's deposit is not system-originated and is held to every per-transaction limit. - `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`. A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 795793b43..6f5b76d53 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -77,6 +77,8 @@ 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, KV or state-gas 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; 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. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 5ab13d9e5..e2b916b65 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -248,7 +248,8 @@ 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`]. pub const fn is_system_originated(&self) -> bool { self.system_originated } @@ -270,20 +271,11 @@ impl MegaContext { self.prices_history } - /// 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. + /// Prepares the common execution layer for a new transaction. Every transaction 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(); - self.bucket_multipliers.reset(); - self.system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); - let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || self.system_originated; - self.set_history_exempt(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 system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); + self.prepare(system_originated); } /// Prepares the context for a system call. Every system-call entry point of @@ -292,9 +284,32 @@ impl MegaContext { /// 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.set_history_exempt(true); + self.prepare(true); + } + + /// Prepares the common execution layer for a transaction or a system call that is, or is not, + /// `system_originated`. + /// + /// The SALT bucket multipliers 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, + /// the KV count, the state gas, and the frame budgets of the first two — 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.bucket_multipliers.reset(); + 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())); } /// Records whether the running transaction is exempt from history gas, and installs the diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 34c0f3416..9193c985c 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -17,7 +17,8 @@ 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 state gas the transaction holds outside each frame, the -/// record the Host staged for the running opcode, and the latch of a transaction a limit stopped. +/// record the Host staged for the running opcode, and where the transaction stands with its +/// limits — within them, latched by one, or exempt from all of them. /// /// 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) @@ -34,13 +35,25 @@ use crate::storage_call_stipend; /// 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. +/// +/// # 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, which answers an exempt transaction with [`LimitCheck::Exempt`] whatever +/// it crossed — a transaction limit or a frame budget, in any dimension — and never latches it. +/// 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, + /// Where the transaction stands with its limits: within them, stopped by the transaction-level + /// limit it latched, or exempt from all of them. The latter two are sticky for the + /// transaction. + standing: LimitCheck, /// 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, @@ -99,7 +112,7 @@ impl AdditionalLimit { pub(crate) fn reset(&mut self) { self.tracker.reset(); self.staged = None; - self.latched = None; + self.standing = LimitCheck::WithinLimit; self.resume_stop = None; self.target_is_authority = false; self.sender = Address::ZERO; @@ -114,23 +127,53 @@ impl AdditionalLimit { self.state_gas.reset(); } - /* The latch */ + /* The latch and the exemption */ /// The stop a transaction-level limit latched, if any. pub const fn latched(&self) -> Option<&LimitCheck> { - self.latched.as_ref() + match &self.standing { + latched @ LimitCheck::ExceedsLimit { .. } => Some(latched), + LimitCheck::WithinLimit | LimitCheck::Exempt => None, + } + } + + /// Whether the running transaction is exempt from every per-transaction limit. + pub const fn is_exempt(&self) -> bool { + self.standing.is_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.standing = LimitCheck::Exempt; } /// 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. + /// frame above it. A later latch does not replace the first, and an exempt transaction is not + /// latched at all: the verdict is then [`LimitCheck::Exempt`]. 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, - }) + self.crossed(kind, limit, used, false) + } + + /// The verdict on `used` crossing `kind`'s `limit`: a frame budget's stop when `frame_local`, + /// which reverts the running frame alone, and the transaction's latch otherwise. + /// + /// Every stop the layer hands out comes from here, so this is where the exemption applies: an + /// exempt transaction's verdict is [`LimitCheck::Exempt`], whatever it crossed. + fn crossed(&mut self, kind: LimitKind, limit: u64, used: u64, frame_local: bool) -> LimitCheck { + match self.standing { + LimitCheck::Exempt => LimitCheck::Exempt, + _ if frame_local => LimitCheck::ExceedsLimit { kind, limit, used, frame_local }, + LimitCheck::WithinLimit => { + self.standing = LimitCheck::ExceedsLimit { kind, limit, used, frame_local }; + self.standing + } + latched @ LimitCheck::ExceedsLimit { .. } => latched, + } } /// Checks the limits after the running frame counted something: what the transaction keeps @@ -143,7 +186,7 @@ impl AdditionalLimit { } if let Some(lane) = self.tracker.current() { if let Some((kind, limit, used)) = lane.net().crossing(lane.budget) { - return LimitCheck::ExceedsLimit { kind, limit, used, frame_local: true }; + return self.crossed(kind, limit, used, true); } } LimitCheck::WithinLimit @@ -154,13 +197,13 @@ impl AdditionalLimit { /// over its budget. Taking it clears the latter, which stops one frame. pub(crate) fn stop_before_run(&mut self) -> Option { let resume_stop = self.resume_stop.take(); - self.latched.or(resume_stop) + self.latched().copied().or(resume_stop) } /// 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. pub(crate) fn apply_latch(&self, result: &mut FrameResult) { - let Some(latched) = &self.latched else { return }; + 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; @@ -384,7 +427,10 @@ impl AdditionalLimit { let records = WRITE_RECORD.times(authorities); let used = self.tracker.net().saturating_add(records); if let Some((kind, limit, used)) = used.crossing(self.limits.tx_usage_limit()) { - return self.latch(kind, limit, used); + let check = self.latch(kind, limit, used); + if check.exceeded_limit() { + return check; + } } self.target_is_authority = target_is_authority; self.tracker.record(records); @@ -442,7 +488,7 @@ impl AdditionalLimit { /// 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 { + if let Some(latched) = self.latched().copied() { self.push_empty_frame(); return latched; } @@ -692,12 +738,15 @@ impl AdditionalLimit { /// cross the limit are taken back before anything else is charged, and a latched transaction's /// runtime phase charges nothing but the account a deposit-like transaction creates for its /// caller. That account exists whatever the transaction does, so a transaction that cannot pay - /// for it is out of gas with or without a stop, and it reports the halt. + /// for it is out of gas with or without a stop, and it reports the halt. An exemption stays: + /// it is the transaction's, not its frames'. pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { if !self.frame_began { let body = self.body_bytes; self.tracker.reset(); - self.latched = None; + if self.standing.exceeded_limit() { + self.standing = LimitCheck::WithinLimit; + } self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); return; } @@ -948,6 +997,91 @@ mod tests { ); } + /// 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) + .with_tx_kv_update_limit(0) + .with_frame_kv_update_limit(0) + .with_tx_state_gas_limit(0) + } + + /// Counts a body, a value call's two records and some state gas, and reports each verdict. + fn count_a_transaction(limit: &mut AdditionalLimit) -> [LimitCheck; 3] { + let body = limit.record_tx_body(crate::TX_BODY_SIZE); + 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); + [body, records, limit.check_state_gas(1_000)] + } + + /// A transaction that is not exempt is stopped by the first limit it crosses: its body latches + /// it. + #[test] + fn test_a_transaction_that_is_not_exempt_is_stopped() { + let mut limit = AdditionalLimit::new(zero_limits()); + let [body, ..] = count_a_transaction(&mut limit); + assert!(body.exceeded_limit() && !body.is_frame_local()); + assert_eq!(limit.latched(), Some(&body)); + assert!(!limit.is_exempt()); + } + + /// An exempt transaction is stopped by no limit, in any dimension, at the transaction or at a + /// frame: every verdict is `Exempt`, nothing is latched 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::Exempt; 3]); + assert_eq!(limit.latch(LimitKind::DataSize, 0, 1), LimitCheck::Exempt); + assert_eq!(limit.latched(), None); + 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 mut result = crate::synthetic_frame_result( + &call_from_to(CALLEE, TARGET, U256::from(1)), + InstructionResult::Stop, + Bytes::new(), + ); + let _ = limit.on_frame_return(&mut result); + assert_eq!(result.instruction_result(), InstructionResult::Stop, "nothing is rewritten"); + assert_eq!(limit.stop_before_run(), None, "and the caller runs on"); + } + + /// 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(); + let check = limit.record_applied_authorities(SENDER, 2, false, 1_000); + assert!(!check.exceeded_limit(), "{check:?}"); + 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. A latch cleared before the first frame keeps it. + #[test] + fn test_the_exemption_lasts_one_transaction() { + let mut limit = AdditionalLimit::new(zero_limits()); + limit.exempt(); + let mut result = crate::synthetic_frame_result( + &call_from_to(SENDER, CALLEE, U256::ZERO), + InstructionResult::OutOfGas, + Bytes::new(), + ); + limit.on_last_frame_return(&mut result); + assert!(limit.is_exempt(), "an out-of-gas before the first frame keeps the exemption"); + + limit.reset(); + assert!(!limit.is_exempt()); + let [body, ..] = count_a_transaction(&mut limit); + assert!(body.exceeded_limit(), "after a reset the body latches again"); + } + /// 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. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 2b98f2464..0c59b5d0d 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -94,6 +94,17 @@ //! limits carry, whose default holds a transaction to //! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size and to nothing else. //! +//! # 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 — run under [`LimitCheck::Exempt`], sticky for the transaction, which the one place +//! every stop comes from answers whatever they cross: the data size, the KV count, the state gas +//! and the frame budgets of the first two. 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 @@ -415,7 +426,7 @@ pub enum LimitCheck { /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, }, - /// The transaction is exempt from metering. + /// The transaction is exempt from every per-transaction limit: it is the protocol's own work. Exempt, } diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index d6e620440..6a0427ce3 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -103,8 +103,9 @@ pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address /// 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. +/// 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 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 || diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 1cf9fda80..0b4a3ebe7 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -13,7 +13,7 @@ use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_primitives::{Bytes, B256, U256}; use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaHardforkConfig, MegaSpecId, + BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaHardforkConfig, MegaSpecId, }; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, @@ -104,6 +104,28 @@ 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 +/// limits their bodies, their writes and their state gas each cross, both calls still record. +#[test] +fn test_the_pre_block_calls_are_held_to_no_limit() { + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(0) + .with_frame_data_size_limit(0) + .with_tx_kv_update_limit(0) + .with_frame_kv_update_limit(0) + .with_tx_state_gas_limit(0); + let ctx = MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(PARENT_BEACON_ROOT), + Bytes::new(), + BlockLimits::no_limits().with_tx_runtime_limits(limits), + ); + 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] 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..f02294075 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -0,0 +1,214 @@ +//! Who is held to no per-transaction limit: a transaction the protocol itself sent, and a system +//! call. +//! +//! The data-size limit, the KV limit, the state-gas limit and the frame budgets of the first two +//! 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, B256, U256}; +use mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, TX_BODY_SIZE, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0}, + context::TxEnv, +}; + +use crate::common::context; + +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) +} + +/// 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() + })) +} + +/// `tx` as a user's deposit: no fee, and a source hash a user's transaction could carry. +fn deposit(mut tx: MegaTransaction) -> MegaTransaction { + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.base.gas_price = 0; + tx +} + +/// Every per-transaction limit the program crosses, one at a time, and all of them together. +fn limits() -> [(&'static str, EvmTxRuntimeLimits); 6] { + 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)), + ("the transaction's KV count", none.with_tx_kv_update_limit(1)), + ("a frame's KV count", none.with_frame_kv_update_limit(1)), + ("the transaction's state gas", none.with_tx_state_gas_limit(1)), + ( + "every limit at zero", + none.with_tx_data_size_limit(0) + .with_frame_data_size_limit(0) + .with_tx_kv_update_limit(0) + .with_frame_kv_update_limit(0) + .with_tx_state_gas_limit(0), + ), + ] +} + +fn execute( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid") +} + +/// 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(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 > 0); + + for (name, limits) in limits() { + let outcome = execute(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. +#[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().latched().copied(), + ) + }; + let (free, free_usage, _) = run(EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{:?}", free.result); + assert_eq!(free_usage.write_records, 3); + + for (name, limits) in limits() { + let (result, usage, latched) = run(limits); + assert!(result.result.is_success(), "{name}: {:?}", result.result); + assert_eq!(latched, 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 KV count or the state gas, 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 none = EvmTxRuntimeLimits::no_limits(); + let cases = [ + ( + "a deposit", + deposit(call_from(CALLER, CONTRACT)), + none.with_tx_kv_update_limit(0), + LimitKind::KVUpdate, + ), + ( + "a deposit", + deposit(call_from(CALLER, CONTRACT)), + none.with_tx_state_gas_limit(0), + LimitKind::StateGrowth, + ), + ( + "a user's call to a system contract", + call_from(CALLER, ORACLE_CONTRACT_ADDRESS), + none.with_tx_data_size_limit(TX_BODY_SIZE), + LimitKind::DataSize, + ), + ( + "a user's call to a system contract", + call_from(CALLER, ORACLE_CONTRACT_ADDRESS), + none.with_tx_kv_update_limit(0), + LimitKind::KVUpdate, + ), + ( + "a user's call to a system contract", + call_from(CALLER, ORACLE_CONTRACT_ADDRESS), + none.with_tx_state_gas_limit(0), + LimitKind::StateGrowth, + ), + ]; + for (name, tx, limits, kind) in cases { + let outcome = execute(db(), tx, limits); + let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}, {kind:?}: stopped")); + assert!( + matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: k, .. } if k == kind), + "{name}: {stop:?}" + ); + assert!( + !outcome.result.is_success() && !outcome.result.is_halt(), + "{name}: {:?}", + outcome.result + ); + } +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index a19a47930..1bdbc888e 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,7 @@ mod history_reservoir; mod inspector; mod intrinsic; mod kv_limit; +mod limit_exemption; mod neutral; mod outcome; mod precompile_gas; From cc97627225ecf5c6d895fa07c9b9cfd6beac7cef Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 15:59:46 -0700 Subject: [PATCH 115/458] test(satin): size the scenario unit tests' gas at the prices the engine runs --- crates/mega-evm/src/test_utils/scenario.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 53b08b572..1d9fb7d66 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -385,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 { @@ -484,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); @@ -506,7 +516,7 @@ mod tests { /// 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(200_000))]); + 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()); From c6cee458c33761e08b535685c8eb30dc1cc62ccf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:39:37 -0700 Subject: [PATCH 116/458] feat(satin): count EIP-7708 transfer logs in the data size revm journals a transfer log for every value movement itself, so no LOG wrapper sees it. Count it where the value moves, by the rule a LOG3 of one word is counted (160 bytes): with the records of a frame start that moves value, before revm builds the frame, and with a SELFDESTRUCT's beneficiary once the opcode completed. It lives on the lane of the frame whose journal checkpoint holds the move, so a failure takes the bytes back with the log, and a crossing stops the frame before any value moves. The count is data size only: no write record and no history, and the history bytes a transaction reports leave it out. Whether a transaction counts transfer logs is read, per transaction, off the configuration revm's journal emits them by; a debug build asserts after every frame start that revm journaled exactly the log that was counted. --- crates/mega-evm/src/block/result.rs | 5 +- crates/mega-evm/src/evm/context.rs | 52 ++++- crates/mega-evm/src/evm/execution.rs | 67 ++++++ crates/mega-evm/src/evm/result.rs | 9 +- crates/mega-evm/src/limit/limit.rs | 320 ++++++++++++++++++++++++++- crates/mega-evm/src/limit/mod.rs | 27 ++- crates/mega-evm/src/limit/record.rs | 36 +++ 7 files changed, 494 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 29de02767..ad64f8986 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -33,8 +33,9 @@ pub struct BlockGasCounters { /// /// They are the history bytes the schedule prices, not the chain's physical growth: the /// block's exempt transactions (its deposits, the transactions the protocol sent) add none, - /// and each body counts its five fixed write records even when fewer fee accounts are - /// written. + /// each body counts its five fixed write records even when fewer fee accounts are written, + /// and the EIP-7708 transfer logs in the block's receipts, which nothing prices, are not in + /// them. pub history_bytes: u64, } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e2b916b65..5fcb52510 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -4,7 +4,7 @@ use delegate::delegate; use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpSpecId}; use revm::{ context::{ - BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, + BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, Transaction, }, context_interface::cfg::GasId, @@ -19,7 +19,7 @@ use crate::{ schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, system::{self, MEGA_SYSTEM_ADDRESS}, - AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, + AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, }; @@ -300,6 +300,7 @@ impl MegaContext { /// 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.system_originated = system_originated; let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; @@ -366,6 +367,16 @@ fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { 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()) @@ -736,6 +747,43 @@ mod tests { 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. + #[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(); + 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))); + } + /// A context is not neutral unless it is asked to be. #[test] fn test_a_new_context_is_not_neutral() { diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index da61ced87..b2e4159f9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -456,11 +456,18 @@ impl EvmTr for MegaEvm None, }; + #[cfg(debug_assertions)] + let transfer_log = ( + ctx.additional_limit.frame_start_transfer_log(&frame_init.frame_input), + ctx.journal_ref().logs().len(), + ); 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_transfer_log_journaled(ctx, transfer_log, outcome.as_ref().err()); match outcome { Ok(address) => { ctx.additional_limit.set_frame_address(address); @@ -901,6 +908,39 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } +/// Asserts that revm journaled the EIP-7708 transfer log the data size counted for a frame's +/// start, once revm has built the frame or answered it: `counted` is whether +/// [`on_frame_init`](crate::AdditionalLimit) counted one, `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 moves the value, from the frame's input, so this is where a +/// divergence from revm's own rule would show. 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. Only transfer +/// logs are compared: a precompile may journal logs of its own. +#[cfg(debug_assertions)] +fn assert_transfer_log_journaled( + ctx: &MegaContext, + (counted, logs_i): (bool, usize), + answer: Option<&FrameResult>, +) { + 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)] @@ -1147,6 +1187,33 @@ 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_transfer_log_journaled(&ctx, (true, 0), None); + } + + /// The guard expects no log where nothing moved, whatever was counted: a creation revm + /// answers — the nonce-overflow answer is a `Return` — and a call it answers with a failure; + /// 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_transfer_log_journaled(&ctx, (false, 0), None); + let refused = synthetic_frame_result(&creation(), InstructionResult::Return, Bytes::new()); + assert_transfer_log_journaled(&ctx, (true, 0), Some(&refused)); + let unfunded = + synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); + assert_transfer_log_journaled(&ctx, (true, 0), Some(&unfunded)); + let answered = synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); + assert_transfer_log_journaled(&ctx, (false, 0), Some(&answered)); + } + /// A charge that stands is held: a frame revm built latches the transaction, and a success /// answer carrying the charge latches it and is rewritten to the stop. #[test] diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 0e768f213..cfdac2d5c 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -20,8 +20,9 @@ //! 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, and a body counts -//! its five fixed write records even when fewer fee accounts are written. +//! 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. use revm::context::result::{ResultAndState, ResultGas}; @@ -74,7 +75,9 @@ pub struct MegaGasUsage { /// 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 kept and the code it deposited. + /// 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 9193c985c..bf4fb675a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -11,7 +11,7 @@ use super::{ record::{HistoryBytes, RecordEffect, StagedRecord}, state_gas::StateGasMeter, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD, WRITE_RECORD_SIZE, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -90,6 +90,9 @@ pub struct AdditionalLimit { history_bytes: u64, /// The state gas the transaction holds outside the running frame, for the state-gas limit. state_gas: StateGasMeter, + /// 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 { @@ -125,6 +128,19 @@ impl AdditionalLimit { self.history_gas_spent = 0; self.history_bytes = 0; self.state_gas.reset(); + 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 latch and the exemption */ @@ -239,8 +255,9 @@ impl AdditionalLimit { } /// The history bytes the last settled transaction appended, whoever paid for them: its body, - /// one write record per account or storage write it kept, the logs it kept and the code it - /// deposited. + /// 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 of its value movements are data size and + /// not history, and are not among them. /// /// Every one of them is priced at the cost per history byte, and /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of @@ -335,6 +352,12 @@ impl AdditionalLimit { /// 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 { @@ -346,18 +369,24 @@ impl AdditionalLimit { if let (StagedRecord::Log { .. }, HistoryBytes::Appended(bytes)) = (&record, history) { self.tracker.record_log_and_code_bytes(bytes); } - let check = match effect { - RecordEffect::None => LimitCheck::WithinLimit, - RecordEffect::Record(usage) => { - self.tracker.record(usage); - self.check() - } + 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); } }; - (check, 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 @@ -484,6 +513,16 @@ 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, revm's own + /// refusal of a move its caller cannot fund included, discards both the log and its bytes. + /// /// 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 { @@ -493,6 +532,9 @@ impl AdditionalLimit { return latched; } self.push_lane(input, depth); + if self.frame_start_transfer_log(input) { + self.tracker.record(TRANSFER_LOG); + } self.check() } @@ -772,6 +814,24 @@ const fn share_of_remaining(remaining: u64) -> u64 { ((remaining * numerator) / denominator) as u64 } +/// 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. /// @@ -815,7 +875,7 @@ impl FrameCharge { #[cfg(test)] mod tests { use super::*; - use crate::WRITE_RECORD_SIZE; + use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; use alloy_primitives::{address, Address, Bytes, U256}; use revm::interpreter::{CallInput, CallValue}; @@ -1082,6 +1142,242 @@ mod tests { assert!(body.exceeded_limit(), "after a reset the body latches again"); } + /// 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 mut result = + crate::synthetic_frame_result(&inner, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&mut result); + let mut result = + crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); + limit.on_last_frame_return(&mut 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 mut result = + crate::synthetic_frame_result(&inner, InstructionResult::Revert, Bytes::new()); + let _ = limit.on_frame_return(&mut result); + assert_eq!(limit.usage(), LimitUsage::ZERO); + } + + /// A frame start whose transfer log crosses a limit is stopped there, before revm moves the + /// value: its own budget reverts it alone, the transaction's limit latches. 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, + }, + ); + assert_eq!(limit.latched(), None, "a frame budget does not latch"); + } + } + + // 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, + }, + ); + assert_eq!(limit.latched(), Some(&check)); + } + } + + /// 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, + target_exists: 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. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0c59b5d0d..b38b908f6 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -31,7 +31,14 @@ //! 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, 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 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 @@ -113,11 +120,15 @@ //! 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. Two sites -//! part them, both by decision: +//! 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 @@ -146,6 +157,11 @@ pub const LOG_BASE_SIZE: u64 = 32; /// Bytes every log topic counts. pub const LOG_TOPIC_SIZE: u64 = 32; +/// 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; @@ -299,6 +315,10 @@ impl EvmTxRuntimeLimits { 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 }; + /// A budget with no bound in either dimension. pub(crate) const UNLIMITED: LimitUsage = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; @@ -476,6 +496,7 @@ mod tests { 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); diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 4979197ee..38fcc4973 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -113,6 +113,14 @@ 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)] @@ -213,4 +221,32 @@ mod tests { }; 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, + target_exists: true, + 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) + ); + } } From ab6b05b311e8f23842c54cdc915e7399f9b8a076 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:48:23 -0700 Subject: [PATCH 117/458] test(satin): build the EIP-7708 transfer log a test expects test_utils gains transfer_log, the LOG3 revm journals for a value movement, and is_transfer_log, which tells it from a log a contract emitted. --- crates/mega-evm/src/test_utils/logs.rs | 51 ++++++++++++++++++++++++++ crates/mega-evm/src/test_utils/mod.rs | 2 + 2 files changed, 53 insertions(+) create mode 100644 crates/mega-evm/src/test_utils/logs.rs 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 14c08a369..5b709397f 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -4,6 +4,7 @@ mod bytes; mod database; mod evm; mod inspectors; +mod logs; mod neutral; mod opcode_gen; mod scenario; @@ -12,6 +13,7 @@ pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; +pub use logs::*; pub use neutral::*; pub use opcode_gen::*; pub use scenario::*; From b539036cc6d6f8117b6de54de5f183f9e420fb66 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:48:31 -0700 Subject: [PATCH 118/458] feat(satin): emit EIP-7708 transfer logs Satin takes EIP-7708 from Amsterdam: every value movement emits a transfer log into the receipt. The spec fixes the switch on and EIP-7708 not disabled, so a caller's configuration cannot take the logs out of a block. The logs are counted in the data size and pay no history gas. The tests that pin a value-moving transaction's data size now carry 160 bytes per transfer log it keeps, while its history gas and history bytes stay where they were; the paired record corpus and the history-byte table check the receipt's transfer logs against the count. The op-revm baseline runs op-revm with the switch on too, and the value-transfer case pins its log and its ledger. The history allowance of a value call is untouched by the transfer log, so the callee's event still has all of it. A Satin-mode state test that moves value now fails on its logs before its state root. --- crates/mega-evm/src/evm/context.rs | 52 +++-- crates/mega-evm/tests/block/counters.rs | 17 +- crates/mega-evm/tests/satin/data_size.rs | 65 +++--- .../mega-evm/tests/satin/data_size_counts.rs | 41 +++- crates/mega-evm/tests/satin/equivalence.rs | 20 +- crates/mega-evm/tests/satin/history_bytes.rs | 50 ++++- crates/mega-evm/tests/satin/kv_limit.rs | 30 ++- .../mega-evm/tests/satin/state_gas_limit.rs | 10 +- .../tests/satin/storage_call_stipend.rs | 37 +++- crates/mega-evm/tests/satin/write_records.rs | 209 +++++++++++++----- crates/mega-state-test/tests/runner.rs | 27 ++- 11 files changed, 406 insertions(+), 152 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 5fcb52510..d3b032270 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -93,9 +93,9 @@ impl MegaContext { /// 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 and the two code-size limits. Every other + /// field (chain id, 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 { @@ -351,16 +351,21 @@ impl MegaContext { /// 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. +/// 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). +/// +/// The system-call reservoir margin is set off rather than left alone: it belongs to the +/// system-call reservoir split. 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.enable_amsterdam_eip7708 = true; + cfg.amsterdam_eip7708_disabled = 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); @@ -445,7 +450,8 @@ 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.eip7708, "EIP-7708 must be on"); + assert!(!cfg.eip7708_disabled, "EIP-7708 must not be disabled"); 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"); @@ -459,6 +465,7 @@ mod tests { eip2780: bool, cap: Option, eip7708: bool, + eip7708_disabled: bool, margin: bool, code_size: Option, initcode_size: Option, @@ -472,6 +479,7 @@ 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, code_size: cfg.limit_contract_code_size, initcode_size: cfg.limit_contract_initcode_size, @@ -503,7 +511,8 @@ 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.enable_amsterdam_eip7708 = false; + cfg.amsterdam_eip7708_disabled = 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); @@ -528,8 +537,13 @@ mod tests { } #[test] - fn test_eip7708_stays_off() { - assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip7708 = true)); + fn test_eip7708_stays_on() { + assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip7708 = false)); + } + + #[test] + fn test_eip7708_cannot_be_disabled() { + assert_satin_cfg(&context_with(|cfg| cfg.amsterdam_eip7708_disabled = true)); } #[test] @@ -664,7 +678,8 @@ mod tests { cfg.enable_amsterdam_eip8037 = false; cfg.enable_amsterdam_eip2780 = false; cfg.tx_gas_limit_cap = None; - cfg.enable_amsterdam_eip7708 = true; + cfg.enable_amsterdam_eip7708 = false; + cfg.amsterdam_eip7708_disabled = true; cfg.limit_contract_code_size = None; cfg.limit_contract_initcode_size = None; cfg @@ -749,7 +764,7 @@ mod tests { /// 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. + /// 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 = @@ -782,6 +797,15 @@ mod tests { 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(); + assert!(ctx.additional_limit.frame_start_transfer_log(&endowed_creation)); } /// A context is not neutral unless it is asked to be. diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 21ad511bb..92fe3e8db 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -3,7 +3,10 @@ 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 mega_evm::{ + test_utils::{transfer_log, BytecodeBuilder}, + BlockGasCounters, BlockLimits, MegaTxEnvelope, +}; use revm::{ bytecode::opcode::{CALL, LOG0, LOG3, POP, PUSH0}, database::State, @@ -239,7 +242,8 @@ fn state_with_allowance() -> State { /// 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. +/// 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() { @@ -252,7 +256,9 @@ fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { 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); - assert_eq!(outcome.result.logs().len(), 1, "the receiver emitted its event"); + 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"); } @@ -270,6 +276,11 @@ fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { let (_, result) = executor.finish_with_counters().expect("the block finishes"); 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", + ); } /// A transaction bound by its floor adds its floor to the block's execution gas. Its history comes diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index bb64c943a..275f34973 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -16,7 +16,7 @@ use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, WRITE_RECORD_SIZE, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -642,8 +642,9 @@ fn test_a_storage_write_one_byte_over_stops_on_the_write() { assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); } -/// A value transfer's recipient is one 40-byte record. One byte over that stops on the record, -/// before the recipient's code runs. +/// 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 = || { @@ -654,22 +655,26 @@ fn test_an_account_write_one_byte_over_stops_on_the_recipient() { }; 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 + record + record); + 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 + record + record, write_records: 2 }); + assert_eq!(fits.usage, LimitUsage { data_size: body + start + record, write_records: 2 }); - let over = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + record - 1); - assert_stopped(&over, body + record - 1, body + record); - 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()) - })); + 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. @@ -771,21 +776,30 @@ const FRESH_SLOT_COUNTED_AT: u64 = 162_306; /// 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), - ("a log of one byte", log0(1), mega_evm::LOG_BASE_SIZE + 1), - ("a SELFDESTRUCT that moves value", selfdestruct, WRITE_RECORD_SIZE), + ("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) in sites { + 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(bytes).expect("the record has a price"); + 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}"); @@ -836,14 +850,15 @@ fn test_the_fresh_slot_boundary_is_the_sum_of_its_parts() { /// 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 cross the limit or fit it, and one gas below it is an out-of-gas under either. +/// 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. #[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: 80 bytes on top of the body. - let records = 2 * WRITE_RECORD_SIZE; - let crosses = mega_evm::TX_BODY_SIZE + records - 1; - let fits = mega_evm::TX_BODY_SIZE + records; + // `A`'s account and `FRESH`'s, and the transfer log: 240 bytes on top of the body. + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let crosses = mega_evm::TX_BODY_SIZE + start - 1; + let fits = mega_evm::TX_BODY_SIZE + start; let charged_at = gas_where_the_write_is_counted(&code, crosses); assert_eq!(gas_where_the_write_is_counted(&code, fits), charged_at); diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 739700ca0..7d0253814 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -3,7 +3,8 @@ //! 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, and the code a creation deploys. A frame that fails keeps nothing, except a creator's +//! 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; @@ -11,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, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -45,6 +46,11 @@ 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) +} + /// Init code that returns `size` zero bytes as the deployed contract. fn constructor_returning(size: u64) -> Bytes { BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() @@ -157,13 +163,19 @@ fn test_what_each_transaction_keeps() { "a value transfer to an existing account", funded().account_balance(CALLEE, U256::from(100)), call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), - records(1), + 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(1), + 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", @@ -171,6 +183,16 @@ fn test_what_each_transaction_keeps() { 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)), @@ -224,7 +246,7 @@ fn test_what_each_transaction_keeps() { "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(2), + records_and_moves(2, 2), ), ( "a child that writes a slot and halts", @@ -251,7 +273,14 @@ fn test_what_each_transaction_keeps() { .account_balance(CALLEE, U256::from(1_000)) .account_balance(EXISTING, U256::from(1)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records(1), + 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", diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 073525e8e..7f3611622 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -29,7 +29,9 @@ use mega_evm::{ TX_GAS_LIMIT_CAP, }, satin_gas_params, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + op_transaction, transfer_log, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; @@ -169,9 +171,10 @@ 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 the +/// system-call reservoir margin off. So op-revm journals the same transfer logs, and the logs of +/// the two are compared as they are. fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); assert_eq!(cfg.gas_params.table(), satin_gas_params().table()); @@ -180,7 +183,8 @@ 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.enable_amsterdam_eip7708); + assert!(!cfg.amsterdam_eip7708_disabled); assert!(!cfg.system_call_state_gas_margin_in_reservoir); } @@ -223,7 +227,13 @@ 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_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. + if !runs_at_measurement_prices() { + assert_eq!(mega.gas.history, (TX_BODY_SIZE + WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE); + } } /// A nested value call above the execution cap, where the reservoir is what pays the history. diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 61480c458..73a720f8d 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -18,10 +18,11 @@ use mega_evm::{ IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, - test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + 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, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -864,16 +865,18 @@ enum Run { /// 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. The one site they part at is an Oracle hint, whose payload is data -/// size and never history. None of these cases draws on an allowance, so the history gas is the -/// bytes at the price as well. +/// 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); + type Case = + (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64); let cases: [Case; 23] = [ ( "the body", @@ -882,6 +885,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE, 0, + 0, ), ( "calldata", @@ -890,6 +894,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + 100, 0, + 0, ), ( "an access list", @@ -898,6 +903,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + 3 * ACCESS_LIST_ADDRESS_SIZE + 3 * ACCESS_LIST_SLOT_SIZE, 0, + 0, ), ( "authorizations, one applied", @@ -906,6 +912,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "a log", @@ -914,6 +921,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + log_bytes(2, 50), 0, + 0, ), ( "a log a reverted child emitted", @@ -925,6 +933,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE, 0, + 0, ), ( "a storage write", @@ -933,6 +942,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "a storage write written back", @@ -947,6 +957,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE, 0, + 0, ), ( "a value transfer's two records", @@ -955,6 +966,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, + 1, ), ( "a SELFDESTRUCT's beneficiary", @@ -963,6 +975,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 1, ), ( "a creation transaction's code", @@ -971,6 +984,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + deploying().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, 0, + 0, ), ( "a nested creation's code", @@ -979,6 +993,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + DEPLOYED, 0, + 0, ), ( "a failed creation: its creator's nonce, and no code", @@ -987,6 +1002,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "output EIP-3541 refuses to deposit", @@ -995,6 +1011,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "output past the code-size limit", @@ -1003,6 +1020,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "a creation transaction whose output EIP-3541 refuses", @@ -1011,6 +1029,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + refused_code().len() as u64, 0, + 0, ), ( "a call an interceptor answers without a frame", @@ -1022,6 +1041,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, + 0, ), ( "a value call an interceptor refuses without a frame", @@ -1030,6 +1050,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE, 0, + 0, ), ( "a creation an inspector answers without running it", @@ -1038,6 +1059,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::AnsweringCreations, TX_BODY_SIZE, 0, + 0, ), ( "a first frame answered with the stop", @@ -1046,6 +1068,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Limited(TX_BODY_SIZE + WRITE_RECORD_SIZE - 1), TX_BODY_SIZE, 0, + 0, ), ( "a stop at a child's write", @@ -1060,6 +1083,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Limited(TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1), TX_BODY_SIZE, 0, + 0, ), ( "a hint sent by the transaction: its calldata is history, its payload is not", @@ -1068,6 +1092,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE + hint_call().len() as u64, 1, + 0, ), ( "a hint sent from a frame", @@ -1079,10 +1104,11 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { Run::Plain, TX_BODY_SIZE, 1, + 0, ), ]; - for (name, db, tx, run, bytes, hints) in cases { + for (name, db, tx, run, bytes, hints, moves) in cases { for gas_limit in GAS_LIMITS { let limit = match run { Run::Limited(limit) => limit, @@ -1106,10 +1132,16 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 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, - "{name} at {gas_limit}: the data size is the history bytes and the hints' payloads", + 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, diff --git a/crates/mega-evm/tests/satin/kv_limit.rs b/crates/mega-evm/tests/satin/kv_limit.rs index 0eff736bb..be7277798 100644 --- a/crates/mega-evm/tests/satin/kv_limit.rs +++ b/crates/mega-evm/tests/satin/kv_limit.rs @@ -137,13 +137,14 @@ fn slot_written(outcome: &MegaTransactionOutcome, address: Address, slot: u64) - /// slot is no change, and the sender is the body's. #[test] fn test_the_kv_count_is_the_write_records_kept() { - let cases: [(&str, Bytes, u64); 7] = [ - ("an empty call", Bytes::new(), 0), - ("three fresh slots", slots(3), 3), + let cases: [(&str, Bytes, u64, u64); 7] = [ + ("an empty call", Bytes::new(), 0, 0), + ("three fresh slots", slots(3), 3, 0), ( "zero written to an empty slot", BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(), 0, + 0, ), ( "one slot written twice", @@ -153,6 +154,7 @@ fn test_the_kv_count_is_the_write_records_kept() { .stop() .build(), 1, + 0, ), ( "one slot written and written back", @@ -162,22 +164,31 @@ fn test_the_kv_count_is_the_write_records_kept() { .stop() .build(), 0, + 0, ), ( "a value transfer: the frame's account and the recipient", then_call(BytecodeBuilder::default(), B, 1).stop().build(), 2, + 1, ), ( "a destruction that moves value: its beneficiary", BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(), 1, + 1, ), ]; - for (name, code, kept) in cases { + for (name, code, kept, transfer_logs) in cases { let outcome = run_kv(funded().account_code(A, code), u64::MAX); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!(outcome.usage, records(kept), "{name}"); + let transfer_log_bytes = transfer_logs * mega_evm::TRANSFER_LOG_SIZE; + let expected = records(kept); + assert_eq!( + outcome.usage, + LimitUsage { data_size: expected.data_size + transfer_log_bytes, ..expected }, + "{name}: the records, and the transfer log of the value it moved" + ); } let transfer = run_under( @@ -186,7 +197,14 @@ fn test_the_kv_count_is_the_write_records_kept() { EvmTxRuntimeLimits::no_limits(), ); assert!(transfer.result.is_success()); - assert_eq!(transfer.usage, records(1), "a value transaction records its recipient alone"); + assert_eq!( + transfer.usage, + LimitUsage { + data_size: records(1).data_size + mega_evm::TRANSFER_LOG_SIZE, + write_records: 1 + }, + "a value transaction records its recipient alone, beside its transfer log" + ); } /* ---------- the transaction's limit ---------- */ diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index b82dfe4df..24091100f 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -460,13 +460,13 @@ fn test_a_frame_revm_decides_is_held_for_its_upfront_charge() { } /// The records a frame's start makes are held before revm builds the frame, and its upfront state -/// gas after revm has decided it. A value call whose records cross the data-size limit is answered -/// with that stop, adds no account, and gives its upfront charge back: the state-gas limit that -/// charge would have crossed is not. +/// gas after revm has decided it. A value call whose records and transfer log cross the data-size +/// limit is answered with that stop, adds no account, and gives its upfront charge back: the +/// state-gas limit that charge would have crossed is not. #[test] fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { let account = one_account(); - let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE - 1; + let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; let db = funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()); let outcome = MegaEvm::new( @@ -486,7 +486,7 @@ fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { used: limit + 1, frame_local: false, }), - "the caller's account and the recipient's, over the limit by one byte", + "the caller's account, the recipient's and the transfer log, over the limit by one byte", ); assert_eq!(outcome.gas.state, 0); } diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 639dfaf40..3d96b8798 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -13,6 +13,10 @@ //! 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; @@ -20,9 +24,9 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, storage_call_stipend, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{BytecodeBuilder, MemoryDatabase}, + test_utils::{is_transfer_log, transfer_log, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - STORAGE_CALL_STIPEND_BYTES, TX_BODY_SIZE, WRITE_RECORD_SIZE, + STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, POP, @@ -84,6 +88,11 @@ fn db(sender_code: Bytes, receiver_code: Bytes) -> MemoryDatabase { .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(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { MegaEvm::new(context(db)).execute_transaction(tx).expect("the transaction is valid") } @@ -126,7 +135,12 @@ fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { let outcome = run(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.result.logs().len(), 1, "the hook emitted its event"); + 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(), @@ -303,7 +317,7 @@ fn test_an_intercepted_call_neither_takes_nor_adds_an_allowance() { let one = run(with_controls(one_event), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); assert!(one.result.is_success(), "{:?}", one.result); - assert_eq!(one.result.logs().len(), 1, "the receiver still had its allowance"); + 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 = run(with_controls(two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); @@ -421,7 +435,8 @@ fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { let outcome = run(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.result.logs().len(), 2, "both hops emitted their event"); + 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!( @@ -525,10 +540,16 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { 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. + // 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(200); + 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), @@ -594,6 +615,6 @@ fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { run(db(sender, event().append(STOP).build()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.result.logs().len(), 1, "the hook emitted its event"); + 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/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 8a6d91c18..47dbf7ae8 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -7,6 +7,9 @@ //! 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; @@ -15,9 +18,9 @@ use mega_evm::{ IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, - test_utils::{BytecodeBuilder, MemoryDatabase}, - LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, StagedRecord, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + test_utils::{is_transfer_log, BytecodeBuilder, MemoryDatabase}, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, + TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -89,7 +92,11 @@ fn test_two_value_calls_record_the_sender_once() { 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"); + 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. @@ -100,7 +107,11 @@ fn test_create_then_call_record_the_frame_account_once() { 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"); + 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. @@ -111,7 +122,11 @@ fn test_two_creates_record_the_creator_once() { 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"); + 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. @@ -148,7 +163,11 @@ fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { 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"); + 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"); @@ -222,7 +241,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_only(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 @@ -270,7 +289,11 @@ fn test_nested_self_call_with_value_counts_once() { /// nothing. #[test] fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { - assert_eq!(nested_delta(&[B, SELF_CALLER]), records_only(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 ---------- */ @@ -347,16 +370,17 @@ fn test_log_counts_its_bytes() { } /// `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), CONTRACT, with_extra(records(1), TRANSFER_LOG_SIZE)), (U256::from(5), CALLEE, body_only()), - (U256::from(5), CALLER, body_only()), + (U256::from(5), CALLER, with_extra(body_only(), TRANSFER_LOG_SIZE)), (U256::ZERO, CONTRACT, body_only()), ]; for (balance, beneficiary, expected) in cases { @@ -559,7 +583,11 @@ 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, with_extra(records(1), mega_evm::AUTHORIZATION_SIZE)); + 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 @@ -612,7 +640,11 @@ fn test_frames_running_as_the_sender_do_not_record_it() { 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. @@ -783,7 +815,11 @@ fn test_value_receiving_child_records_itself_once() { 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 @@ -808,7 +844,11 @@ fn test_zero_value_child_starts_unrecorded() { .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"); + 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`. @@ -834,7 +874,11 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { 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 @@ -857,8 +901,8 @@ 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), - "the created account, CONTRACT2" + with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), + "the created account, CONTRACT2, and two transfer logs" ); } @@ -877,7 +921,7 @@ fn test_top_level_self_call_counts_the_sender_as_recorded() { 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. @@ -919,7 +963,11 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { 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 ---------- */ @@ -937,6 +985,9 @@ struct Paired { /// 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, } @@ -978,6 +1029,7 @@ fn paired_corpus() -> Vec { other_bytes, records, hint_bytes: 0, + transfer_logs: 0, beneficiary: Address::ZERO, }; let to_callee = |code: Bytes| funded().account_code(CALLEE, code); @@ -1007,7 +1059,10 @@ fn paired_corpus() -> Vec { 0, 1, ), - case("a value transfer", to_callee(calling(CONTRACT, 1)), plain(), 0, 2), + 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()), @@ -1031,15 +1086,21 @@ fn paired_corpus() -> Vec { 32 + 2 * 32 + 32, 0, ), - case( - "a nested creation", - to_callee( - append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(), - ), - plain(), - 0, - 2, - ), + 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)), @@ -1047,16 +1108,19 @@ fn paired_corpus() -> Vec { 0, 1, ), - case( - "a destruction that moves value", - to_callee( - BytecodeBuilder::default().push_address(CONTRACT).append(SELFDESTRUCT).build(), + 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, ) - .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()) @@ -1073,13 +1137,16 @@ fn paired_corpus() -> Vec { 0, 0, ), - case( - "a value transaction", - funded(), - call(CALLER, CONTRACT, U256::from(1), GAS_LIMIT), - 0, - 1, - ), + 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), @@ -1102,8 +1169,9 @@ fn paired_corpus() -> Vec { 0, 0, ), - // The two cases where a transaction's data size and its history part company. Both are - // decisions, stated in the byte table; each is written out here with the number it pays. + // 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( @@ -1121,6 +1189,7 @@ fn paired_corpus() -> Vec { }, 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))), @@ -1138,6 +1207,11 @@ fn paired_corpus() -> Vec { ] } +/// 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 { @@ -1158,11 +1232,12 @@ fn send_hint(data: &[u8]) -> Bytes { /// 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 the last two cases are where a transaction's two totals part: -/// an Oracle hint's payload is data size that is not history, and a transfer to the block -/// beneficiary pays a record the transaction body's five already bound. Both 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. +/// 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() { @@ -1179,12 +1254,19 @@ fn test_every_kept_write_pays_one_record_of_history() { .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 expected = (body + case.other_bytes + case.records * WRITE_RECORD_SIZE) * CPHB; - assert_eq!(outcome.gas.history, expected, "{}: the history it pays", case.name); + 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, - body + case.other_bytes + case.records * WRITE_RECORD_SIZE + case.hint_bytes, + history_bytes + case.hint_bytes + case.transfer_logs * TRANSFER_LOG_SIZE, "{}: the data size the limit counts", case.name, ); @@ -1230,7 +1312,11 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { 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, records(2), "the transfer that ran wrote two accounts"); + 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 @@ -1262,7 +1348,7 @@ impl Inspector, EthInterpreter> for KvWeighsNoMore /// 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 deployed code and the hint's payload. +/// logs — the transfer logs among them — the deployed code and the hint's payload. /// /// So a KV limit binds only below the data-size limit's fortieth: at the production data-size /// caps a transaction keeps at most 327,680 records, whatever its KV limit. @@ -1281,7 +1367,10 @@ fn test_the_kv_count_never_weighs_more_than_the_data_size() { 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, + 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, ); diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index aa491e480..26208b50c 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -151,20 +151,25 @@ fn test_a_fixture_ethereum_filled_passes_in_equivalence_mode() { /// 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. +/// 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(); - let unit = unit(&[Fork::Osaka], json!({ "gasLimit": ["0x0f4240"] })); - 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]); - - let report = run(&[path], config(Mode::Satin, Fork::Osaka)); - assert_eq!(failure_kind(outcomes(&report)[0]), Some(FailureKind::StateRootMismatch)); - let summary = report.summary(); - assert_eq!(summary.unattributed, 1, "Satin mode attributes nothing"); - assert!(summary.deviated.is_empty()); + 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. From 8ddd0ec404c8ff8cd3f2fe1c18d583fa5f3cff34 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:53:12 -0700 Subject: [PATCH 119/458] test(satin): give BytecodeBuilder the programs that move value call, callcode, create, create2 and selfdestruct move value the way a test of EIP-7708 needs; log3_word is the shape of a transfer log; return_returndata, revert_with_returndata and return_top hand a result back to the transaction. --- crates/mega-evm/src/test_utils/opcode_gen.rs | 133 ++++++++++++++++++- 1 file changed, 130 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs index a5dca8e55..641cf2031 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; @@ -156,14 +157,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 +275,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); From 927de0542b5f5891ad297d6bb5f0c87fc49ae55c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:53:12 -0700 Subject: [PATCH 120/458] test(satin): hold a transfer log to no gas on any ledger Every way a transaction moves value runs with EIP-7708 switched off and on, below the execution cap and above it: the gas on every ledger, the history bytes, the write records and the state are the same, and the transfer logs add 160 bytes of data size each and nothing else. A crate-private constructor builds the configuration without the switch for the comparison; no caller can. --- crates/mega-evm/src/evm/context.rs | 10 ++ crates/mega-evm/src/evm/history.rs | 159 +++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index d3b032270..307c7945c 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -137,6 +137,16 @@ impl MegaContext { 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 diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index 94e1aa4ed..16730b2c7 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -144,6 +144,165 @@ mod tests { 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] From 7d0a627526d29c48ed6a8799d782b763da6ef792 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 17:57:24 -0700 Subject: [PATCH 121/458] test(satin): pin the transfer log's count at every site that moves value The transaction's value, its creation's endowment, a value CALL to a contract, to an account without code and to a precompile, a CREATE's and a CREATE2's endowment, and a SELFDESTRUCT's balance, each below and above the execution cap: the exact bytes it adds and the log the receipt carries, with history left at the body and the records; a frame budget one byte short, which stops the moving frame alone before anything moves; the transaction's limit one byte short, which latches; a failure above the move, which takes the bytes back. Each stop is the one a LOG3 of one word makes where the same bytes are counted. Also what moves nothing to another account and so logs nothing (a CALLCODE, a call to itself, a burn, an unfunded or refused call), a deposit's value against its mint, and a system transaction's value, which no limit stops. --- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/transfer_logs.rs | 685 +++++++++++++++++++ 2 files changed, 686 insertions(+) create mode 100644 crates/mega-evm/tests/satin/transfer_logs.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 1bdbc888e..ff4a9d590 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -32,4 +32,5 @@ mod static_callee; mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; +mod transfer_logs; mod write_records; 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..d6e92a7f6 --- /dev/null +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -0,0 +1,685 @@ +//! 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 stops the transaction; 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. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, keccak256, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + history_gas, + 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, MegaEvm, + MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP}, + context::TxEnv, +}; + +use crate::common::context; + +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"); + +/// 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 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())) + } + } + } +} + +/// 98% of `remaining`, the share a child frame is given. +fn share(remaining: u64) -> u64 { + (u128::from(remaining) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / + u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 +} + +/// 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 +} + +fn execute( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid") +} + +/// 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` 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(db, tx, EvmTxRuntimeLimits::no_limits()); + + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!( + transfer_logs(&outcome), + [transfer_log(site.sender(), site.recipient(), U256::from(VALUE))], + "{case}: the receipt's transfer log", + ); + assert_eq!(balance(&outcome, site.recipient()), U256::from(VALUE), "{case}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body + site.bytes(), write_records: site.records() }, + "{case}: the body, the records and one transfer log", + ); + let history_bytes = body + site.records() * WRITE_RECORD_SIZE; + assert_eq!(outcome.gas.history_bytes, history_bytes, "{case}: no history bytes"); + assert_eq!(outcome.gas.history, history_gas(history_bytes).unwrap(), "{case}"); + 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 nothing is latched. The transaction's own +/// frame has no caller, so its stop reverts the transaction, still without a latch. +/// +/// 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(db, tx, limits), body) + }; + + let (fits, _) = run(cap); + assert!(fits.result.is_success(), "{case}: at the budget: {:?}", fits.result); + assert_eq!(fits.limit_exceeded, None, "{case}"); + + let (over, body) = run(cap - 1); + assert_eq!(over.limit_exceeded, None, "{case}: a frame budget latches nothing"); + 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 transaction there: it latches, the +/// stop names the data size and the limit, the whole transaction reverts, and the move's bytes are +/// reported in the figure that crossed. A `LOG3` of one word where the transfer log is, after the +/// same bytes of records, crosses the same way. At the transaction's own frame, whose budget is +/// the limit, a limit of exactly the bytes holds. +#[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(db, tx, limits), body, limit) + }; + + let (outcome, body, limit) = run(1); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: body + site.bytes(), + frame_local: false, + }), + "{case}: the transaction is stopped at the move", + ); + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{case}"); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + assert_eq!( + outcome.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the stop is what the transaction reports", + ); + assert!(outcome.result.logs().is_empty(), "{case}: every log went"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + if variant == Variant::Plain { + let to = site.recipient(); + assert_eq!(balance(&outcome, to), U256::ZERO, "{case}: no value moved"); + } + assert_reservoir_paid(&case, gas_limit, &outcome); + + if site.depth() == 0 { + let (fits, _, _) = run(0); + assert!(fits.result.is_success(), "{case}: at the limit: {:?}", fits.result); + } + } + } + } +} + +/// 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(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 the caller cannot fund, or 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; + let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize); 8] = [ + ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 1, 0), + ("a CALL to itself", db(actor().call(ACTOR, value)), 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 the caller cannot fund", + db(actor().call(RECEIVER, U256::from(100 * VALUE))), + call(ACTOR, 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(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( + 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(db(actor()), call(DESTRUCTOR, 0), EvmTxRuntimeLimits::no_limits()); + assert_eq!(balance(&older, DESTRUCTOR), value, "an older account keeps its balance"); +} + +/// 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() { + const DEPOSITOR: Address = address!("0000000000000000000000000000000000d000de"); + let deposit = |mint: u128, value: u64| { + let mut tx = OpTx(op_transaction(TxEnv { + caller: DEPOSITOR, + kind: TxKind::Call(RECEIVER), + value: U256::from(value), + gas_limit: 1_000_000, + gas_price: 0, + ..Default::default() + })); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.deposit.mint = Some(mint); + tx + }; + let db = || MemoryDatabase::default().account_code(RECEIVER, Bytes::from_static(&[STOP])); + + let tx = deposit(1_000, 400); + let body = transaction_body_bytes(&tx); + let outcome = execute(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(db(), deposit(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( + db(), + deposit(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 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])) + }; + 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(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(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", + ); + } +} From b060196aebeba4348dabfb6f55ce65cd947e3026 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 18:00:18 -0700 Subject: [PATCH 122/458] test(block): pin the transfer logs in a block's receipts A block with a value transfer, a value call a contract passes on after an event of its own, a creation with an endowment and a destruction: each receipt carries its transfer logs in execution order around the contract's event, its bloom is its logs' and includes them, and the block's data size counts them while its history bytes do not. A deposit's receipt logs its value and not its mint; a system transaction moves no value and logs no transfer. --- crates/mega-evm/tests/block/main.rs | 1 + crates/mega-evm/tests/block/transfer_logs.rs | 224 +++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 crates/mega-evm/tests/block/transfer_logs.rs diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 9263eb4f1..006e68c14 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -14,3 +14,4 @@ mod rules; mod salt; mod schedule; mod state_gas; +mod transfer_logs; 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..fedbf3bad --- /dev/null +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -0,0 +1,224 @@ +//! 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, Signed, TxLegacy, TxReceipt}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{ + address, logs_bloom, Address, BloomInput, Bytes, Log, Signature, 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, database::State}; + +use crate::common::{self, executor, CALLER, CHAIN_ID}; + +/// 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 legacy transaction from `signer` with `value`. +fn legacy( + signer: Address, + nonce: u64, + to: TxKind, + value: u64, + input: Bytes, +) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 1_000_000, + gas_limit: 1_000_000, + to, + value: U256::from(value), + input, + }; + let signed = Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(nonce as u8 + 0x10), + ); + Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), signer) +} + +/// 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: 1_000_000, + 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"); +} From a53f6acc21a7aa2115f40534287893d44c87230e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 18:00:18 -0700 Subject: [PATCH 123/458] test(satin): pin that SLOTNUM pushes the block's slot number The value a node supplies in BlockEnv::slot_num, and zero for a block that leaves it unset. --- crates/mega-evm/tests/satin/schedule.rs | 36 +++++++++++++------------ 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 6f02c7485..80ede9f8d 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -295,22 +295,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"); } From b4790701038230d913406b1e8567fee7a32002fc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 18:02:07 -0700 Subject: [PATCH 124/458] docs(satin): say that value movements are logged and what the logs count AGENTS.md and the crate README: EIP-7708 is on and not disabled; every value movement leaves a transfer log in the receipt; the log is data size, counted by the rule a LOG3 of one word is where the value moves, and neither history nor a record, so data size and history part at a third site; a deposit's mint and a destruction to itself log nothing; SLOTNUM pushes the node's slot number. The module table drops EIP-7708 and SLOTNUM from what is still to come. The state-test README names the logs among what Satin mode differs on. --- AGENTS.md | 40 +++++++++++++++++++------------- crates/mega-evm/README.md | 11 ++++++--- crates/mega-state-test/README.md | 2 +- 3 files changed, 33 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3b545fa90..2c9f11ba8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,28 +99,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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | -| `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | -| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `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 SALT pricing hook, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`) and the debug-build check that revm journaled the transfer log a frame start counted (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | +| `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/` | 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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | +| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`, `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`) | — | ### 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, 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 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, 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. 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. @@ -137,14 +138,20 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 two sites, both by decision — an Oracle hint's payload is data size that is never history, 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. + 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 and binds nothing: history charges the same bytes at a higher rate. - 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 debug build asserts after every frame start that revm 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, a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, deployed code revm would deposit before the creation is committed (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 before it is forwarded. + 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, 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 revm would deposit before the creation is committed (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 before it is forwarded. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (see the block executor below). @@ -190,6 +197,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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, 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. @@ -237,9 +245,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 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. + `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: 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. + 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/`) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 6f5b76d53..ee65643cf 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -29,6 +29,9 @@ Today it runs transactions through its own handler over op-revm's, with EIP-8037 The gas schedule is Amsterdam's with three changes: the entries EIP-8038 repriced go back to their Osaka values, 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. @@ -39,7 +42,8 @@ The common execution layer is in place: the frame lifecycle the later mechanisms 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. +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 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. `EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB of data size. @@ -81,12 +85,13 @@ The last two are held to no per-transaction limit either, for the same reason 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; 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. +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 byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, and a body counts its five fixed write records even when fewer fee accounts are written. +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. The KV and state-gas limits are in place too. 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 the KV limit holds it by the data-size limit's rules: a transaction limit that stops the transaction, and a record budget per frame, 98% of what the parent has left. diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 81e541529..dd0c46d64 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -11,7 +11,7 @@ The library keeps the `state_test` import name. 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, history and the access entries it pressed back on purpose, so almost every stateful fixture differs; the count is what CI shows, and it never fails the job. + Satin prices state, history and the access entries it pressed back on purpose, 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. From 6f6599b6ebfbac4c0e44dfd2e7f734fc08dc500d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 18:03:26 -0700 Subject: [PATCH 125/458] bench(satin): run 200 value calls next to op-revm transact/value_calls sends one wei 200 times to an account with no code, which revm answers without running: every frame start counts its records and its transfer log before revm moves the value. The run before measuring is held to 200 transfer logs, each counted. --- crates/mega-evm/benches/transact.rs | 33 ++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 5d1ef2b7f..88bcf27db 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -17,6 +17,9 @@ //! 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. +//! - `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. //! - `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 @@ -51,10 +54,12 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + is_transfer_log, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, - MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + MegaSpecId, TestExternalEnvs, 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::{ @@ -77,6 +82,7 @@ const SALT_CALLER: Address = address!("0x000000000000000000000000000000000010000 const INTERCEPTED: Address = address!("0x0000000000000000000000000000000000100007"); const MISSING: Address = address!("0x0000000000000000000000000000000000100008"); const LIMITED: Address = address!("0x0000000000000000000000000000000000100009"); +const VALUE_CALLER: Address = address!("0x000000000000000000000000000000000010000a"); /// A selector `MegaAccessControl` intercepts, and one it does not. const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; @@ -198,6 +204,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) @@ -275,6 +290,8 @@ fn bench_transact(c: &mut Criterion) { .account_code(INTERCEPTED, system_caller_code(IS_DISABLED)) .account_code(MISSING, system_caller_code(UNKNOWN_SELECTOR)) .account_code(LIMITED, limited_code()) + .account_balance(VALUE_CALLER, U256::from(REPEAT)) + .account_code(VALUE_CALLER, value_caller_code()) .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); let cfg = mega_context(db.clone()).cfg().clone(); @@ -289,6 +306,7 @@ fn bench_transact(c: &mut Criterion) { ("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)), + ("value_calls", call_tx(VALUE_CALLER, Bytes::new(), 30_000_000)), ]; let mut group = c.benchmark_group("transact"); @@ -320,6 +338,15 @@ fn bench_transact(c: &mut Criterion) { 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", + ); + } _ => {} } group.bench_function(format!("{workload}/satin"), |b| { From 4be009a702334b623a892530dc87689c5ae679f2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 18:57:31 -0700 Subject: [PATCH 126/458] feat(satin): run a keyless deployment as a native creation A depth-0 keylessDeploy call is rewritten, before interception and before an inspector sees it, into a CREATE frame the signer starts at its Nick's-Method address. The call becomes a frame no code runs in: its lane and journal checkpoint are pushed, it pays the fixed overhead and what the CREATE opcode charges its frame (the signer's account when the nonce bump creates it, the created account, the two frame-start records), and it forwards the override capped to what it has left. The creation's result is settled into it and answered in the IKeylessDeploy ABI. --- crates/mega-evm/src/evm/context.rs | 9 +- crates/mega-evm/src/evm/execution.rs | 76 ++-- crates/mega-evm/src/limit/limit.rs | 32 +- crates/mega-evm/src/limit/mod.rs | 1 + crates/mega-evm/src/system/intercept.rs | 27 +- .../mega-evm/src/system/keyless/dispatch.rs | 414 +++++++++++++++--- crates/mega-evm/src/system/keyless/mod.rs | 66 ++- crates/mega-evm/src/system/keyless/settle.rs | 244 +++++++++++ crates/mega-evm/tests/satin/equivalence.rs | 113 +++-- .../tests/satin/synthetic_frame_gas.rs | 8 +- .../mega-evm/tests/system/keyless/charges.rs | 250 +++++++++++ .../mega-evm/tests/system/keyless/deploy.rs | 24 + .../{keyless.rs => keyless/dispatch.rs} | 80 ++-- crates/mega-evm/tests/system/keyless/mod.rs | 210 +++++++++ 14 files changed, 1340 insertions(+), 214 deletions(-) create mode 100644 crates/mega-evm/src/system/keyless/settle.rs create mode 100644 crates/mega-evm/tests/system/keyless/charges.rs create mode 100644 crates/mega-evm/tests/system/keyless/deploy.rs rename crates/mega-evm/tests/system/{keyless.rs => keyless/dispatch.rs} (71%) create mode 100644 crates/mega-evm/tests/system/keyless/mod.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e2b916b65..57917c676 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -18,7 +18,7 @@ use crate::{ history::transaction_body_bytes, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{self, MEGA_SYSTEM_ADDRESS}, + system::{self, keyless::KeylessCall, MEGA_SYSTEM_ADDRESS}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, }; @@ -55,6 +55,10 @@ pub struct MegaContext, /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. #[cfg(any(test, feature = "test-utils"))] neutral: bool, @@ -85,6 +89,7 @@ impl MegaContext { bucket_multipliers: BucketMultipliers::default(), system_originated: false, prices_history: true, + keyless_call: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -301,6 +306,8 @@ impl MegaContext { fn prepare(&mut self, system_originated: bool) { self.additional_limit.reset(); self.bucket_multipliers.reset(); + // A transaction that failed with an error left its `keylessDeploy` call unsettled. + self.keyless_call = None; self.system_originated = system_originated; let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; self.set_history_exempt(exempt); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index da61ced87..88e63ab42 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -48,7 +48,11 @@ use revm::{ use crate::{ evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, - system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, + system::{ + is_deposit_like_transaction, + keyless::{self, Rewrite}, + MEGA_SYSTEM_ADDRESS, + }, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, MegaInstructions, }; @@ -257,12 +261,20 @@ where /// 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. + /// + /// The outermost frame of a keyless deployment is the creation its `keylessDeploy` call + /// started, and the call is the transaction's own frame: the creation's result is settled into + /// the call first, which answers in the `IKeylessDeploy` ABI ([`keyless::settle`]). The + /// translation is made here, where every first-frame result arrives — a creation answered at + /// its start never returns through the frame lifecycle — and after the inspector saw the + /// creation end. fn last_frame_result( &mut self, evm: &mut Self::Evm, frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { + keyless::settle::<_, _, Self::Error>(evm.ctx_mut(), frame_result)?; evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); self.op.last_frame_result(evm, frame_result, parent_gas)?; // The write record the transaction's own frame makes was charged before execution; a @@ -398,9 +410,11 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Some(answer), + Rewrite::Rewritten | Rewrite::NotKeyless => self.intercept(&frame_init), + }; + if let Some(mut result) = answer { self.inner.ctx.additional_limit.push_empty_frame(); hold_upfront_state_gas(&mut self.inner.ctx, Some(&mut result)); 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() { @@ -518,9 +536,12 @@ impl EvmTr for MegaEvm Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); + let keyless = keyless::rewrite(ctx, &mut frame_init)?; 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 @@ -589,6 +616,12 @@ where frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } + if let Rewrite::Answered(mut output) = keyless { + ctx.additional_limit.push_empty_frame(); + hold_upfront_state_gas(ctx, Some(&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(); let logs_i = ctx.journal().logs().len(); if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { @@ -797,27 +830,14 @@ 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 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 + crate::system::intercept(&mut self.inner.ctx, inputs) } } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 9193c985c..9dfd55eb2 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -632,12 +632,12 @@ impl AdditionalLimit { /// 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, and the count here, on the input that - /// survived interception and the keyless rewrite. They agree because the rewrite is the - /// identity today. The mechanism that makes it rewrite a call into a creation — native - /// keyless deployment — changes which records a frame's start makes, and must reconcile the - /// charge with them; until it does, a divergence trips here in every debug build rather than - /// mis-charging the caller and mis-splitting the refund its failure gets back. + /// opcode, on the input revm's instruction built, or at the keyless rewrite, 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: the keyless rewrite runs at the transaction's + /// own frame, which no opcode starts, and charges for the creation it builds itself. 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, @@ -683,6 +683,26 @@ impl AdditionalLimit { } } + /// 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. + pub(crate) fn set_frame_creator(&mut self, creator: Address) { + let sender = self.sender; + if let Some(lane) = self.tracker.current_mut() { + lane.address = Some(creator); + lane.account_recorded = creator == sender; + } + } + + /// The number of frames with a lane: the frames on the call stack, and a `keylessDeploy` call + /// whose creation is running. + pub(crate) fn frame_depth(&self) -> usize { + self.tracker.depth() + } + /// Pushes the lane of a frame answered without running: a result built without an /// interpreter keeps the lanes aligned with the frames revm returns. /// diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0c59b5d0d..ffe06aad6 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -130,6 +130,7 @@ mod record; mod state_gas; pub use limit::AdditionalLimit; +pub(crate) use limit::FrameStartRecords; pub(crate) use record::HistoryBytes; pub use record::StagedRecord; diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index a2b5c40d6..9cafecaea 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 rewrite 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,15 +70,17 @@ 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 rewrite 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, @@ -108,21 +110,20 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option( ctx: &mut MegaContext, - inputs: &mut CallInputs, - depth: usize, + inputs: &CallInputs, ) -> 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::KeylessDeploy => None, InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs), InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 133643156..73e47f9e2 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -1,75 +1,389 @@ -//! 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 is rewritten +//! into. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::ops::Range; +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::{ + context::{Cfg, ContextError, ContextTr, JournalTr, Transaction}, + context_interface::{ + cfg::{GasId, StateGasCharge, StateGasSite}, + journaled_state::JournalCheckpoint, + Host, + }, handler::FrameResult, - interpreter::{CallInputs, InstructionResult}, + interpreter::{ + interpreter_action::FrameInit, CallInputs, CallScheme, CreateInputs, CreateScheme, + FrameInput, Gas, InstructionResult, + }, + primitives::KECCAK_EMPTY, }; use crate::{ + 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, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, }, - ExternalEnvTypes, MegaContext, + untouched_call_gas, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, MegaContext, }; -/// Recognises a `keylessDeploy` call and charges it, or answers it when it cannot go on. +/// What the keyless rewrite made of a frame about to start. +#[derive(Debug)] +pub(crate) enum Rewrite { + /// The frame is not a keyless deployment; it starts as it is. + NotKeyless, + /// The frame is now the creation the `keylessDeploy` call stands for. The call's lane is + /// pushed and its [`KeylessCall`] is on the context, waiting for the creation's result. + Rewritten, + /// The call is answered without a frame: a rule refused it, or it could not pay for what its + /// creation's start makes. Nothing was written and no lane was pushed for it. + Answered(FrameResult), +} + +/// A `keylessDeploy` call rewritten into its creation, from the rewrite until the creation's +/// result is settled into it ([`settle`](super::settle)). +/// +/// The call is a frame no code runs in: its lane is pushed and its journal checkpoint taken as +/// any frame's, and its gas holds what it paid before its creation started. The creation is its +/// child, and returns into it as a creation returns into the frame whose `CREATE` started it. +#[derive(Debug)] +pub(crate) struct KeylessCall { + /// The call's gas: the gas and the reservoir the transaction's frame was forwarded, less the + /// overhead, the upfront charges and the gas forwarded to the creation. + pub(super) gas: Gas, + /// The journal checkpoint taken before the creation's start wrote anything. + pub(super) checkpoint: JournalCheckpoint, + /// The address the creation deploys at. + pub(super) deploy_address: Address, + /// The call's return range. + pub(super) memory_offset: Range, + /// Whether the transaction's own start charged the call a new account. + pub(super) charged_new_account_state_gas: bool, + /// The history the creation's lane gave back for the records the creation did not keep. + pub(super) returned_history: u64, +} + +/// Turns a `keylessDeploy` call at the transaction's own frame into the creation it stands for, +/// or answers it; any other frame is [`Rewrite::NotKeyless`]. /// /// # 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 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. +/// A `CALL` to [`KEYLESS_DEPLOY_ADDRESS`] whose first four bytes are the `keylessDeploy` +/// selector, at depth 0: 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. A transaction the latch already +/// stopped is not dispatched either: its frame is answered with the stop. +/// +/// # What the call pays, and what it is held to /// -/// # What it charges +/// In this order, each refusal an answer with the call's 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; a call that +/// cannot pay it is answered out of gas. +/// 2. The call carries no value (`NoEtherTransfer()`). +/// 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`). +/// 8. Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation +/// (`SignerHasCode()`). +/// 9. The deploy address holds no code (`ContractAlreadyExists()`), read cold and without its code, +/// so the address is in the transaction's state and in a witness without its bytecode. +/// 10. The signer can fund the transaction's value (`InsufficientBalance()`). +/// 11. What the `CREATE` opcode would charge its frame for the creation's start: the signer's +/// account when the creation's nonce bump is what creates it, the created account when the +/// deploy address is empty — both state gas, priced by the SALT bucket they land in — and the +/// write records of the two accounts, as history. A call that cannot pay is answered out of +/// gas. +/// 12. 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 +/// A refusal writes nothing, so the answer takes back every charge but the overhead with it. A +/// database read or a SALT lookup that fails fails the transaction with its cause, as it does at +/// every other site. /// -/// 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( +/// # The creation +/// +/// The creation is started as the signer's, at the signer's Nick's-Method address +/// (`CreateScheme::Custom`), at depth 1 below the call: the call's lane is pushed first, as the +/// transaction's own frame's is, and the creation is its child from there on — its share of the +/// data-size and KV budgets, its records, its forward and the reservoir it inherits, the +/// state-gas limit, the latch. The call's journal checkpoint is taken before the creation's +/// start writes the signer's nonce, so a call that is stopped takes that write back with the +/// rest. +#[inline] +pub(crate) fn rewrite( + ctx: &mut MegaContext, + frame_init: &mut FrameInit, +) -> Result> { + match &frame_init.frame_input { + FrameInput::Call(inputs) if is_dispatched(ctx, inputs, frame_init.depth) => { + rewrite_dispatched(ctx, frame_init) + } + _ => Ok(Rewrite::NotKeyless), + } +} + +/// [`rewrite`] of a call [`is_dispatched`] took. Kept out of line: every frame asks whether it is +/// a keyless deployment, one transaction in a great many is. +#[inline(never)] +fn rewrite_dispatched( + ctx: &mut MegaContext, + frame_init: &mut FrameInit, +) -> Result> { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return Ok(Rewrite::NotKeyless) }; + let mut gas = untouched_call_gas(inputs); + let deployment = match prepare(ctx, inputs, &mut gas)? { + Ok(deployment) => deployment, + Err(refusal) => return Ok(Rewrite::Answered(refusal.answer(inputs, gas))), + }; + let memory_offset = inputs.return_memory_offset.clone(); + let charged_new_account_state_gas = inputs.charged_new_account_state_gas; + + // The call's own lane, as the transaction's frame pushes it. A call carrying no value makes + // no record, so its start crosses nothing the body did not. + let _ = ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); + ctx.additional_limit.set_frame_creator(deployment.signer); + ctx.additional_limit.note_caller_state_gas(gas.state_gas_spent()); + if let Some((on_lane, caller)) = deployment.record_charges { + ctx.additional_limit.stage_frame_charge(deployment.records, on_lane, caller); + } + let checkpoint = ctx.journal_mut().checkpoint(); + + 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_call = Some(KeylessCall { + gas, + checkpoint, + deploy_address: deployment.deploy_address, + memory_offset, + charged_new_account_state_gas, + returned_history: 0, + }); + frame_init.frame_input = FrameInput::Create(Box::new(create)); + frame_init.depth += 1; + Ok(Rewrite::Rewritten) +} + +/// Whether `inputs` is a `keylessDeploy` call the rewrite takes: a `CALL` at `depth` 0 to +/// [`KEYLESS_DEPLOY_ADDRESS`] carrying the `keylessDeploy` selector, in a transaction the latch +/// has not stopped. +/// +/// The depth is tested first: every frame below the transaction's own leaves after one +/// comparison. +#[inline] +fn is_dispatched( ctx: &MegaContext, - inputs: &mut CallInputs, + inputs: &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; +) -> bool { + depth == 0 && + inputs.target_address == KEYLESS_DEPLOY_ADDRESS && + inputs.scheme == CallScheme::Call && + ctx.additional_limit.latched().is_none() && + peek_selector(&inputs.input, ctx) == Some(IKeylessDeploy::keylessDeployCall::SELECTOR) +} + +/// A creation the call passed every rule for and paid the start of. +struct Deployment { + signer: Address, + 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 answered instead of rewritten. +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 { + /// 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) = match self { + Self::Rule(error) => (InstructionResult::Revert, encode_error_result(error)), + Self::OutOfGas => { + gas.spend_all(); + (InstructionResult::OutOfGas, Bytes::new()) + } + }; + 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 [`rewrite`] lists; the deployment to start, or why the call is answered. +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, + }); + } + 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 signer_info = ctx.journal_mut().inspect_account(signer, checks_code)?.info.clone(); + 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); + } + if ctx.journal_mut().inspect_account_code_hash(deploy_address)? != 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. The signer's nonce bump + // is what creates an empty signer's account; a caller the opcode starts from exists already. + if signer_info.is_empty() { + let charge = + StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)); + if !gas.record_state_cost(state_gas(ctx, charge)?) { + 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 (Some(on_lane), Some(caller)) = ( + write_record_history_gas(records.on_lane), + write_record_history_gas(u64::from(records.caller)), + ) else { + return Ok(Err(Refusal::OutOfGas)); + }; + if !on_lane.checked_add(caller).is_some_and(|cost| gas.record_history_cost(cost)) { + return Ok(Err(Refusal::OutOfGas)); + } + Some((on_lane, caller)) + } else { + None + }; + + 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, + }); + } + let forwarded = gas.record_regular_cost(gas_limit); + debug_assert!(forwarded, "the forward is capped to what the call has left"); + + Ok(Ok(Deployment { + signer, + 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/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index ce8237db0..7ff0a8f8a 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -1,23 +1,67 @@ -//! 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 rewritten into the creation it +//! stands for, before the frame starts and before any interceptor or inspector sees it +//! ([`rewrite`]). The call becomes a frame no code runs in: 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, seen by +//! an inspector as one, and returned into the call as one returns into the frame that started it. +//! The call then answers in the `IKeylessDeploy` ABI ([`settle`]). There is no second EVM and no +//! state to merge. +//! +//! What the native frame means for a deployment: +//! +//! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. +//! - The signer's nonce is bumped by the creation, as any creator's is, and stays bumped when the +//! deployment fails: that is the replay barrier. A deployment is refused once the signer's nonce +//! is above 1 (`SignerNonceTooHigh`), so a signer gets at most two attempts that fail — the first +//! bumps its nonce to 1, the second to 2 — and a third is refused. +//! - 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 deployed contract's account is charged as the `CREATE` opcode charges it, and 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. +//! - A limit the deployment crosses stops it as it stops any frame: a frame budget reverts the +//! creation, and the call returns `ExecutionReverted` with the limit's revert data; a transaction +//! limit stops the transaction, and the call reverts with the stop, taking back the signer's +//! nonce with everything else. +//! +//! # The error ABI +//! +//! The contract's errors are unchanged, and so are the rules that produce them. Four of them have +//! no producer here: `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. +//! `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, which carries no fallback and +//! reverts with empty data, and so does a `keylessDeploy` call a contract makes: 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::{rewrite, KeylessCall, Rewrite}; +pub(crate) use settle::{give_back_history, settle}; use alloy_primitives::{address, Address}; @@ -32,7 +76,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..4356f5f7e --- /dev/null +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -0,0 +1,244 @@ +//! 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. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +use alloy_evm::Database; +use alloy_primitives::{Address, Bytes}; +use alloy_sol_types::SolCall; +use revm::{ + context::{ + result::{FromStringError, HaltReason, OutOfGasError}, + ContextTr, JournalTr, + }, + handler::FrameResult, + interpreter::{CallOutcome, Gas, InstructionResult, InterpreterResult, SuccessOrHalt}, + primitives::KECCAK_EMPTY, +}; + +use crate::{ + settle_frame_result, + system::keyless::{ + encode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + ExternalEnvTypes, MegaContext, MegaHaltReason, +}; + +use super::dispatch::KeylessCall; + +/// Keeps `refund`, the history gas the creation's lane gave back when the creation returned, for +/// the `keylessDeploy` call that paid it: the creation is the outermost frame revm runs, so no +/// frame of revm's receives it. +pub(crate) fn give_back_history( + ctx: &mut MegaContext, + refund: u64, +) { + if let Some(call) = &mut ctx.keyless_call { + call.returned_history = call.returned_history.saturating_add(refund); + } +} + +/// Settles the result of a keyless deployment's creation into the `keylessDeploy` call that +/// started it, and replaces `result` with the call's own. Nothing to do for a transaction that +/// started no keyless deployment. +/// +/// The call's gas takes the creation's back exactly as a `CREATE`'s frame does +/// ([`settle_frame_result`]): 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. The history of the records the creation did not keep comes +/// back too. The creation's lane was popped when it returned, or is popped here when it never +/// ran. +/// +/// Then the call answers, as a frame that resumes after its child returned would: +/// +/// - with the stop a limit left it, when there is one: the latched one, or its own budget's, which +/// the creator's nonce record a failed creation leaves on its lane can cross. The call reverts +/// with it, and its journal checkpoint goes with the revert, the signer's nonce included; +/// - otherwise with `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 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. +pub(crate) fn settle( + ctx: &mut MegaContext, + result: &mut FrameResult, +) -> Result<(), ERROR> +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + ERROR: From + FromStringError, +{ + let Some(mut call) = ctx.keyless_call.take() else { return Ok(()) }; + // The call's lane and the creation's: the creation returned through the frame lifecycle when + // it ran, and never reached it when it was answered at its start. + if ctx.additional_limit.frame_depth() > 1 { + let refund = ctx.additional_limit.on_frame_return(result); + call.returned_history = call.returned_history.saturating_add(refund); + } + settle_frame_result::<_, ERROR>(ctx, call.gas.tracker_mut(), result)?; + call.gas.refill_history(call.returned_history); + + let (status, output) = match ctx.additional_limit.stop_before_run() { + Some(stop) => (InstructionResult::Revert, stop.revert_data()), + None => answer(ctx, &call, result), + }; + if status.is_ok() { + ctx.journal_mut().checkpoint_commit(); + } else { + ctx.journal_mut().checkpoint_revert(call.checkpoint); + } + *result = FrameResult::Call(CallOutcome { + result: InterpreterResult::new(status, output, call.gas), + memory_offset: call.memory_offset, + was_precompile_called: false, + precompile_call_logs: Vec::new(), + charged_new_account_state_gas: call.charged_new_account_state_gas, + charged_state_gas_address: KEYLESS_DEPLOY_ADDRESS, + }); + Ok(()) +} + +/// The `keylessDeploy` answer of a call whose creation settled into `result`. +/// +/// 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. +fn answer( + ctx: &MegaContext, + call: &KeylessCall, + result: &FrameResult, +) -> (InstructionResult, Bytes) { + let gas_used = creation_gas_used(result.gas()); + let instruction_result = result.instruction_result(); + if instruction_result.is_revert() { + let output = result.interpreter_result().output.clone(); + return failed(KeylessDeployError::ExecutionReverted { gas_used, output }, gas_used); + } + if !instruction_result.is_ok() { + let reason = match SuccessOrHalt::::from(instruction_result) { + SuccessOrHalt::Halt(reason) => reason, + _ => MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic)), + }; + return failed(KeylessDeployError::ExecutionHalted { gas_used, reason }, gas_used); + } + let FrameResult::Create(outcome) = result else { + return refused(KeylessDeployError::NoContractCreated); + }; + let Some(address) = outcome.address else { + return refused(KeylessDeployError::NoContractCreated); + }; + if address != call.deploy_address { + return refused(KeylessDeployError::AddressMismatch); + } + // 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. + let deployed = ctx.journal_ref().state.get(&address).is_some_and(|account| { + account.info.code_hash != KECCAK_EMPTY && !account.is_selfdestructed() + }); + if !deployed { + return failed(KeylessDeployError::EmptyCodeDeployed { gas_used }, gas_used); + } + returned(gas_used, address, Bytes::new()) +} + +/// `keylessDeploy`'s return for a deployment that failed with `error`. +fn failed(error: KeylessDeployError, gas_used: u64) -> (InstructionResult, Bytes) { + returned(gas_used, Address::ZERO, encode_error_result(error)) +} + +/// `keylessDeploy`'s return: a success, whatever the deployment did. +fn returned( + 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()) +} + +/// A revert of the call with `error`. +fn refused(error: KeylessDeployError) -> (InstructionResult, Bytes) { + (InstructionResult::Revert, encode_error_result(error)) +} + +/// 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::*; + + /// 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/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 073525e8e..eb72b6b10 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -11,7 +11,7 @@ //! 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, the `KeylessDeploy` overhead, the system-address transaction, +//! 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. @@ -40,7 +40,7 @@ use revm::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, - context_interface::cfg::{gas_params::Eip2780TxInfo, GasId}, + context_interface::cfg::GasId, inspector::NoOpInspector, state::EvmState, ExecuteEvm, Journal, @@ -536,82 +536,79 @@ 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 rewrite: 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", - ); - 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 what is left once the history ledger - // every Satin transaction carries is taken off is the charge. - 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(); - 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", + mega.state.get(&CREATE2_FACTORY_CONTRACT).map(|account| account.info.code_hash), + Some(CREATE2_FACTORY_CODE_HASH), ); assert_eq!( - op.result.gas().tx_gas_used(), - floor, - "op-revm spends below the floor, so its receipt is the floor", + op.result.output().cloned().unwrap_or_default(), + Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR), + "op-revm runs the method body", ); assert!( - mega.result.gas().tx_gas_used() - op.result.gas().tx_gas_used() - mega.gas.history < - charged, - "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", + op.state.get(&CREATE2_FACTORY_CONTRACT).is_none_or(|account| account.info.is_empty()), + "op-revm deploys nothing", ); + + // 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"); } /// Where Satin leaves op-revm on every transaction: the history gas of the bytes it appends to diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 4e3a9c0f8..39c8f6477 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -436,16 +436,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)), ); } 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..77eea63e3 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -0,0 +1,250 @@ +//! 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 alloy_primitives::Address; +use mega_evm::{ + satin_gas_params, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, write_record_history_gas, + BucketId, ExternalEnvs, MegaContext, MegaSpecId, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{ + bytecode::opcode::{PUSH0, REVERT}, + context_interface::cfg::GasId, +}; + +use super::*; +use crate::common::block; + +/// The length of the runtime the tests deploy. +const RUNTIME_LEN: usize = 5; + +/// The schedule's entry `id`. +fn entry(id: GasId) -> u64 { + satin_gas_params().get(id) +} + +/// The history gas of one write record. +fn record() -> u64 { + write_record_history_gas(1).expect("a record has a price") +} + +/// The history gas of `bytes` bytes. +fn history(bytes: u64) -> u64 { + mega_evm::history_gas(bytes).expect("a byte count has a price") +} + +/// 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, as regular gas; +/// - 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 deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + 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 + 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 + 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 + 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"); + } +} + +/// A Satin context over `db` reading `envs`. +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. +fn bucket(account: Address) -> BucketId { + as SaltEnv>::bucket_id_for_account(account) +} + +/// `envs` with `account`'s bucket at multiplier `m`. +fn crowded(envs: TestExternalEnvs, account: Address, m: u64) -> TestExternalEnvs { + envs.with_bucket_capacity(bucket(account), MIN_BUCKET_SIZE as u64 * m) +} + +/// 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() { + 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", + ); + } + } +} 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..f883804ac --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -0,0 +1,24 @@ +//! What a keyless deployment deploys, and what it reports. + +use alloy_primitives::U256; +use mega_evm::system::keyless::tests::{ + CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, + CREATE2_FACTORY_TX, +}; + +use super::*; + +/// The canonical `CREATE2` factory deploys at its canonical address, from its canonical signer. +#[test] +fn test_the_create2_factory_deploys_at_its_address() { + 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 signer's nonce is spent"); + } +} diff --git a/crates/mega-evm/tests/system/keyless.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs similarity index 71% rename from crates/mega-evm/tests/system/keyless.rs rename to crates/mega-evm/tests/system/keyless/dispatch.rs index fa846c82e..85892d2cd 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 is either rewritten into +//! its deployment or answered. 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, }; +/// 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 @@ -154,35 +159,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/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs new file mode 100644 index 000000000..f485c0fd8 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -0,0 +1,210 @@ +//! `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 dispatch; + +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, + system::keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + test_utils::MemoryDatabase, + EvmTxRuntimeLimits, MegaEvm, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{CODECOPY, PUSH0, RETURN}, + context::result::ExecutionResult, +}; + +use crate::common::{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 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 { + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let mut code = vec![0x60, len, 0x60, 10, PUSH0, CODECOPY, 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] +} + +/// 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 [`CALLER`] over `db` at `gas_limit`, under +/// `limits`. +pub(crate) fn run_with( + db: MemoryDatabase, + data: Bytes, + gas_limit: u64, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.gas_limit = gas_limit; + 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, + ] +} From ffadce1c8acb7dba55e2a95cc0881e3380a2ea5b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:04:31 -0700 Subject: [PATCH 127/458] test(satin): hold keyless deployments to the nine rules Every rule of the legacy engine, its error and what a refusal leaves: the overhead and nothing else. The balance rule asks for the value alone, a failed read or SALT lookup fails the transaction with its cause, and rule 4 counts real nonces, so a signer gets two failing attempts and not a third. Ports the parked rows that pinned the rules. --- crates/mega-evm/tests/_pending/README.md | 27 +- .../tests/_pending/rex2/keyless_deploy.rs | 468 ------------- .../mega-evm/tests/_pending/rex5/db_error.rs | 236 ------- .../tests/_pending/rex5/keyless_fee_free.rs | 487 ------------- .../rex5/keyless_gas_cap_postcap_recheck.rs | 302 -------- .../_pending/rex5/keyless_replay_barrier.rs | 68 -- .../tests/_pending/src/sandbox/execution.rs | 159 ----- .../mega-evm/tests/system/keyless/charges.rs | 56 +- crates/mega-evm/tests/system/keyless/mod.rs | 80 ++- crates/mega-evm/tests/system/keyless/rules.rs | 650 ++++++++++++++++++ 10 files changed, 747 insertions(+), 1786 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/db_error.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs delete mode 100644 crates/mega-evm/tests/_pending/src/sandbox/execution.rs create mode 100644 crates/mega-evm/tests/system/keyless/rules.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5c0826b69..a98539f48 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -33,10 +33,10 @@ Do not add a `_pending/main.rs`. | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | -| native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | +| native keyless deployment | 39 | 39 | 0 | 7 | 32 | 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** | **329** | **304** | **25** | **232** | **90** | **7** | +| **Total** | **293** | **270** | **23** | **210** | **76** | **7** | ## Tests ported in place @@ -275,6 +275,20 @@ These 54 rows run in a real test target now, adapted to the Satin API: the state | `src/limit/kv_update.rs` | the state-growth and KV limits (1) | 1 | `tests/satin/kv_limit.rs` | | **Total** | | **54** | | +## Tests ported by native keyless deployment + +These 36 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `rex2/keyless_deploy.rs` | native keyless deployment (18) | 18 | `tests/system/keyless/rules.rs` | +| `rex5/db_error.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | +| `rex5/keyless_fee_free.rs` | native keyless deployment (9) | 9 | `tests/system/keyless/rules.rs` | +| `rex5/keyless_gas_cap_postcap_recheck.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | +| `rex5/keyless_replay_barrier.rs` | native keyless deployment (1) | 1 | `tests/system/keyless/rules.rs` | +| `src/sandbox/execution.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/rules.rs` | +| **Total** | | **36** | | + ## Tests retired after the inventory These 21 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. @@ -338,7 +352,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/oracle.rs` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | | `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex2/keyless_deploy.rs` | 36 | 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) | +| `rex2/keyless_deploy.rs` | 18 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 3 (native keyless deployment · validation rules 1-9 unchanged); rewrite 2 (native keyless deployment · D36) | | `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) | @@ -353,11 +367,9 @@ 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/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/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/keyless_fee_free.rs` | 3 | rewrite 3 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)) | +| `rex5/keyless_replay_barrier.rs` | 2 | rewrite 2 (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) | @@ -372,5 +384,4 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | diff --git a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs index ebcffe02b..c0b2f803f 100644 --- a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs @@ -243,142 +243,6 @@ fn test_keyless_deploy_create2_factory() { // 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 @@ -408,204 +272,6 @@ fn test_keyless_deploy_rex6_success_still_commits_deployed_code() { ); } -#[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. @@ -773,66 +439,6 @@ fn test_keyless_deploy_execution_halted_invalid_opcode() { // 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. @@ -921,30 +527,6 @@ fn test_keyless_deploy_nonce_override_to_zero() { 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 // ============================================================================= @@ -1601,56 +1183,6 @@ fn test_keyless_deploy_reads_existing_contract() { 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 // ============================================================================= 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/keyless_fee_free.rs b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs index 3c8bf8483..cde58feca 100644 --- a/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs @@ -202,35 +202,6 @@ const STOP_RUNTIME_INIT_CODE: &[u8] = &[ // 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 // ============================================================================ @@ -239,114 +210,6 @@ fn test_rex5_value_zero_signer_zero_balance_deploys_successfully() { // 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 // ============================================================================ @@ -550,111 +413,6 @@ fn test_rex5_runtime_halt_returns_execution_halted_with_replay_barrier_consumed( // 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 @@ -673,259 +431,14 @@ fn set_eip7702_delegation_at(db: &mut MemoryDatabase, address: Address, delegate // 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 index cc0dc2cce..cbba779f2 100644 --- a/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs @@ -133,74 +133,6 @@ fn build_keyless_tx_with_init_code(init_code: Bytes) -> (Bytes, Address) { // 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) // ============================================================================ 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/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 77eea63e3..8aac8fa92 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -5,37 +5,14 @@ //! beyond it is the overhead, the charges its call makes for the creation's start, and what the //! creation itself spent — its `gasUsed`. -use alloy_primitives::Address; -use mega_evm::{ - satin_gas_params, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, write_record_history_gas, - BucketId, ExternalEnvs, MegaContext, MegaSpecId, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::{PUSH0, REVERT}, - context_interface::cfg::GasId, -}; +use mega_evm::system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS; +use revm::bytecode::opcode::{PUSH0, REVERT}; use super::*; -use crate::common::block; /// The length of the runtime the tests deploy. const RUNTIME_LEN: usize = 5; -/// The schedule's entry `id`. -fn entry(id: GasId) -> u64 { - satin_gas_params().get(id) -} - -/// The history gas of one write record. -fn record() -> u64 { - write_record_history_gas(1).expect("a record has a price") -} - -/// The history gas of `bytes` bytes. -fn history(bytes: u64) -> u64 { - mega_evm::history_gas(bytes).expect("a byte count has a price") -} - /// 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: /// @@ -160,35 +137,6 @@ fn test_a_failed_deployment_gives_the_created_account_back() { } } -/// A Satin context over `db` reading `envs`. -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. -fn bucket(account: Address) -> BucketId { - as SaltEnv>::bucket_id_for_account(account) -} - -/// `envs` with `account`'s bucket at multiplier `m`. -fn crowded(envs: TestExternalEnvs, account: Address, m: u64) -> TestExternalEnvs { - envs.with_bucket_capacity(bucket(account), MIN_BUCKET_SIZE as u64 * m) -} - /// 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] diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index f485c0fd8..1cb1466ce 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -9,24 +9,28 @@ mod charges; mod deploy; mod dispatch; +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, - EvmTxRuntimeLimits, MegaEvm, MegaTransactionOutcome, + write_record_history_gas, 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::{call_tx, context, system_db}; +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]; @@ -104,8 +108,16 @@ pub(crate) fn keyless_deploy_call(tx: &[u8], gas_limit_override: U256) -> Bytes /// 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 mut code = vec![0x60, len, 0x60, 10, PUSH0, CODECOPY, 0x60, len, PUSH0, RETURN]; + 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() } @@ -125,16 +137,28 @@ pub(crate) fn db_for(deployment: &Deployment, balance: U256) -> MemoryDatabase { db.account_balance(deployment.signer, balance) } -/// Runs the `keylessDeploy` transaction `data` from [`CALLER`] over `db` at `gas_limit`, under +/// 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") @@ -208,3 +232,51 @@ pub(crate) fn beyond( 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 history gas of one write record. +pub(crate) fn record() -> u64 { + write_record_history_gas(1).expect("a record has a price") +} + +/// The history gas of `bytes` bytes. +pub(crate) fn history(bytes: u64) -> u64 { + mega_evm::history_gas(bytes).expect("a byte count has a price") +} + +/// 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/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs new file mode 100644 index 000000000..73f34aa2b --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -0,0 +1,650 @@ +//! The rules a `keylessDeploy` call is held to before its creation starts, and what a refusal +//! leaves behind: nothing but the overhead. +//! +//! The rules and the error ABI are the legacy engine's. 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: the creation bumps the signer's +//! nonce whether it succeeds or not, so a signer gets two attempts that fail and not a third. + +use alloy_primitives::{address, keccak256, Signature}; +use mega_evm::{ + alloy_consensus::TxEip1559, + constants::MAX_INITCODE_SIZE, + system::keyless::{ + tests::{ + CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, + NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX, + }, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + test_utils::{ErrorInjectingDatabase, InjectedDbError}, + MegaSpecId, MegaTransactionError, TestExternalEnvs, +}; +use revm::{ + bytecode::opcode::{PUSH0, REVERT}, + context::{result::EVMError, CfgEnv}, + context_interface::cfg::GasId, + state::{AccountInfo, Bytecode}, +}; + +use super::*; + +/// 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 1: the call carries no value. A deployment is made by its signer, and the contract holds +/// no balance. +#[test] +fn test_keyless_deploy_rejects_ether_transfer() { + let deployment = small(); + for gas_limit in GAS_LIMITS { + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ONE); + 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), KeylessDeployError::NoEtherTransfer, "at {gas_limit}"); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. +#[test] +fn test_keyless_deploy_gas_limit_too_low() { + let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, GAS_LIMITS[0]); + 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. The canonical `CREATE2` factory was signed for a chain that charges no state gas +/// for deployed code: without a reservoir its 100,000 gas does not cover the code it deposits, +/// and the creation runs out of gas; 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 narrow = submit(system_db(), CREATE2_FACTORY_TX, 100_000, 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, 100_000, "the creation ran on the signed gas limit, and spent it"); + assert_eq!(nonce(&narrow, CREATE2_FACTORY_DEPLOYER), 1, "the nonce is spent all the same"); + + let wide = submit(system_db(), CREATE2_FACTORY_TX, 100_000, GAS_LIMITS[1]); + assert_eq!(returned(&wide).deployedAddress, CREATE2_FACTORY_CONTRACT); +} + +/// The gas limit at which a `keylessDeploy` of `deployment` 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 created account +/// and the two records, and the forward. +fn gas_limit_forwarding(deployment: &Deployment, forward: u64) -> u64 { + let intrinsic = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]) + .result + .gas() + .total_gas_spent(); + intrinsic + + KEYLESS_DEPLOY_OVERHEAD_GAS + + entry(GasId::create_state_gas()) + + 2 * record() + + forward +} + +/// 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. +#[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, 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. +#[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, 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() { + let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + let new_account = entry(GasId::new_account_state_gas()); + let gas_limit = gas_limit_forwarding(&deployment, 500_000 + 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: 500_000, + provided_gas_limit: 500_000 + 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() { + let mut corrupted = CREATE2_FACTORY_TX.to_vec(); + corrupted[102..134].fill(0xff); + let outcome = submit(system_db(), &corrupted, LARGE_OVERRIDE, GAS_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); +} + +/// So does `r = 0`, which no signature has. +#[test] +fn test_keyless_deploy_rejects_corrupted_signature() { + 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_LIMITS[0]); + 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() { + let mut modified = CREATE2_FACTORY_TX.to_vec(); + modified[135..167].fill(0x33); + let outcome = submit(system_db(), &modified, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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 garbage in [&[0xde, 0xad, 0xbe, 0xef][..], &[], &CREATE2_FACTORY_TX[..100]] { + let outcome = submit(system_db(), garbage, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding); +} + +/// The transaction must be a creation. +#[test] +fn test_keyless_deploy_not_contract_creation() { + let outcome = submit(system_db(), NON_CONTRACT_CREATION_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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() { + let outcome = submit(system_db(), POST_EIP155_CHAIN_1_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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() { + let deployment = Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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()); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, 2_000_000_000); + assert_eq!( + refusal(&outcome), + KeylessDeployError::InitCodeTooLarge { + size: MAX_INITCODE_SIZE as u64 + 1, + max: MAX_INITCODE_SIZE as u64, + }, + ); + assert_nothing_written(&outcome, &deployment, 0); +} + +/// Rule 4: the signer's nonce is at most 1. +#[test] +fn test_keyless_deploy_signer_nonce_too_high() { + let deployment = small(); + let db = system_db().account_nonce(deployment.signer, 2); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + assert_nothing_written(&outcome, &deployment, 2); +} + +/// Rule 4 counts the creation's own nonce bumps: a signer whose deployment fails twice — the +/// first bump takes it from 0 to 1, the second from 1 to 2 — is refused the third time. The +/// deploy address stays the same through all three. +#[test] +fn test_satin_caps_a_signer_at_two_failing_attempts() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let mut db = system_db(); + for attempt in 1..=2 { + let outcome = run_nth( + db.clone(), + deployment.call_data(LARGE_OVERRIDE), + GAS_LIMITS[0], + EvmTxRuntimeLimits::no_limits(), + attempt - 1, + ); + assert!( + matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. }), + "attempt {attempt}", + ); + assert_eq!(nonce(&outcome, deployment.signer), attempt, "attempt {attempt}"); + revm::DatabaseCommit::commit(&mut db, outcome.result_and_state.state); + } + let third = run_nth( + db, + deployment.call_data(LARGE_OVERRIDE), + GAS_LIMITS[0], + EvmTxRuntimeLimits::no_limits(), + 2, + ); + assert_eq!(refusal(&third), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); +} + +/// 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() { + let deployment = small(); + let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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() { + 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_LIMITS[0]; + 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() { + 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_LIMITS[0]; + 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), "injected code_by_hash() error"); +} + +/// An EIP-7702 delegation is not code: a signer that delegated deploys. +#[test] +fn test_a_delegated_signer_deploys() { + 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_LIMITS[0]); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 2); +} + +/// Rule 5: the deploy address holds no code. +#[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); + } +} + +/// 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_deploy_address_in_witness_rex6() { + let db = system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); + let outcome = submit(db, CREATE2_FACTORY_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); + assert!(outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT)); +} + +/// A second deployment of the same transaction finds its address taken. +#[test] +fn test_keyless_deploy_twice_fails_second_time() { + let mut db = system_db(); + let first = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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_LIMITS[0], 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() { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + assert_nothing_written(&outcome, &deployment, 0); +} + +/// A signer holding part of the value is refused too. +#[test] +fn test_keyless_deploy_insufficient_balance_partial() { + 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_LIMITS[0]); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); +} + +/// A signer holding exactly the value deploys, and the value moves to the contract. +#[test] +fn test_keyless_deploy_balance_exactly_sufficient() { + 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_LIMITS[0]); + 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), + ); + } +} + +/// The value is real, so it must be funded. +#[test] +fn test_the_value_must_be_funded() { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1_000)); + for gas_limit in GAS_LIMITS { + let db = db_for(&deployment, U256::from(999)); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance, "at {gas_limit}"); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// 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. +#[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. +#[test] +fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { + 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_000; + 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 it: no account was added, so the signer's account is not charged, +/// and the refusal writes nothing. +#[test] +fn test_a_call_refused_after_its_charges_keeps_none_of_them() { + let deployment = Deployment::signed(0, 500_000, 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, 500_000); + 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)); + assert_eq!( + [total, regular, state, history_gas], + [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 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. +#[test] +fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { + let deployment = + Deployment::signed(0, 500_000, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let refused = submit( + system_db(), + &deployment.tx, + LARGE_OVERRIDE, + gas_limit_forwarding(&deployment, 500_000), + ); + assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); + assert_eq!(nonce(&refused, deployment.signer), 0); + assert_eq!(refused.gas.state, 0); + + let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); + 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() { + let mut db = ErrorInjectingDatabase::new(system_db()); + db.fail_on_account = Some(CREATE2_FACTORY_CONTRACT); + assert_db_error(run_on(db, CREATE2_FACTORY_TX), "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() { + 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).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() { + let mut db = ErrorInjectingDatabase::new(system_db()); + db.fail_on_account = Some(CREATE2_FACTORY_DEPLOYER); + assert_db_error(run_on(db, CREATE2_FACTORY_TX), "injected basic() error"); +} + +/// A `keylessDeploy` of `tx` over `db`, at the narrow gas limit. +fn run_on( + db: ErrorInjectingDatabase, + tx: &[u8], +) -> 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_LIMITS[0]; + 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() { + 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_LIMITS[0]; + 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) + ), + } + } +} From ab7a6042426bbf2c78df2ba513cb4ad7f86fb8ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:08:39 -0700 Subject: [PATCH 128/458] test(satin): pin what a native keyless deployment deploys and reports The canonical deployments, every outcome the ABI reports, the nonce the creation spends, the logs, value and storage a constructor keeps, ORIGIN and GASPRICE of the transaction, the fees, the SALT and oracle environments the creation runs in, and a failed transaction leaving nothing for the next. Ports the remaining parked rows; the volatile-access rows go to detention, and the residual-overflow halt is retired. --- crates/mega-evm/tests/_pending/README.md | 37 +- .../tests/_pending/rex2/keyless_deploy.rs | 1263 ----------------- crates/mega-evm/tests/_pending/rex2/main.rs | 1 - .../tests/_pending/rex4/keyless_deploy.rs | 263 ---- crates/mega-evm/tests/_pending/rex4/main.rs | 1 - .../_pending/rex5/keyless_empty_code_logs.rs | 272 ---- .../tests/_pending/rex5/keyless_fee_free.rs | 444 ------ .../_pending/rex5/keyless_replay_barrier.rs | 251 ---- crates/mega-evm/tests/_pending/rex5/main.rs | 5 - .../tests/_pending/rex5/sandbox_accounting.rs | 201 --- .../rex6/keyless_sandbox_hardening.rs | 383 ----- crates/mega-evm/tests/_pending/rex6/main.rs | 1 - .../mega-evm/tests/system/keyless/deploy.rs | 696 ++++++++- 13 files changed, 708 insertions(+), 3110 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/keyless_deploy.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_replay_barrier.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index a98539f48..c3c83bfcf 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,15 +28,14 @@ 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 | -| detention | 83 | 78 | 5 | 73 | 10 | 0 | +| detention | 88 | 83 | 5 | 73 | 15 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | -| native keyless deployment | 39 | 39 | 0 | 7 | 32 | 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** | **293** | **270** | **23** | **210** | **76** | **7** | +| **Total** | **259** | **236** | **23** | **203** | **49** | **7** | ## Tests ported in place @@ -277,27 +276,32 @@ These 54 rows run in a real test target now, adapted to the Satin API: the state ## Tests ported by native keyless deployment -These 36 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. The counts above are lower than the inventory's by exactly these rows. +These 69 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| -| `rex2/keyless_deploy.rs` | native keyless deployment (18) | 18 | `tests/system/keyless/rules.rs` | +| `rex2/keyless_deploy.rs` | native keyless deployment (36) | 36 | `tests/system/keyless/charges.rs`, `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | +| `rex4/keyless_deploy.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/deploy.rs` | | `rex5/db_error.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | -| `rex5/keyless_fee_free.rs` | native keyless deployment (9) | 9 | `tests/system/keyless/rules.rs` | +| `rex5/keyless_empty_code_logs.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/deploy.rs` | +| `rex5/keyless_fee_free.rs` | native keyless deployment (12) | 12 | `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | | `rex5/keyless_gas_cap_postcap_recheck.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | -| `rex5/keyless_replay_barrier.rs` | native keyless deployment (1) | 1 | `tests/system/keyless/rules.rs` | +| `rex5/keyless_replay_barrier.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | +| `rex5/sandbox_accounting.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/charges.rs`, `tests/system/keyless/deploy.rs` | +| `rex6/keyless_sandbox_hardening.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/deploy.rs` | | `src/sandbox/execution.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/rules.rs` | -| **Total** | | **36** | | +| **Total** | | **69** | | ## Tests retired after the inventory -These 21 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 22 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 | |---|---|---:|---| | `mini_rex/compute_gas_limit.rs` | compute gas (2) | 2 | Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | | `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 | +| `rex5/sandbox_accounting.rs` | native keyless deployment (1) | 1 | The residual-overflow halt was the sandbox's safety net for the usage it merged after the deployment ran; a native deployment is held to every limit as it runs, and a crossing stops it as it stops any frame | | `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 | | `src/system/control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | @@ -305,7 +309,7 @@ They are not counted above. | `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | -| **Total** | | **21** | | +| **Total** | | **22** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -332,6 +336,11 @@ They are not counted above. | `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_beneficiary_balance_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_block_env_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_coinbase_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_oracle_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | | `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_beneficiary_triggers_detention` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | | `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_compute_overflow_skips_authorities` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | @@ -352,7 +361,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/oracle.rs` | 12 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | | `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex2/keyless_deploy.rs` | 18 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 3 (native keyless deployment · validation rules 1-9 unchanged); rewrite 2 (native keyless deployment · D36) | | `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) | @@ -362,23 +370,18 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 1 | 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)) | | `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/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | -| `rex5/keyless_fee_free.rs` | 3 | rewrite 3 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)) | -| `rex5/keyless_replay_barrier.rs` | 2 | rewrite 2 (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/sandbox_accounting.rs` | 5 | rewrite 5 (detention · native sub-frame: parent tracker sees child directly) | | `rex5/selfdestruct_beneficiary.rs` | 2 | keep 2 (detention) | | `rex6/beneficiary_detention.rs` | 13 | keep 13 (detention · D08) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/eip7702_authority_accounting.rs` | 2 | rewrite 2 (detention · 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/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/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | 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 c0b2f803f..000000000 --- a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs +++ /dev/null @@ -1,1263 +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 -// ============================================================================= - -/// 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_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_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"); -} - -// ============================================================================= -// 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); -} - -// ============================================================================= -// 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"); -} - -// ============================================================================= -// 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 index af70245a9..894f4c0f1 100644 --- a/crates/mega-evm/tests/_pending/rex2/main.rs +++ b/crates/mega-evm/tests/_pending/rex2/main.rs @@ -1,4 +1,3 @@ //! Tests for Rex2 hardfork features. -mod keyless_deploy; mod oracle_hint; 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/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index 5f824b2b2..c677a12bf 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -7,6 +7,5 @@ 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/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 cde58feca..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs +++ /dev/null @@ -1,444 +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 -// ============================================================================ - -// ============================================================================ -// 2. REX4 keeps the `gas_cost + value` balance precheck -// ============================================================================ - -// ============================================================================ -// 3. value > 0 still requires the signer to fund the transfer (REX5) -// ============================================================================ - -// ============================================================================ -// 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 -// ============================================================================ - -/// 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 -// ============================================================================ - -// ============================================================================ -// 11. Pre-sandbox materialization OOG halts before the sandbox ever runs -// ============================================================================ - -// ============================================================================ -// 12. Sandbox-validate-reject still pays the upfront materialization charge -// ============================================================================ - -// ============================================================================ -// 13. Step-1 dispatch-overhead OOG when the call's gas_limit is below the fixed cost -// ============================================================================ 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 cbba779f2..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs +++ /dev/null @@ -1,251 +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 -// ============================================================================ - -// ============================================================================ -// 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 index 0dcc3c499..d446a9465 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -4,12 +4,7 @@ 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 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; diff --git a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs index d9e13f7cd..da087d410 100644 --- a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs @@ -357,40 +357,6 @@ fn decode_keyless_deploy_return( // 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, @@ -608,170 +574,3 @@ fn test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code() { // ============================================================================ // 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/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 index 54d1f6c42..9d8a9549a 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -12,7 +12,6 @@ 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/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index f883804ac..3592a46a9 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -1,16 +1,58 @@ -//! What a keyless deployment deploys, and what it reports. +//! 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::U256; -use mega_evm::system::keyless::tests::{ - CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, - CREATE2_FACTORY_TX, +use alloy_primitives::{address, 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, REVERT, SELFDESTRUCT, 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)) +} -/// The canonical `CREATE2` factory deploys at its canonical address, from its canonical signer. +/// 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_the_create2_factory_deploys_at_its_address() { +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()); @@ -19,6 +61,644 @@ fn test_the_create2_factory_deploys_at_its_address() { 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 signer's nonce is spent"); + 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 len in [1, 2, 3] { + let deployment = Deployment::new(deploying(&runtime(len))); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + 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() { + 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_LIMITS[0], 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); +} + +/// A successful deployment spends the signer's nonce, from 0 to 1. +#[test] +fn test_keyless_deploy_increments_nonce_from_zero() { + let deployment = Deployment::new(deploying(&runtime(1))); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 1); +} + +/// A signer at nonce 1 still deploys at its Nick's-Method address, which is its first creation's +/// and not its nonce's, and ends at nonce 2: the creation bumps the real nonce. +#[test] +fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { + let deployment = Deployment::new(deploying(&runtime(1))); + let db = system_db().account_nonce(deployment.signer, 1); + let outcome = deploy(db, &deployment, GAS_LIMITS[0]); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 2); +} + +/// 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() { + let deployment = Deployment::new(Bytes::from_static(&[INVALID])); + let outcome = run_with( + system_db(), + deployment.call_data(2_000_000), + GAS_LIMITS[0], + 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 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 + 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 init_code in [Bytes::new(), Bytes::from_static(&[PUSH0, PUSH0, RETURN])] { + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + 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); + } +} + +/// 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + let deployment = Deployment::new(deploying(&[0xef, 0x00])); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); + let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, GAS_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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 its log: the call reports `EmptyCodeDeployed` +/// and the receipt carries the log, because the creation succeeded — it just left no code. +#[test] +fn test_an_empty_code_deployment_keeps_its_logs() { + 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_LIMITS[0]); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 1); + assert_eq!(logs[0].topics(), [topic]); + assert_eq!(logs[0].data.data, Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef])); + 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() { + let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0]; + 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 outer deployment deploys; the inner one does not. +#[test] +fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { + let inner = Deployment::new(deploying(&[0x00, 0x00])); + let data = inner.call_data(LARGE_OVERRIDE); + 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); + let outer = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &outer, GAS_LIMITS[0]); + assert_eq!(returned(&outcome).deployedAddress, outer.address); + let status = + outcome.state[&outer.address].storage.get(&U256::ZERO).map(|slot| slot.present_value); + assert_eq!(status, Some(U256::ZERO), "the inner call failed"); + 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() { + 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_LIMITS[0]); + 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() { + 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_LIMITS[0], + 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_LIMITS[0], + 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 deployment that fails at run time spends the signer's nonce and pays for its account, as a +/// successful one does. +#[test] +fn test_a_deployment_that_fails_still_spends_the_nonce_and_pays_for_the_signer() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); +} + +/// A successful deployment spends the nonce too, and pays for the signer's account, the +/// contract's account and its code. +#[test] +fn test_a_deployment_that_succeeds_spends_the_nonce_and_pays_for_three_accounts() { + let data = keyless_deploy_call(CREATE2_FACTORY_TX, U256::from(LARGE_OVERRIDE)); + let outcome = run_with(system_db(), data, GAS_LIMITS[0], EvmTxRuntimeLimits::no_limits()); + assert_eq!(returned(&outcome).deployedAddress, CREATE2_FACTORY_CONTRACT); + assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 1); + let code_len = outcome.state[&CREATE2_FACTORY_CONTRACT] + .info + .code + .as_ref() + .map_or(0, |code| code.original_bytes().len()); + assert_eq!( + outcome.gas.state, + entry(GasId::new_account_state_gas()) + + entry(GasId::create_state_gas()) + + satin_gas_params().code_deposit_state_gas(code_len), + ); +} + +/// 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() { + 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_LIMITS[0]; + 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_LIMITS[0]; + 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"); +} From 8bc0805d8f451b6be9015dbf367544457a5b7fce Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:12:57 -0700 Subject: [PATCH 129/458] fix(satin): charge no signer account for a creation that never started A keyless call charges the signer's account because the creation's start bumps the signer's nonce, which is what creates it. A creation an inspector answers in its place never starts, so the charge goes back at settlement when the signer's nonce was not spent. Pins what an inspector sees of a keyless deployment: the creation from its start to its end and every step of its init code, and a refused call as the call it is. --- .../mega-evm/src/system/keyless/dispatch.rs | 18 +- crates/mega-evm/src/system/keyless/settle.rs | 14 ++ .../tests/system/keyless/inspector.rs | 213 ++++++++++++++++++ crates/mega-evm/tests/system/keyless/mod.rs | 1 + 4 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 crates/mega-evm/tests/system/keyless/inspector.rs diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 73e47f9e2..36ecb381d 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -67,6 +67,12 @@ pub(crate) struct KeylessCall { pub(super) checkpoint: JournalCheckpoint, /// 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 call's return range. pub(super) memory_offset: Range, /// Whether the transaction's own start charged the call a new account. @@ -181,6 +187,9 @@ fn rewrite_dispatched( gas, checkpoint, deploy_address: deployment.deploy_address, + signer: deployment.signer, + signer_nonce: deployment.signer_nonce, + signer_account_charge: deployment.signer_account_charge, memory_offset, charged_new_account_state_gas, returned_history: 0, @@ -212,6 +221,9 @@ fn is_dispatched( /// 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, @@ -320,10 +332,12 @@ fn prepare( // What the `CREATE` opcode charges its frame for the creation's start. The signer's nonce bump // is what creates an empty signer's account; a caller the opcode starts from exists already. + let mut signer_account_charge = 0; if signer_info.is_empty() { let charge = StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)); - if !gas.record_state_cost(state_gas(ctx, charge)?) { + signer_account_charge = state_gas(ctx, charge)?; + if !gas.record_state_cost(signer_account_charge) { return Ok(Err(Refusal::OutOfGas)); } } @@ -364,6 +378,8 @@ fn prepare( Ok(Ok(Deployment { signer, + signer_nonce: signer_info.nonce, + signer_account_charge, deploy_address, value: tx.value, init_code: tx.input.clone(), diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 4356f5f7e..d35459b9e 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -83,6 +83,12 @@ where } settle_frame_result::<_, ERROR>(ctx, call.gas.tracker_mut(), result)?; call.gas.refill_history(call.returned_history); + // 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. + if call.signer_account_charge > 0 && account_nonce(ctx, call.signer) == call.signer_nonce { + call.gas.refill_reservoir(call.signer_account_charge); + } let (status, output) = match ctx.additional_limit.stop_before_run() { Some(stop) => (InstructionResult::Revert, stop.revert_data()), @@ -147,6 +153,14 @@ fn answer( returned(gas_used, address, Bytes::new()) } +/// 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(gas_used, Address::ZERO, encode_error_result(error)) 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..d0957c827 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -0,0 +1,213 @@ +//! What an inspector sees of a keyless deployment: the creation it is, from its start to its end, +//! and every step of its init code. The rewrite runs before the inspector is told the frame +//! starts, so the root of the trace is a `create` from the signer, not an opaque call. + +use mega_evm::{ + system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{LOG0, PUSH0, REVERT}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, CreateScheme, Gas, InstructionResult, Interpreter, + InterpreterResult, + }, + Database, Inspector, +}; + +use super::*; +use crate::common::context; + +/// 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)); + } +} + +/// The `keylessDeploy` transaction of `deployment` at `gas_limit`. +fn keyless_tx(deployment: &Deployment, gas_limit: u64) -> MegaTransaction { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx +} + +/// 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, gas_limit)).expect("valid"); + let seen = Recorder { + events: evm.inspector().events.clone(), + answer_creations: evm.inspector().answer_creations, + }; + (outcome, seen) +} + +type Outcome = MegaTransactionOutcome; + +/// The root of a keyless deployment's trace is the creation: the signer creates at its +/// Nick's-Method address, the inspector sees every step of the init code and its log, and the +/// creation ends at that address. No `call` to `KeylessDeploy` is reported. +#[test] +fn test_the_inspector_sees_the_deployment_as_a_creation() { + 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.first(), + Some(&Event::Create( + deployment.signer, + CreateScheme::Custom { address: deployment.address } + )), + ); + assert_eq!( + events.last(), + Some(&Event::CreateEnd(InstructionResult::Return, Some(deployment.address))), + ); + assert!(!events.iter().any(|event| matches!(event, Event::Call(_) | Event::CallEnd(_)))); + 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))); + } +} + +/// The traced run and the plain run agree to the gas. +#[test] +fn test_an_inspected_deployment_costs_what_a_plain_one_does() { + let deployment = Deployment::new(deploying(&runtime(3))); + for gas_limit in GAS_LIMITS { + let (inspected, _) = inspect(&deployment, Recorder::default(), gas_limit); + let plain = deploy(system_db(), &deployment, gas_limit); + assert_eq!(inspected.result, plain.result, "at {gas_limit}"); + assert_eq!(inspected.gas, plain.gas); + assert_eq!(inspected.usage, plain.usage); + } +} + +/// 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() { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); + let (outcome, recorder) = inspect(&deployment, Recorder::default(), GAS_LIMITS[0]); + 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 reports it. +#[test] +fn test_a_failed_deployment_ends_as_a_revert_in_the_trace() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let (outcome, recorder) = inspect(&deployment, Recorder::default(), GAS_LIMITS[0]); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!( + recorder.events.last(), + Some(&Event::CreateEnd(InstructionResult::Revert, Some(deployment.address))), + ); +} + +/// 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 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))); + 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], + [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], + "at {gas_limit}", + ); + assert_eq!( + recorder.events, + [ + Event::Create( + deployment.signer, + CreateScheme::Custom { address: deployment.address } + ), + Event::CreateEnd(InstructionResult::Revert, None), + ], + ); + } +} diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index 1cb1466ce..1defed98e 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -9,6 +9,7 @@ mod charges; mod deploy; mod dispatch; +mod inspector; mod rules; use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; From be66158993825ead2e995f1cbd16daebdeb5209a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:13:04 -0700 Subject: [PATCH 130/458] test(satin): hold a keyless deployment to every limit A frame budget reverts the creation alone and the call reports it; a transaction limit stops the transaction and takes the deployment back whole, the signer's nonce included; the state gas of the creation's start is held once the creation is built, and the code it deposits before it is written. Pins the three leakage paths for the call: an answer carries the reservoir, a stopped transaction gives back all but what ran, and the unspent forward comes back the same on success and on revert. --- .../mega-evm/tests/system/keyless/limits.rs | 364 ++++++++++++++++++ crates/mega-evm/tests/system/keyless/mod.rs | 1 + 2 files changed, 365 insertions(+) create mode 100644 crates/mega-evm/tests/system/keyless/limits.rs 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..f10e489f3 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -0,0 +1,364 @@ +//! 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 and KV budgets, the transaction's limits, +//! the state-gas limit. A frame budget reverts the creation alone, and the call answers +//! `ExecutionReverted` with the stop's revert data, the signer's nonce spent. A transaction limit +//! stops the transaction: the call reverts with the stop and 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 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, +}; +use revm::bytecode::opcode::{LOG0, PUSH0, REVERT}; + +use super::*; +use crate::common::context; + +/// Init code that logs `len` bytes of data and deploys a one-byte runtime. +fn logging(len: u64) -> Bytes { + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .push_number(len) + .push_number(0_u64) + .append(LOG0) + .build_vec(); + constructor(&prefix, &runtime(1)) +} + +/// 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) { + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!(nonce(outcome, deployment.signer), 0, "the signer's nonce is taken back"); + assert!(code_hash(outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + let [_, regular, state, history_gas, history_bytes] = beyond(outcome, &reference); + assert_eq!([state, history_gas, history_bytes], [0; 3], "at {gas_limit}"); + assert!(regular >= KEYLESS_DEPLOY_OVERHEAD_GAS, "the overhead stays spent"); + assert_eq!(outcome.usage.write_records, 0, "no record is kept"); + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + outcome.result.gas().reservoir_remaining(), + reference.result.gas().reservoir_remaining(), + "the reservoir comes back", + ); + } +} + +/// A log that crosses the transaction's data-size limit stops the transaction: the call reverts +/// with the stop, and the deployment is taken back whole. +#[test] +fn test_a_deployment_crossing_the_transaction_data_size_limit_stops_it() { + let deployment = Deployment::new(logging(2_000)); + let limit = body_bytes(&deployment) + 2 * 40 + 100; + 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!(matches!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, frame_local: false, .. }) + )); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// 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 deployment before its init code runs. +#[test] +fn test_the_creations_start_crossing_the_limit_stops_the_transaction() { + 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!(stop(&outcome), MegaLimitExceeded { kind: 0, limit }); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// 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 transaction is not latched. +#[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, None, "a budget, not the transaction's limit"); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// A transaction KV limit reaches the creation as its share: 98% of what the call has left, +/// rounded down. A limit of two leaves the creation one, and the two records its start makes cross +/// it: the creation is stopped before its init code runs, alone, and the signer's nonce is spent. +/// Records come one at a time, so inside the creation its share always binds before the +/// transaction's limit does. +#[test] +fn test_a_kv_limit_below_the_creations_start_stops_the_creation_at_its_start() { + let deployment = Deployment::new(filling_a_slot()); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2), + ); + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { + unreachable!() + }; + assert_eq!(gas_used, 0, "the init code never ran"); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(nonce(&outcome, deployment.signer), 1, "a stopped creation spends the nonce"); + assert_eq!(outcome.usage.write_records, 1); + } +} + +/// And a KV budget of three gives the creation two records — its start's — so the slot it fills +/// reverts it alone. +#[test] +fn test_a_deployment_crossing_its_kv_budget_reverts_alone() { + let deployment = Deployment::new(filling_a_slot()); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(3), + ); + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 2 }); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// The state gas of the creation's start — the signer's account and the created account — is held +/// once the creation is built, as a `CREATE`'s upfront charge is: a limit below it stops the +/// transaction before the init code runs. +#[test] +fn test_the_upfront_state_gas_is_held_to_the_state_gas_limit() { + let deployment = Deployment::new(deploying(&runtime(1))); + let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit: upfront - 1 }); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// A slot the constructor fills counts on top of the upfront state gas. +#[test] +fn test_a_deployment_crossing_the_state_gas_limit_stops_it() { + let deployment = Deployment::new(filling_a_slot()); + let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); + let limit = upfront + entry(GasId::sstore_set_state_gas()) - 1; + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit }); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// And so does the code it deposits: a limit one short of it stops the transaction before the +/// code is written. +#[test] +fn test_the_deposited_code_is_held_to_the_state_gas_limit() { + let deployment = Deployment::new(deploying(&runtime(5))); + let limit = entry(GasId::new_account_state_gas()) + + entry(GasId::create_state_gas()) + + satin_gas_params().code_deposit_state_gas(5) - + 1; + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit }); + assert_stopped_whole(&outcome, &deployment, 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()); + let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); + // The creation gets 98% of what the call has left, rounded down: room for its three records + // and its byte of code, and for its three records. + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(body_bytes(&deployment) + 3 * 40 + 1 + 10) + .with_tx_kv_update_limit(4) + .with_tx_state_gas_limit( + upfront + + entry(GasId::sstore_set_state_gas()) + + satin_gas_params().code_deposit_state_gas(1), + ); + 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 creation's start — the forward capped below the signed gas limit, which only a +/// signed gas limit near the execution cap reaches above it — gives the charges 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(), + ); +} + +/// The call gets back what its creation did not spend, the same way whether the creation +/// succeeds or reverts: the transaction spends the overhead, 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 + + 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 + new_account + record() + returned(&revert).gasUsed, + "revert at {gas_limit}", + ); + } +} + +/// 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); +} + +use revm::primitives::KECCAK_EMPTY; diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index 1defed98e..000d8dca2 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -10,6 +10,7 @@ mod charges; mod deploy; mod dispatch; mod inspector; +mod limits; mod rules; use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; From ff2b6bf839415e22d35c8910765505dd2e4675d9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:14:26 -0700 Subject: [PATCH 131/458] test(satin): run every keyless case below and above the execution cap A case that can only be reached below the cap says why: above it the transaction's frame is forwarded the cap itself and the reservoir pays the call's state and history charges. --- .../mega-evm/tests/system/keyless/deploy.rs | 646 ++++++++++-------- .../tests/system/keyless/inspector.rs | 32 +- crates/mega-evm/tests/system/keyless/rules.rs | 527 ++++++++------ 3 files changed, 679 insertions(+), 526 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 3592a46a9..3b2578fc4 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -81,11 +81,13 @@ fn test_keyless_deploy_eip1820() { /// deployed code is the runtime the init code returned. #[test] fn test_the_deploy_address_is_the_signers_first_creation_address() { - for len in [1, 2, 3] { - let deployment = Deployment::new(deploying(&runtime(len))); - let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); - assert_eq!(returned(&outcome).deployedAddress, deployment.signer.create(0)); - assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&runtime(len)))); + 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)))); + } } } @@ -97,34 +99,40 @@ fn keccak(code: &[u8]) -> B256 { /// What a deployment writes survives a commit: the account is created with its code. #[test] fn test_a_deployment_survives_a_commit() { - 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_LIMITS[0], 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); + 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); + } } /// A successful deployment spends the signer's nonce, from 0 to 1. #[test] fn test_keyless_deploy_increments_nonce_from_zero() { - let deployment = Deployment::new(deploying(&runtime(1))); - let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 1); + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&runtime(1))); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } } /// A signer at nonce 1 still deploys at its Nick's-Method address, which is its first creation's /// and not its nonce's, and ends at nonce 2: the creation bumps the real nonce. #[test] fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { - let deployment = Deployment::new(deploying(&runtime(1))); - let db = system_db().account_nonce(deployment.signer, 1); - let outcome = deploy(db, &deployment, GAS_LIMITS[0]); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 2); + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&runtime(1))); + let db = system_db().account_nonce(deployment.signer, 1); + let outcome = deploy(db, &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 2); + } } /// Init code that reverts: the call succeeds and reports `ExecutionReverted` with the revert @@ -149,18 +157,20 @@ fn test_keyless_deploy_execution_reverted() { /// forward. #[test] fn test_keyless_deploy_execution_halted_invalid_opcode() { - let deployment = Deployment::new(Bytes::from_static(&[INVALID])); - let outcome = run_with( - system_db(), - deployment.call_data(2_000_000), - GAS_LIMITS[0], - 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); + 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, @@ -206,14 +216,16 @@ fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { /// Init code that returns nothing deploys no code: `EmptyCodeDeployed`, and the nonce is spent. #[test] fn test_keyless_deploy_empty_initcode() { - 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_LIMITS[0]); - 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); + 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); + } } } @@ -221,17 +233,19 @@ fn test_keyless_deploy_empty_initcode() { /// is left, and the call reports `EmptyCodeDeployed`. #[test] fn test_keyless_deploy_init_code_selfdestructs() { - 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_LIMITS[0]); - 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); + 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 @@ -239,118 +253,134 @@ fn test_keyless_deploy_init_code_selfdestructs() { /// 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() { - 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_LIMITS[0]); - 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()),); + 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() { - let deployment = Deployment::new(deploying(&[0xef, 0x00])); - let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + 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() { - 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_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + 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() { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); - let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, GAS_LIMITS[0]); - 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))); + 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() { - 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_LIMITS[0]); - 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)); + 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() { - 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_LIMITS[0]); - 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"); + 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() { - 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_LIMITS[0]); - 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))); + 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 @@ -380,65 +410,73 @@ fn test_failed_initcode_keeps_no_storage() { /// address. #[test] fn test_keyless_deploy_emits_logs() { - 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_LIMITS[0]); - 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())); + 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 its log: the call reports `EmptyCodeDeployed` /// and the receipt carries the log, because the creation succeeded — it just left no code. #[test] fn test_an_empty_code_deployment_keeps_its_logs() { - 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_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - let logs = outcome.result.logs(); - assert_eq!(logs.len(), 1); - assert_eq!(logs[0].topics(), [topic]); - assert_eq!(logs[0].data.data, Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef])); - assert_eq!(nonce(&outcome, deployment.signer), 1); + 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 { .. })); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 1); + assert_eq!(logs[0].topics(), [topic]); + assert_eq!(logs[0].data.data, Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef])); + 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() { - let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); - let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - assert!(outcome.result.logs().is_empty()); + 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() { - 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_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); - assert!(outcome.result.logs().is_empty()); + 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`. @@ -513,47 +551,52 @@ fn test_beneficiary_receives_fees_on_execution_failure() { /// with `NotIntercepted()`, and nothing is deployed. #[test] fn test_keyless_deploy_not_intercepted_for_inner_calls() { - 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_LIMITS[0]; - 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)); + 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 outer deployment deploys; the inner one does not. #[test] fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { - let inner = Deployment::new(deploying(&[0x00, 0x00])); - let data = inner.call_data(LARGE_OVERRIDE); - 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); - let outer = Deployment::new(running(prefix)); - let outcome = deploy(system_db(), &outer, GAS_LIMITS[0]); - assert_eq!(returned(&outcome).deployedAddress, outer.address); - let status = - outcome.state[&outer.address].storage.get(&U256::ZERO).map(|slot| slot.present_value); - assert_eq!(status, Some(U256::ZERO), "the inner call failed"); - assert!(code_hash(&outcome, inner.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - assert_eq!(nonce(&outcome, inner.signer), 0); + for gas_limit in GAS_LIMITS { + let inner = Deployment::new(deploying(&[0x00, 0x00])); + let data = inner.call_data(LARGE_OVERRIDE); + 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); + let outer = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &outer, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, outer.address); + let status = + outcome.state[&outer.address].storage.get(&U256::ZERO).map(|slot| slot.present_value); + assert_eq!(status, Some(U256::ZERO), "the inner call failed"); + 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 @@ -579,29 +622,31 @@ fn test_a_deployment_is_priced_by_the_transactions_salt_env() { /// in the transaction's own environment. #[test] fn test_a_constructor_reaches_the_oracle_service() { - 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_LIMITS[0]); - 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); + 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 @@ -622,83 +667,92 @@ fn test_a_deployment_is_counted_where_it_writes() { /// created, does not. #[test] fn test_a_retry_does_not_pay_for_the_signer_again() { - 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_LIMITS[0], - 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_LIMITS[0], - 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); + 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 deployment that fails at run time spends the signer's nonce and pays for its account, as a /// successful one does. #[test] fn test_a_deployment_that_fails_still_spends_the_nonce_and_pays_for_the_signer() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!(nonce(&outcome, deployment.signer), 1); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); + } } /// A successful deployment spends the nonce too, and pays for the signer's account, the /// contract's account and its code. #[test] fn test_a_deployment_that_succeeds_spends_the_nonce_and_pays_for_three_accounts() { - let data = keyless_deploy_call(CREATE2_FACTORY_TX, U256::from(LARGE_OVERRIDE)); - let outcome = run_with(system_db(), data, GAS_LIMITS[0], EvmTxRuntimeLimits::no_limits()); - assert_eq!(returned(&outcome).deployedAddress, CREATE2_FACTORY_CONTRACT); - assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 1); - let code_len = outcome.state[&CREATE2_FACTORY_CONTRACT] - .info - .code - .as_ref() - .map_or(0, |code| code.original_bytes().len()); - assert_eq!( - outcome.gas.state, - entry(GasId::new_account_state_gas()) + - entry(GasId::create_state_gas()) + - satin_gas_params().code_deposit_state_gas(code_len), - ); + 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()); + assert_eq!(returned(&outcome).deployedAddress, CREATE2_FACTORY_CONTRACT); + assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 1); + let code_len = outcome.state[&CREATE2_FACTORY_CONTRACT] + .info + .code + .as_ref() + .map_or(0, |code| code.original_bytes().len()); + assert_eq!( + outcome.gas.state, + entry(GasId::new_account_state_gas()) + + entry(GasId::create_state_gas()) + + satin_gas_params().code_deposit_state_gas(code_len), + ); + } } /// 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() { - 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_LIMITS[0]; - 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_LIMITS[0]; - 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"); + 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"); + } } diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index d0957c827..620a6bb5d 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -159,25 +159,29 @@ fn test_an_inspected_deployment_costs_what_a_plain_one_does() { /// refusal; no creation starts. #[test] fn test_a_refused_call_is_seen_as_a_call() { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); - let (outcome, recorder) = inspect(&deployment, Recorder::default(), GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); - assert_eq!( - recorder.events, - [Event::Call(KEYLESS_DEPLOY_ADDRESS), Event::CallEnd(InstructionResult::Revert)], - ); + 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 reports it. #[test] fn test_a_failed_deployment_ends_as_a_revert_in_the_trace() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let (outcome, recorder) = inspect(&deployment, Recorder::default(), GAS_LIMITS[0]); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!( - recorder.events.last(), - Some(&Event::CreateEnd(InstructionResult::Revert, Some(deployment.address))), - ); + 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 { .. })); + assert_eq!( + recorder.events.last(), + Some(&Event::CreateEnd(InstructionResult::Revert, Some(deployment.address))), + ); + } } /// An inspector that answers the creation itself — a tool's rewrite — starts no creation: the diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 73f34aa2b..a1dc23bfe 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -9,7 +9,7 @@ use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ alloy_consensus::TxEip1559, - constants::MAX_INITCODE_SIZE, + constants::{MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, system::keyless::{ tests::{ CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, @@ -77,11 +77,16 @@ fn test_keyless_deploy_rejects_ether_transfer() { /// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. #[test] fn test_keyless_deploy_gas_limit_too_low() { - let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, GAS_LIMITS[0]); - assert_eq!( - refusal(&outcome), - KeylessDeployError::GasLimitTooLow { tx_gas_limit: 100_000, provided_gas_limit: 99_999 }, - ); + 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 @@ -121,6 +126,11 @@ fn gas_limit_forwarding(deployment: &Deployment, forward: u64) -> u64 { /// 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))); @@ -134,6 +144,11 @@ fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { } /// 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))); @@ -172,125 +187,153 @@ fn test_the_signers_account_can_take_the_forward_below_the_signed_gas_limit() { /// nothing. #[test] fn test_keyless_deploy_invalid_signature() { - let mut corrupted = CREATE2_FACTORY_TX.to_vec(); - corrupted[102..134].fill(0xff); - let outcome = submit(system_db(), &corrupted, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); + 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() { - 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_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); + 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() { - let mut modified = CREATE2_FACTORY_TX.to_vec(); - modified[135..167].fill(0x33); - let outcome = submit(system_db(), &modified, LARGE_OVERRIDE, GAS_LIMITS[0]); - 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"); + 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 garbage in [&[0xde, 0xad, 0xbe, 0xef][..], &[], &CREATE2_FACTORY_TX[..100]] { - let outcome = submit(system_db(), garbage, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "{garbage:02x?}"); + 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"); } - let mut trailing = CREATE2_FACTORY_TX.to_vec(); - trailing.push(0x00); - let outcome = submit(system_db(), &trailing, LARGE_OVERRIDE, GAS_LIMITS[0]); - 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() { - 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_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding); + 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() { - let outcome = submit(system_db(), NON_CONTRACT_CREATION_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::NotContractCreation); + 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() { - let outcome = submit(system_db(), POST_EIP155_CHAIN_1_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::NotPreEIP155); + 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() { - let deployment = Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); - assert_nothing_written(&outcome, &deployment, 0); + 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()); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, 2_000_000_000); - assert_eq!( - refusal(&outcome), - KeylessDeployError::InitCodeTooLarge { - size: MAX_INITCODE_SIZE as u64 + 1, - max: MAX_INITCODE_SIZE as u64, - }, - ); - assert_nothing_written(&outcome, &deployment, 0); + // 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 [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + 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); + } } /// Rule 4: the signer's nonce is at most 1. #[test] fn test_keyless_deploy_signer_nonce_too_high() { - let deployment = small(); - let db = system_db().account_nonce(deployment.signer, 2); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); - assert_nothing_written(&outcome, &deployment, 2); + 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); + } } /// Rule 4 counts the creation's own nonce bumps: a signer whose deployment fails twice — the @@ -298,103 +341,116 @@ fn test_keyless_deploy_signer_nonce_too_high() { /// deploy address stays the same through all three. #[test] fn test_satin_caps_a_signer_at_two_failing_attempts() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let mut db = system_db(); - for attempt in 1..=2 { - let outcome = run_nth( - db.clone(), + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let mut db = system_db(); + for attempt in 1..=2 { + let outcome = run_nth( + db.clone(), + deployment.call_data(LARGE_OVERRIDE), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + attempt - 1, + ); + assert!( + matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. }), + "attempt {attempt}", + ); + assert_eq!(nonce(&outcome, deployment.signer), attempt, "attempt {attempt}"); + revm::DatabaseCommit::commit(&mut db, outcome.result_and_state.state); + } + let third = run_nth( + db, deployment.call_data(LARGE_OVERRIDE), - GAS_LIMITS[0], + gas_limit, EvmTxRuntimeLimits::no_limits(), - attempt - 1, + 2, ); - assert!( - matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. }), - "attempt {attempt}", - ); - assert_eq!(nonce(&outcome, deployment.signer), attempt, "attempt {attempt}"); - revm::DatabaseCommit::commit(&mut db, outcome.result_and_state.state); + assert_eq!(refusal(&third), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); } - let third = run_nth( - db, - deployment.call_data(LARGE_OVERRIDE), - GAS_LIMITS[0], - EvmTxRuntimeLimits::no_limits(), - 2, - ); - assert_eq!(refusal(&third), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); } /// 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() { - let deployment = small(); - let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); - assert_nothing_written(&outcome, &deployment, 0); + 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() { - 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_LIMITS[0]; - let outcome = MegaEvm::new(context(db).with_cfg(cfg)) - .execute_transaction(tx) - .expect("a valid transaction"); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); + 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() { - 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_LIMITS[0]; - 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); + 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), "injected code_by_hash() error"); + 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() { - 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_LIMITS[0]); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 2); + 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), 2); + } } /// Rule 5: the deploy address holds no code. @@ -413,53 +469,64 @@ fn test_keyless_deploy_contract_already_exists() { /// reverts. #[test] fn test_keyless_deploy_contract_already_exists_deploy_address_in_witness_rex6() { - let db = system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - let outcome = submit(db, CREATE2_FACTORY_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); - assert!(outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT)); + for gas_limit in GAS_LIMITS { + let db = + system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); + let outcome = submit(db, CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); + assert!(outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT)); + } } /// A second deployment of the same transaction finds its address taken. #[test] fn test_keyless_deploy_twice_fails_second_time() { - let mut db = system_db(); - let first = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, GAS_LIMITS[0]); - 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_LIMITS[0], EvmTxRuntimeLimits::no_limits(), 1); - assert_eq!(refusal(&second), KeylessDeployError::ContractAlreadyExists); + 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() { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); - assert_nothing_written(&outcome, &deployment, 0); + 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. #[test] fn test_keyless_deploy_insufficient_balance_partial() { - 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_LIMITS[0]); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + 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); + } } /// A signer holding exactly the value deploys, and the value moves to the contract. #[test] fn test_keyless_deploy_balance_exactly_sufficient() { - 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_LIMITS[0]); - 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))); + 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 @@ -491,6 +558,9 @@ fn test_the_value_must_be_funded() { /// 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(); @@ -505,6 +575,9 @@ fn test_a_call_below_the_overhead_reads_nothing() { /// 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() { let deployment = small(); @@ -520,6 +593,11 @@ fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { /// A call refused after it paid for the creation's start — the forward capped below the signed /// gas limit — keeps none of it: no account was added, so the signer's account is not charged, /// and the refusal writes nothing. +/// +/// 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_none_of_them() { let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); @@ -538,6 +616,8 @@ fn test_a_call_refused_after_its_charges_keeps_none_of_them() { /// 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 deployment = @@ -552,19 +632,23 @@ fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { assert_eq!(nonce(&refused, deployment.signer), 0); assert_eq!(refused.gas.state, 0); - let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[0]); - assert!(matches!(failure(&failed), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!(nonce(&failed, deployment.signer), 1); - assert_eq!(failed.gas.state, entry(GasId::new_account_state_gas())); + 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() { - let mut db = ErrorInjectingDatabase::new(system_db()); - db.fail_on_account = Some(CREATE2_FACTORY_CONTRACT); - assert_db_error(run_on(db, CREATE2_FACTORY_TX), "injected basic() error"); + 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 @@ -572,35 +656,41 @@ fn test_a_failed_read_of_the_deploy_address_fails_the_transaction() { /// `ContractAlreadyExists`, rather than failing. #[test] fn test_the_occupancy_read_needs_no_code() { - 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).expect("the occupancy read needs no code"); - assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); + 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() { - let mut db = ErrorInjectingDatabase::new(system_db()); - db.fail_on_account = Some(CREATE2_FACTORY_DEPLOYER); - assert_db_error(run_on(db, CREATE2_FACTORY_TX), "injected basic() error"); + 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 the narrow gas limit. +/// 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_LIMITS[0]; + call.0.base.gas_limit = gas_limit; MegaEvm::new(context(db)).execute_transaction(call) } @@ -623,28 +713,33 @@ fn assert_db_error( /// for either of the two accounts the call charges: the price is never guessed. #[test] fn test_a_failed_salt_lookup_fails_the_transaction() { - 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_LIMITS[0]; - 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) - ), + 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) + ), + } } } } From 7a4561daf29d0e966abc23c0fd258094e342328e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:15:53 -0700 Subject: [PATCH 132/458] bench(satin): measure a keyless deployment next to the same creation on op-revm The canonical CREATE2 factory through keylessDeploy, checked to deploy before it is measured, and its init code as an op-revm creation transaction. --- crates/mega-evm/benches/transact.rs | 71 ++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 5d1ef2b7f..b4198c54e 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -27,6 +27,12 @@ //! written (`satin`); and under a state-gas limit one gas short, so the last slot crosses and the //! transaction is stopped (`stopped`). Its op-revm baseline is `data_size_limit/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 its settlement into the ABI answer. +//! //! 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 @@ -50,7 +56,14 @@ use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + system::{ + keyless::{ + decode_keyless_tx, + tests::{CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_TX}, + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, + }, + IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + }, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, TX_BODY_SIZE, @@ -275,7 +288,8 @@ fn bench_transact(c: &mut Criterion) { .account_code(INTERCEPTED, system_caller_code(IS_DISABLED)) .account_code(MISSING, system_caller_code(UNKNOWN_SELECTOR)) .account_code(LIMITED, limited_code()) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); let cfg = mega_context(db.clone()).cfg().clone(); let mut depth = [0u8; 32]; @@ -436,6 +450,59 @@ fn bench_transact(c: &mut Criterion) { }); } + // 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 = [ From 7f1d452dc9151309845b14da26c3cb828ee00f5d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:18:30 -0700 Subject: [PATCH 133/458] docs: describe keyless deployment as a native creation The module table, the system contracts' dispatch, a keyless paragraph and the lanes contract in AGENTS.md; the keyless patterns and anti-patterns in the system module's guide; the crate README; and the error variants that now have no producer. --- AGENTS.md | 40 ++++++++++------- crates/mega-evm/README.md | 15 +++++-- crates/mega-evm/src/evm/frame.rs | 11 ++--- crates/mega-evm/src/system/AGENTS.md | 12 +++-- crates/mega-evm/src/system/keyless/error.rs | 50 +++++++++++---------- 5 files changed, 78 insertions(+), 50 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3b545fa90..c93db7dd1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,17 +99,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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | -| `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | -| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `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, the keyless rewrite point and the keyless settlement, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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) | revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | +| `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | +| `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`); keyless deployment as a native creation: the dispatch, the overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (the detention and compute-ledger semantics the two control contracts answer with, and the Host's oracle reads) | +| `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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -174,9 +174,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. - Four of the six system contracts answer calls through their interceptors (`system/`). + Three of the six system contracts answer calls through their interceptors (`system/`), and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless rewrite 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 the control contracts' compute-ledger semantics 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. + `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until detention and the control contracts' compute-ledger semantics fill them in, and the Oracle forwards a `sendHint` payload to the node's oracle service. +- 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 rewrite (`keyless::rewrite`) runs in `frame_init` before interception and in `inspect_frame_init` before the inspector is told the frame starts, so the creation is an ordinary creation from there on and an inspector's root is a `create`. + It charges the fixed overhead, holds the call to the legacy engine's nine rules and error ABI, charges what the `CREATE` opcode charges its frame — the signer's account when the creation's nonce bump creates it and the created account, both SALT-priced state gas, and the creation's two write records — and starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left. + The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. + A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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, and the signer's nonce stays spent. + `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, so a signer gets two failing attempts and not a third. + `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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 and limit-check protocol describe mechanisms that do not exist here; the contracts below replace them. 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. @@ -202,6 +210,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The KV count a node reports is the write-record count, and the KV 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. + A `keylessDeploy` call rewritten into its creation pushes a lane of its own, under the creation's: the creation is the outermost frame revm runs, so the history its lane gives back is kept for the call (`keyless::give_back_history`), and the keyless settlement pops the creation's lane when the creation never ran. The state-gas limit's entry of what is held outside each frame is pushed and popped with the lane. - **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. @@ -224,9 +233,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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 rewrite 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. @@ -246,6 +255,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - `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. +- `system/` — tests of the system contracts: the interceptor dispatch, what each contract answers, keyless deployment (`system/keyless/`) and the system-address transaction. - `_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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 6f5b76d53..a62612402 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -61,11 +61,20 @@ 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 are deployed at Satin activation, together with the EIP-7997 factory at `0x4e59…`. -Four of them answer calls through an interceptor instead of running their bytecode. +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 the control contracts' compute-ledger semantics 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 Oracle forwards a `sendHint` payload to the node's oracle service. + +`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 becomes a native creation before any interceptor or inspector sees it. +The call pays a fixed 100,000 gas, is held to the legacy engine's nine rules and error ABI, and pays what a `CREATE` opcode charges its frame: the signer's account when the creation's nonce bump is what creates it, 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 — and the signer's nonce stays spent either way; a transaction limit the deployment crosses stops the transaction and takes the deployment back whole. +A signer is refused once its nonce is above 1, so it gets two deployments that fail and not a third. +A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. 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. @@ -96,7 +105,7 @@ A transaction's state growth is the EIP-8037 state gas it spends, so the state-g It is a limit on gas, so a slot or an account in a crowded SALT bucket reaches it sooner. Every one of these limits is unlimited unless a node sets it. -Gas detention and keyless deployment arrive in later changes. +Gas detention arrives in a later change. ## Quick start diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 09d08538d..8f6b5b9fa 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 its rules refuse, and, when it lands, +//! precompile normalisation. 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; @@ -16,7 +16,8 @@ //! `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. +//! mechanism that settles a result into a caller itself — a keyless deployment's call, which +//! takes back its creation's result as the frame of a `CREATE` does. use alloy_primitives::Bytes; use revm::{ diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index a9dbd1896..76c003de3 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -6,7 +6,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch ## 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`). +- `keyless/`: native keyless deployment. The `KeylessDeploy` address, code and ABI and the semantics of a deployment (`mod.rs`); the dispatch, the overhead, the nine rules, the charges of the creation's start and the rewrite into a creation (`dispatch.rs`); the settlement of the creation into its call and the ABI answer (`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, and its interceptor. - `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor. - `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, and the [`SequencerRegistryConfig`] that seeds it. No interceptor. @@ -16,12 +16,15 @@ 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. +- `keylessDeploy` is not intercepted: a call a transaction makes is taken by the keyless rewrite, which runs before interception in `frame_init` and before the inspector's `frame_start` in `inspect_frame_init`, and becomes 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. +- An interceptor that lets the frame run charges nothing: the frame starts as it was built. +- A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context); it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped. +- What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps the signer's spent nonce, 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. - 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. @@ -46,6 +49,8 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 translate its result anywhere but the settlement: the call pays the start as a `CREATE`'s frame does, and only `last_frame_result` sees every first-frame result, the creation answered at its start included. +- 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. @@ -59,6 +64,7 @@ The executor hands it to the pre-block observer, then commits: the sequence the ## 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 settlement and the answer; `evm/execution.rs` for where the two are called; `tests/system/keyless/` for the tests. - 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. - Add a predeploy: a spec in `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. diff --git a/crates/mega-evm/src/system/keyless/error.rs b/crates/mega-evm/src/system/keyless/error.rs index de7925f21..f005da0de 100644 --- a/crates/mega-evm/src/system/keyless/error.rs +++ b/crates/mega-evm/src/system/keyless/error.rs @@ -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,14 +37,15 @@ 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, @@ -54,6 +54,10 @@ pub enum KeylessDeployError { }, /// The call's remaining budget in some resource dimension was below the deployment's /// known upfront usage, so the deployment was not started. + /// + /// The legacy engine's, which ran the deployment with a budget of its own and preflighted it. + /// Kept in the ABI with no producer here: a native deployment is held to the call's own + /// budgets as it runs. ParentBudgetExceeded { /// The resource dimension, as the raw `kind` code of the `IKeylessDeploy` error. The /// Satin resource dimensions and their codes are not defined yet. @@ -80,39 +84,37 @@ pub enum KeylessDeployError { provided_gas_limit: u64, }, /// The remaining compute gas is insufficient to pay for the keyless deploy overhead. + /// + /// Kept in the ABI with no producer here: the overhead is regular gas, and a call that + /// cannot pay it runs out of gas. 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. + /// An internal failure (a failed read). Selector-only, so the error ABI does not depend on + /// upstream `Display` text. + /// + /// Kept in the ABI with no producer here: a failed read or SALT lookup fails the transaction + /// with its cause, as it does at every other site. 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`. + /// The inner transaction failed its validation as a transaction. Selector-only for the same + /// reason as `InternalError`. + /// + /// The legacy engine's, which ran the deployment as a transaction of its own. Kept in the + /// ABI with no producer here: the deployment is a creation, not a transaction. InvalidTransaction, /// The keylessDeploy call was not intercepted (only returned by Solidity contract for inner /// calls) From 31aafcfbbc9483d599597090c88bb27b7d9f1557 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:21:55 -0700 Subject: [PATCH 134/458] refactor(satin): leave nothing in the keyless settlement a test cannot reach The halt reason, which the ABI drops, is its own function with a test; the answers to a creation revm reports at another address, which no deployment reaches, share the one comparison every deployment makes; and the signer's account is given back on the nonce alone, a signer that had one having been charged nothing. --- crates/mega-evm/src/system/keyless/settle.rs | 54 ++++++++++++++------ 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index d35459b9e..39b732992 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -86,7 +86,8 @@ where // 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. - if call.signer_account_charge > 0 && account_nonce(ctx, call.signer) == call.signer_nonce { + // A signer that had an account was charged nothing, and gets nothing back. + if account_nonce(ctx, call.signer) == call.signer_nonce { call.gas.refill_reservoir(call.signer_account_charge); } @@ -127,21 +128,22 @@ fn answer( return failed(KeylessDeployError::ExecutionReverted { gas_used, output }, gas_used); } if !instruction_result.is_ok() { - let reason = match SuccessOrHalt::::from(instruction_result) { - SuccessOrHalt::Halt(reason) => reason, - _ => MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic)), - }; + let reason = halt_reason(instruction_result); return failed(KeylessDeployError::ExecutionHalted { gas_used, reason }, gas_used); } - let FrameResult::Create(outcome) = result else { - return refused(KeylessDeployError::NoContractCreated); - }; - let Some(address) = outcome.address else { - return refused(KeylessDeployError::NoContractCreated); + let created = match result { + FrameResult::Create(outcome) => outcome.address, + FrameResult::Call(_) => None, }; - if address != call.deploy_address { - return refused(KeylessDeployError::AddressMismatch); + if created != Some(call.deploy_address) { + let error = if created.is_some() { + KeylessDeployError::AddressMismatch + } else { + KeylessDeployError::NoContractCreated + }; + return (InstructionResult::Revert, encode_error_result(error)); } + let address = call.deploy_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. let deployed = ctx.journal_ref().state.get(&address).is_some_and(|account| { @@ -182,9 +184,13 @@ fn returned( (InstructionResult::Return, output.into()) } -/// A revert of the call with `error`. -fn refused(error: KeylessDeployError) -> (InstructionResult, Bytes) { - (InstructionResult::Revert, encode_error_result(error)) +/// 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 @@ -205,6 +211,24 @@ fn creation_gas_used(gas: &Gas) -> u64 { 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() { From 0bfa1268832ad64f207e43d68409cf2811bcc052 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:21:55 -0700 Subject: [PATCH 135/458] test(satin): pin the keyless edges a signer, a limit and the latch reach A signer that sends its own deployment makes no record of its own; init code of exactly the limit passes rule 8; and a transaction its body latched is answered with the stop and never rewritten, on the inspected path too. --- .../mega-evm/tests/system/keyless/charges.rs | 23 +++++++++++++++++++ .../tests/system/keyless/inspector.rs | 20 ++++++++++++++++ .../mega-evm/tests/system/keyless/limits.rs | 20 ++++++++++++++++ crates/mega-evm/tests/system/keyless/rules.rs | 14 +++++++++++ 4 files changed, 77 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 8aac8fa92..60885237b 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -196,3 +196,26 @@ fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { } } } + +/// 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. +#[test] +fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + 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_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + // The transaction bumped its sender from 0 to 1, and the creation from 1 to 2. + assert_eq!(nonce(&outcome, deployment.signer), 2); + 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); + } +} diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 620a6bb5d..b02db8639 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -215,3 +215,23 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { ); } } + +/// A transaction the latch stopped before its first frame is not rewritten on the inspected path +/// either, where the rewrite runs before the latch is consulted: the inspector sees the call and +/// its stop, and no creation. +#[test] +fn test_a_latched_transaction_is_seen_as_the_call_it_is() { + 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 outcome = evm.execute_transaction(keyless_tx(&deployment, gas_limit)).expect("valid"); + assert!(outcome.limit_exceeded.is_some(), "at {gas_limit}"); + assert_eq!( + evm.inspector().events, + [Event::Call(KEYLESS_DEPLOY_ADDRESS), Event::CallEnd(InstructionResult::Revert)], + ); + assert!(!outcome.state.contains_key(&deployment.signer)); + } +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index f10e489f3..3a55b7665 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -90,6 +90,26 @@ fn assert_stopped_whole(outcome: &Outcome, deployment: &Deployment, gas_limit: u } } +/// A transaction whose body alone crosses its data-size limit is stopped before its first frame, +/// and that frame is not a deployment: the call is answered with the stop, and no rule reads the +/// signer. +#[test] +fn test_a_transaction_latched_by_its_body_deploys_nothing() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit: 100 }, "at {gas_limit}"); + assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); + let [total, ..] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!(total, 0, "not even the overhead is charged"); + } +} + /// A log that crosses the transaction's data-size limit stops the transaction: the call reverts /// with the stop, and the deployment is taken back whole. #[test] diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index a1dc23bfe..edd36261c 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -324,6 +324,20 @@ fn test_init_code_over_the_limit_is_refused() { } } +/// 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 [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + 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() { From 646c88f6c2624fd075679f0a0cb3e28dd69deaf8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:22:06 -0700 Subject: [PATCH 136/458] chore(deps): pin the revm fork to the withheld-gas branch Gas detention needs the fork's withheld part of a frame's regular gas: a cap that holds regular charges back while every other reader of the frame's gas (GAS, the call forward, the SSTORE sentry, the skip-cold checks, what a callee inherits) sees the whole of it, and a record of the regular charge the withheld part would have paid. The twelve patched crates move together to the branch head until the fork tags a release that carries the API. --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 24 ++++++++++++------------ 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 124e95cac..5c777ebc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -718,7 +718,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -729,7 +729,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -3819,7 +3819,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "revm-bytecode", "revm-context", @@ -3838,7 +3838,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "bitvec", "phf 0.13.1", @@ -3849,7 +3849,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "bitvec", "cfg-if", @@ -3865,7 +3865,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3880,7 +3880,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "alloy-eips", "derive_more", @@ -3894,7 +3894,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "auto_impl", "either", @@ -3907,7 +3907,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "auto_impl", "derive-where", @@ -3925,7 +3925,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "auto_impl", "either", @@ -3960,7 +3960,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3972,7 +3972,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3996,7 +3996,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "alloy-primitives", "once_cell", @@ -4006,7 +4006,7 @@ dependencies = [ [[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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "alloy-eip7928", "bitflags 2.11.1", @@ -4019,7 +4019,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" 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?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" dependencies = [ "alloy-eip7928", "k256", diff --git a/Cargo.toml b/Cargo.toml index 2aedfcc4f..40e71fdcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -234,18 +234,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.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", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } [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 26113b11531c86f3705f8f56f066ea4fcabb2236 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:37:20 -0700 Subject: [PATCH 137/458] fix(satin): count nothing for a frame start revm refuses on its caller's account A frame start is counted before revm decides it. revm refuses a start on its caller's account, before it moves or writes anything, for a value the caller cannot fund and for a creation whose creator's nonce cannot be bumped. Such a start now gets an empty lane: no records, no transfer log, no history charged at the opcode or before the first frame, so no limit stops it for bytes it never makes. The caller's account is read from the journal without loading anything; it is always loaded by then. A creation onto an occupied address stays counted: revm decides it on the created address's account, which is not loaded yet. The debug-build frame-start check now also asserts that revm refused exactly the starts predicted. --- crates/mega-evm/src/evm/execution.rs | 171 +++++++++++++++++++----- crates/mega-evm/src/evm/instructions.rs | 17 +-- crates/mega-evm/src/limit/limit.rs | 13 +- crates/mega-evm/src/limit/mod.rs | 10 ++ 4 files changed, 169 insertions(+), 42 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index b2e4159f9..3f5680891 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -41,7 +41,7 @@ use revm::{ CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, SharedMemory, }, - primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, Inspector, Journal, }; @@ -402,7 +402,9 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm None, }; #[cfg(debug_assertions)] - let transfer_log = ( + let counted = ( ctx.additional_limit.frame_start_transfer_log(&frame_init.frame_input), + refused, ctx.journal_ref().logs().len(), ); let outcome = match self.inner.frame_init(frame_init)? { @@ -467,7 +476,7 @@ impl EvmTr for MegaEvm { ctx.additional_limit.set_frame_address(address); @@ -908,23 +917,38 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } -/// Asserts that revm journaled the EIP-7708 transfer log the data size counted for a frame's -/// start, once revm has built the frame or answered it: `counted` is whether -/// [`on_frame_init`](crate::AdditionalLimit) counted one, `logs_i` the journal's log count before -/// revm acted, and `answer` revm's answer when it did not build the frame. +/// 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 moves the value, from the frame's input, so this is where a -/// divergence from revm's own rule would show. 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. Only transfer -/// logs are compared: a precompile may journal logs of its own. +/// 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. +/// 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_transfer_log_journaled( +fn assert_start_as_counted( ctx: &MegaContext, - (counted, logs_i): (bool, usize), + (counted, refused, logs_i): (bool, bool, usize), answer: Option<&FrameResult>, ) { + 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(), @@ -1025,6 +1049,52 @@ 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, + } +} + +/// 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) + }) +} + /// The nonce of an account the journal holds; zero for one it does not. fn account_nonce( ctx: &MegaContext, @@ -1084,7 +1154,11 @@ struct AppliedAuthorities { /// 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. +/// first frame's record does not, so what it cost is kept for the settlement to give back. 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. /// `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, @@ -1094,14 +1168,17 @@ fn charge_records_made_outside_a_frame( if !ctx.prices_history() { return true; } - let top_level_record = match ctx.tx().kind() { + let tx = ctx.tx(); + let writes_a_record = match tx.kind() { TxKind::Create => true, TxKind::Call(to) => { - !ctx.tx().value().is_zero() && - to != ctx.tx().caller() && + !tx.value().is_zero() && + to != tx.caller() && !ctx.additional_limit.target_is_authority() } }; + let top_level_record = + writes_a_record && !caller_refuses(ctx, tx.caller(), tx.value(), tx.kind().is_create()); let Some(top_level) = write_record_history_gas(u64::from(top_level_record)) else { return false; }; @@ -1194,24 +1271,54 @@ mod tests { #[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_transfer_log_journaled(&ctx, (true, 0), None); + 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 expects no log where nothing moved, whatever was counted: a creation revm - /// answers — the nonce-overflow answer is a `Return` — and a call it answers with a failure; - /// and none for a frame nothing was counted for. + /// 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_transfer_log_journaled(&ctx, (false, 0), None); - let refused = synthetic_frame_result(&creation(), InstructionResult::Return, Bytes::new()); - assert_transfer_log_journaled(&ctx, (true, 0), Some(&refused)); + 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_transfer_log_journaled(&ctx, (true, 0), Some(&unfunded)); + 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_transfer_log_journaled(&ctx, (false, 0), Some(&answered)); + assert_start_as_counted(&ctx, (false, false, 0), Some(&answered)); } /// A charge that stands is held: a frame revm built latches the transaction, and a success diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 58c764b68..9f5a3a70a 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -67,7 +67,7 @@ use crate::{ MegaContext, }; -use super::MegaInstructions; +use super::{caller_refuses_start, MegaInstructions}; /// The context an instruction of the Satin engine runs with. type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; @@ -233,10 +233,11 @@ fn selfdestruct( /// 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. A frame revm refuses once it has it — a value call the caller cannot fund, -/// one past the call-stack limit — makes no records either, 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`]). +/// 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. +/// 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. That charge is held to the state-gas @@ -253,10 +254,10 @@ fn charge_frame_start( 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 call the balance cannot fund, an out-of-gas — leaves no such action and makes - // no records. + // 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)) => { + Some(InterpreterAction::NewFrame(input)) if !caller_refuses_start(host, input) => { host.additional_limit.frame_start_records(input) } _ => return result, diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index bf4fb675a..4d2504ffb 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -520,8 +520,17 @@ impl AdditionalLimit { /// 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, revm's own - /// refusal of a move its caller cannot fund included, discards both the log and its bytes. + /// 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, and it is called only for a start revm + /// makes as far as the caller's account decides it. A start revm refuses there — a value its + /// caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes + /// nothing, and gets an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)). + /// The one refusal decided after the count is a creation onto an occupied address: revm reads + /// the created address's account only once it builds the frame. Its records and transfer log + /// are counted, a crossing they cause stops the creation before revm could refuse it, and + /// without a crossing revm's refusal fails the creation and discards them. /// /// 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. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index b38b908f6..f0b48f6eb 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -40,6 +40,16 @@ //! 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 From acd72249784738f0e00f2225fdc0e4cb05d06a1d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:37:41 -0700 Subject: [PATCH 138/458] test(satin): pin that a frame start revm refuses runs as it does without a limit A value CALL, and a CALLCODE, their caller cannot fund: under the transaction's limit and under a frame budget each one byte short of what the move would count, the transaction runs exactly as with no limit, and funded to the last wei the same limits stop it. The caller is charged nothing for the records such a call would make, so one that keeps less than their history carries on. A deposit its depositor cannot fund fails as a deposit, not as a stop. A creation onto an occupied address is the one refusal decided after the count: its records and transfer log cross the transaction's limit before revm fails it on the collision. --- crates/mega-evm/tests/satin/transfer_logs.rs | 234 +++++++++++++++++-- 1 file changed, 217 insertions(+), 17 deletions(-) diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index d6e92a7f6..b87540b4a 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -17,6 +17,11 @@ //! which stops the transaction; 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, TxKind, B256, U256}; @@ -58,6 +63,8 @@ const REVERTER: Address = address!("0000000000000000000000000000000000d00006"); 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; @@ -275,6 +282,21 @@ fn execute( .expect("the transaction is valid") } +/// 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), + gas_limit: 1_000_000, + 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() @@ -578,29 +600,181 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { 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(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(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(db(VALUE, &actor), tx.clone(), tx_limit); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: body + bytes - 1, + used: body + bytes, + frame_local: false, + }), + "{name}: funded to the last wei, the move is counted", + ); + let stopped = execute(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. + let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); + assert!(150_000 / 64 < records, "the actor keeps less than the records cost"); + let gas_limit = 21_000 + history_gas(transaction_body_bytes(&tx(0))).unwrap() + 150_000; + + let refused = execute(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(refused.result.is_success(), "{:?}", refused.result); + let funded = execute(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(funded.result.is_halt(), "{:?}", funded.result); +} + +/// 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. +#[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) + .stop() + .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(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{:?}", free.result); + 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(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: body + Site::Create2.bytes(), + frame_local: false, + }), + ); + assert!(!stopped.result.is_success(), "the stop reverts the transaction"); +} + /// 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() { - const DEPOSITOR: Address = address!("0000000000000000000000000000000000d000de"); - let deposit = |mint: u128, value: u64| { - let mut tx = OpTx(op_transaction(TxEnv { - caller: DEPOSITOR, - kind: TxKind::Call(RECEIVER), - value: U256::from(value), - gas_limit: 1_000_000, - gas_price: 0, - ..Default::default() - })); - tx.0.deposit.source_hash = B256::repeat_byte(0x11); - tx.0.deposit.mint = Some(mint); - tx - }; let db = || MemoryDatabase::default().account_code(RECEIVER, Bytes::from_static(&[STOP])); - let tx = deposit(1_000, 400); + let tx = deposit(TxKind::Call(RECEIVER), 1_000, 400); let body = transaction_body_bytes(&tx); let outcome = execute(db(), tx, EvmTxRuntimeLimits::no_limits()); assert!(outcome.result.is_success(), "{:?}", outcome.result); @@ -616,7 +790,8 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { ); assert_eq!((outcome.gas.history, outcome.gas.history_bytes), (0, 0), "a deposit pays none"); - let minted = execute(db(), deposit(1_000, 0), EvmTxRuntimeLimits::no_limits()); + let minted = + execute(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)); @@ -624,7 +799,7 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { let limit = body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; let stopped = execute( db(), - deposit(1_000, 400), + deposit(TxKind::Call(RECEIVER), 1_000, 400), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); assert_eq!( @@ -636,6 +811,31 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { 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(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_halt(), "{kind:?}: {:?}", free.result); + assert_eq!(free.result.tx_gas_used(), 1_000_000, "{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(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 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. From 2e7433645a6946ef4906375ba3ae1e4e5dd08ea4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:38:05 -0700 Subject: [PATCH 139/458] fix(satin): keep nothing of a creation revm answers without its creator's nonce bump MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Such a creation wrote and moved nothing, so its lane now drops everything its start counted — the created account's record and the transfer log with the creator's record — and its caller gets back all it paid for them, whatever the answer. One such answer is a success: a creator whose nonce cannot be bumped is answered with a Return and no address, which merged the lane before. The start of that creation is already predicted and counts nothing; this holds the lane to revm's answer regardless. No account reaches that nonce by executing. A deposit runs from it, its nonce being unchecked, and so does a user's creation with the nonce check off; both are pinned: nothing kept, no limit stops them, and the user's creation pays history for its body alone. --- crates/mega-evm/src/evm/execution.rs | 5 +- crates/mega-evm/src/limit/frame_limit.rs | 18 ++++++ crates/mega-evm/src/limit/limit.rs | 47 ++++++++++++++-- crates/mega-evm/tests/satin/transfer_logs.rs | 58 +++++++++++++++++++- 4 files changed, 119 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 3f5680891..10d4a0943 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -455,9 +455,8 @@ impl EvmTr for MegaEvm { Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 9e5ac9c1c..fa6bc5e1e 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -269,6 +269,24 @@ impl FrameLimitTracker { self.total_used = self.total_used.saturating_sub(WRITE_RECORD); } + /// Takes back everything the running frame's start counted, its caller's record included + /// ([`drop_caller_record`](Self::drop_caller_record)): the start did not happen after all, so + /// the lane keeps nothing whatever the frame's answer, and its caller gets back all it paid + /// for the records. Must run before the frame runs, when its start is all the lane holds. + pub(crate) fn undo_frame_start(&mut self) { + self.drop_caller_record(); + let Some(lane) = self.lanes.last_mut() else { return }; + debug_assert_eq!( + lane.refund, + LimitUsage::ZERO, + "a frame that has not run took nothing back" + ); + debug_assert_eq!(lane.log_and_code_bytes, 0, "a frame that has not run logged nothing"); + self.total_used = self.total_used.saturating_sub(lane.used); + lane.used = LimitUsage::ZERO; + lane.records_made = false; + } + /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or /// the transaction's), a failure discards it. /// diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 4d2504ffb..8df7a78a1 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -608,13 +608,19 @@ impl AdditionalLimit { forwarded.min(self.limits.frame_usage_limit()) } - /// Takes a creation's creator record back: the creation failed before bumping the nonce. + /// Takes back what a creation's start counted: revm answered the creation without bumping its + /// creator's nonce, so the start wrote nothing and moved nothing — no creator's nonce, no + /// created account, no transfer log. /// - /// The record is gone, so the caller gets its history back when the frame returns: the lane no - /// longer holds a creator's record, and a lane that holds none gives its caller's charge back - /// with the rest. + /// A failure would discard the lane anyway, but not the creator's record, which outlives a + /// failed creation once the nonce was bumped. And one answer of this kind is a success: a + /// creator whose nonce cannot be bumped is answered with a `Return` and no address, which + /// would merge the lane into the caller's. Such a start is predicted and counts nothing in + /// the first place ([`on_frame_init`](Self::on_frame_init)); this holds the lane to revm's + /// answer whatever was counted. The caller gets back all it paid for the records when the + /// frame returns. pub(crate) fn creation_did_not_bump_nonce(&mut self) { - self.tracker.drop_caller_record(); + self.tracker.undo_frame_start(); } fn push_lane(&mut self, input: &FrameInput, depth: usize) { @@ -1170,6 +1176,37 @@ mod tests { ))) } + /// A creation revm answers without bumping its creator's nonce keeps nothing its start + /// counted, whatever the answer: a failure, and the success a creator whose nonce cannot be + /// bumped is answered with. The created account's record, the transfer log and the creator's + /// record all go, the caller gets back all it paid for them, and the creator's account is no + /// longer counted as recorded, so its next value transfer records it. + #[test] + fn test_a_creation_that_did_not_bump_the_nonce_keeps_nothing() { + let inner = creation(CALLEE, U256::from(1)); + for answer in [InstructionResult::Return, InstructionResult::OutOfFunds] { + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); + limit.on_frame_init(&inner, 1); + assert_eq!( + limit.usage(), + LimitUsage { + data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 2, + }, + "{answer:?}: the created account, the creator and the log", + ); + + limit.creation_did_not_bump_nonce(); + let mut result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); + assert_eq!(limit.on_frame_return(&mut result), 3_000, "{answer:?}: all of it back"); + assert_eq!(limit.usage(), LimitUsage::ZERO, "{answer:?}: nothing kept"); + let next = limit.frame_start_records(&call_from_to(CALLEE, TARGET, U256::from(1))); + assert!(next.caller, "{answer:?}: the creator is not recorded"); + } + } + /// 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 diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index b87540b4a..266953dec 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -40,7 +40,10 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP}, - context::TxEnv, + context::{ + result::{ExecutionResult, Output}, + TxEnv, + }, }; use crate::common::context; @@ -836,6 +839,59 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { } } +/// 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(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. From 11bbf95b0762e775b232ff9639c4edadb501383f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:38:12 -0700 Subject: [PATCH 140/458] docs(satin): say which frame starts are counted before revm decides them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md and the crate README: 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 no log and no record and is charged nothing; a creation onto an occupied address is the one refusal decided after the count, so a crossing it causes stops the creation first; a creation revm answers without the nonce bump keeps nothing. The debug-build check now covers the refusals too. --- AGENTS.md | 9 ++++++--- crates/mega-evm/README.md | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2c9f11ba8..5d83bb784 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -101,7 +101,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, 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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`) and the debug-build check that revm journaled the transfer log a frame start counted (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `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, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges 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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | | `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/` | 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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | detention | @@ -149,9 +149,12 @@ 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 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 debug build asserts after every frame start that revm 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. + 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 creation revm answers without bumping its creator's nonce keeps nothing its start counted, whatever the answer. + 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, 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 revm would deposit before the creation is committed (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 before it is forwarded. + 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 revm would deposit before the creation is committed (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 before it is forwarded. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (see the block executor below). diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index ee65643cf..8b843fe43 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -44,6 +44,7 @@ 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. `EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB of data size. From 05dd156072c6a8fec245b60ea5fdb8897bed3bac Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:38:17 -0700 Subject: [PATCH 141/458] docs(satin): say that a dynamic precompile's own logs are not counted The data size counts a log where a LOG opcode completes, so logs a precompile a node adds writes itself are not in it. --- crates/mega-evm/src/evm/precompiles.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 712f504e2..d515d53dc 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -45,6 +45,9 @@ pub fn satin_precompiles_map() -> PrecompilesMap { /// /// 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>; From e8a140c23e99e4419bade56dcb33deff7e68a21b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:42:15 -0700 Subject: [PATCH 142/458] feat(limit): make gas detention's caps runtime limits The two caps a read of volatile data sets become fields of EvmTxRuntimeLimits, as on the legacy engine: the block environment's (and the block beneficiary's) and the Oracle's. The default holds both at the spec's 20,000,000; no_limits leaves them unlimited, and a transaction whose caps are both unlimited is not detained. A block's default limits carry the spec's caps, BlockLimits::no_limits clears them. The neutral configuration no longer switches detention off on its own: the execution-spec gate's runner installs no_limits, which now turns it off through the same path as every other limit. --- AGENTS.md | 11 +- crates/mega-evm/README.md | 3 +- crates/mega-evm/src/access/detention.rs | 130 ++++++++++-------- crates/mega-evm/src/access/mod.rs | 13 +- crates/mega-evm/src/block/limit.rs | 28 ++-- crates/mega-evm/src/constants.rs | 4 +- crates/mega-evm/src/evm/context.rs | 13 +- crates/mega-evm/src/limit/mod.rs | 71 +++++++++- crates/mega-evm/src/test_utils/neutral.rs | 5 +- crates/mega-evm/tests/block/detention.rs | 8 +- crates/mega-evm/tests/satin/detention.rs | 51 ++++++- crates/mega-evm/tests/satin/neutral.rs | 12 +- .../mega-evm/tests/satin/volatile_access.rs | 2 +- 13 files changed, 258 insertions(+), 93 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 90c39445a..afbf08173 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,10 +104,10 @@ 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 lifecycle (detention's hooks included), 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, the volatile-read marks and refusals and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | | `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit) | the detention caps as runtime limits | +| `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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit, the gas withheld per frame and its release, the compute figure across frames, and the volatile-access switch with its refusals (`detention.rs`) | the control contracts steering the switch | | `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (steering the detention switch, the 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, detention caps) | 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 | +| `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 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | @@ -165,7 +165,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 them, a system transaction being promoted to a deposit. 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 20,000,000 (see Gas detention below). +- 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). Crossing the cap stops the transaction through the latch, with `MegaLimitExceeded` of kind compute. - `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`. @@ -192,12 +192,13 @@ 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 and an applied EIP-7702 authority that is; 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, a system call and the neutral configuration are not detained. + A system-originated transaction and a system call are not detained, and 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 spent, read off `Gas`: state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. - A read sets a limit — the transaction's compute at the read plus `BLOCK_ENV_ACCESS_COMPUTE_GAS` or `ORACLE_ACCESS_COMPUTE_GAS`, 20,000,000 each — and the limit only goes down, so the most restrictive read binds. + 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. + `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. 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: the regular ledger at every moment. - **The enforcement point: withheld gas.** The interpreter stops a frame on one condition only, running out of regular gas, so every frame that runs keeps no more regular gas than the limit leaves the transaction; the rest moves into its reservoir, where state and history charges still reach it and regular charges cannot. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index e2173f876..da05a3651 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -104,7 +104,8 @@ Every frame keeps no more regular gas than the limit leaves the transaction; the A frame that runs out of gas while gas is still withheld from it crossed the cap: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, and the sender gets back everything withheld. A frame that runs out of its own gas still halts. 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 protocol's own transactions, the system calls and the execution-spec gate's neutral configuration are not detained. +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. Keyless deployment arrives in a later change. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 8d821a7b8..a1d249409 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -9,10 +9,7 @@ use alloy_primitives::{Bytes, U256}; use revm::interpreter::{Gas, InstructionResult}; use super::VolatileDataAccess; -use crate::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, - system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, -}; +use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; /// What detention keeps of one frame that runs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -60,11 +57,13 @@ pub struct Detention { 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 and the - /// neutral configuration's are not. + /// 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, - /// Whether the neutral configuration runs, which detains no transaction. - neutral: 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. @@ -85,12 +84,17 @@ pub struct Detention { } impl Detention { - /// Clears the state for a new transaction, keeping its allocation. `detains` is whether the - /// transaction's reads are held to a cap. - pub(crate) fn reset(&mut self, detains: bool) { + /// 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 && !self.neutral; + 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; #[cfg(any(test, feature = "test-utils"))] { @@ -107,13 +111,6 @@ impl Detention { self.frames.clear(); } - /// Turns detention off for every transaction from the next one on: the neutral - /// configuration. - #[cfg(any(test, feature = "test-utils"))] - pub(crate) const fn set_neutral(&mut self, neutral: bool) { - self.neutral = neutral; - } - /// 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. @@ -130,7 +127,7 @@ impl Detention { /// 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. + /// read nothing a cap holds. /// /// Compute here is the transaction's regular gas spent in its frames, without its intrinsic /// gas. @@ -214,8 +211,12 @@ impl Detention { forwarded: u64, ) { self.accessed |= observed; + let cap = self.cap_of(observed); + if cap == u64::MAX { + return; + } let compute = self.compute(gas, depth).saturating_sub(forwarded); - let limit = compute.saturating_add(cap_of(observed)); + let limit = compute.saturating_add(cap); self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); self.cap_frame(gas, depth, compute); } @@ -228,8 +229,10 @@ impl Detention { return; } self.accessed |= access; - let limit = cap_of(access); - self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); + let limit = self.cap_of(access); + if limit != u64::MAX { + self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); + } } /// Holds the running frame at `depth` to the limit again, after an opcode that can hand it @@ -363,6 +366,19 @@ impl Detention { .saturating_sub(self.burned) } + /// 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 + } + /// Withholds from the frame at `depth` the regular gas it has beyond what the limit leaves /// the transaction, `compute` being the transaction's compute now. /// @@ -393,18 +409,6 @@ pub fn volatile_data_access_disabled_revert_data(access: VolatileDataAccess) -> data.into() } -/// The cap a read of `access` sets: the lowest of the caps of the kinds it holds. -fn cap_of(access: VolatileDataAccess) -> u64 { - let mut cap = u64::MAX; - if access.has_block_env_access() || access.has_beneficiary_balance_access() { - cap = cap.min(BLOCK_ENV_ACCESS_COMPUTE_GAS); - } - if access.has_oracle_access() { - cap = cap.min(ORACLE_ACCESS_COMPUTE_GAS); - } - cap -} - /// The regular gas a frame spent: its limit, less what it has left, less the state and history /// gas that spilled onto its regular gas. #[inline] @@ -447,6 +451,7 @@ pub(crate) fn release(gas: &mut Gas, withheld: u64) { #[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 { @@ -455,23 +460,21 @@ mod tests { fn detaining() -> Detention { let mut detention = Detention::default(); - detention.reset(true); + 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; both caps are the - /// same today, so every kind sets the same one. + /// 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() { - assert_eq!(cap_of(VolatileDataAccess::TIMESTAMP), BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert_eq!(cap_of(VolatileDataAccess::SLOT_NUM), BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert_eq!(cap_of(VolatileDataAccess::BENEFICIARY_BALANCE), BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert_eq!(cap_of(VolatileDataAccess::ORACLE), ORACLE_ACCESS_COMPUTE_GAS); - assert_eq!( - cap_of(VolatileDataAccess::ORACLE | VolatileDataAccess::TIMESTAMP), - BLOCK_ENV_ACCESS_COMPUTE_GAS.min(ORACLE_ACCESS_COMPUTE_GAS) - ); - assert_eq!(cap_of(VolatileDataAccess::empty()), u64::MAX); + 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 caps the frame at its compute then plus the cap: the regular gas beyond it moves @@ -644,17 +647,36 @@ mod tests { assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); } - /// A transaction that is not detained records nothing and caps nothing. + /// 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_transaction_is_not_detained() { + 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(false); + 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.observe(VolatileDataAccess::TIMESTAMP); - assert!(!detention.has_reads()); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); - assert_eq!(detention.compute_limit(), None); - assert_eq!(detention.accessed(), VolatileDataAccess::empty()); + assert_eq!(detention.compute_limit(), None, "an unlimited cap sets no limit"); + assert_eq!(frame.remaining(), 100_000_000); + 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 324943933..83cbaa4d0 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -11,9 +11,16 @@ //! //! | Kind | Read by | Cap | //! |---|---|---| -//! | the block environment | `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH` | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) | -//! | 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, and an applied EIP-7702 authority that is | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) | -//! | the Oracle's storage | `SLOAD` in the Oracle's own frame | [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS) | +//! | 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, and an applied EIP-7702 authority 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)): the spec's, +//! [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) and +//! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default, and a +//! caller's limits may set either. 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. //! //! `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: they are the diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index b63c4e4f8..c87e8b67c 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -3,8 +3,9 @@ //! [`BlockLimits`] is the configuration a node passes in the block execution context; //! [`BlockLimiter`] is the state one block keeps while it executes. Data size defaults to the //! production caps — [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) for the block and -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) for each transaction — and every other -//! limit defaults to unlimited. [`BlockLimits::no_limits`] clears the data-size caps too. +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) for each transaction — gas detention's caps +//! to the spec's, and every other limit to unlimited. [`BlockLimits::no_limits`] clears the +//! data-size and detention caps too. //! //! # When each limit is checked //! @@ -109,7 +110,8 @@ pub struct BlockLimits { /// /// [`Default`] sets the transaction data-size limit to /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) and leaves the frame cap unlimited, so a - /// frame's budget is the 98% share of what its parent has left. + /// frame's budget is the 98% share of what its parent has left; gas detention's caps are the + /// spec's, as [`EvmTxRuntimeLimits::default`] holds them. pub tx_runtime_limits: EvmTxRuntimeLimits, } @@ -139,15 +141,18 @@ impl BlockLimits { /// The limits a block runs under when its caller configures nothing else. /// - /// Every dimension is unlimited except data size: the block holds - /// [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) bytes, and each transaction holds - /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT). The block executor installs the - /// transaction half on the EVM. + /// Every dimension is unlimited except data size and gas detention's caps: the block holds + /// [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) bytes, each transaction holds + /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT), and a read of volatile data caps the + /// transaction's compute at the spec's caps. The block executor installs the transaction half + /// on the EVM. pub const fn with_production_data_limits() -> Self { let mut limits = Self::no_limits(); limits.block_txs_data_limit = crate::constants::BLOCK_DATA_LIMIT; limits.tx_runtime_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT); + .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) + .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) + .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS); limits } @@ -499,13 +504,18 @@ mod tests { use super::*; use alloy_primitives::B256; - /// A block that configures nothing holds the production data-size caps and nothing else. + /// A block that configures nothing holds the production data-size caps and gas detention's + /// caps, and nothing else. #[test] fn test_the_default_limits_are_the_production_data_size_caps() { let limits = BlockLimits::default(); assert_eq!(limits, BlockLimits::with_production_data_limits()); assert_eq!(limits.block_txs_data_limit, crate::constants::BLOCK_DATA_LIMIT); assert_eq!(limits.tx_runtime_limits.tx_data_size_limit, crate::constants::TX_DATA_LIMIT); + assert_eq!( + limits.tx_runtime_limits, + EvmTxRuntimeLimits::default().with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) + ); assert_eq!(limits.tx_runtime_limits.frame_data_size_limit, u64::MAX); assert_eq!(limits.tx_gas_limit, u64::MAX); assert_eq!(limits.block_execution_gas_limit, u64::MAX); diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index d5c99566c..0176019ab 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -15,8 +15,8 @@ //! | [`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 block's default transaction limits | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the block's default data-size limit | -//! | [`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) | gas detention | -//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | gas detention | +//! | [`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) | the default detention cap of the runtime limits | +//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits | //! //! 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 diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 7a7c5bdd7..6d9117788 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -110,7 +110,6 @@ impl MegaContext { #[cfg(any(test, feature = "test-utils"))] { self.neutral = false; - self.detention.set_neutral(false); } self } @@ -130,7 +129,9 @@ impl MegaContext { /// 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. - /// - No transaction is detained: a read of volatile data caps nothing. + /// - 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 @@ -141,7 +142,6 @@ impl MegaContext { self.cfg = cfg; self.neutral = true; self.prices_history = false; - self.detention.set_neutral(true); self } @@ -338,7 +338,12 @@ impl MegaContext { // 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. - self.detention.reset(!system_originated); + 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(); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index d1f90ff8c..ce9c118d3 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -201,7 +201,8 @@ pub struct LimitUsage { pub write_records: u64, } -/// Limits one transaction's data size, write records and state gas. +/// Limits one transaction's data size, write records, state gas and compute after a read of +/// volatile data. /// /// [`tx_data_size_limit`](Self::tx_data_size_limit) and /// [`tx_kv_update_limit`](Self::tx_kv_update_limit) stop the transaction. A frame's own budget in @@ -214,7 +215,17 @@ pub struct LimitUsage { /// budget. /// /// [`tx_state_gas_limit`](Self::tx_state_gas_limit) holds the transaction's state gas and stops -/// the transaction; it has no frame budget. Every limit is unlimited unless a caller sets it. +/// the transaction; it has no frame 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. They default to +/// the spec's, [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] and [`ORACLE_ACCESS_COMPUTE_GAS`]; every other +/// limit is unlimited unless a caller sets it. [`no_limits`](Self::no_limits) leaves every one +/// unlimited, the caps included, and a transaction whose caps are both unlimited is not detained. +/// +/// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS +/// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EvmTxRuntimeLimits { /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. @@ -236,16 +247,27 @@ pub struct EvmTxRuntimeLimits { /// slot or an account in a crowded SALT bucket costs its bucket's multiple of the schedule's /// entry, and reaches the limit that many times sooner. pub tx_state_gas_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 stops the + /// transaction. `u64::MAX` caps nothing. + 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 stops the transaction. `u64::MAX` caps nothing. + pub oracle_access_compute_gas_limit: u64, } impl Default for EvmTxRuntimeLimits { + /// Gas detention's caps at the spec's, every other limit unlimited. fn default() -> Self { Self::no_limits() + .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) + .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS) } } 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. pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, @@ -253,6 +275,8 @@ impl EvmTxRuntimeLimits { tx_kv_update_limit: u64::MAX, frame_kv_update_limit: u64::MAX, tx_state_gas_limit: u64::MAX, + block_env_access_compute_gas_limit: u64::MAX, + oracle_access_compute_gas_limit: u64::MAX, } } @@ -286,6 +310,19 @@ impl EvmTxRuntimeLimits { 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 + } + /// The transaction's limits on what it keeps, one per dimension of [`LimitUsage`]. pub(crate) const fn tx_usage_limit(&self) -> LimitUsage { LimitUsage { data_size: self.tx_data_size_limit, write_records: self.tx_kv_update_limit } @@ -502,6 +539,8 @@ mod tests { tx_kv_update_limit, frame_kv_update_limit, tx_state_gas_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, } = EvmTxRuntimeLimits::no_limits(); for limit in [ tx_data_size_limit, @@ -509,10 +548,34 @@ mod tests { tx_kv_update_limit, frame_kv_update_limit, tx_state_gas_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, ] { assert_eq!(limit, u64::MAX); } - assert_eq!(EvmTxRuntimeLimits::default(), EvmTxRuntimeLimits::no_limits()); + } + + /// The default holds gas detention's caps at the spec's and leaves every other limit + /// unlimited; a caller's limits change either cap alone. + #[test] + fn test_the_default_caps_detention_at_the_specs_and_nothing_else() { + use crate::constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}; + let default = EvmTxRuntimeLimits::default(); + assert_eq!(default.block_env_access_compute_gas_limit, BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(default.oracle_access_compute_gas_limit, ORACLE_ACCESS_COMPUTE_GAS); + assert_eq!( + default + .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] diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 39b8386c0..d6de5c13b 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -12,8 +12,9 @@ //! common execution layer, and the gate's runner installs //! [`EvmTxRuntimeLimits::no_limits`](crate::EvmTxRuntimeLimits::no_limits) in equivalence mode, //! under which neither the data-size, the KV nor the state-gas limit binds, at the transaction or -//! at a frame. 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. +//! at 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. //! //! 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 diff --git a/crates/mega-evm/tests/block/detention.rs b/crates/mega-evm/tests/block/detention.rs index b1dbd70e9..2eab471a7 100644 --- a/crates/mega-evm/tests/block/detention.rs +++ b/crates/mega-evm/tests/block/detention.rs @@ -4,7 +4,8 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::Bytes; use mega_evm::{ - constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, LimitCheck, LimitKind, + constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, BlockLimits, LimitCheck, + LimitKind, }; use revm::{ bytecode::opcode::{JUMP, JUMPDEST, MCOPY, POP, PUSH0, TIMESTAMP}, @@ -12,7 +13,7 @@ use revm::{ database::State, }; -use crate::common::{self, executor_with_env, unlimited_ctx, user_tx}; +use crate::common::{self, block_ctx, executor_with_env, user_tx}; /// Reads the block's timestamp, then copies memory forever. fn read_then_spin() -> Bytes { @@ -37,7 +38,8 @@ fn test_a_stopped_transaction_is_included_with_a_failed_receipt_that_bills_what_ let mut state = State::builder().with_database(db).build(); let mut env = common::evm_env(); env.block_env.gas_limit = 100_000_000; - let mut executor = executor_with_env(&mut state, unlimited_ctx(), env); + // The production limits: the block's default holds the spec's detention caps. + let mut executor = executor_with_env(&mut state, block_ctx(BlockLimits::default()), env); executor.apply_pre_execution_changes().expect("the block starts"); let gas_limit = 29_000_000; diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 39c4ac56b..16ffb555b 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -16,8 +16,9 @@ use mega_evm::{ constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, 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, LimitCheck, LimitKind, MegaContext, MegaEvm, - MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, VolatileDataAccess, + volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, + MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, + VolatileDataAccess, }; use revm::{ bytecode::opcode::*, @@ -610,6 +611,52 @@ fn test_the_most_restrictive_limit_binds_whatever_the_order() { } } +/// 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. + let run = run_under(limits, spin(op(BytecodeBuilder::default(), TIMESTAMP))); + assert_eq!(assert_stopped(&run, intrinsic), 2 + 1_000_000); + + let run = run_under( + limits, + spin(call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS)), + ); + let limit = assert_stopped(&run, intrinsic); + 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 + ); + } +} + /// Spending exactly the cap after the read is within it; the limit is strict. #[test] fn test_spending_exactly_the_cap_completes() { diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index ff41ef0a7..81dd71ebc 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -21,7 +21,8 @@ use mega_evm::{ neutral_cfg, neutralize_evm, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, - EthSpecId, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, VolatileDataAccess, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + VolatileDataAccess, }; use op_revm::{ constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, @@ -74,6 +75,7 @@ fn block() -> BlockEnv { 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) @@ -217,6 +219,7 @@ fn run_against_ethereum(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outc 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); @@ -287,8 +290,10 @@ fn test_neutral_programs_match_ethereum() { } } -/// The neutral configuration detains nothing: a program that reads the block environment and the -/// block beneficiary's account records no read and sets no compute limit, and matches Ethereum. +/// 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() @@ -300,6 +305,7 @@ fn test_neutral_reads_of_volatile_data_detain_nothing() { 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); diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index fcfe78350..ef24ec5d5 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -238,7 +238,7 @@ fn test_detention_leaves_a_data_size_stop_to_the_data_size_limit() { 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::no_limits().with_tx_data_size_limit(data_limit), + 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"); From ae7892f80607e7b368e874ab6e8de89002aa92a1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:46:15 -0700 Subject: [PATCH 143/458] feat(access): hold detained frames on the fork's withheld gas Gas detention held a frame to its compute limit by moving the regular gas above it into the frame's EIP-8037 reservoir. That changed what every other reader of the frame's gas saw (GAS, the 63/64 forward, the SSTORE sentry, the skip-cold checks, what a callee inherits), and it could not tell a charge the moved gas would have paid from a real out-of-gas. The frame's spendable part is now held with the fork's limit_spendable, at the allowance the limit leaves the transaction: at a read once it is committed, at every frame start and resume, and after SSTORE. Every other reader sees the whole regular gas, as without the read. Compute is the regular ledger read off Gas, where withheld gas is never spent, less what halts burn. A frame that halts out of gas with the fork's crossing record crossed the limit: it becomes the latched MegaLimitExceeded(2, limit) revert, its gas the record's withheld part, so its spendable part counts as spent and the stop reports the limit as used. Every other out-of-gas halts and burns as it would without the read. A precompile's or an interceptor's answer that spent more than the allowance the frame would have run on is answered out of gas with a crossing record and settled by the same rule; an answer that halts burns its gas limit. The wrappers note what a frame has left when a charge fails on an out-of-gas the halt then zeroes, and KECCAK256 and the four copies into memory get a wrapper for it, so what a halt burns is not counted as compute. --- crates/mega-evm/src/access/detention.rs | 456 +++++++++++++---------- crates/mega-evm/src/evm/execution.rs | 94 ++++- crates/mega-evm/src/evm/instructions.rs | 108 ++++-- crates/mega-evm/tests/satin/detention.rs | 52 +-- 4 files changed, 458 insertions(+), 252 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index a1d249409..fc05a4507 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -2,11 +2,11 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::cell::Cell; +use core::{cell::Cell, num::NonZeroU64}; use std::vec::Vec; use alloy_primitives::{Bytes, U256}; -use revm::interpreter::{Gas, InstructionResult}; +use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult}; use super::VolatileDataAccess; use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; @@ -14,36 +14,46 @@ use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; /// What detention keeps of one frame that runs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct DetainedFrame { - /// Regular gas withheld from the frame, which its reservoir holds until the frame returns. - withheld: u64, - /// The frame's own compute when it suspended on a child: its regular gas spent, less what - /// detention withheld. + /// 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, } -/// Gas detention for the running transaction: which volatile data it read, the most compute it -/// may reach because of it, and what each frame had withheld to enforce that. +/// 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 its limit less what it has left, less the state and history gas that spilled onto its -/// regular gas, which are not compute. The transaction's compute is its frames' compute: the -/// frame that runs, read off its [`Gas`], 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. +/// 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 ([`regular_spent`]). 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 one part of the regular ledger that is not compute is what a halt burns: a frame that -/// halts consumes the gas it had left without running anything with it. That gas is taken off the -/// transaction's compute when the frame returns. A frame that ran out of gas has nothing left by -/// then, so what it had when the charge failed counts as spent. +/// 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 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 ([`note_halt`](Self::note_halt)). The two charges no wrapper sees — an opcode's +/// static gas and `EXP`'s exponent — are bounded by their own price, and what a frame had left +/// below it counts as compute. /// /// # Refused reads /// @@ -79,6 +89,8 @@ pub struct Detention { suspended: u64, /// 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, /// One entry per frame that runs or is suspended, the running one last. frames: Vec, } @@ -108,6 +120,7 @@ impl Detention { self.limit = None; self.suspended = 0; self.burned = 0; + self.left_at_halt = None; self.frames.clear(); } @@ -197,9 +210,9 @@ impl Detention { self.observed.replace(VolatileDataAccess::empty()) } - /// Commits the reads `observed` of the opcode the frame at `depth` completed, whose gas is - /// `gas`: the transaction's limit becomes its compute now plus the reads' cap, unless it is - /// already lower, and the frame keeps no more regular gas than the limit leaves it. + /// Commits the reads `observed` of the opcode the running frame completed, whose gas is `gas`: + /// 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. /// /// `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. @@ -207,7 +220,6 @@ impl Detention { &mut self, observed: VolatileDataAccess, gas: &mut Gas, - depth: usize, forwarded: u64, ) { self.accessed |= observed; @@ -215,10 +227,9 @@ impl Detention { if cap == u64::MAX { return; } - let compute = self.compute(gas, depth).saturating_sub(forwarded); - let limit = compute.saturating_add(cap); - self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); - self.cap_frame(gas, depth, compute); + 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 @@ -229,23 +240,32 @@ impl Detention { return; } self.accessed |= access; - let limit = self.cap_of(access); - if limit != u64::MAX { - self.limit = Some(self.limit.map_or(limit, |current| current.min(limit))); + let cap = self.cap_of(access); + if cap != u64::MAX { + self.lower_limit(cap); } } - /// Holds the running frame at `depth` to the limit again, after an opcode that can hand it - /// regular gas back: a storage write restored to its original value refills the state and - /// history gas it spilled onto regular gas, which may have spilled before the limit was set. + /// 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 recap(&mut self, gas: &mut Gas, depth: usize) { - if self.limit.is_some() { - let compute = self.compute(gas, depth); - self.cap_frame(gas, depth, compute); + 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 @@ -262,17 +282,18 @@ impl Detention { return; } 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 = caller.at_suspension.saturating_sub(gas.limit()); - self.suspended = self.suspended.saturating_add(caller.contribution); + 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"); - self.recap(gas, depth); + self.hold(gas); } /// The frame at `depth`, whose gas is `gas`, suspended to start a child. Its compute stands @@ -283,30 +304,24 @@ impl Detention { return; } if let Some(frame) = self.frames.get_mut(depth) { - frame.at_suspension = regular_spent(gas).saturating_sub(frame.withheld); + frame.at_suspension = regular_spent(gas); } } - /// The frame at `depth` returns `result` with `gas`: the gas withheld from it goes back into - /// its regular gas, and the switch turns back on if the frame, or a frame below it, turned it - /// off. When the frame halts, what the halt burns is not compute. + /// 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 limit, and the compute the transaction had spent, when the frame ran out of - /// gas while detention still held back some of what it withheld: the cap bound before the - /// frame's own gas, and the frame must stop the transaction rather than halt. - /// - /// Without detention the frame would have had `min(withheld, reservoir)` more regular gas when - /// it ran out ([`release`]). While that is above zero the charge that failed may have been one - /// the cap refused, and the cap is the tighter of the two bounds, so it is the one reported. - /// Once the frame's state and history charges have drawn the reservoir dry, the withheld gas - /// is spent and the frame ran out exactly where it would have undetained: its own gas. + /// Returns the limit 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 stop the + /// transaction rather than halt. #[inline] pub(crate) fn on_frame_end( &mut self, result: InstructionResult, gas: &mut Gas, depth: usize, - ) -> Option<(u64, u64)> { + ) -> Option { + let left_at_halt = self.left_at_halt.take(); if self.disabled_from.is_some_and(|from| from >= depth) { self.disabled_from = None; } @@ -314,18 +329,66 @@ impl Detention { return None; } debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); - let withheld = self.frames.last().map_or(0, |frame| frame.withheld); - let held_back = withheld.min(gas.reservoir()); - let stop = (held_back > 0 && runs_out_of_gas(result)) - .then(|| (self.limit.unwrap_or(u64::MAX), self.compute(gas, depth))); self.frames.pop(); - release(gas, withheld); - if stop.is_none() && result.is_halt() { + if let Some(limit) = self.stop(gas) { + return Some(limit); + } + if result.is_halt() { // The settlement rolls the spill back into regular gas and burns it all. - let burned = gas.remaining().saturating_add(gas.state_gas_spilled()); - self.burned = self.burned.saturating_add(burned); + let left = left_at_halt.unwrap_or_else(|| gas.remaining()); + self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled()); } - stop + None + } + + /// The frame at `depth`, whose gas limit was `gas_limit`, was answered without running — + /// `result` is the answer: a precompile's, an interceptor's, an inspector's, or revm's for a + /// call it did not start. + /// + /// 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: it is answered out of gas, marked as a crossing + /// of what the frame would have had withheld, and settled by the same rule as a frame that ran + /// ([`stop`](Self::stop)). Returns the limit when it crossed. + pub(crate) fn on_answer( + &mut self, + result: &mut InterpreterResult, + depth: usize, + gas_limit: u64, + ) -> Option { + if !self.detains { + return None; + } + if result.result.is_halt() { + self.burned = self.burned.saturating_add(gas_limit); + return None; + } + let limit = self.limit?; + let allowance = limit.saturating_sub(self.compute_at_start(depth, gas_limit)); + if gas_limit.saturating_sub(result.gas.remaining()) <= 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. + let withheld = NonZeroU64::new(gas_limit - allowance)?; + result.result = InstructionResult::OutOfGas; + result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); + self.stop(&mut result.gas) + } + + /// 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 gas becomes the withheld part at the crossing: the spendable part the frame had + /// counts as spent, which brings the transaction's compute to the limit, and the withheld part + /// goes back to its caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not + /// (`MemoryOOG`), 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.withheld()); + gas.clear_withheld_crossing(); + self.limit } /* The switch */ @@ -357,15 +420,36 @@ impl Detention { /* Helpers */ - /// The transaction's compute while the frame at `depth` runs with `gas`. - fn compute(&self, gas: &Gas, depth: usize) -> u64 { - let own = self.frames.get(depth).map_or(0, |frame| frame.withheld); + /// The transaction's compute while the running frame has `gas`. + fn compute(&self, gas: &Gas) -> u64 { + self.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.suspended - .saturating_add(regular_spent(gas)) - .saturating_sub(own) + .saturating_add(self.caller_contribution(depth, gas_limit)) .saturating_sub(self.burned) } + /// 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)) + } + + /// 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 { @@ -378,25 +462,6 @@ impl Detention { } cap } - - /// Withholds from the frame at `depth` the regular gas it has beyond what the limit leaves - /// the transaction, `compute` being the transaction's compute now. - /// - /// The gas moves into the frame's reservoir. A regular charge cannot draw on the reservoir, - /// so the frame cannot compute with it; a state or history charge draws on the reservoir - /// first, so the frame can still pay for what it writes and appends, which is not compute. - fn cap_frame(&mut self, gas: &mut Gas, depth: usize, compute: u64) { - let Some(limit) = self.limit else { return }; - let allowance = limit.saturating_sub(compute); - let excess = gas.remaining().saturating_sub(allowance); - if excess == 0 { - return; - } - let Some(frame) = self.frames.get_mut(depth) else { return }; - gas.set_remaining(gas.remaining() - excess); - gas.set_reservoir(gas.reservoir().saturating_add(excess)); - frame.withheld = frame.withheld.saturating_add(excess); - } } /// The revert data of a read of `access` refused while volatile-data access is switched off: @@ -409,45 +474,13 @@ pub fn volatile_data_access_disabled_revert_data(access: VolatileDataAccess) -> data.into() } -/// The regular gas a frame spent: its limit, less what it has left, less the state and history -/// gas that spilled onto its regular gas. +/// 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()) } -/// Whether `result` is running out of gas: a charge the frame could not pay. Running into the -/// memory limit is not, nor is a precompile's out-of-gas, which no frame that runs returns. -const fn runs_out_of_gas(result: InstructionResult) -> bool { - matches!( - result, - InstructionResult::OutOfGas | - InstructionResult::MemoryOOG | - InstructionResult::InvalidOperandOOG | - InstructionResult::ReentrancySentryOOG - ) -} - -/// Hands `withheld` back to the regular gas of the frame whose final gas is `gas`, as if it had -/// never been withheld. -/// -/// Withheld gas sits in the reservoir, where the frame's state and history charges may have drawn -/// on it. What is left of it goes back to regular gas; what was drawn is counted as having -/// spilled onto regular gas, which is where those charges would have come from had nothing been -/// withheld. The frame's result then settles exactly as it would have without detention: a -/// success or a revert gives the caller the unspent regular gas, a halt burns it, and the -/// reservoir returns to what the caller handed down. -#[inline] -pub(crate) fn release(gas: &mut Gas, withheld: u64) { - if withheld == 0 { - return; - } - let back = withheld.min(gas.reservoir()); - gas.set_reservoir(gas.reservoir() - back); - gas.set_remaining(gas.remaining().saturating_add(back)); - gas.add_state_gas_spilled(withheld - back); -} - #[cfg(test)] mod tests { use super::*; @@ -477,24 +510,22 @@ mod tests { assert_eq!(detention.cap_of(VolatileDataAccess::empty()), u64::MAX); } - /// A read caps the frame at its compute then plus the cap: the regular gas beyond it moves - /// into the reservoir, and the frame returns it on release. + /// 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); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert_eq!(detention.compute_limit(), Some(1_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); - assert_eq!(frame.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert_eq!(frame.reservoir(), 7 + 100_000_000 - 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); - assert_eq!((frame.remaining(), frame.reservoir()), (100_000_000 - 1_000, 7)); - assert_eq!(frame.state_gas_spilled(), 0); } /// A limit only goes down: a later read with room for more leaves it where it is. @@ -503,67 +534,73 @@ 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.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000); } - /// What a state charge drew from the withheld gas counts as spilled once released: that is - /// where it would have come from, and a revert gives it back to regular gas as a spill. + /// State and history gas draw the withheld part first and are not compute: the frame's + /// allowance is what it was. #[test] - fn test_release_counts_what_state_drew_as_spilled() { + 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); - let withheld = 100_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS; - assert!(frame.record_state_cost(withheld + 10)); - assert_eq!(frame.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 10); + 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); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + } - detention.on_frame_end(InstructionResult::Revert, &mut frame, 0); - assert_eq!(frame.remaining(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 10); - assert_eq!(frame.reservoir(), 0); - assert_eq!(frame.state_gas_spilled(), withheld + 10); - frame.rollback_state_gas(); - assert_eq!(frame.remaining(), 100_000_000, "a revert gives all of it back"); + /// A regular charge the withheld part would have paid is the cap: the frame's gas becomes the + /// withheld part, and the spendable part it had counts as spent. + #[test] + fn test_a_crossing_stops_with_the_withheld_part_left() { + 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); + 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); + assert_eq!(stop, Some(BLOCK_ENV_ACCESS_COMPUTE_GAS), "{result:?}"); + assert_eq!(frame.remaining(), 100_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(frame.withheld_crossing(), None); + assert_eq!(regular_spent(&frame), BLOCK_ENV_ACCESS_COMPUTE_GAS, "compute at the limit"); + } } - /// Out of gas with gas withheld is the cap binding; out of gas without is the frame's own. + /// An out-of-gas nothing withheld could have paid halts and burns what the frame had. #[test] - fn test_out_of_gas_is_the_cap_only_with_gas_withheld() { + 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); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); + assert!(!frame.record_regular_cost(100_000_001)); + detention.note_halt(frame.remaining()); frame.spend_all(); - let stop = detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0); - assert_eq!(stop, Some((BLOCK_ENV_ACCESS_COMPUTE_GAS, BLOCK_ENV_ACCESS_COMPUTE_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.remaining(), 1_000_000, "nothing to withhold"); assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + assert_eq!(detention.burned, 100_000_000); - // Withheld gas the frame's writes drew dry is spent: the frame ran out of its own gas. + // A frame nothing was withheld from runs out of its own gas. let mut detention = detaining(); - let mut frame = gas(100_000_000, 0); + 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!(frame.record_state_cost(frame.reservoir())); + 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); - - for result in [InstructionResult::MemoryLimitOOG, InstructionResult::InvalidFEOpcode] { - 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_eq!(detention.on_frame_end(result, &mut frame, 0), None, "{result:?}"); - } } /// A child's compute adds to its caller's; the caller's forwarded gas and the child's stipend @@ -575,39 +612,84 @@ mod tests { 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, 1), 9_000 - 2_300); + assert_eq!(detention.compute(&child), 9_000 - 2_300); assert!(child.record_regular_cost(4_000)); - assert_eq!(detention.compute(&child, 1), 9_000 + 4_000 - 2_300); + 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, 0), 9_000 + 4_000 - 2_300); + assert_eq!(detention.compute(&caller), 9_000 + 4_000 - 2_300); assert_eq!(detention.suspended, 0); } /// 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. + /// 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 than the frame's allowance is + /// answered out of gas and stops at the limit, with what the frame would have had withheld. + #[test] + fn test_an_answer_is_held_to_the_allowance_it_would_have_run_on() { let mut detention = detaining(); - let mut caller = gas(1_000_000, 0); + let mut caller = gas(100_000_000, 0); detention.on_frame_run(&mut caller, 0); - assert!(caller.record_regular_cost(500_000)); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); + assert!(caller.record_withheld_first_cost(90_000_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)); - assert_eq!(detention.on_frame_end(InstructionResult::InvalidFEOpcode, &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, 0), 1_000); - assert_eq!(detention.burned, 500_000 - 1_000); + 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 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; + + let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, InstructionResult::Return); + assert_eq!( + detention.on_answer(&mut beyond, 1, 90_000_000), + Some(BLOCK_ENV_ACCESS_COMPUTE_GAS) + ); + assert_eq!(beyond.result, InstructionResult::OutOfGas); + assert_eq!(beyond.gas.remaining(), 90_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); } /// The switch holds for the frame that turned it off and every frame below it, turns back on @@ -672,11 +754,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.remaining(), 100_000_000); - detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); + assert_eq!(frame.withheld(), 0); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0); assert_eq!(detention.compute_limit(), Some(5)); } } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index c56c90f91..78eeab37f 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -408,6 +408,10 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm( /// its budget, and the creator reverts alone. /// /// 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 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. +/// 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: &mut MegaContext, @@ -792,13 +803,17 @@ fn before_frame_run( } /// 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 gets the regular gas -/// detention withheld from it back into its result. +/// 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 while detention still held back some of what it withheld crossed -/// the compute limit rather than its own gas: its halt becomes the transaction-level stop, a revert -/// carrying `MegaLimitExceeded` (kind: compute), and the transaction is latched, so no caller -/// resumes. The withheld gas goes back with the revert, to the caller and in the end to the sender. +/// 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 transaction-level stop +/// ([`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, @@ -811,20 +826,63 @@ fn after_frame_run( } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); - let Some((limit, compute)) = + if let Some(limit) = ctx.detention.on_frame_end(instruction_result, result.gas_mut(), frame.depth) - else { - return; - }; - let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, limit, compute); - let result = result.interpreter_result_mut(); - result.result = InstructionResult::Revert; - result.output = stop.revert_data(); + { + stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), limit); + } } Err(_) => {} } } +/// Holds a frame answered without running to the compute limit: the answer to a frame of +/// `gas_limit` at `depth`, which its caller forwarded. +/// +/// revm runs a precompile inside frame init against the whole gas the caller forwarded, the part +/// gas detention withholds from the caller's regular charges included; an interceptor's answer is +/// built the same way. 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`](crate::Detention)). An answer that halts 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(limit) = ctx.detention.on_answer(answer, depth, gas_limit) { + stop_at_the_compute_limit(ctx, answer, limit); + } +} + +/// 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 transaction-level stop: a +/// revert carrying `MegaLimitExceeded` (kind: compute), with the transaction latched, so no caller +/// resumes. The frame's gas is what detention left it — the withheld part at the crossing — which +/// goes back with the revert, to the caller and in the end to the sender. +/// +/// The crossing charge's size is not kept, so the stop reports the limit as what was used +/// ([`LimitCheck::ExceedsLimit`]): the transaction's compute reached it exactly, the spendable gas +/// the frame had counting as spent. +fn stop_at_the_compute_limit( + ctx: &mut MegaContext, + result: &mut InterpreterResult, + limit: u64, +) { + let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, limit, limit); + result.result = InstructionResult::Revert; + result.output = stop.revert_data(); +} + /// 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. diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 69eb3f1cf..dde16367e 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -45,11 +45,16 @@ //! 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 -//! caps the frame at what the compute limit leaves it. +//! 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. //! +//! 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. +//! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. //! @@ -61,16 +66,16 @@ use revm::{ bytecode::opcode::{ - BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, CREATE, CREATE2, - DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, LOG0, LOG1, - LOG2, LOG3, LOG4, NUMBER, SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, - TIMESTAMP, + BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, CALLDATACOPY, CODECOPY, COINBASE, + CREATE, CREATE2, DELEGATECALL, DIFFICULTY, 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::{block_info, contract, gas_table_spec, host}, + instructions::{block_info, contract, gas_table_spec, host, memory, system}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, @@ -102,7 +107,7 @@ pub(crate) fn mega_instructions( 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); 28] = [ + let wrappers: [(u8, InstructionFn); 33] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -131,6 +136,11 @@ pub(crate) fn mega_instructions( (EXTCODECOPY, extcodecopy::), (EXTCODEHASH, extcodehash::), (SLOAD, sload::), + (KECCAK256, keccak256::), + (CALLDATACOPY, calldatacopy::), + (CODECOPY, codecopy::), + (RETURNDATACOPY, returndatacopy::), + (MCOPY, mcopy::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -166,7 +176,7 @@ fn commit_after(interpreter, host, history)?; + let settled = settle_history::(interpreter, host, history); + if settled.is_err() { + return note_halt(interpreter, host, settled); + } } result } @@ -254,8 +267,8 @@ fn sstore( 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 capped again. - host.detention.recap(&mut interpreter.gas, interpreter.input.depth); + // never crosses a limit: no stop's result is pending when the frame is held again. + host.detention.hold(&mut interpreter.gas); result } @@ -306,7 +319,7 @@ fn charge_frame_start( Some(InterpreterAction::NewFrame(input)) => { host.additional_limit.frame_start_records(input) } - _ => return result, + _ => return note_halt(interpreter, host, result), }; if !host.prices_history() { return result; @@ -315,11 +328,11 @@ fn charge_frame_start( write_record_history_gas(records.on_lane), write_record_history_gas(u64::from(records.caller)), ) else { - return Err(abandon_frame(interpreter)); + return abandon_frame(interpreter, host); }; - let Some(cost) = on_lane.checked_add(caller) else { return Err(abandon_frame(interpreter)) }; + let Some(cost) = on_lane.checked_add(caller) else { return abandon_frame(interpreter, host) }; if !interpreter.gas.record_history_cost(cost) { - return Err(abandon_frame(interpreter)); + return abandon_frame(interpreter, host); } inherit_reservoir(interpreter); host.additional_limit.stage_frame_charge(records, on_lane, caller); @@ -333,11 +346,38 @@ fn charge_frame_start( /// 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) -> InstructionResult { - let _ = interpreter.take_next_action(); - InstructionResult::OutOfGas +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. @@ -410,7 +450,7 @@ fn read_volatile( 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 result; + return note_halt(interpreter, host, result); } settle_reads(interpreter, host, result, gas) } @@ -435,7 +475,7 @@ fn settle_reads( } }; if !completed { - return result; + 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. @@ -445,10 +485,7 @@ fn settle_reads( } _ => 0, }; - let depth = interpreter.input.depth; - host.detention.commit_reads(observed, &mut interpreter.gas, depth, forwarded); - // A frame the opcode is about to start inherits the reservoir the cap moved gas into. - inherit_reservoir(interpreter); + host.detention.commit_reads(observed, &mut interpreter.gas, forwarded); result } @@ -534,6 +571,29 @@ state_read! { sload => host::sload, "SLOAD", "the Oracle's storage"; } +/// Defines an opcode whose own charge has no bound, as revm's instruction with what the frame had +/// left noted when the charge fails ([`note_halt`]). +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"; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 16ffb555b..0f23c5200 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1179,8 +1179,9 @@ fn test_the_switch_is_scoped_to_its_subtree() { /* ---------- 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, and what it hears from `remainingComputeGas()` is no more -/// than the limit leaves it. +/// 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 — so what the caller hears from +/// `remainingComputeGas()`, the gas it forwarded, is what it hears after a push of the same price. #[test] fn test_an_interceptors_answer_does_not_lift_the_cap() { let calldata = IMegaLimitControl::remainingComputeGasCall {}.abi_encode(); @@ -1207,27 +1208,32 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { ); assert_stopped(&run, intrinsic); - // The answer, read without the loop. - 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(32_u8) - .push_number(0_u8) - .append(RETURN) - .build(); - let run = execute( - MemoryDatabase::default().account_code(CONTRACT, code), - tx(CALLER, CONTRACT, gas_limit), - ); - let answer = U256::from_be_slice(run.outcome.result.output().unwrap()); - assert!(answer < U256::from(CAP), "the call was forwarded from the capped frame: {answer}"); + // The answer, 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) + .push_number(32_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); + U256::from_be_slice(run.outcome.result.output().unwrap()) + }; + let detained = answer(TIMESTAMP); + assert!(detained > U256::from(CAP), "the whole forward: {detained}"); + assert_eq!(detained, answer(PUSH0), "the forward the call makes without the read"); } } From 7d4993ac5353a37e28060f02ee0108b126f25aee Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:47:16 -0700 Subject: [PATCH 144/458] fix(access): name a refused BLOCKHASH for the hash it reads revm's BLOCKHASH loads the block number before the hash, so a read refused while volatile-data access is off named BlockNumber (0). The opcode's wrapper now names the refusal BlockHash (7), the access type the legacy engine reported and the one a caller decoding the enum expects. --- crates/mega-evm/src/access/detention.rs | 16 ++++++++++++-- crates/mega-evm/src/evm/instructions.rs | 15 ++++++++++++- crates/mega-evm/tests/satin/detention.rs | 27 ++++++++++++++---------- 3 files changed, 44 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index fc05a4507..4b5361855 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -199,6 +199,15 @@ impl Detention { !(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()); @@ -713,8 +722,11 @@ 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"); - assert!(detention.refuses(VolatileDataAccess::TIMESTAMP)); - assert_eq!(detention.take_refused(), Some(VolatileDataAccess::TIMESTAMP)); + 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"); diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index dde16367e..f7a1215ae 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -546,7 +546,20 @@ block_env_read! { basefee => block_info::basefee, "BASEFEE"; blobbasefee => block_info::blob_basefee, "BLOBBASEFEE"; slotnum => block_info::slot_num_enabled, "SLOTNUM"; - blockhash => host::blockhash, "BLOCKHASH"; +} + +/// `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 that loads an account or a slot, as revm's instruction in diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 0f23c5200..52bfc2209 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1045,7 +1045,7 @@ fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { "BLOCKHASH", BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).build(), 3 + 20, - VolatileDataAccess::BLOCK_NUMBER, + VolatileDataAccess::BLOCK_HASH, ), ( "BALANCE", @@ -1122,19 +1122,24 @@ fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { } /// The refusal of a `SLOTNUM` names access type 12, one past the contract's enum; the others name -/// their enum variant. +/// their enum variant, `BLOCKHASH`'s the hash it reads (7), as on the legacy engine, although +/// revm's instruction loads the block number first. #[test] fn test_the_refusal_names_the_access_type() { use mega_evm::system::{IMegaAccessControl, VolatileDataAccessType}; - assert_eq!( - volatile_data_access_disabled_revert_data(VolatileDataAccess::ORACLE), - Bytes::from( - IMegaAccessControl::VolatileDataAccessDisabled { - accessType: VolatileDataAccessType::Oracle - } - .abi_encode() - ) - ); + 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); let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); assert_eq!(&slot_num[..4], IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR.as_slice()); assert_eq!(U256::from_be_slice(&slot_num[4..]), U256::from(12)); From 131f0ce264b6987776f47035c06e78e05fc2685f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:57:44 -0700 Subject: [PATCH 145/458] fix(access): settle a stopped answer on the gas its caller forwarded An interceptor that charges its frame by taking gas off the frame's limit answers on less than the caller forwarded. When that answer crossed the compute limit, the stop set its remaining gas to the withheld part of the forwarded gas, above the answer's own limit, and a tracer reading the answer's gas saw more left than it was given. The stop now puts the answer's limit back to what the caller forwarded. --- crates/mega-evm/src/access/detention.rs | 5 +- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/withheld_gas.rs | 68 +++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 crates/mega-evm/tests/satin/withheld_gas.rs diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 4b5361855..ca83368bb 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -378,9 +378,12 @@ impl Detention { 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. + // limit is above the allowance and the frame would have had the rest withheld. An + // interceptor that charged by taking gas off the frame's limit answered on less than it + // was forwarded; the frame is settled on what it was forwarded. let withheld = NonZeroU64::new(gas_limit - allowance)?; result.result = InstructionResult::OutOfGas; + result.gas.tracker_mut().set_limit(gas_limit); result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); self.stop(&mut result.gas) } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index f4ac0e9b5..17aa681b1 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -34,4 +34,5 @@ mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; mod volatile_access; +mod withheld_gas; mod write_records; 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..9fe4c8a5f --- /dev/null +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -0,0 +1,68 @@ +//! 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 alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::{op_transaction, MemoryDatabase}, + EvmTxRuntimeLimits, MegaEvm, +}; +use revm::context::TxEnv; + +use crate::detention::{assert_stopped, context, run_on, Calls, BELOW, BENEFICIARY, CALLER}; + +/* ---------- answers ---------- */ + +/// An interceptor that charges its frame by taking gas off the frame's limit and then answers is +/// held to the allowance as a precompile is: a `keylessDeploy` call carrying value, from the +/// beneficiary under a cap below the keyless overhead, stops at the cap instead of answering. The +/// stop's gas is the frame's as its caller forwarded it, so a tracer reading the answer sees the +/// allowance spent and the rest left. +#[test] +fn test_an_interceptors_charge_is_held_to_what_the_limit_leaves() { + let calldata: Bytes = IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), + gasLimitOverride: U256::ZERO, + } + .abi_encode() + .into(); + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS / 2; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let run = |caller: Address| { + let db = MemoryDatabase::default().account_balance(caller, U256::from(10)); + let tx = OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), + gas_limit: BELOW, + value: U256::from(1), + data: calldata.clone(), + ..Default::default() + })); + let evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let mut evm = evm.with_inspector(Calls::default()); + let run = run_on(&mut evm, tx); + (run, evm.inspector().calls[0].spent) + }; + let ((detained, stop_spent), (plain, answer_spent)) = (run(BENEFICIARY), run(CALLER)); + assert_eq!(answer_spent, 0, "the answer spent nothing of the limit it was left"); + assert_eq!(stop_spent, cap, "the stop spent the allowance of the limit it was forwarded"); + assert_eq!( + plain.outcome.result.output(), + Some(&Bytes::from(IKeylessDeploy::NoEtherTransfer::SELECTOR.to_vec())), + "the answer without detention" + ); + assert_eq!(detained.limit, Some(cap), "the sender is the beneficiary"); + let intrinsic = plain.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; + assert_stopped(&detained, intrinsic); +} From 476fdeff513537d2781567e20d039a7ba42f98c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:59:40 -0700 Subject: [PATCH 146/458] test(access): pin a detained transaction against its undetained twin Each case runs with a read of the block's timestamp and with a push of the same price in its place. The two bill the same on every ledger and end the same unless the compute crosses the limit: - GAS, the SSTORE sentry and a bounded callee's writes see the whole regular gas after a read; - an out-of-gas no gas could pay halts, at the transaction's own frame, in a callee its caller catches, and in a creation that cannot pay its deposit; - what a halting callee burns, on a hash, a copy, a log, an operand, a memory expansion, an invalid opcode, an abandoned value call's records or a precompile rejecting its input, is not compute; - a callee within the cap, of every kind and one an inspector answers, bills as without the read, and a call that reads the beneficiary costs what a call to a warm empty account costs; - a callee computing past the cap, and a precompile priced above the allowance but within its forward, stop the transaction at the limit, which the stop reports as used whatever a callee burned before it; - a SLOTNUM refusal is past the access-control enum; BLOCKHASH's names BlockHash. --- crates/mega-evm/tests/satin/withheld_gas.rs | 747 +++++++++++++++++++- 1 file changed, 741 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 9fe4c8a5f..e7396a738 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -11,19 +11,736 @@ //! same two gas and reads nothing, in its place. use alloy_op_evm::OpTx; -use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - system::keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, - test_utils::{op_transaction, MemoryDatabase}, - EvmTxRuntimeLimits, MegaEvm, + constants::TX_GAS_LIMIT_CAP, + system::{ + keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, + IMegaAccessControl, VolatileDataAccessType, + }, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, + MegaContext, MegaEvm, MegaHaltReason, VolatileDataAccess, }; -use revm::context::TxEnv; +use revm::{ + bytecode::opcode::*, + context::{ + result::{ExecutionResult, HaltReason, OutOfGasError}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, + InterpreterResult, + }, + Database, Inspector, +}; + +use crate::detention::{ + assert_stopped, burn, context, execute, intrinsic, op, run_on, spin, tx, work, Calls, 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"); + +/// 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() +} + +/// 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. Below the +/// execution cap the callee runs out of gas on its third fresh slot, 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(); + for (gas_limit, status) in [(BELOW, 0), (ABOVE, 1)] { + let (detained, plain) = with_and_without_read(|first| { + let parent = + call_keeping_status(op(BytecodeBuilder::default(), first), CHILD, Some(150_000)); + 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 callee bounded to 150,000"); + 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"); + } +} + +/* ---------- 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, fn(BytecodeBuilder) -> BytecodeBuilder, 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 than the transaction has halts as without the read: +/// a failed state charge is never the cap. +#[test] +fn test_a_creation_that_cannot_pay_its_deposit_halts_as_without_the_read() { + let run = |first| { + let initcode = op(BytecodeBuilder::default(), first) + .push_number(70_000_u32) + .append_many([PUSH0, RETURN]) + .build(); + let create = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: initcode, + gas_limit: BELOW, + ..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, fn(BytecodeBuilder) -> BytecodeBuilder); 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 400,000, 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. 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; + for gas_limit in TIERS { + for (name, callee) in &cases { + let records = name.starts_with("a value call"); + if records && gas_limit == ABOVE { + continue; + } + let (to, gas) = if records { (MIDDLE, Some(400_000)) } else { (CHILD, None) }; + 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 400,000; 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) - 400_000; + let margin = detained.limit.unwrap() - compute; + assert!(margin < 150_000, "{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"); + } +} + +/// 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 transaction stops at the limit, and the caller never stores the status it would have +/// stored without the read. +#[test] +fn test_a_callee_computing_past_the_cap_stops_the_transaction() { + 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"); + assert_stopped(&detained, intrinsic(gas_limit)); + assert_eq!(slot(&detained, 0), None, "the caller never resumed"); + } +} + +/// The stop reports the limit 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 limit and what the callee burned, and nothing past either. +#[test] +fn test_the_stop_reports_the_limit_whatever_a_callee_burned() { + let cases: [(&str, Bytes); 3] = [ + ("out of gas", huge_hash(BytecodeBuilder::default()).stop().build()), + ("out of memory gas", huge_memory(BytecodeBuilder::default()).stop().build()), + ("an invalid opcode", BytecodeBuilder::default().append(INVALID).build()), + ]; + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + for (name, child) 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(); + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false + }), + "{name}" + ); + let burned = run.outcome.gas.regular - intrinsic - limit; + assert!( + (4_990_000..=5_000_000).contains(&burned), + "{name}: the callee burned {burned}" + ); + } + } +} + +/* ---------- the same bill ---------- */ -use crate::detention::{assert_stopped, context, run_on, Calls, BELOW, BENEFICIARY, CALLER}; +/// 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 ---------- */ +/// The calldata of a modexp of a 1,024-byte zero base to an exponent of `exponent_len` bytes, all +/// ones, modulo a 1,024-byte modulus of one: its price grows with the exponent, and its result is +/// cheap to compute. +fn modexp_input(exponent_len: usize) -> Vec { + let mut input = Vec::new(); + for len in [1_024_usize, exponent_len, 1_024] { + input.extend_from_slice(&U256::from(len).to_be_bytes::<32>()); + } + input.extend(core::iter::repeat_n(0_u8, 1_024)); + input.extend(core::iter::repeat_n(0xff_u8, exponent_len)); + let mut modulus = vec![0_u8; 1_024]; + modulus[1_023] = 1; + input.extend(modulus); + input +} + +/// A contract that copies its calldata into memory and calls modexp with it and `gas` (all of it +/// when `None`), after `first`, storing the call's status. +fn calls_modexp(first: u8, gas: Option) -> Bytes { + let code = op(BytecodeBuilder::default(), first) + .append_many([CALLDATASIZE, PUSH0, PUSH0, CALLDATACOPY]) + .append_many([PUSH0, PUSH0, CALLDATASIZE, PUSH0]) + .push_address(MODEXP); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + store_status(code.append(STATICCALL)) +} + +/// A transaction from `CALLER` to `CONTRACT` carrying `input`. +fn tx_with(input: &[u8], gas_limit: u64) -> mega_evm::MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit, + data: input.to_vec().into(), + ..Default::default() + })) +} + +/// The regular gas modexp charges for `input`, read off the call's own result. +fn modexp_price(input: &[u8]) -> u64 { + let db = MemoryDatabase::default().account_code(CONTRACT, calls_modexp(PUSH0, None)); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(input, BELOW)); + assert!(run.outcome.result.is_success()); + let call = evm.inspector().calls.iter().find(|call| call.target == MODEXP).unwrap(); + assert_eq!(call.result, InstructionResult::Return); + call.spent +} + +/// revm runs a precompile inside the frame's start, against all the gas the caller forwarded, the +/// part detention withholds from the caller's own charges included. A precompile whose price is +/// within what the limit leaves the transaction runs as without the read; one whose price is above +/// it, though within what the caller forwarded, crosses the cap and stops the transaction at the +/// limit; and one whose price is above what it was forwarded runs out of gas as without the read. +#[test] +fn test_a_precompile_is_held_to_what_the_limit_leaves() { + let (within, above) = (modexp_input(32), modexp_input(64)); + let (within_price, above_price) = (modexp_price(&within), modexp_price(&above)); + assert!(within_price < CAP / 2, "{within_price}"); + assert!(above_price > CAP + CAP / 10, "{above_price}"); + for gas_limit in TIERS { + let run = |first, gas, input: &[u8]| { + let db = MemoryDatabase::default().account_code(CONTRACT, calls_modexp(first, gas)); + run_on(&mut MegaEvm::new(context(db)), tx_with(input, gas_limit)) + }; + + let (detained, plain) = (run(TIMESTAMP, None, &within), run(PUSH0, None, &within)); + assert_as_without_read(&detained, &plain, "a price within the allowance"); + assert_eq!(slot(&detained, 0), Some(U256::from(1))); + + let (detained, plain) = (run(TIMESTAMP, None, &above), run(PUSH0, None, &above)); + assert_eq!(slot(&plain, 0), Some(U256::from(1)), "the precompile runs without the read"); + // What a transaction carrying the same input spends before its first instruction. + let stops = MemoryDatabase::default() + .account_code(CONTRACT, BytecodeBuilder::default().stop().build()); + let intrinsic = execute(stops, tx_with(&above, gas_limit)).outcome.gas.regular; + let limit = assert_stopped(&detained, intrinsic); + assert!(limit < above_price, "the stop billed the allowance, not the price"); + + // Forwarded less than its price: a precompile's out-of-gas, the call's failure. + let short = Some(u32::try_from(within_price).unwrap() - 1); + let (detained, plain) = (run(TIMESTAMP, short, &within), run(PUSH0, short, &within)); + assert_as_without_read(&detained, &plain, "a price above the forward"); + assert_eq!(slot(&detained, 0), Some(U256::ZERO)); + } +} + /// An interceptor that charges its frame by taking gas off the frame's limit and then answers is /// held to the allowance as a precompile is: a `keylessDeploy` call carrying value, from the /// beneficiary under a cap below the keyless overhead, stops at the cap instead of answering. The @@ -66,3 +783,21 @@ fn test_an_interceptors_charge_is_held_to_what_the_limit_leaves() { let intrinsic = plain.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; assert_stopped(&detained, intrinsic); } + +/* ---------- the refusal's access type ---------- */ + +/// A `SLOTNUM` refusal carries access type 12, which `IMegaAccessControl`'s enum does not declare: +/// a decoder that validates the enum rejects it, while every other refusal decodes, `BLOCKHASH`'s +/// as `BlockHash`. The enum is the access-control contract's to extend. +#[test] +fn test_a_slotnum_refusal_is_past_the_enum() { + let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); + assert!(IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&slot_num).is_err()); + let block_hash = volatile_data_access_disabled_revert_data(VolatileDataAccess::BLOCK_HASH); + assert_eq!( + IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&block_hash) + .unwrap() + .accessType, + VolatileDataAccessType::BlockHash + ); +} From e3beaa9d2484a723886aa647358794dc28f47006 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 19:59:55 -0700 Subject: [PATCH 147/458] style(test): name the out-of-gas endings the detention twins append --- crates/mega-evm/tests/satin/withheld_gas.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index e7396a738..a87996183 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -103,6 +103,9 @@ 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) @@ -221,7 +224,7 @@ fn test_the_sstore_sentry_reads_the_whole_regular_gas() { /// 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, fn(BytecodeBuilder) -> BytecodeBuilder, OutOfGasError); 3] = [ + 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), @@ -275,7 +278,7 @@ fn test_a_creation_that_cannot_pay_its_deposit_halts_as_without_the_read() { /// failure and completes, as without the read. #[test] fn test_a_callees_out_of_gas_is_caught_as_without_the_read() { - let cases: [(&str, fn(BytecodeBuilder) -> BytecodeBuilder); 4] = [ + 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), From ea370a2cce55921ac7802b44221fe7b9989e48d4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:02:10 -0700 Subject: [PATCH 148/458] test(access): port the two applied-authority rows detention owns An applied EIP-7702 authority that is the block beneficiary detains the transaction from its first frame; one that is not detains nothing. Under a cap below what the authorization costs before any frame, nothing stops before the first frame, since intrinsic gas is not compute: the authorization stands, and the first frame is held to the cap. The emptied pending file goes with them. --- crates/mega-evm/tests/_pending/README.md | 11 +- .../rex6/eip7702_authority_accounting.rs | 286 ------------------ crates/mega-evm/tests/_pending/rex6/main.rs | 5 - .../mega-evm/tests/satin/volatile_access.rs | 111 ++++++- 4 files changed, 112 insertions(+), 301 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 28d14269f..d16fd7d4c 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 | -| detention | 2 | 2 | 0 | 0 | 2 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | @@ -36,7 +35,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** | **248** | **228** | **20** | **159** | **82** | **7** | +| **Total** | **246** | **226** | **20** | **159** | **80** | **7** | ## Tests ported in place @@ -277,7 +276,7 @@ These 54 rows run in a real test target now, adapted to the Satin API: the state ## Tests ported by detention -These 81 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. +These 83 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -294,9 +293,10 @@ These 81 rows run in a real test target now, adapted to the Satin API and to the | `rex4/gas_detention.rs` | detention (3) | 3 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex5/selfdestruct_beneficiary.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex6/beneficiary_detention.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex6/eip7702_authority_accounting.rs` | detention (2) | 2 | `tests/satin/volatile_access.rs` | | `src/access/volatile.rs` | detention (4) | 4 | `crates/mega-evm/src/access/volatile.rs` | | `src/limit/compute_gas.rs` | detention (1) | 1 | `tests/satin/detention.rs` | -| **Total** | | **81** | | +| **Total** | | **83** | | ## Tests retired after the inventory @@ -341,8 +341,6 @@ They are not counted above. | `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | -| `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_beneficiary_triggers_detention` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | -| `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_compute_overflow_skips_authorities` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | ## Files @@ -381,7 +379,6 @@ 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) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/eip7702_authority_accounting.rs` | 2 | rewrite 2 (detention · 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/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) | 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 38317d540..000000000 --- a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs +++ /dev/null @@ -1,286 +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 -// ============================================================================ - -/// 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:?}", - ); -} - -/// 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})", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs index 148d812c9..4dac99935 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -1,13 +1,8 @@ //! 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 common; mod create2_metering_order; mod create_frame_accounting; -mod eip7702_authority_accounting; mod error_paths; mod fee_reward_accounting; mod frame_local_accounting; diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index ef24ec5d5..ab23d2e4c 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -21,9 +21,9 @@ use mega_evm::{ use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult, state::Bytecode}; use crate::detention::{ - assert_stopped, call, context, execute, intrinsic, on_beneficiary, op, run_on, spin, tx, - with_delegation, work, Calls, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, DELEGATOR, - TIERS, + assert_stopped, burn, call, context, execute, intrinsic, on_beneficiary, op, run_on, spin, + stop_data, tx, with_delegation, work, Calls, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, + DELEGATOR, TIERS, }; /// A second contract, never the beneficiary. @@ -596,3 +596,108 @@ fn test_a_call_to_the_access_control_contract_costs_its_overhead() { // The pushes (2 + 2 + 3 + 2 + 2 + 3 + 3), the cold call (2,600), POP and GAS. assert_eq!(consumed, U256::from(17 + 2_600 + 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()); + } +} + +/// 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. + let past = run(spin(BytecodeBuilder::default())); + assert_eq!( + past.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: tiny, + used: tiny, + frame_local: false + }) + ); + assert_eq!(past.outcome.result.output(), Some(&stop_data(tiny))); + assert_eq!(past.outcome.gas.regular, intrinsic + tiny); + assert_eq!(past.outcome.gas.state, stops.outcome.gas.state); + assert!(delegates_to_child(&past, BENEFICIARY), "the authorization stands"); + } +} From 8e2fb77b32ff9a754a9e13ce282d385de70e280c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:05:11 -0700 Subject: [PATCH 149/458] docs(access): describe detention on the fork's withheld gas AGENTS.md's gas detention section, the contract of the common execution layer on per-frame gas caps, the crate README and the access module describe the withheld part of a frame's regular gas: what reads it, the three points that hold a frame's spendable part, the crossing record the stop is classified on, answers held to the same allowance, what a halt burns, and why nothing withheld is ever released. LimitCheck documents that a compute stop reports the limit as used. --- AGENTS.md | 72 ++++++++------ crates/mega-evm/README.md | 8 +- crates/mega-evm/src/access/detention.rs | 11 +-- crates/mega-evm/src/access/mod.rs | 99 +++++++++++-------- crates/mega-evm/src/limit/mod.rs | 10 +- .../mega-evm/tests/satin/volatile_access.rs | 4 +- 6 files changed, 118 insertions(+), 86 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index afbf08173..edfec979a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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. +- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), which upstream revm does not have. ## Architecture @@ -99,17 +100,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 (detention's hooks included), 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, the volatile-read marks and refusals and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, 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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | -| `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit, the gas withheld per frame and its release, the compute figure across frames, and the volatile-access switch with its refusals (`detention.rs`) | the control contracts steering the switch | -| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (steering the detention switch, the 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 default detention caps) | 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `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 (detention's hooks and its hold on answered frames included), 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, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | +| `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/` | 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 latch, the transaction body and deployed code on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 (`detention.rs`) | the control contracts steering the switch | +| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (steering the detention switch, the 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 default detention caps) | 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`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, 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`) | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -166,7 +167,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 them, a system transaction being promoted to a deposit. 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). - Crossing the cap stops the transaction through the latch, with `MegaLimitExceeded` of kind compute. + 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 transaction through the latch, with `MegaLimitExceeded` of kind compute; 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`. A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. @@ -181,7 +183,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until the control contracts' semantics fill them in — steering detention's switch and answering with the compute ledger — 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 limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. - Its gas leakage pitfalls apply to one mechanism here, detention, which adjusts a frame's gas; how it handles them is below. + 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 @@ -196,24 +198,34 @@ Detention caps how much a transaction may still compute once it read such data ( - **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 spent, read off `Gas`: state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. + 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. 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. `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. - 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: the regular ledger at every moment. -- **The enforcement point: withheld gas.** - The interpreter stops a frame on one condition only, running out of regular gas, so every frame that runs keeps no more regular gas than the limit leaves the transaction; the rest moves into its reservoir, where state and history charges still reach it and regular charges cannot. - The frame is held to the limit at the read (the wrapper), at its start and at every resume (`before_frame_run`), and after an `SSTORE` that restored a slot and so refilled regular gas. - At the frame's end (`after_frame_run`, before revm settles the result) the withheld gas is released: what is left of it goes back to regular gas and what state and history drew from it counts as spilled, which maps the result onto exactly what it would have been undetained. -- **The stop.** - A frame that runs out of gas while detention still holds back some of what it withheld (withheld gas left in its reservoir) crossed the cap, not its own gas: the result becomes the latch's revert, `MegaLimitExceeded(2, limit)`, and the withheld gas goes back to the sender with it. - A frame detention withheld nothing from, or whose writes drew the withheld gas dry, ran out of its own gas and halts. -- **The three leakage paths.** - A frame answered without running (an interceptor, the latch, the depth guard, an inspector) has nothing withheld and hands its forwarded gas back, and the caller is held to the limit as it resumes. - The transaction-level stop releases every frame's withheld gas on the way up, so the sender gets back what nobody spent. - A frame's return releases on success, revert and halt alike: a halt burns the released gas as it would have burned it undetained. +- **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 withheld part. + 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 latch's revert, `MegaLimitExceeded(2, limit)`, with its gas the record's withheld part: the spendable part it had counts as spent, which brings the compute to the limit exactly, and the withheld part goes back to the sender. + The settlement is the same whether the halt zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`). + The stop reports the limit as what was used (`LimitCheck::ExceedsLimit`): the size of the charge that crossed is not kept. + 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 whole forward, the caller's withheld part included, and an interceptor builds its answer the same way. + 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer); an interceptor that charged by taking gas off the frame's limit is settled on the limit the caller forwarded. + An answer that halts burns its whole gas limit. +- **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 a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. + The two charges no wrapper sees, an opcode's static gas and `EXP`'s exponent, are bounded by their own price, and what a frame had below it counts as compute. - **Refused reads.** `MegaAccessControl` can switch volatile-data access off for a frame and every frame below it (the state is `Detention`'s; the interceptor steers it once the control contracts' semantics land, and `MegaContext::with_volatile_access_disabled_from` is the test helper). - 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; `SLOTNUM` names access type 12, which the contract's enum does not declare. + 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, which the contract's enum does not declare. ### Contracts of the common execution layer @@ -248,9 +260,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. 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. -- **A per-frame gas adjustment is released where the frame ends.** - Detention withholds regular gas into a frame's reservoir; `after_frame_run` releases it on every path, before revm settles the result, and a frame that never ran has nothing to release. - A later mechanism that adjusts a frame's gas settles it at the same point, and a result an opcode already built (a limit's stop) holds the frame's gas as it stood, so nothing is withheld after it. +- **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.** diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index da05a3651..df00ed51c 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -100,9 +100,11 @@ Every one of these limits is unlimited unless a node sets it. 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 Host marks the read where it loads the value, and the most restrictive read binds. -Every frame keeps no more regular gas than the limit leaves the transaction; the rest waits in its reservoir, where state and history charges still reach it, and goes back into the frame's regular gas when the frame returns. -A frame that runs out of gas while gas is still withheld from it crossed the cap: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, and the sender gets back everything withheld. -A frame that runs out of its own gas still halts. +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: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. +A precompile or an interceptor's answer that spent more than the limit left the frame is the same crossing. +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 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index ca83368bb..ce8d94b9d 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -30,9 +30,9 @@ struct DetainedFrame { /// /// 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 ([`regular_spent`]). 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. +/// 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 @@ -51,9 +51,8 @@ struct DetainedFrame { /// 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 ([`note_halt`](Self::note_halt)). The two charges no wrapper sees — an opcode's -/// static gas and `EXP`'s exponent — are bounded by their own price, and what a frame had left -/// below it counts as compute. +/// notes it first. The two charges no wrapper sees — an opcode's static gas and `EXP`'s exponent — +/// are bounded by their own price, and what a frame had left below it counts as compute. /// /// # Refused reads /// diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 83cbaa4d0..daf939de9 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -38,56 +38,67 @@ //! # 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, and neither is what a halting -//! frame burns ([`Detention`]). 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. +//! 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`]). +//! 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. Every frame -//! that runs keeps no more regular gas than the limit leaves the transaction; the rest is -//! *withheld* — moved into the frame's reservoir — until the frame returns. Three points hold -//! this, and between them no frame can compute past the limit: -//! -//! - **the read**: the opcode that read volatile data withholds from its own frame, right after the -//! Host's load, so the instructions after it run on what the cap leaves; +//! 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: +//! +//! - **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 caps its callers as they resume, and the -//! gas a child hands back cannot be computed with past the limit; +//! 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, so the frame is held to the limit again. +//! 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 withheld part it could not draw. +//! +//! # The stop //! -//! A frame that runs out of regular gas while detention still holds back some of what it withheld -//! has crossed the cap, not its own gas: undetained, the frame would have had that gas to charge -//! against, so the cap is the tighter bound. The frame then stops the transaction the way every +//! 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 stops the transaction the way every //! transaction-level limit does — it reverts with `MegaLimitExceeded` (kind: compute), the //! transaction is latched, no caller resumes, and the transaction settles like an EIP-8037 revert -//! (see [`AdditionalLimit`](crate::AdditionalLimit)). What the frame had left of its allowance when -//! the charge failed is spent; the withheld gas is not, and goes back to the sender. A frame -//! detention withheld nothing from runs out of its own gas, and halts: a child forwarded less -//! than the limit leaves the transaction halts on its own, and its caller resumes. So does a frame -//! whose state and history charges drew the withheld gas dry: it ran out where it would have -//! undetained. -//! -//! State and history charges are not held back. They draw on the reservoir first, where the -//! withheld gas sits, so a detained frame pays for what it writes and appends as it would have. -//! -//! # Withheld gas does not leak -//! -//! Withheld gas is regular gas the frame was given and must neither be lost nor escape the cap. -//! A frame's end hands it back into the frame's regular gas before the result settles, as if it -//! had never been withheld ([`release`](detention::release)), on every path: -//! -//! - **a frame answered without running** — an interceptor's answer, the latch, the depth guard, an -//! inspector — never runs, so nothing is withheld from it; the answer carries the forwarded gas -//! back to its caller, and the caller is held to the limit when it resumes; -//! - **the transaction-level stop** returns the stopped frame's withheld gas with the revert, and -//! every caller's with its own, so the sender gets back what nobody spent; -//! - **the frame's return** releases on success, revert and halt alike: a success or a revert hands -//! the unspent gas to the caller, which is held to the limit as it resumes, and a halt burns it -//! as it would have burned it undetained. +//! (see [`AdditionalLimit`](crate::AdditionalLimit)). The stopped frame's gas is the withheld part +//! at the crossing: the spendable part it had counts as spent, which brings the transaction's +//! compute to the limit exactly, and the withheld part goes back to the sender. The stop reports +//! the limit as what was used; the size of the charge that crossed is not kept. +//! +//! 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 all the gas the caller forwarded, the caller's withheld part included, and +//! an interceptor builds its answer likewise: an answer that spent more than the allowance the +//! frame would have run on is answered out of gas and marked as a crossing, and the same rule stops +//! the transaction. +//! +//! # 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 withheld part back with +//! its revert; 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 //! @@ -95,8 +106,10 @@ //! 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 `SLOTNUM` -//! refusal names access type 12, which the contract's `VolatileDataAccessType` does not declare. +//! 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, which the contract's +//! `VolatileDataAccessType` does not declare. mod detention; mod volatile; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index ce9c118d3..12a1511f0 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -7,8 +7,9 @@ //! //! 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. It stops a transaction through the same latch ([`AdditionalLimit::latch`]), with the -//! compute the transaction may reach as the limit. +//! count, and it holds a frame to the cap with the gas the frame may spend. It stops a transaction +//! through the same latch ([`AdditionalLimit::latch`]), with the compute the transaction may reach +//! as the limit, and the limit as what was used ([`LimitCheck::ExceedsLimit`]). //! //! 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 @@ -464,6 +465,11 @@ pub enum LimitCheck { /// The limit crossed. limit: u64, /// The usage that crossed it. + /// + /// For [`LimitKind::ComputeGas`] it is the limit itself. Gas detention stops a frame on a + /// regular charge its spendable gas could not pay, and the charge's size is not kept; the + /// spendable gas the frame had counts as spent, which brings the transaction's compute to + /// the limit exactly. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index ab23d2e4c..6ca34df6a 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -129,8 +129,8 @@ fn test_detention_starts_afresh_for_every_transaction() { assert!(second.outcome.gas.regular > CAP); } -/// A read that stays within the cap costs what it ran: the gas detention withheld goes back -/// when the transaction ends, below and above the execution cap. +/// A read that stays within the cap costs what it ran: the gas detention withheld is never +/// spent, below and above the execution cap. #[test] fn test_a_read_within_the_cap_bills_what_ran() { for gas_limit in TIERS { From 4ad1a95fdd45be6e9a83642cbff82afeea6eb181 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:14:29 -0700 Subject: [PATCH 150/458] bench(access): hash and copy into memory next to op-revm A new transact arm runs 200 rounds of a 32-byte KECCAK256, MCOPY, CALLDATACOPY and CODECOPY and an empty RETURNDATACOPY, the opcodes that now run in a wrapper noting what an out-of-gas halt burns. The data-size and state-limit arms build their limits on the default, which carries gas detention's caps, rather than on no_limits, which now turns detention off: they keep measuring a transaction as it runs in a block. --- crates/mega-evm/benches/transact.rs | 35 +++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 18ec982a6..a5a168847 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -23,6 +23,10 @@ //! 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` and an empty `RETURNDATACOPY`: 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 @@ -67,8 +71,9 @@ use mega_evm::{ use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, BALANCE, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, - MSTORE, NUMBER, POP, PUSH0, PUSH1, SLOAD, SSTORE, STATICCALL, STOP, SUB, SWAP1, TIMESTAMP, + ADDRESS, BALANCE, CALL, CALLDATACOPY, CALLDATALOAD, CODECOPY, DUP1, 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, @@ -87,6 +92,7 @@ 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"); /// The block beneficiary of the benchmark's block, `BlockEnv`'s default. const BENEFICIARY: Address = Address::ZERO; @@ -168,6 +174,25 @@ fn reader_code() -> Bytes { 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]); + } + 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 { @@ -319,6 +344,7 @@ fn bench_transact(c: &mut Criterion) { .account_code(LIMITED, limited_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); let cfg = mega_context(db.clone()).cfg().clone(); @@ -336,6 +362,7 @@ fn bench_transact(c: &mut Criterion) { ("system_address_misses", call_tx(MISSING, 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)), ]; let mut group = c.benchmark_group("transact"); @@ -411,7 +438,7 @@ fn bench_transact(c: &mut Criterion) { let limited_tx = call_tx(LIMITED, Bytes::new(), LIMITED_GAS_LIMIT); let limited = |limit| { mega_context(db.clone()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)) + .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(); @@ -465,7 +492,7 @@ fn bench_transact(c: &mut Criterion) { .state; let state_limited = |limit| { mega_context(db.clone()).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() + EvmTxRuntimeLimits::default() .with_tx_state_gas_limit(limit) .with_tx_kv_update_limit(REPEAT), ) From 9643768a3613df8586fcb70c0a5a95dd1381ef19 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:27:51 -0700 Subject: [PATCH 151/458] fix(satin): keep a failed keyless deployment from spending a signer's nonce past 1 A keylessDeploy call is permissionless and the signed transaction public, so a nonce every failed deployment spent let anybody make a signer's address undeployable with two failing calls. A failed deployment now keeps the signer's nonce bump only from 0 to 1: from nonce 1 the settlement sets the nonce back and takes the bump's write record and its history back. A deployment that succeeds keeps revm's bump, and rule 4 is unchanged. --- AGENTS.md | 5 +- crates/mega-evm/README.md | 5 +- crates/mega-evm/src/limit/frame_limit.rs | 35 +++ crates/mega-evm/src/limit/limit.rs | 19 ++ crates/mega-evm/src/system/AGENTS.md | 2 +- .../mega-evm/src/system/keyless/dispatch.rs | 7 + crates/mega-evm/src/system/keyless/mod.rs | 9 +- crates/mega-evm/src/system/keyless/settle.rs | 67 +++++- .../mega-evm/tests/system/keyless/limits.rs | 21 ++ crates/mega-evm/tests/system/keyless/rules.rs | 205 ++++++++++++++++-- 10 files changed, 332 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c93db7dd1..18e14b29c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -181,9 +181,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The rewrite (`keyless::rewrite`) runs in `frame_init` before interception and in `inspect_frame_init` before the inspector is told the frame starts, so the creation is an ordinary creation from there on and an inspector's root is a `create`. It charges the fixed overhead, holds the call to the legacy engine's nine rules and error ABI, charges what the `CREATE` opcode charges its frame — the signer's account when the creation's nonce bump creates it and the created account, both SALT-priced state gas, and the creation's two write records — and starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left. The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. - A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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, and the signer's nonce stays spent. + A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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, so a signer gets two failing attempts and not a third. + Rule 4 (signer nonce at most 1) counts real nonces: a deployment that succeeds spends the signer's nonce, and one that fails spends it only from 0 to 1. + From nonce 1 a failed deployment leaves the nonce at 1 and takes the bump's write record and its history back, so no number of failing calls — the call is permissionless and the signed transaction public — gets the signer's deployment refused. `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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 and limit-check protocol 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 a62612402..0941e953e 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -72,8 +72,9 @@ A `keylessDeploy` call a transaction makes becomes a native creation before any The call pays a fixed 100,000 gas, is held to the legacy engine's nine rules and error ABI, and pays what a `CREATE` opcode charges its frame: the signer's account when the creation's nonce bump is what creates it, 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 — and the signer's nonce stays spent either way; a transaction limit the deployment crosses stops the transaction and takes the deployment back whole. -A signer is refused once its nonce is above 1, so it gets two deployments that fail and not a third. +Once the creation returns the call answers in the contract's ABI — the deployed address, or the error the creation failed with; a transaction limit the deployment crosses stops the transaction and takes the deployment back whole. +A signer is refused once its nonce is above 1. +A deployment that succeeds spends the signer's nonce, and one that fails spends it only from 0 to 1: a signer at nonce 1 stays there however often its deployment fails, so nobody can use up its attempts. A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. 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. diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 9e5ac9c1c..0c99f91ee 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -269,6 +269,20 @@ impl FrameLimitTracker { self.total_used = self.total_used.saturating_sub(WRITE_RECORD); } + /// 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. /// @@ -529,6 +543,27 @@ mod tests { assert_eq!(t.net(), t.net_uncached()); } + /// 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, UNLIMITED, 0)); + t.record(bytes(7)); + t.push(Lane::new(None, true, UNLIMITED, 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() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 9dfd55eb2..a1f65d6f2 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -697,6 +697,25 @@ impl AdditionalLimit { } } + /// 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 its budget, 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 + } + /// The number of frames with a lane: the frames on the call stack, and a `keylessDeploy` call /// whose creation is running. pub(crate) fn frame_depth(&self) -> usize { diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 76c003de3..79194d0db 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -24,7 +24,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 charges nothing: the frame starts as it was built. - A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context); it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped. -- What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps the signer's spent nonce, 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. +- What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps the signer's spent nonce, 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 that failed from nonce 1 keeps no bump: the settlement sets the nonce back and takes the record and its history back, so a signer's failures stop at nonce 1 and nobody can use up its attempts. - 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. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 36ecb381d..da5170786 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -73,6 +73,11 @@ pub(crate) struct KeylessCall { /// 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, /// The call's return range. pub(super) memory_offset: Range, /// Whether the transaction's own start charged the call a new account. @@ -190,6 +195,8 @@ fn rewrite_dispatched( 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(), memory_offset, charged_new_account_state_gas, returned_history: 0, diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 7ff0a8f8a..053ca40ac 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -17,10 +17,11 @@ //! What the native frame means for a deployment: //! //! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. -//! - The signer's nonce is bumped by the creation, as any creator's is, and stays bumped when the -//! deployment fails: that is the replay barrier. A deployment is refused once the signer's nonce -//! is above 1 (`SignerNonceTooHigh`), so a signer gets at most two attempts that fail — the first -//! bumps its nonce to 1, the second to 2 — and a third is refused. +//! - 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 that fails keeps the +//! bump only from 0 to 1, which is the replay barrier; from nonce 1 it leaves the nonce at 1, and +//! keeps no record of the bump. The call is permissionless and the signed transaction public, so +//! no number of failing calls, whoever makes them, gets a signer's deployment refused. //! - 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 deployed contract's account is charged as the `CREATE` opcode charges it, and given back diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 39b732992..d1e0dd9bf 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -13,6 +13,7 @@ use revm::{ result::{FromStringError, HaltReason, OutOfGasError}, ContextTr, JournalTr, }, + context_interface::journaled_state::account::JournaledAccountTr, handler::FrameResult, interpreter::{CallOutcome, Gas, InstructionResult, InterpreterResult, SuccessOrHalt}, primitives::KECCAK_EMPTY, @@ -51,16 +52,22 @@ pub(crate) fn give_back_history( /// back too. The creation's lane was popped when it returned, or is popped here when it never /// ran. /// +/// A deployment that failed keeps the signer's nonce bump only when it took the signer from 0 to +/// 1: a failed deployment from nonce 1 leaves it at 1 ([`keep_no_second_bump`]). 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. +/// /// Then the call answers, as a frame that resumes after its child returned would: /// /// - with the stop a limit left it, when there is one: the latched one, or its own budget's, which -/// the creator's nonce record a failed creation leaves on its lane can cross. The call reverts -/// with it, and its journal checkpoint goes with the revert, the signer's nonce included; +/// the nonce record a failed creation leaves a signer at nonce 0 on the call's lane can cross. +/// The call reverts with it, and its journal checkpoint goes with the revert, the signer's nonce +/// included; /// - otherwise with `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 whose deployment failed has spent its nonce all the same. +/// 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 @@ -87,9 +94,14 @@ where // 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. - if account_nonce(ctx, call.signer) == call.signer_nonce { + let bumped = account_nonce(ctx, call.signer) != call.signer_nonce; + if !bumped { call.gas.refill_reservoir(call.signer_account_charge); } + // A deployment that failed from nonce 1 keeps no bump: the address stays deployable. + if bumped && call.signer_nonce > 0 && !holds_code(ctx, call.deploy_address) { + keep_no_second_bump(ctx, &mut call, result)?; + } let (status, output) = match ctx.additional_limit.stop_before_run() { Some(stop) => (InstructionResult::Revert, stop.revert_data()), @@ -143,16 +155,47 @@ fn answer( }; return (InstructionResult::Revert, encode_error_result(error)); } - let address = call.deploy_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. - let deployed = ctx.journal_ref().state.get(&address).is_some_and(|account| { - account.info.code_hash != KECCAK_EMPTY && !account.is_selfdestructed() - }); - if !deployed { + if !holds_code(ctx, call.deploy_address) { return failed(KeylessDeployError::EmptyCodeDeployed { gas_used }, gas_used); } - returned(gas_used, address, Bytes::new()) + returned(gas_used, call.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 nonce bump of a failed deployment by 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 fail. +/// +/// The record goes unless the signer's account keeps another write it stands for: the value a +/// creation that succeeded moved out of it, having deployed no code. A creation that failed took +/// its value transfer back with the rest of its writes. +fn keep_no_second_bump( + ctx: &mut MegaContext, + call: &mut KeylessCall, + result: &FrameResult, +) -> Result<(), ERROR> +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + ERROR: From, +{ + ctx.journal_mut().load_account_mut(call.signer)?.data.set_nonce(call.signer_nonce); + let moved_value = call.moves_value && result.instruction_result().is_ok(); + if !moved_value && ctx.additional_limit.take_back_creator_record() { + call.gas.refill_history(call.signer_record_charge); + } + Ok(()) } /// The nonce of an account the journal holds; zero for one it does not. diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 3a55b7665..b117a78fb 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -186,6 +186,27 @@ fn test_the_signers_record_can_put_the_call_over_its_budget() { } } +/// 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 transaction KV limit reaches the creation as its share: 98% of what the call has left, /// rounded down. A limit of two leaves the creation one, and the two records its start makes cross /// it: the creation is stopped before its init code runs, alone, and the signer's nonce is spent. diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index edd36261c..9e9021b9e 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -3,8 +3,9 @@ //! //! The rules and the error ABI are the legacy engine's. 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: the creation bumps the signer's -//! nonce whether it succeeds or not, so a signer gets two attempts that fail and not a third. +//! signer's balance — and rule 4, which now counts real nonces: a deployment that succeeds bumps +//! the signer's nonce as any creation does, and one that fails keeps the bump only from 0 to 1. +//! A signer at nonce 1 stays there however often its deployment fails, whoever submits it. use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ @@ -13,18 +14,20 @@ use mega_evm::{ system::keyless::{ tests::{ CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, - NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX, + EIP1820_CONTRACT, EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, + POST_EIP155_CHAIN_1_TX, }, KEYLESS_DEPLOY_OVERHEAD_GAS, }, - test_utils::{ErrorInjectingDatabase, InjectedDbError}, + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, MegaSpecId, MegaTransactionError, TestExternalEnvs, }; use revm::{ - bytecode::opcode::{PUSH0, REVERT}, + bytecode::opcode::{INVALID, MSTORE, PUSH0, REVERT}, context::{result::EVMError, CfgEnv}, context_interface::cfg::GasId, state::{AccountInfo, Bytecode}, + DatabaseCommit, }; use super::*; @@ -350,37 +353,195 @@ fn test_keyless_deploy_signer_nonce_too_high() { } } -/// Rule 4 counts the creation's own nonce bumps: a signer whose deployment fails twice — the -/// first bump takes it from 0 to 1, the second from 1 to 2 — is refused the third time. The -/// deploy address stays the same through all three. +/// Rule 4 counts real nonces, and a deployment that fails takes its signer from 0 to 1 and no +/// further: a signer at nonce 1 stays there however often its deployment fails. #[test] -fn test_satin_caps_a_signer_at_two_failing_attempts() { +fn test_a_signer_at_nonce_one_stays_there_however_often_it_fails() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let mut db = system_db(); - for attempt in 1..=2 { + let mut db = system_db().account_nonce(deployment.signer, 1); + for attempt in 0..10 { let outcome = run_nth( db.clone(), deployment.call_data(LARGE_OVERRIDE), gas_limit, EvmTxRuntimeLimits::no_limits(), - attempt - 1, + attempt, ); assert!( matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. }), - "attempt {attempt}", + "attempt {attempt} at {gas_limit}", + ); + assert_eq!(nonce(&outcome, deployment.signer), 1, "attempt {attempt} at {gas_limit}"); + db.commit(outcome.result_and_state.state); + } + } +} + +/// 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() { + // Signed for chains that charge no state gas for deployed code: without a reservoir, the + // signed gas limit does not cover the code a canonical deployment deposits. + for deploying_at in GAS_LIMITS { + for (tx, signed, signer, address) in [ + (CREATE2_FACTORY_TX, 100_000, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_CONTRACT), + (EIP1820_TX, 800_000, EIP1820_DEPLOYER, EIP1820_CONTRACT), + ] { + 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, ); - assert_eq!(nonce(&outcome, deployment.signer), attempt, "attempt {attempt}"); - revm::DatabaseCommit::commit(&mut db, outcome.result_and_state.state); } - let third = run_nth( - db, - deployment.call_data(LARGE_OVERRIDE), - gas_limit, + } +} + +/// 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`. +fn fail_then_deploy( + tx: &[u8], + signed: u64, + signer: Address, + address: Address, + failing_at: u64, + deploying_at: u64, +) { + 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(), - 2, + attempt, ); - assert_eq!(refusal(&third), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + 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, + 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), 2, "a deployment that succeeds bumps the nonce"); +} + +/// 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. +/// The record stays only when a creation that deployed no code moved value out of the signer's +/// account: the record then stands for that write. A deployment that deployed no code keeps the +/// record of the account it created. +#[test] +fn test_every_way_a_deployment_from_nonce_one_fails_leaves_the_nonce_at_one() { + let one = U256::ONE; + let kv_share_of_one = EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2); + 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(), 1), + ( + "no code carrying value", + Deployment::with_value(Bytes::new(), one), + EvmTxRuntimeLimits::no_limits(), + 2, + ), + ("stopped at its start", Deployment::new(deploying(&runtime(1))), kv_share_of_one, 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}"); } } From bf194bbfce2d179ac6dc1fcb44dffec25869a18e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:33:44 -0700 Subject: [PATCH 152/458] fix(satin): show an inspector a keyless deployment's call and its creation The call's journal checkpoint was taken before the inspector's create hook, so a depth-aware tracer hung the creation under an empty depth-0 node and the call to KeylessDeploy appeared nowhere. The inspector is now told the call starts, then the creation as its child one journal depth below, and the call's end once the creation is settled into it: the inspected execution settles the deployment before the last-frame step does, and reports the call's end with the answer it gave. --- AGENTS.md | 5 +- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/evm/execution.rs | 113 +++++++++++--- crates/mega-evm/src/system/AGENTS.md | 6 +- .../mega-evm/src/system/keyless/dispatch.rs | 19 ++- crates/mega-evm/src/system/keyless/mod.rs | 16 +- crates/mega-evm/src/system/keyless/settle.rs | 21 +-- .../tests/system/keyless/inspector.rs | 141 +++++++++++++++--- 8 files changed, 245 insertions(+), 78 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 18e14b29c..3eddca035 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,9 +178,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 the control contracts' compute-ledger semantics fill them in, and the Oracle forwards a `sendHint` payload to the node's oracle service. - 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 rewrite (`keyless::rewrite`) runs in `frame_init` before interception and in `inspect_frame_init` before the inspector is told the frame starts, so the creation is an ordinary creation from there on and an inspector's root is a `create`. + The rewrite (`keyless::rewrite`) runs in `frame_init` before interception, so the creation is an ordinary creation from there on. + An inspector sees the frames the deployment is made of: `inspect_frame_init` tells it the call starts, rewrites the call, then tells it the creation starts, as the call's child one journal depth below, and `MegaHandler::inspect_execution` tells it the call ended once the creation is settled into it. It charges the fixed overhead, holds the call to the legacy engine's nine rules and error ABI, charges what the `CREATE` opcode charges its frame — the signer's account when the creation's nonce bump creates it and the created account, both SALT-priced state gas, and the creation's two write records — and starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left. - The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. + The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` — or, inspected, `inspect_execution` just before it — settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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: a deployment that succeeds spends the signer's nonce, and one that fails spends it only from 0 to 1. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 0941e953e..2ad16dd81 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -68,7 +68,7 @@ A method that takes no value answers a value-bearing call with `NonZeroTransfer( The Oracle forwards a `sendHint` payload to the node's oracle service. `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 becomes a native creation before any interceptor or inspector sees it. +A `keylessDeploy` call a transaction makes becomes a native creation before any interceptor sees it; a tracer sees the call, and the creation as its child. The call pays a fixed 100,000 gas, is held to the legacy engine's nine rules and error ABI, and pays what a `CREATE` opcode charges its frame: the signer's account when the creation's nonce bump is what creates it, 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. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 88e63ab42..34f9fc517 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -23,11 +23,12 @@ use revm::{ }, 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, @@ -266,8 +267,9 @@ where /// started, and the call is the transaction's own frame: the creation's result is settled into /// the call first, which answers in the `IKeylessDeploy` ABI ([`keyless::settle`]). The /// translation is made here, where every first-frame result arrives — a creation answered at - /// its start never returns through the frame lifecycle — and after the inspector saw the - /// creation end. + /// its start never returns through the frame lifecycle. The inspected path settles it earlier, + /// to tell the inspector the call ended ([`InspectorHandler::inspect_execution`]), and the + /// settlement here then finds nothing to do. fn last_frame_result( &mut self, evm: &mut Self::Evm, @@ -378,6 +380,33 @@ where + IsTxError, { type IT = EthInterpreter; + + /// revm's inspected execution, with the end of a keyless deployment's call reported. + /// + /// The call is the transaction's own frame, which runs no code, and its creation is the + /// outermost frame revm runs: revm's loop tells the inspector the creation ended, and nothing + /// tells it the call did. So the creation is settled into the call here, before + /// [`last_frame_result`](Handler::last_frame_result) would settle it, and the inspector is + /// told the call ended with the answer the settlement made. The rest is revm's. + fn inspect_execution( + &mut self, + evm: &mut Self::Evm, + checkpoint: JournalCheckpoint, + gas: &mut GasTracker, + ) -> Result, Self::Error> { + let Some(first_frame_input) = self.first_frame_input(evm, gas)? else { + unwind_runtime_oog(evm.ctx(), checkpoint)?; + return Ok(None); + }; + evm.ctx().journal_mut().checkpoint_commit(); + let mut frame_result = self.inspect_run_exec_loop(evm, first_frame_input)?; + let (ctx, inspector) = evm.ctx_inspector(); + if let Some(call) = keyless::settle::<_, _, Self::Error>(ctx, &mut frame_result)? { + frame_end_checked(ctx, inspector, &FrameInput::Call(call), &mut frame_result); + } + self.last_frame_result(evm, &mut frame_result, gas)?; + Ok(Some(frame_result)) + } } impl EvmTr for MegaEvm { @@ -593,34 +622,37 @@ where /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it, and its /// answer is held to the state-gas limit as revm's own is ([`hold_upfront_state_gas`]). /// - /// The keyless rewrite runs before the inspector is told the frame starts, so a keyless - /// deployment starts as the creation it is: the inspector sees `create` and `create_end`, and - /// every step of the init code between them. A `keylessDeploy` call the rewrite answers is - /// seen as the call it is, `call` and `call_end` paired around the answer. + /// A keyless deployment is seen as the frames it is made of. The inspector is told the + /// transaction's `keylessDeploy` call starts; the keyless rewrite then turns it into its + /// creation, and the inspector is told the creation starts, as the call's child, one journal + /// depth below it. Every step of the init code follows, then the creation's end, and the + /// call's end once the creation is settled into it + /// ([`inspect_execution`](InspectorHandler::inspect_execution)). A `keylessDeploy` call the + /// rewrite answers is seen as the call it is, `call` and `call_end` paired around the answer. #[inline] fn inspect_frame_init( &mut self, mut frame_init: FrameInit, ) -> Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); - let keyless = keyless::rewrite(ctx, &mut frame_init)?; - 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(); - hold_upfront_state_gas(ctx, Some(&mut output)); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); - return Ok(ItemOrResult::Result(output)); + if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + return answered_by_inspector(ctx, inspector, &frame_init, output) + .map(ItemOrResult::Result); } - if let Rewrite::Answered(mut output) = keyless { - ctx.additional_limit.push_empty_frame(); - hold_upfront_state_gas(ctx, Some(&mut output)); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); - return Ok(ItemOrResult::Result(output)); + match keyless::rewrite(ctx, &mut frame_init)? { + Rewrite::NotKeyless => {} + Rewrite::Answered(mut output) => { + ctx.additional_limit.push_empty_frame(); + hold_upfront_state_gas(ctx, Some(&mut output)); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); + return Ok(ItemOrResult::Result(output)); + } + Rewrite::Rewritten => { + if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + return answered_by_inspector(ctx, inspector, &frame_init, output) + .map(ItemOrResult::Result); + } + } } let frame_input = frame_init.frame_input.clone(); let logs_i = ctx.journal().logs().len(); @@ -875,6 +907,39 @@ fn hold_upfront_state_gas( } } +/// revm's unwinding of a runtime phase that ran out of gas before the first frame. +/// +/// Called through this function rather than directly: the inspector handler's bounds keep the +/// compiler from reading the journal's database error as `DB::Error`, and here nothing does. +fn unwind_runtime_oog( + ctx: &mut MegaContext, + checkpoint: JournalCheckpoint, +) -> Result<(), DB::Error> { + runtime_oog_unwind(ctx, checkpoint) +} + +/// Settles `output`, the answer the inspector gave the frame `frame_init` starts in its place. +/// 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. An empty lane stands in for the frame, and +/// the inspector is told it ended. +fn answered_by_inspector( + ctx: &mut MegaContext, + inspector: &mut INSP, + frame_init: &FrameInit, + mut output: FrameResult, +) -> Result>> +where + INSP: Inspector, EthInterpreter>, +{ + if let Some(answer) = answer_before_building(ctx, frame_init)? { + output = answer; + } + ctx.additional_limit.push_empty_frame(); + hold_upfront_state_gas(ctx, Some(&mut output)); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); + Ok(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( diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 79194d0db..f648fffe5 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -16,14 +16,14 @@ 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. -- `keylessDeploy` is not intercepted: a call a transaction makes is taken by the keyless rewrite, which runs before interception in `frame_init` and before the inspector's `frame_start` in `inspect_frame_init`, and becomes a native `CREATE` of its signer. Its test costs one comparison on every frame: the depth, then the address and the selector. +- `keylessDeploy` is not intercepted: a call a transaction makes is taken by the keyless rewrite, which runs before interception in `frame_init`, and between the inspector's `frame_start` of the call and that of the creation in `inspect_frame_init`, and becomes 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 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 charges nothing: the frame starts as it was built. -- A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context); it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped. +- A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context); it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped; the inspected path settles it in `inspect_execution` just before, and tells the inspector the call ended. - What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps the signer's spent nonce, 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 that failed from nonce 1 keeps no bump: the settlement sets the nonce back and takes the record and its history back, so a signer's failures stop at nonce 1 and nobody can use up its attempts. - 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. @@ -49,7 +49,7 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 translate its result anywhere but the settlement: the call pays the start as a `CREATE`'s frame does, and only `last_frame_result` sees every first-frame result, the creation answered at its start included. +- Do not charge a keyless deployment's start out of the creation's gas, and do not translate its result anywhere but the settlement: the call pays the start as a `CREATE`'s frame does, and only `last_frame_result` (and `inspect_execution` before it) sees every first-frame result, the creation answered at its start included. - 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. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index da5170786..f78a49f58 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -4,7 +4,6 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::ops::Range; use std::boxed::Box; use alloy_evm::Database; @@ -60,6 +59,9 @@ pub(crate) enum Rewrite { /// child, and returns into it as a creation returns into the frame whose `CREATE` started it. #[derive(Debug)] pub(crate) struct KeylessCall { + /// The call's inputs, as the transaction's frame was started with them: what the call + /// returns into, and what an inspector is told the call ended from. + pub(super) inputs: Box, /// The call's gas: the gas and the reservoir the transaction's frame was forwarded, less the /// overhead, the upfront charges and the gas forwarded to the creation. pub(super) gas: Gas, @@ -78,10 +80,6 @@ pub(crate) struct KeylessCall { pub(super) signer_record_charge: u64, /// Whether the creation moves value out of the signer's account. pub(super) moves_value: bool, - /// The call's return range. - pub(super) memory_offset: Range, - /// Whether the transaction's own start charged the call a new account. - pub(super) charged_new_account_state_gas: bool, /// The history the creation's lane gave back for the records the creation did not keep. pub(super) returned_history: u64, } @@ -165,8 +163,6 @@ fn rewrite_dispatched( Ok(deployment) => deployment, Err(refusal) => return Ok(Rewrite::Answered(refusal.answer(inputs, gas))), }; - let memory_offset = inputs.return_memory_offset.clone(); - let charged_new_account_state_gas = inputs.charged_new_account_state_gas; // The call's own lane, as the transaction's frame pushes it. A call carrying no value makes // no record, so its start crosses nothing the body did not. @@ -188,7 +184,13 @@ fn rewrite_dispatched( ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); + let FrameInput::Call(inputs) = + core::mem::replace(&mut frame_init.frame_input, FrameInput::Create(Box::new(create))) + else { + unreachable!("the rewrite starts from the call it dispatched") + }; ctx.keyless_call = Some(KeylessCall { + inputs, gas, checkpoint, deploy_address: deployment.deploy_address, @@ -197,11 +199,8 @@ fn rewrite_dispatched( signer_account_charge: deployment.signer_account_charge, signer_record_charge: deployment.record_charges.map_or(0, |(_, caller)| caller), moves_value: !deployment.value.is_zero(), - memory_offset, - charged_new_account_state_gas, returned_history: 0, }); - frame_init.frame_input = FrameInput::Create(Box::new(create)); frame_init.depth += 1; Ok(Rewrite::Rewritten) } diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 053ca40ac..38da964e9 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -5,14 +5,14 @@ //! # A native creation //! //! A `keylessDeploy(bytes,uint256)` call a transaction makes is rewritten into the creation it -//! stands for, before the frame starts and before any interceptor or inspector sees it -//! ([`rewrite`]). The call becomes a frame no code runs in: 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, seen by -//! an inspector as one, and returned into the call as one returns into the frame that started it. -//! The call then answers in the `IKeylessDeploy` ABI ([`settle`]). There is no second EVM and no -//! state to merge. +//! stands for, before the frame starts and before any interceptor sees it ([`rewrite`]). The call +//! becomes a frame no code runs in: 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. The call then answers in the `IKeylessDeploy` ABI +//! ([`settle`]). 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: //! diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index d1e0dd9bf..841b06d3f 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -3,7 +3,7 @@ #[cfg(not(feature = "std"))] use alloc as std; -use std::vec::Vec; +use std::{boxed::Box, vec::Vec}; use alloy_evm::Database; use alloy_primitives::{Address, Bytes}; @@ -15,7 +15,9 @@ use revm::{ }, context_interface::journaled_state::account::JournaledAccountTr, handler::FrameResult, - interpreter::{CallOutcome, Gas, InstructionResult, InterpreterResult, SuccessOrHalt}, + interpreter::{ + CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, SuccessOrHalt, + }, primitives::KECCAK_EMPTY, }; @@ -42,8 +44,9 @@ pub(crate) fn give_back_history( } /// Settles the result of a keyless deployment's creation into the `keylessDeploy` call that -/// started it, and replaces `result` with the call's own. Nothing to do for a transaction that -/// started no keyless deployment. +/// started it, and replaces `result` with the call's own; returns the call's inputs, which an +/// inspector is told the call ended from. Nothing to do for a transaction that started no keyless +/// deployment. /// /// The call's gas takes the creation's back exactly as a `CREATE`'s frame does /// ([`settle_frame_result`]): the unspent forward, the reservoir, the creation's state and history @@ -75,13 +78,13 @@ pub(crate) fn give_back_history( pub(crate) fn settle( ctx: &mut MegaContext, result: &mut FrameResult, -) -> Result<(), ERROR> +) -> Result>, ERROR> where DB: Database, ExtEnvs: ExternalEnvTypes, ERROR: From + FromStringError, { - let Some(mut call) = ctx.keyless_call.take() else { return Ok(()) }; + let Some(mut call) = ctx.keyless_call.take() else { return Ok(None) }; // The call's lane and the creation's: the creation returned through the frame lifecycle when // it ran, and never reached it when it was answered at its start. if ctx.additional_limit.frame_depth() > 1 { @@ -114,13 +117,13 @@ where } *result = FrameResult::Call(CallOutcome { result: InterpreterResult::new(status, output, call.gas), - memory_offset: call.memory_offset, + memory_offset: call.inputs.return_memory_offset.clone(), was_precompile_called: false, precompile_call_logs: Vec::new(), - charged_new_account_state_gas: call.charged_new_account_state_gas, + charged_new_account_state_gas: call.inputs.charged_new_account_state_gas, charged_state_gas_address: KEYLESS_DEPLOY_ADDRESS, }); - Ok(()) + Ok(Some(call.inputs)) } /// The `keylessDeploy` answer of a call whose creation settled into `result`. diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index b02db8639..4521db602 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -1,6 +1,7 @@ -//! What an inspector sees of a keyless deployment: the creation it is, from its start to its end, -//! and every step of its init code. The rewrite runs before the inspector is told the frame -//! starts, so the root of the trace is a `create` from the signer, not an opaque call. +//! 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 mega_evm::{ system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, MegaTransaction, @@ -14,9 +15,10 @@ use revm::{ }, Database, Inspector, }; +use revm_inspectors::tracing::{types::CallKind, TracingInspector, TracingInspectorConfig}; use super::*; -use crate::common::context; +use crate::common::{context, CALLER}; /// What an inspector was told, in order. #[derive(Debug, Clone, PartialEq, Eq)] @@ -103,11 +105,11 @@ fn inspect(deployment: &Deployment, recorder: Recorder, gas_limit: u64) -> (Outc type Outcome = MegaTransactionOutcome; -/// The root of a keyless deployment's trace is the creation: the signer creates at its -/// Nick's-Method address, the inspector sees every step of the init code and its log, and the -/// creation ends at that address. No `call` to `KeylessDeploy` is reported. +/// 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_deployment_as_a_creation() { +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)); @@ -117,17 +119,22 @@ fn test_the_inspector_sees_the_deployment_as_a_creation() { assert_eq!(returned(&outcome).deployedAddress, deployment.address); let events = recorder.events; assert_eq!( - events.first(), - Some(&Event::Create( - deployment.signer, - CreateScheme::Custom { address: deployment.address } - )), + events[..2], + [ + Event::Call(KEYLESS_DEPLOY_ADDRESS), + Event::Create( + deployment.signer, + CreateScheme::Custom { address: deployment.address } + ), + ], ); assert_eq!( - events.last(), - Some(&Event::CreateEnd(InstructionResult::Return, Some(deployment.address))), + events[events.len() - 2..], + [ + Event::CreateEnd(InstructionResult::Return, Some(deployment.address)), + Event::CallEnd(InstructionResult::Return), + ], ); - assert!(!events.iter().any(|event| matches!(event, Event::Call(_) | Event::CallEnd(_)))); let steps: Vec = events .iter() .filter_map(|event| match event { @@ -170,16 +177,21 @@ fn test_a_refused_call_is_seen_as_a_call() { } } -/// A creation whose init code reverts ends as a revert in the trace, and the call reports it. +/// 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!( - recorder.events.last(), - Some(&Event::CreateEnd(InstructionResult::Revert, Some(deployment.address))), + events[events.len() - 2..], + [ + Event::CreateEnd(InstructionResult::Revert, Some(deployment.address)), + Event::CallEnd(InstructionResult::Return), + ], ); } } @@ -206,19 +218,20 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { 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 the latch stopped before its first frame is not rewritten on the inspected path -/// either, where the rewrite runs before the latch is consulted: the inspector sees the call and -/// its stop, and no creation. +/// either: the inspector sees the call and its stop, and no creation. #[test] fn test_a_latched_transaction_is_seen_as_the_call_it_is() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -235,3 +248,89 @@ fn test_a_latched_transaction_is_seen_as_the_call_it_is() { assert!(!outcome.state.contains_key(&deployment.signer)); } } + +/// 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, 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() +} From d92f24cc1e65ec2930840b8952dc9c33d0de289e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:38:39 -0700 Subject: [PATCH 153/458] fix(satin): refuse a keyless call that fails several rules with the legacy engine's error The signer's account is charged where the legacy engine charged it, after the signer's rules, and the forward is checked right after, before the deploy address and the balance are read. The charges of the creation's start come after every rule, and the forward is checked again after them. A matrix of calls failing two rules at once pins that each reports the error the legacy engine reported. --- .../mega-evm/src/system/keyless/dispatch.rs | 68 +++-- crates/mega-evm/tests/system/keyless/mod.rs | 1 + .../tests/system/keyless/precedence.rs | 287 ++++++++++++++++++ crates/mega-evm/tests/system/keyless/rules.rs | 3 +- 4 files changed, 334 insertions(+), 25 deletions(-) create mode 100644 crates/mega-evm/tests/system/keyless/precedence.rs diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index f78a49f58..4e4d9789f 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -113,17 +113,25 @@ pub(crate) struct KeylessCall { /// 7. The signer's nonce is at most 1 (`SignerNonceTooHigh`). /// 8. Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation /// (`SignerHasCode()`). -/// 9. The deploy address holds no code (`ContractAlreadyExists()`), read cold and without its code, -/// so the address is in the transaction's state and in a witness without its bytecode. -/// 10. The signer can fund the transaction's value (`InsufficientBalance()`). -/// 11. What the `CREATE` opcode would charge its frame for the creation's start: the signer's -/// account when the creation's nonce bump is what creates it, the created account when the -/// deploy address is empty — both state gas, priced by the SALT bucket they land in — and the -/// write records of the two accounts, as history. A call that cannot pay is answered out of -/// gas. -/// 12. The gas the creation is forwarded is `gasLimitOverride`, capped to what the call has left, +/// 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 is answered 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 cold and 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: 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 is answered +/// 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`). /// +/// 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 refusal writes nothing, so the answer takes back every charge but the overhead with it. A /// database read or a SALT lookup that fails fails the transaction with its cause, as it does at /// every other site. @@ -313,6 +321,20 @@ fn prepare( 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), @@ -329,15 +351,10 @@ fn prepare( { refuse!(KeylessDeployError::SignerHasCode); } - if ctx.journal_mut().inspect_account_code_hash(deploy_address)? != 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. The signer's nonce bump - // is what creates an empty signer's account; a caller the opcode starts from exists already. + // 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 = @@ -347,6 +364,15 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } + forward!(); + if ctx.journal_mut().inspect_account_code_hash(deploy_address)? != 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, after every rule. 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 { @@ -372,13 +398,7 @@ fn prepare( None }; - 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, - }); - } + let gas_limit = forward!(); let forwarded = gas.record_regular_cost(gas_limit); debug_assert!(forwarded, "the forward is capped to what the call has left"); diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index 000d8dca2..d91a8cfb8 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -11,6 +11,7 @@ mod deploy; mod dispatch; mod inspector; mod limits; +mod precedence; mod rules; use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; 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..64812bb3a --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -0,0 +1,287 @@ +//! 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. + +use mega_evm::{ + system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::MemoryDatabase, +}; + +use super::*; + +/// The gas limit the matrix's deployments are signed with. +const SIGNED: u64 = 500_000; + +/// 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`], with `provided`. +const fn too_low(provided: u64) -> Answer { + Answer::Refused(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: SIGNED, + 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, 0); + let carrying = signed(SIGNED, 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 - 1), + gas_limit, + answer: too_low(SIGNED - 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); + } +} + +/// 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()); + let plain = signed(SIGNED, 0); + let carrying = signed(SIGNED, 1); + let carrying_two = signed(SIGNED, 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), 1_000), + 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), 1_000), + 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 - 1), + answer: too_low(SIGNED - 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 - 1), + answer: too_low(SIGNED - 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 - 1), + answer: too_low(SIGNED - 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), + 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), + 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), + }, + ]; + cases.into_iter().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. +#[test] +fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { + let plain = signed(SIGNED, 0); + let small = signed(1_000, 0); + let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); + let charges = 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), + answer: too_low(SIGNED - charges), + }, + ]; + cases.into_iter().for_each(Case::check); +} diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 9e9021b9e..ac773f0cf 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -1,7 +1,8 @@ //! The rules a `keylessDeploy` call is held to before its creation starts, and what a refusal //! leaves behind: nothing but the overhead. //! -//! The rules and the error ABI are the legacy engine's. What moved is the balance rule, which +//! 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 that succeeds bumps //! the signer's nonce as any creation does, and one that fails keeps the bump only from 0 to 1. From 25b5eedf3cc6fb63d4b34567dbadf76a0040289e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:43:27 -0700 Subject: [PATCH 154/458] fix(satin): charge a keyless call the regular gas a CREATE opcode charges The call paid for the creation's start what the CREATE opcode charges in state and history gas, but not its regular gas: the schedule's create entry and EIP-3860's cost per word of init code. It now pays both after every rule, before the created account and the records, as the opcode orders them; the fixed overhead stays, for decoding the transaction and recovering its signer. The figures are pinned at one and two words and at the maximum init-code size, below and above the execution cap. --- .../mega-evm/src/system/keyless/dispatch.rs | 21 ++++--- .../mega-evm/tests/system/keyless/charges.rs | 58 +++++++++++++++++-- .../mega-evm/tests/system/keyless/deploy.rs | 9 ++- .../tests/system/keyless/inspector.rs | 8 ++- .../mega-evm/tests/system/keyless/limits.rs | 57 ++++++++++++++++-- crates/mega-evm/tests/system/keyless/mod.rs | 7 +++ .../tests/system/keyless/precedence.rs | 8 ++- crates/mega-evm/tests/system/keyless/rules.rs | 51 +++++++++------- 8 files changed, 172 insertions(+), 47 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 4e4d9789f..244634e9c 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -101,8 +101,8 @@ pub(crate) struct KeylessCall { /// /// In this order, each refusal an answer with the call's gas as it stands: /// -/// 1. [`KEYLESS_DEPLOY_OVERHEAD_GAS`] of regular gas, whatever the deployment does; a call that -/// cannot pay it is answered out of gas. +/// 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 is answered out of gas. /// 2. The call carries no value (`NoEtherTransfer()`). /// 3. Its arguments decode, and so does the transaction they carry: a signed legacy creation, no /// chain id, no trailing bytes (`MalformedEncoding()`, `NotContractCreation()`, @@ -120,10 +120,11 @@ pub(crate) struct KeylessCall { /// 11. The deploy address holds no code (`ContractAlreadyExists()`), read cold and 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: 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 is answered -/// out of gas. +/// 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 is answered 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`). /// @@ -372,7 +373,13 @@ fn prepare( refuse!(KeylessDeployError::InsufficientBalance); } - // What the `CREATE` opcode charges its frame for the creation's start, after every rule. + // 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 { diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 60885237b..ccc1884ea 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -5,7 +5,7 @@ //! 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::system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS; +use mega_evm::{constants::MAX_INITCODE_SIZE, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS}; use revm::bytecode::opcode::{PUSH0, REVERT}; use super::*; @@ -16,7 +16,7 @@ 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, as regular gas; +/// - 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; @@ -24,7 +24,9 @@ const RUNTIME_LEN: usize = 5; /// deposited and the history of the same bytes. #[test] fn test_every_charge_of_a_deployment_is_accounted_for() { - let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + 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; @@ -38,14 +40,18 @@ fn test_every_charge_of_a_deployment_is_accounted_for() { let created = entry(GasId::create_state_gas()); assert_eq!( total, - KEYLESS_DEPLOY_OVERHEAD_GAS + new_account + created + 2 * record() + gas_used, + 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 + creation_regular, "at {gas_limit}"); + 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)); @@ -130,13 +136,53 @@ fn test_a_failed_deployment_gives_the_created_account_back() { 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 + gas_used, "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, 32,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 itself spends nothing, and every other charge of the call is +/// state and history gas. +#[test] +fn test_the_call_pays_the_create_opcodes_regular_gas() { + assert_eq!(create_regular(1), 32_000 + 2); + assert_eq!(create_regular(33), 32_000 + 4); + assert_eq!(create_regular(MAX_INITCODE_SIZE), 32_000 + 65_536); + let state = entry(GasId::new_account_state_gas()) + entry(GasId::create_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 [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + 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, 2 * record(), "{len} bytes at {gas_limit}"); + assert_eq!( + total, + regular_expected + state + 2 * record(), + "{len} bytes 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] diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 3b2578fc4..83c97afa9 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -193,7 +193,8 @@ fn test_a_constructor_out_of_gas_is_execution_halted() { } /// A halted deployment is paid for, and its nonce is spent: the transaction spends the overhead, -/// the signer's account and its nonce record, and the whole forward. +/// 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])); @@ -207,7 +208,11 @@ fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { let new_account = entry(GasId::new_account_state_gas()); assert_eq!( total, - KEYLESS_DEPLOY_OVERHEAD_GAS + new_account + record() + SIGNED_GAS_LIMIT, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(1) + + new_account + + record() + + SIGNED_GAS_LIMIT, "at {gas_limit}", ); } diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 4521db602..aa922c846 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -198,11 +198,13 @@ 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 and the -/// reference's gas, and nothing else. +/// 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); @@ -212,7 +214,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], - [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], + [opcode, opcode, 0, 0, 0], "at {gas_limit}", ); assert_eq!( diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index b117a78fb..f6b57ae15 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -326,8 +326,8 @@ fn test_a_deployment_within_every_limit_deploys() { } /// An answer built without a frame carries the reservoir the call inherited: a call refused after -/// it paid for the creation's start — the forward capped below the signed gas limit, which only a -/// signed gas limit near the execution cap reaches above it — gives the charges back to the +/// 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() { @@ -348,9 +348,51 @@ fn test_a_refusal_after_the_charges_gives_the_reservoir_back() { ); } +/// 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, what the call kept of the creation's -/// start, and the creation's `gasUsed`, and nothing else, below and above the execution cap. +/// 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))); @@ -363,6 +405,7 @@ fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { assert_eq!( total, KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(deploying(&runtime(1)).len()) + new_account + entry(GasId::create_state_gas()) + 2 * record() + @@ -375,7 +418,11 @@ fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { beyond(&revert, &reference(reverting.call_data(LARGE_OVERRIDE), gas_limit)); assert_eq!( total, - KEYLESS_DEPLOY_OVERHEAD_GAS + new_account + record() + returned(&revert).gasUsed, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(3) + + new_account + + record() + + returned(&revert).gasUsed, "revert at {gas_limit}", ); } diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index d91a8cfb8..dc1898cb1 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -241,6 +241,13 @@ 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. pub(crate) fn record() -> u64 { write_record_history_gas(1).expect("a record has a price") diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 64812bb3a..fb2e3a596 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -260,13 +260,17 @@ fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { /// 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. +/// 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, 0); let small = signed(1_000, 0); let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); - let charges = entry(GasId::create_state_gas()) + 2 * record(); + 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", diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index ac773f0cf..f58f0f8fe 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -2,11 +2,11 @@ //! leaves behind: nothing but the overhead. //! //! 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 that succeeds bumps -//! the signer's nonce as any creation does, and one that fails keeps the bump only from 0 to 1. -//! A signer at nonce 1 stays there however often its deployment fails, whoever submits it. +//! 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 that succeeds bumps the signer's nonce as +//! any creation does, and one that fails keeps the bump only from 0 to 1. A signer at nonce 1 +//! stays there however often its deployment fails, whoever submits it. use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ @@ -111,22 +111,29 @@ fn test_keyless_deploy_gas_limit_exactly_equal() { assert_eq!(returned(&wide).deployedAddress, CREATE2_FACTORY_CONTRACT); } -/// The gas limit at which a `keylessDeploy` of `deployment` 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 created account -/// and the two records, and the forward. -fn gas_limit_forwarding(deployment: &Deployment, forward: u64) -> u64 { +/// 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 } +/// 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. @@ -138,7 +145,7 @@ fn gas_limit_forwarding(deployment: &Deployment, forward: u64) -> u64 { #[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, 499_999); + 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), @@ -156,7 +163,7 @@ fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { #[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, 500_000); + 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); } @@ -169,7 +176,8 @@ fn test_a_forward_at_the_signed_gas_limit_deploys() { fn test_the_signers_account_can_take_the_forward_below_the_signed_gas_limit() { let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); let new_account = entry(GasId::new_account_state_gas()); - let gas_limit = gas_limit_forwarding(&deployment, 500_000 + new_account / 2); + let gas_limit = + gas_limit_forwarding(&deployment, one_byte_init_len(), 500_000 + 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"); @@ -767,26 +775,25 @@ fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { } /// A call refused after it paid for the creation's start — the forward capped below the signed -/// gas limit — keeps none of it: no account was added, so the signer's account is not charged, -/// and the refusal writes nothing. +/// 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_none_of_them() { +fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { let deployment = Deployment::signed(0, 500_000, 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, 500_000); + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 500_000); 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)); - assert_eq!( - [total, regular, state, history_gas], - [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0], - ); + 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); } @@ -802,7 +809,7 @@ fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { system_db(), &deployment.tx, LARGE_OVERRIDE, - gas_limit_forwarding(&deployment, 500_000), + gas_limit_forwarding(&deployment, 3, 500_000), ); assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); assert_eq!(nonce(&refused, deployment.signer), 0); From 299f8cfd7a0adc9ba550b0ca7c938fcb7bb3564c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:45:06 -0700 Subject: [PATCH 155/458] test(satin): pin that a keyless deployment's gasUsed counts its spend before refunds --- .../mega-evm/tests/system/keyless/charges.rs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index ccc1884ea..507b507eb 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -183,6 +183,41 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { } } +/// `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] From 121c8603ae4a36a44c9ef7092b8e521da5385321 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:45:06 -0700 Subject: [PATCH 156/458] docs: describe the keyless rule order and the CREATE opcode's charges The rules keep the legacy engine's order, so a call several rules refuse reports the legacy engine's error; the call pays the CREATE opcode's regular gas on top of the overhead, which pays for decoding and signer recovery; gasUsed is counted before refunds; and a selector the contract declares, such as version(), answers. --- AGENTS.md | 4 +++- crates/mega-evm/README.md | 3 ++- crates/mega-evm/src/system/keyless/mod.rs | 18 +++++++++++------- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3eddca035..185f518a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,7 +180,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 rewrite (`keyless::rewrite`) runs in `frame_init` before interception, so the creation is an ordinary creation from there on. An inspector sees the frames the deployment is made of: `inspect_frame_init` tells it the call starts, rewrites the call, then tells it the creation starts, as the call's child one journal depth below, and `MegaHandler::inspect_execution` tells it the call ended once the creation is settled into it. - It charges the fixed overhead, holds the call to the legacy engine's nine rules and error ABI, charges what the `CREATE` opcode charges its frame — the signer's account when the creation's nonce bump creates it and the created account, both SALT-priced state gas, and the creation's two write records — and starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left. + 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. The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` — or, inspected, `inspect_execution` just before it — settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 2ad16dd81..a6ff919bd 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -69,7 +69,8 @@ The Oracle forwards a `sendHint` payload to the node's oracle service. `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 becomes a native creation before any interceptor sees it; a tracer sees the call, and the creation as its child. -The call pays a fixed 100,000 gas, is held to the legacy engine's nine rules and error ABI, and pays what a `CREATE` opcode charges its frame: the signer's account when the creation's nonce bump is what creates it, the created account, and the two write records of the creation's start. +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 transaction limit the deployment crosses stops the transaction and takes the deployment back whole. diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 38da964e9..ab164dbff 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -24,10 +24,12 @@ //! no number of failing calls, whoever makes them, gets a signer's deployment refused. //! - 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 deployed contract's account is charged as the `CREATE` opcode charges it, and given back -//! when the deployment fails, at the price it was charged. +//! - 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. +//! 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 it as it stops any frame: a frame budget reverts the //! creation, and the call returns `ExecutionReverted` with the limit's revert data; a transaction //! limit stops the transaction, and the call reverts with the stop, taking back the signer's @@ -35,7 +37,8 @@ //! //! # The error ABI //! -//! The contract's errors are unchanged, and so are the rules that produce them. Four of them have +//! The contract's errors are unchanged, and so are the rules that produce them and the order they +//! are checked in, so a call several rules refuse reports the legacy engine's error. Four have //! no producer here: `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 @@ -46,9 +49,10 @@ //! //! # The contract //! -//! Every selector but `keylessDeploy` runs the deployed bytecode, which carries no fallback and -//! reverts with empty data, and so does a `keylessDeploy` call a contract makes: its method body -//! reverts with `NotIntercepted()`. +//! 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. From cfd78a83ad8098b19288c5d1e664f8ac34ca8c90 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:45:44 -0700 Subject: [PATCH 157/458] test(satin): park the stopped keyless deployment's volatile-data row for detention The retired row also pinned that a keyless deployment a transaction limit stops still reports the volatile data its creation read, and that the stop stays the limit's rather than detention's. That is detention's behaviour, as for the five sibling rows: the test goes back to the parked file under detention, and the README is regenerated. --- crates/mega-evm/tests/_pending/README.md | 12 +- .../tests/_pending/rex5/sandbox_accounting.rs | 114 ++++++++++++++++++ 2 files changed, 120 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index c3c83bfcf..37361324c 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,14 +28,14 @@ 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 | -| detention | 88 | 83 | 5 | 73 | 15 | 0 | +| detention | 89 | 84 | 5 | 73 | 16 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 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** | **259** | **236** | **23** | **203** | **49** | **7** | +| **Total** | **260** | **237** | **23** | **203** | **50** | **7** | ## Tests ported in place @@ -294,14 +294,13 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests retired after the inventory -These 22 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 21 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 | |---|---|---:|---| | `mini_rex/compute_gas_limit.rs` | compute gas (2) | 2 | Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | | `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 | -| `rex5/sandbox_accounting.rs` | native keyless deployment (1) | 1 | The residual-overflow halt was the sandbox's safety net for the usage it merged after the deployment ran; a native deployment is held to every limit as it runs, and a crossing stops it as it stops any frame | | `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 | | `src/system/control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | @@ -309,7 +308,7 @@ They are not counted above. | `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | -| **Total** | | **22** | | +| **Total** | | **21** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -340,6 +339,7 @@ They are not counted above. | `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_block_env_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | | `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_coinbase_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | | `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_oracle_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | +| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_volatile_bitmap_survives_residual_overflow_halt` | detention | a keyless deployment a transaction limit stops still reports the volatile data its creation read, and the stop stays the limit's | | `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | | `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_beneficiary_triggers_detention` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | | `rex6/eip7702_authority_accounting.rs` | `test_rex6_authority_compute_overflow_skips_authorities` | detention | detention owns whether an applied authority that is the block beneficiary lowers the compute cap, and what a compute overflow before the first frame does to the authorizations | @@ -376,7 +376,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `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` | 5 | rewrite 5 (detention · native sub-frame: parent tracker sees child directly) | +| `rex5/sandbox_accounting.rs` | 6 | rewrite 6 (detention · native sub-frame: parent tracker sees child directly) | | `rex5/selfdestruct_beneficiary.rs` | 2 | keep 2 (detention) | | `rex6/beneficiary_detention.rs` | 13 | keep 13 (detention · D08) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | diff --git a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs index da087d410..fc5f2c784 100644 --- a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs @@ -574,3 +574,117 @@ fn test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code() { // ============================================================================ // OUTER EVM GAS DEBIT (REX5+) // ============================================================================ + +/// 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, + ); +} From ea85776e1420adce4d5840288ff26acd7d633bb2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:46:28 -0700 Subject: [PATCH 158/458] docs: say what a keyless call refused after the creation's charges keeps --- crates/mega-evm/src/system/keyless/dispatch.rs | 7 ++++--- crates/mega-evm/tests/system/keyless/rules.rs | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 244634e9c..59e948631 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -133,9 +133,10 @@ pub(crate) struct KeylessCall { /// 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 refusal writes nothing, so the answer takes back every charge but the overhead with it. A -/// database read or a SALT lookup that fails fails the transaction with its cause, as it does at -/// every other site. +/// A refusal writes nothing, so the answer 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 /// diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index f58f0f8fe..d3acebdb5 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -1,5 +1,6 @@ //! The rules a `keylessDeploy` call is held to before its creation starts, and what a refusal -//! leaves behind: nothing but the overhead. +//! 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 From 70bfd21bcb26ab732abae3c73825a93a6c7d77d9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 20:47:21 -0700 Subject: [PATCH 159/458] chore(deps): pin the revm fork to v40.0.3-mega.3 The fork released the withheld-gas API as v40.0.3-mega.3, whose tree is the one the twelve patched crates were pinned to by revision. They move to the tag together. --- Cargo.lock | 26 +++++++++++++------------- Cargo.toml | 24 ++++++++++++------------ 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c777ebc6..bc87411fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3819,7 +3819,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "revm-bytecode", "revm-context", @@ -3838,7 +3838,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "bitvec", "phf 0.13.1", @@ -3849,7 +3849,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "bitvec", "cfg-if", @@ -3865,7 +3865,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3880,7 +3880,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "alloy-eips", "derive_more", @@ -3894,7 +3894,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "auto_impl", "either", @@ -3907,7 +3907,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "auto_impl", "derive-where", @@ -3925,7 +3925,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "auto_impl", "either", @@ -3960,7 +3960,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3972,7 +3972,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3996,7 +3996,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "alloy-primitives", "once_cell", @@ -4006,7 +4006,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "alloy-eip7928", "bitflags 2.11.1", @@ -4019,7 +4019,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=d40bef104a24f1a62161ed539457c330c8e9a743#d40bef104a24f1a62161ed539457c330c8e9a743" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" dependencies = [ "alloy-eip7928", "k256", diff --git a/Cargo.toml b/Cargo.toml index 40e71fdcf..20389ab59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -234,18 +234,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", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "d40bef104a24f1a62161ed539457c330c8e9a743" } +revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } [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 a461c02cadd0c13b89a9355e44b8679fb903ce86 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:05:21 -0700 Subject: [PATCH 160/458] test(satin): pin that the inspected path unwinds a runtime out-of-gas as the plain one does --- crates/mega-evm/tests/satin/write_records.rs | 66 +++++++++++++++----- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 8a6d91c18..a31d57388 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -721,20 +721,25 @@ fn test_authorities_crossing_the_cap_are_not_applied() { assert_eq!(outcome.usage, with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE)); } -/// 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)); // 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()); @@ -751,7 +756,16 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { fails = middle; } } - let outcome = run_at(succeeds - 1).expect("one gas short of succeeding is still included"); + 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, @@ -765,6 +779,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"); From 83724ef99f0e899940dc1fdfe77797fedd9447ae Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:34:02 -0700 Subject: [PATCH 161/458] fix(access): run a precompile on the allowance, not the forward revm runs a precompile inside the frame's start against the frame's gas limit, and detention classified its answer only afterwards. A precompile priced between the allowance and the forward computed in full, while the stop billed only the allowance. After a read, a call to a precompile forwarded more than the allowance its frame would start with now runs on that allowance. Its answer gets the rest of the forward back before it is settled. A precompile out of gas on the allowance is marked as a crossing, and the same classification stops the transaction. Priced within the allowance, a precompile answers as it would without the read. The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call its caller survives. --- AGENTS.md | 8 +- crates/mega-evm/README.md | 3 +- crates/mega-evm/src/access/detention.rs | 118 ++++++-- crates/mega-evm/src/access/mod.rs | 20 +- crates/mega-evm/src/evm/execution.rs | 45 +++- crates/mega-evm/tests/satin/withheld_gas.rs | 281 ++++++++++++++++---- 6 files changed, 387 insertions(+), 88 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index edfec979a..cc031247d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -216,9 +216,11 @@ Detention caps how much a transaction may still compute once it read such data ( The stop reports the limit as what was used (`LimitCheck::ExceedsLimit`): the size of the charge that crossed is not kept. 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 whole forward, the caller's withheld part included, and an interceptor builds its answer the same way. - 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer); an interceptor that charged by taking gas off the frame's limit is settled on the limit the caller forwarded. - An answer that halts burns its whole gas limit. + 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 run on the allowance (`hold_precompile` in `MegaEvm::frame_init`), and its answer gets the rest of the forward back (`Detention::restore_forward`). + Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. + The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. + 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer); an interceptor that charged by taking gas off the frame's limit is settled on the limit the caller forwarded. + An answer that halts otherwise burns its whole gas limit. - **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 a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. The two charges no wrapper sees, an opcode's static gas and `EXP`'s exponent, are bounded by their own price, and what a frame had below it counts as compute. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index df00ed51c..1961fb2e3 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -103,7 +103,8 @@ The Host marks the read where it loads the value, and the most restrictive read 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: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. -A precompile or an interceptor's answer that spent more than the limit left the frame is the same crossing. +A precompile is run on what the limit leaves its frame, not on all its caller forwarded: one priced past that computes nothing and is the same crossing, as is an interceptor's answer that spent more than it. +A precompile priced past its whole forward is the crossing too, where without the read it would be a failed call its caller survives. 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 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index ce8d94b9d..934d2bd90 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -349,14 +349,24 @@ impl Detention { 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, an inspector's, or revm's for a /// call it did not start. /// - /// 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: it is answered out of gas, marked as a crossing - /// of what the frame would have had withheld, and settled by the same rule as a frame that ran + /// An answer marked as a crossing — a precompile 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: it is answered out of gas and marked as a crossing of what the + /// frame would have had withheld. A crossing is settled by the same rule as a frame that ran /// ([`stop`](Self::stop)). Returns the limit when it crossed. pub(crate) fn on_answer( &mut self, @@ -367,26 +377,46 @@ impl Detention { if !self.detains { return None; } - if result.result.is_halt() { - self.burned = self.burned.saturating_add(gas_limit); - return None; - } - let limit = self.limit?; - let allowance = limit.saturating_sub(self.compute_at_start(depth, gas_limit)); - if gas_limit.saturating_sub(result.gas.remaining()) <= allowance { - return None; + 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)?; + if gas_limit.saturating_sub(result.gas.remaining()) <= 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. An + // interceptor that charged by taking gas off the frame's limit answered on less than + // it was forwarded; the frame is settled on what it was forwarded. + let withheld = NonZeroU64::new(gas_limit - allowance)?; + result.result = InstructionResult::OutOfGas; + result.gas.tracker_mut().set_limit(gas_limit); + result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); } - // 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. An - // interceptor that charged by taking gas off the frame's limit answered on less than it - // was forwarded; the frame is settled on what it was forwarded. - let withheld = NonZeroU64::new(gas_limit - allowance)?; - result.result = InstructionResult::OutOfGas; - result.gas.tracker_mut().set_limit(gas_limit); - result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); self.stop(&mut result.gas) } + /// Gives a precompile's answer, 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 of the withheld part, + /// and [`on_answer`](Self::on_answer) settles it as the stop. + /// + /// The precompile's price is not known without running it, so 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 = result.gas.limit().saturating_add(withheld.get()); + result.gas.tracker_mut().set_limit(forward); + if result.result == InstructionResult::PrecompileOOG { + result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); + } else if !result.result.is_halt() { + result.gas.erase_cost(withheld.get()); + } + } + /// 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. /// @@ -703,6 +733,54 @@ mod tests { assert_eq!(beyond.gas.remaining(), 90_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); } + /// 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 rest left. + #[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); + 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); + assert_eq!(out_of_gas.gas.withheld_crossing(), Some(WithheldCrossing::new(withheld))); + assert_eq!( + detention.on_answer(&mut out_of_gas, 1, 90_000_000), + Some(BLOCK_ENV_ACCESS_COMPUTE_GAS) + ); + assert_eq!(out_of_gas.gas.remaining(), withheld.get(), "the allowance counts as spent"); + assert_eq!(out_of_gas.gas.withheld_crossing(), None); + assert_eq!(detention.burned, 0, "a crossing burns nothing"); + } + /// 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] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index daf939de9..db49a6485 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -56,7 +56,8 @@ //! //! 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: +//! 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; @@ -85,10 +86,19 @@ //! 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 all the gas the caller forwarded, the caller's withheld part included, and -//! an interceptor builds its answer likewise: an answer that spent more than the allowance the -//! frame would have run on is answered out of gas and marked as a crossing, and the same rule stops -//! the transaction. +//! 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 run on that +//! allowance, and its answer gets the rest of the forward back. Priced within the allowance, it +//! answers as it would without the read. Priced past it, it answers out of gas without computing; +//! the answer is marked as a crossing, and the same rule stops the transaction. The price is not +//! known without running the precompile, so one priced past its whole forward runs out of the +//! allowance too, and is the stop, where without the read it would be a failed call that burns +//! its forward and that its caller survives. A precompile run on the allowance 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 than the allowance the frame would have run on is +//! answered out of gas and marked as a crossing, and the same rule stops the transaction. //! //! # Nothing withheld leaks //! diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 78eeab37f..be795a1c5 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -6,7 +6,7 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::cell::Cell; +use core::{cell::Cell, num::NonZeroU64}; use op_revm::{ handler::{IsTxError, OpHandler}, @@ -49,7 +49,7 @@ use crate::{ evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, - write_record_history_gas, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, + write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, }; @@ -410,7 +410,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm None, }; + let withheld = hold_precompile(ctx, &self.inner.precompiles, &mut frame_init); let outcome = match self.inner.frame_init(frame_init)? { ItemOrResult::Item(frame) => Ok(frame.interpreter.input.target_address), ItemOrResult::Result(result) => Err(result), @@ -480,6 +482,9 @@ impl EvmTr for MegaEvm( /// Holds a frame answered without running to the compute limit: the answer to a frame of /// `gas_limit` at `depth`, which its caller forwarded. /// -/// revm runs a precompile inside frame init against the whole gas the caller forwarded, the part -/// gas detention withholds from the caller's regular charges included; an interceptor's answer is -/// built the same way. 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`](crate::Detention)). An answer that halts burns what it was given. +/// 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 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, @@ -856,6 +862,27 @@ fn settle_answer( } } +/// Holds a precompile the frame `frame_init` is about to call to what gas detention's limit leaves +/// it, and returns what it took off the forward: 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. +/// +/// The precompile runs on the allowance and sees it as its gas limit; its answer gets the rest +/// back ([`Detention::restore_forward`]) before it is settled. A call to anything else, and a +/// forward within the allowance, run as they are. +fn hold_precompile( + ctx: &MegaContext, + precompiles: &PrecompilesMap, + frame_init: &mut FrameInit, +) -> Option { + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return None }; + let allowance = ctx.detention.allowance(frame_init.depth, inputs.gas_limit)?; + let withheld = NonZeroU64::new(inputs.gas_limit.saturating_sub(allowance))?; + precompiles.get(&inputs.bytecode_address)?; + inputs.gas_limit = allowance; + Some(withheld) +} + /// The gas limit of the frame `input` starts. const fn input_gas_limit(input: &FrameInput) -> u64 { match input { diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index a87996183..d281f0601 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -10,6 +10,9 @@ //! 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}; @@ -34,6 +37,8 @@ use revm::{ interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, }, + precompile::{modexp, PrecompileHalt, PrecompileId, PrecompileOutput}, + primitives::HashMap, Database, Inspector, }; @@ -654,29 +659,63 @@ fn test_a_call_that_reads_the_beneficiary_costs_what_a_warm_account_costs() { /* ---------- answers ---------- */ -/// The calldata of a modexp of a 1,024-byte zero base to an exponent of `exponent_len` bytes, all -/// ones, modulo a 1,024-byte modulus of one: its price grows with the exponent, and its result is -/// cheap to compute. -fn modexp_input(exponent_len: usize) -> Vec { +/// A precompile that charges the price its input names, as one big-endian word. +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. +type Runs = Arc>>; + +/// The precompile at [`PRICED`], recording what it runs on into `runs`. +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 to compute: a 1,024-byte base with no zero byte, an +/// exponent of `exponent_len` bytes, all ones, and an odd 1,024-byte modulus, then `padding` +/// zero bytes the precompile ignores. Its price grows with the exponent, and so does the work. +fn costly_modexp_input(exponent_len: usize, padding: usize) -> Vec { let mut input = Vec::new(); for len in [1_024_usize, exponent_len, 1_024] { input.extend_from_slice(&U256::from(len).to_be_bytes::<32>()); } - input.extend(core::iter::repeat_n(0_u8, 1_024)); + input.extend((0..1_024_u32).map(|i| (i % 251) as u8 + 1)); input.extend(core::iter::repeat_n(0xff_u8, exponent_len)); - let mut modulus = vec![0_u8; 1_024]; - modulus[1_023] = 1; + let mut modulus: Vec = (0..1_024_u32).map(|i| (i % 241) as u8).collect(); + modulus[0] = 0xff; + modulus[1_023] |= 1; input.extend(modulus); + input.extend(core::iter::repeat_n(0_u8, padding)); input } -/// A contract that copies its calldata into memory and calls modexp with it and `gas` (all of it +/// 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_modexp(first: u8, gas: Option) -> Bytes { +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(MODEXP); + .push_address(to); let code = match gas { Some(gas) => code.push_number(gas), None => code.append(GAS), @@ -684,63 +723,205 @@ fn calls_modexp(first: u8, gas: Option) -> Bytes { store_status(code.append(STATICCALL)) } -/// A transaction from `CALLER` to `CONTRACT` carrying `input`. -fn tx_with(input: &[u8], gas_limit: u64) -> mega_evm::MegaTransaction { +/// 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: CALLER, - kind: TxKind::Call(CONTRACT), + caller, + kind: TxKind::Call(to), gas_limit, data: input.to_vec().into(), ..Default::default() })) } -/// The regular gas modexp charges for `input`, read off the call's own result. -fn modexp_price(input: &[u8]) -> u64 { - let db = MemoryDatabase::default().account_code(CONTRACT, calls_modexp(PUSH0, None)); - let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); - let run = run_on(&mut evm, tx_with(input, BELOW)); - assert!(run.outcome.result.is_success()); - let call = evm.inspector().calls.iter().find(|call| call.target == MODEXP).unwrap(); - assert_eq!(call.result, InstructionResult::Return); - call.spent +/// 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. +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 the precompile 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 crosses the limit. Priced a unit past it, it answers +/// out of gas without computing, and the transaction stops, billed exactly the allowance the +/// precompile ran on. +#[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)) + }; + let stopped = |run: &PrecompileRun, price: u64| { + let input = U256::from(price).to_be_bytes::<32>(); + assert_stopped(&run.run, intrinsic_with(&input, gas_limit)); + }; + + // Priced past every allowance: the stop, whose bill says what the allowance was. + let past = run(TIMESTAMP, CAP + 1); + stopped(&past, CAP + 1); + let allowance = past.spent; + assert!(allowance < CAP, "{allowance}"); + assert_eq!(past.ran_on, [(allowance, false)], "run on the allowance, computing nothing"); + + 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); + } + } + } } -/// revm runs a precompile inside the frame's start, against all the gas the caller forwarded, the -/// part detention withholds from the caller's own charges included. A precompile whose price is -/// within what the limit leaves the transaction runs as without the read; one whose price is above -/// it, though within what the caller forwarded, crosses the cap and stops the transaction at the -/// limit; and one whose price is above what it was forwarded runs out of gas as without the read. +/// Modexp on a costly input, 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 the transaction stops at the limit — 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 the +/// transaction stops at the limit. Without the read the call fails and its caller goes on: the +/// precompile's price is not known without running it, so 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) = (modexp_input(32), modexp_input(64)); - let (within_price, above_price) = (modexp_price(&within), modexp_price(&above)); - assert!(within_price < CAP / 2, "{within_price}"); - assert!(above_price > CAP + CAP / 10, "{above_price}"); + 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_modexp(first, gas)); - run_on(&mut MegaEvm::new(context(db)), tx_with(input, gas_limit)) + 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)); + assert_stopped(&detained.run, intrinsic_with(&above, gas_limit)); + let allowance = detained.spent; + 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, &plain, "a price within the allowance"); - assert_eq!(slot(&detained, 0), Some(U256::from(1))); + 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)); + assert_stopped(&detained.run, intrinsic_with(&above, gas_limit)); + assert!( + matches!(detained.ran_on[..], [(gas, false)] if gas < CAP), + "{:?}", + detained.ran_on + ); + 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"); + } +} - let (detained, plain) = (run(TIMESTAMP, None, &above), run(PUSH0, None, &above)); - assert_eq!(slot(&plain, 0), Some(U256::from(1)), "the precompile runs without the read"); - // What a transaction carrying the same input spends before its first instruction. - let stops = MemoryDatabase::default() - .account_code(CONTRACT, BytecodeBuilder::default().stop().build()); - let intrinsic = execute(stops, tx_with(&above, gas_limit)).outcome.gas.regular; - let limit = assert_stopped(&detained, intrinsic); - assert!(limit < above_price, "the stop billed the allowance, not the price"); - - // Forwarded less than its price: a precompile's out-of-gas, the call's failure. - let short = Some(u32::try_from(within_price).unwrap() - 1); - let (detained, plain) = (run(TIMESTAMP, short, &within), run(PUSH0, short, &within)); - assert_as_without_read(&detained, &plain, "a price above the forward"); - assert_eq!(slot(&detained, 0), Some(U256::ZERO)); +/// A modexp priced far above the cap, 58,687,488 and 125,796,352 gas, called after a read with all +/// the gas, is run on the allowance, computes nothing, and the transaction is billed the limit. A +/// transaction the beneficiary sends straight to the precompile is detained from the start, so the +/// precompile runs on the cap itself. The same transaction from another sender computes. +#[test] +fn test_a_precompile_priced_past_the_cap_computes_nothing() { + for (exponent_len, price) in [(128, 58_687_488), (256, 125_796_352)] { + let input = costly_modexp_input(exponent_len, 0); + // 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 code = calls_precompile(TIMESTAMP, MODEXP, None); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let called = run_precompile(db, MODEXP, recording_modexp, tx_with(&input, gas_limit)); + assert_stopped(&called.run, intrinsic_with(&input, gas_limit)); + assert!( + matches!(called.ran_on[..], [(gas, false)] if gas < CAP), + "{:?}", + called.ran_on + ); + + 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, CAP); + assert_stopped(&sent.run, intrinsic); + } } } From 45b03b1733dd4dcefce51b3328555d0c99b5a3e0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:35:14 -0700 Subject: [PATCH 162/458] fix(access): count an interceptor's charge as compute when its frame runs An interceptor that charges a frame by taking gas off its limit does its own work, decoding and recovering a signer. When it answered the call, the charge was compute; when it let the frame run, the transaction's own frame counted from its charged limit and the charge was lost, because that frame has no caller whose regular gas holds it. The charge is now compute on both paths. The transaction's own frame has it added when the frame is built, and a deeper frame's caller already holds it. A charge the allowance cannot pay is answered and stopped before the frame runs, so the stop bills the limit, as the answered path does. --- AGENTS.md | 1 + crates/mega-evm/README.md | 1 + crates/mega-evm/src/access/detention.rs | 54 +++++++++++++- crates/mega-evm/src/access/mod.rs | 6 +- crates/mega-evm/src/evm/execution.rs | 20 +++++- crates/mega-evm/tests/satin/withheld_gas.rs | 78 ++++++++++++++++----- 6 files changed, 139 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc031247d..d0604cd34 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -220,6 +220,7 @@ Detention caps how much a transaction may still compute once it read such data ( Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer); an interceptor that charged by taking gas off the frame's limit is settled on the limit the caller forwarded. + That charge is compute whether the call is answered or its frame runs (`Detention::charge_crosses`, `on_charged_frame_built`): one the allowance cannot pay is answered and stopped before the frame runs, and the transaction's own frame, which has no caller to hold it, has it added when the frame is built. An answer that halts otherwise burns its whole gas limit. - **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 a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 1961fb2e3..5a10b7f45 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -105,6 +105,7 @@ So a transaction that reads runs as it would without the read until a regular ch That charge crossed the cap: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. A precompile is run on what the limit leaves its frame, not on all its caller forwarded: one priced past that computes nothing and is the same crossing, as is an interceptor's answer that spent more than it. A precompile priced past its whole forward is the crossing too, where without the read it would be a failed call its caller survives. +An interceptor's own charge on a frame is compute whether it answers the call or lets the frame run. 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 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 934d2bd90..f414f398b 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -43,10 +43,17 @@ struct DetainedFrame { /// /// ```text /// compute = Σ suspended callers (spent at suspension − child's gas limit) +/// + an interceptor's charge on the transaction's own frame /// + regular_spent(running frame) /// − burned /// ``` /// +/// An interceptor that charges a frame by taking gas off its limit charges compute: its own work, +/// decoding and recovering a signer, whether it then answers the call or lets the frame run. A +/// caller's regular gas spent holds all it forwarded, and its contribution takes only the frame's +/// limit off, so the charge is in it; the transaction's own frame has no caller, and its charge is +/// added when the frame is built. +/// /// 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 @@ -84,7 +91,8 @@ pub struct Detention { accessed: VolatileDataAccess, /// The most compute the transaction may reach, once it read volatile data. limit: Option, - /// The compute of the frames suspended on a child that runs. + /// The compute of the frames suspended on a child that runs, and an interceptor's charge on + /// the transaction's own frame. suspended: u64, /// The regular gas the frames that halted burned without running anything with it. burned: u64, @@ -357,6 +365,27 @@ impl Detention { Some(limit.saturating_sub(self.compute_at_start(depth, gas_limit))) } + /// Whether an interceptor's `charge` on a frame at `depth` that its caller forwarded + /// `gas_limit` crosses the limit. The interceptor took the charge off the frame's limit and + /// lets the frame run; the charge is its own work — decoding, recovering a signer — and + /// compute, whether the frame then runs or is answered. A charge the allowance cannot pay is + /// a regular charge past the limit, and the frame must be answered for the stop rather than + /// run ([`on_answer`](Self::on_answer)). + pub(crate) fn charge_crosses(&self, depth: usize, gas_limit: u64, charge: u64) -> bool { + self.allowance(depth, gas_limit).is_some_and(|allowance| charge > allowance) + } + + /// The frame at `depth` was built on a gas limit an interceptor took `charge` off + /// ([`charge_crosses`](Self::charge_crosses)), and the charge is compute. A deeper frame's + /// caller already holds it: the caller's regular gas spent carries all it forwarded, and its + /// contribution takes only the frame's limit off. The transaction's own frame has no caller, + /// so its charge is added to the transaction's compute here. + pub(crate) fn on_charged_frame_built(&mut self, depth: usize, charge: u64) { + if depth == 0 { + self.suspended = self.suspended.saturating_add(charge); + } + } + /// The frame at `depth`, whose gas limit was `gas_limit`, was answered without running — /// `result` is the answer: a precompile's, an interceptor's, an inspector's, or revm's for a /// call it did not start. @@ -781,6 +810,29 @@ mod tests { assert_eq!(detention.burned, 0, "a crossing burns nothing"); } + /// An interceptor's charge is compute, counted once: the transaction's own frame has no + /// caller, so its charge is added when the frame is built; a deeper frame's caller already + /// holds its charge in what it forwarded. A charge past the allowance crosses the limit. + #[test] + fn test_an_interceptors_charge_is_compute() { + let mut detention = detaining(); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + assert!(!detention.charge_crosses(0, 100_000_000, BLOCK_ENV_ACCESS_COMPUTE_GAS)); + assert!(detention.charge_crosses(0, 100_000_000, BLOCK_ENV_ACCESS_COMPUTE_GAS + 1)); + + detention.on_charged_frame_built(0, 100_000); + let mut frame = gas(100_000_000 - 100_000, 0); + detention.on_frame_run(&mut frame, 0); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 100_000); + + assert!(frame.record_withheld_first_cost(500_000)); + detention.on_frame_suspend(&frame, 0); + detention.on_charged_frame_built(1, 100_000); + let mut child = gas(500_000 - 100_000, 0); + detention.on_frame_run(&mut child, 1); + assert_eq!(detention.compute(&child), 200_000, "each charge once"); + } + /// 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] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index db49a6485..61dd5586c 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -98,7 +98,11 @@ //! //! An interceptor builds its answer on all the gas the caller forwarded, the caller's withheld //! part included: an answer that spent more than the allowance the frame would have run on is -//! answered out of gas and marked as a crossing, and the same rule stops the transaction. +//! answered out of gas and marked as a crossing, and the same rule stops the transaction. An +//! interceptor may instead charge the frame, by taking gas off its limit, and let it run. The +//! charge is the interceptor's own work, and compute whether the call is then answered or runs: +//! one the allowance cannot pay stops the transaction before the frame runs, and one it can pay +//! leaves the frame the rest. //! //! # Nothing withheld leaks //! diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index be795a1c5..7f735cacd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -47,7 +47,7 @@ use revm::{ use crate::{ evm::{history::transaction_body_bytes, inspector::frame_end_checked}, - history_gas, synthetic_frame_result, + history_gas, synthetic_call_result, synthetic_frame_result, system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, @@ -449,6 +449,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm { ctx.additional_limit.set_frame_address(address); + ctx.detention.on_charged_frame_built(depth, charge); hold_upfront_state_gas(ctx, None); Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } @@ -930,13 +933,26 @@ impl MegaEvm { /// 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. + /// + /// The charge is compute for gas detention. One that crosses the compute limit is answered + /// here, as a frame that spent the charge and nothing else, which the answer's settlement + /// turns into the stop ([`settle_answer`]), as it does an interceptor's answer that spent + /// past the limit. #[inline] 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, frame_init.depth) + let forwarded = inputs.gas_limit; + let ctx = &mut self.inner.ctx; + if let Some(answer) = crate::system::intercept(ctx, inputs, frame_init.depth) { + return Some(answer); + } + let charge = forwarded - inputs.gas_limit; + ctx.detention + .charge_crosses(frame_init.depth, forwarded, charge) + .then(|| synthetic_call_result(inputs, InstructionResult::Stop, Bytes::new())) } /// The keyless deployment rewrite: a keyless deployment call turned into the native creation diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index d281f0601..6d8542084 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -19,7 +19,10 @@ use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, system::{ - keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, + keyless::{ + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, IMegaAccessControl, VolatileDataAccessType, }, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, @@ -925,11 +928,17 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { } } -/// An interceptor that charges its frame by taking gas off the frame's limit and then answers is -/// held to the allowance as a precompile is: a `keylessDeploy` call carrying value, from the -/// beneficiary under a cap below the keyless overhead, stops at the cap instead of answering. The -/// stop's gas is the frame's as its caller forwarded it, so a tracer reading the answer sees the -/// allowance spent and the rest left. +/// An interceptor that charges its frame by taking gas off the frame's limit charges compute, +/// whether it then answers the call or lets the frame run: a `keylessDeploy` call from the +/// beneficiary, carrying value (answered, `NoEtherTransfer()`) or not (the frame runs the deployed +/// contract to `NotIntercepted()`), against the same call from another sender. +/// +/// - Under a cap below the keyless overhead, the charge alone crosses the limit: both stop at it, +/// and the stop's gas is the frame's as its caller forwarded it, so a tracer reading the answer +/// sees the allowance spent and the rest left. +/// - Under a cap a hundred gas above the overhead, the charge fits: the answer is the same as +/// without the read, and the frame that runs has a hundred gas of compute left for itself, so it +/// stops at the limit where it would run on. #[test] fn test_an_interceptors_charge_is_held_to_what_the_limit_leaves() { let calldata: Bytes = IKeylessDeploy::keylessDeployCall { @@ -938,15 +947,16 @@ fn test_an_interceptors_charge_is_held_to_what_the_limit_leaves() { } .abi_encode() .into(); - let cap = KEYLESS_DEPLOY_OVERHEAD_GAS / 2; - let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); - let run = |caller: Address| { - let db = MemoryDatabase::default().account_balance(caller, U256::from(10)); + let run = |caller: Address, value: u64, cap: u64| { + 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: BELOW, - value: U256::from(1), + value: U256::from(value), data: calldata.clone(), ..Default::default() })); @@ -955,17 +965,51 @@ fn test_an_interceptors_charge_is_held_to_what_the_limit_leaves() { let run = run_on(&mut evm, tx); (run, evm.inspector().calls[0].spent) }; - let ((detained, stop_spent), (plain, answer_spent)) = (run(BENEFICIARY), run(CALLER)); - assert_eq!(answer_spent, 0, "the answer spent nothing of the limit it was left"); - assert_eq!(stop_spent, cap, "the stop spent the allowance of the limit it was forwarded"); + // What each call spends before its first instruction: the answered one spends the overhead, + // taken off the limit it answers on, and nothing of that limit. + let (answered, spent) = run(CALLER, 1, KEYLESS_DEPLOY_OVERHEAD_GAS / 2); + assert_eq!(spent, 0); assert_eq!( - plain.outcome.result.output(), + answered.outcome.result.output(), Some(&Bytes::from(IKeylessDeploy::NoEtherTransfer::SELECTOR.to_vec())), "the answer without detention" ); + let answered_intrinsic = answered.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; + let (runs, _) = run(CALLER, 0, KEYLESS_DEPLOY_OVERHEAD_GAS / 2); + assert!(!runs.outcome.result.is_success(), "the contract's own NotIntercepted()"); + let ran = runs.outcome.gas.regular - intrinsic_of_keyless(&calldata); + assert!(ran > KEYLESS_DEPLOY_OVERHEAD_GAS + 100, "{ran}"); + + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS / 2; + let (detained, stop_spent) = run(BENEFICIARY, 1, cap); assert_eq!(detained.limit, Some(cap), "the sender is the beneficiary"); - let intrinsic = plain.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; - assert_stopped(&detained, intrinsic); + assert_eq!(stop_spent, cap, "the stop spent the allowance of the limit it was forwarded"); + assert_stopped(&detained, answered_intrinsic); + let (detained, stop_spent) = run(BENEFICIARY, 0, cap); + assert_eq!(stop_spent, cap, "stopped before it ran, on the same allowance"); + assert_stopped(&detained, intrinsic_of_keyless(&calldata)); + + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + 100; + let (detained, _) = run(BENEFICIARY, 1, cap); + assert_eq!(detained.outcome.result, answered.outcome.result, "the charge fits the allowance"); + assert_eq!(detained.outcome.gas, answered.outcome.gas); + let (detained, _) = run(BENEFICIARY, 0, cap); + assert_stopped(&detained, intrinsic_of_keyless(&calldata)); +} + +/// What a `keylessDeploy` call without value, from `CALLER`, spends before its first +/// instruction: the same call with the contract not deployed spends the overhead and nothing else. +fn intrinsic_of_keyless(calldata: &Bytes) -> u64 { + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), + gas_limit: BELOW, + data: calldata.clone(), + ..Default::default() + })); + let run = execute(MemoryDatabase::default(), tx); + assert!(run.outcome.result.is_success(), "no code: the call stops at once"); + run.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS } /* ---------- the refusal's access type ---------- */ From 0611f6abedcff9d0a9e8a4c9beca56422036ea50 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:36:03 -0700 Subject: [PATCH 163/458] fix(access): note what a frame had when EXP's exponent charge fails EXP's exponent charge, up to 1,600, failed outside every wrapper, so what the halting frame had left was counted as compute rather than burned. EXP now runs in the same wrapper as KECCAK256 and the copies into memory, which notes the frame's gas when its charge fails. The one charge no wrapper sees is an opcode's static gas, made by the step loop before the opcode runs. What a frame had when it fails counts as compute: per halting frame, under the failed charge's price, at most 4,999 on SELFDESTRUCT. Burned gas counted as compute only brings the stop earlier. The docs now state that bound instead of a per-transaction one, and a test pins it on fifty halts on SELFDESTRUCT's static charge. --- AGENTS.md | 5 +- crates/mega-evm/README.md | 1 + crates/mega-evm/src/access/detention.rs | 12 ++- crates/mega-evm/src/access/mod.rs | 3 + crates/mega-evm/src/evm/instructions.rs | 21 +++-- crates/mega-evm/tests/satin/withheld_gas.rs | 95 ++++++++++++++++++++- 6 files changed, 123 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d0604cd34..fb1bbf52b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -223,8 +223,9 @@ Detention caps how much a transaction may still compute once it read such data ( That charge is compute whether the call is answered or its frame runs (`Detention::charge_crosses`, `on_charged_frame_built`): one the allowance cannot pay is answered and stopped before the frame runs, and the transaction's own frame, which has no caller to hold it, has it added when the frame is built. An answer that halts otherwise burns its whole gas limit. - **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 a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. - The two charges no wrapper sees, an opcode's static gas and `EXP`'s exponent, are bounded by their own price, and what a frame had below it counts as compute. + 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` can switch volatile-data access off for a frame and every frame below it (the state is `Detention`'s; the interceptor steers it once the control contracts' semantics land, and `MegaContext::with_volatile_access_disabled_from` is the test helper). 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 5a10b7f45..80a6b7461 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -99,6 +99,7 @@ Every one of these limits is unlimited unless a node sets it. 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index f414f398b..c434c262b 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -58,8 +58,16 @@ struct DetainedFrame { /// 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. The two charges no wrapper sees — an opcode's static gas and `EXP`'s exponent — -/// are bounded by their own price, and what a frame had left below it counts as compute. +/// 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, under the failed charge's price, which is 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 /// diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 61dd5586c..decb5877d 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -40,6 +40,9 @@ //! 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 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. diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index f7a1215ae..83c164b44 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -53,7 +53,9 @@ //! 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. +//! 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 revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -67,15 +69,15 @@ use revm::{ bytecode::opcode::{ BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, CALLDATACOPY, CODECOPY, COINBASE, - CREATE, CREATE2, DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, - KECCAK256, LOG0, LOG1, LOG2, LOG3, LOG4, MCOPY, NUMBER, RETURNDATACOPY, SELFBALANCE, - SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, TIMESTAMP, + 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::{block_info, contract, gas_table_spec, host, memory, system}, + instructions::{arithmetic, block_info, contract, gas_table_spec, host, memory, system}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, @@ -107,7 +109,7 @@ pub(crate) fn mega_instructions( 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); 33] = [ + let wrappers: [(u8, InstructionFn); 34] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -141,6 +143,7 @@ pub(crate) fn mega_instructions( (CODECOPY, codecopy::), (RETURNDATACOPY, returndatacopy::), (MCOPY, mcopy::), + (EXP, exp::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -584,8 +587,9 @@ state_read! { sload => host::sload, "SLOAD", "the Oracle's storage"; } -/// Defines an opcode whose own charge has no bound, as revm's instruction with what the frame had -/// left noted when the charge fails ([`note_halt`]). +/// 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.")] @@ -605,6 +609,7 @@ unbounded_charge! { codecopy => system::codecopy, "CODECOPY"; returndatacopy => system::returndatacopy, "RETURNDATACOPY"; mcopy => memory::mcopy, "MCOPY"; + exp => arithmetic::exp, "EXP"; } #[cfg(test)] diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 6d8542084..ae970bb7f 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -46,8 +46,8 @@ use revm::{ }; use crate::detention::{ - assert_stopped, burn, context, execute, intrinsic, op, run_on, spin, tx, work, Calls, Run, - ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, + assert_stopped, burn, context, execute, intrinsic, op, run_on, spin, stop_data, tx, work, + Calls, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, }; /// A contract between the transaction's frame and `CHILD`. @@ -387,6 +387,97 @@ fn test_what_a_halting_callee_burns_is_not_compute() { } } +/// 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 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 regular +/// ledger holds 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. +#[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))); + assert_eq!( + detained.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false + }) + ); + let overshoot = detained.outcome.gas.regular - intrinsic(gas_limit) - limit; + assert!(overshoot < 5_000, "{overshoot}"); + 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"); + } +} + /// 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]) From 8b8816dc2ed9126369584b2f4bdde038b58d4eb6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:37:45 -0700 Subject: [PATCH 164/458] docs(access): state the stipend bound, the system exemption and no_limits Three decisions detention rests on, stated where the mechanism is described: - A value call's stipend stays outside compute, which is regular gas drawn from the transaction's own pools. Each value call costs its caller at least 9,100 of compute and lets its callee run at most 2,300 on the stipend, so the gas run after a read is at most about 25% more than the cap. - System-originated transactions and system calls are exempt from all detention, the block environment included, by the same rule that exempts them from the per-transaction limits. - no_limits turns detention off together with every other per-transaction limit. It is for equivalence mode, benches and tests, not for executing the chain, which runs on the default caps. --- AGENTS.md | 5 ++++- crates/mega-evm/src/access/detention.rs | 6 ++++++ crates/mega-evm/src/access/mod.rs | 14 +++++++++++--- crates/mega-evm/src/block/limit.rs | 4 +++- crates/mega-evm/src/limit/mod.rs | 21 +++++++++++++++++---- 5 files changed, 41 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fb1bbf52b..2e681f41b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -194,14 +194,17 @@ 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 and an applied EIP-7702 authority that is; 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, and neither is a transaction under `no_limits()`, which the execution-spec gate's runner installs. + 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. `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 `BlockLimits::default()` detain. - **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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index c434c262b..ac1c094f2 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -48,6 +48,12 @@ struct DetainedFrame { /// − 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, and each value call costs its caller at least 9,100 of compute — the +/// 9,000 of the value transfer and a warm access of 100 — so the gas run after a read is at most +/// about 25% (2,300 / 9,100) more than the cap. +/// /// An interceptor that charges a frame by taking gas off its limit charges compute: its own work, /// decoding and recovering a signer, whether it then answers the call or lets the frame run. A /// caller's regular gas spent holds all it forwarded, and its contribution takes only the frame's diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index decb5877d..263d6944a 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -20,11 +20,14 @@ //! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default, and a //! caller's limits may set either. 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. +//! 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: they are the -//! protocol maintaining its own state, the Oracle's included. +//! 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 //! @@ -43,6 +46,11 @@ //! 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 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 the read's cap. The limit only //! goes down, so the most restrictive of several reads is the one that binds, whatever their //! order. diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index c87e8b67c..b70faf498 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -122,7 +122,9 @@ impl Default for BlockLimits { } impl BlockLimits { - /// No limit at all. + /// No limit at all, gas detention's caps included, so no transaction of the block is + /// detained ([`EvmTxRuntimeLimits::no_limits`]): for benches and tests, not for executing the + /// chain. pub const fn no_limits() -> Self { Self { tx_gas_limit: u64::MAX, diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 12a1511f0..447c4d175 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -223,7 +223,8 @@ pub struct LimitUsage { /// caps: the compute a transaction may still spend once it read volatile data. They default to /// the spec's, [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] and [`ORACLE_ACCESS_COMPUTE_GAS`]; every other /// limit is unlimited unless a caller sets it. [`no_limits`](Self::no_limits) leaves every one -/// unlimited, the caps included, and a transaction whose caps are both unlimited is not detained. +/// unlimited, the caps included, and a transaction whose caps are both unlimited is not detained: +/// limits built from it do not execute the chain. /// /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS @@ -250,10 +251,18 @@ pub struct EvmTxRuntimeLimits { pub tx_state_gas_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 stops the - /// transaction. `u64::MAX` caps nothing. + /// transaction. + /// + /// `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 stops the transaction. `u64::MAX` caps nothing. + /// at the read plus this. Crossing it stops the transaction. + /// + /// `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, } @@ -268,7 +277,11 @@ impl Default for EvmTxRuntimeLimits { impl EvmTxRuntimeLimits { /// No limit at all: gas detention's caps are unlimited too, so no read of volatile data caps - /// anything. + /// 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 [`Default`], which holds detention's caps at the spec's. pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, From 41b7a1e14bf6be18afbaf8af673e192d2b84f634 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:38:01 -0700 Subject: [PATCH 165/458] test(access): pin that the default runtime limits detain EvmTxRuntimeLimits::default() and the transaction half of BlockLimits::default() hold a read of the block environment and of the Oracle to the spec's caps; no_limits() is what turns detention off. --- crates/mega-evm/tests/satin/detention.rs | 39 ++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 52bfc2209..2616f7636 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -16,9 +16,9 @@ use mega_evm::{ constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, 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, EvmTxRuntimeLimits, LimitCheck, LimitKind, - MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, - VolatileDataAccess, + volatile_data_access_disabled_revert_data, BlockLimits, EvmTxRuntimeLimits, LimitCheck, + LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, VolatileDataAccess, }; use revm::{ bytecode::opcode::*, @@ -657,6 +657,39 @@ fn test_a_callers_limits_set_the_caps() { } } +/// The default runtime limits detain: [`EvmTxRuntimeLimits::default`], and the transaction half +/// of [`BlockLimits::default`] that a block executor installs, hold each kind of read to the +/// spec's cap. It is `no_limits` that turns detention off, with every other per-transaction limit. +#[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(), BlockLimits::default().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}" + ); + + let run = run_under(EvmTxRuntimeLimits::no_limits(), ×tamp); + assert!(!run.detains); + assert_eq!(run.limit, None); + } +} + /// Spending exactly the cap after the read is within it; the limit is strict. #[test] fn test_spending_exactly_the_cap_completes() { From 38b072ee1c0953dae8baae3077b5fbe69924deb8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 21:39:49 -0700 Subject: [PATCH 166/458] bench(access): run EXP in the wrapped-charge arm EXP now runs in the wrapper that notes a frame's gas when its charge fails. The hashes_and_copies arm runs one EXP of a one-byte exponent each round, next to the other opcodes in that wrapper. --- crates/mega-evm/benches/transact.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index a5a168847..f97d365fe 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -24,9 +24,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` and an empty `RETURNDATACOPY`: 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: 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 @@ -71,9 +71,9 @@ use mega_evm::{ use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, BALANCE, CALL, CALLDATACOPY, CALLDATALOAD, CODECOPY, DUP1, GAS, ISZERO, JUMPDEST, - JUMPI, KECCAK256, LOG0, LOG2, MCOPY, MSTORE, NUMBER, POP, PUSH0, PUSH1, RETURNDATACOPY, - SLOAD, SSTORE, STATICCALL, STOP, SUB, SWAP1, TIMESTAMP, + 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, @@ -188,7 +188,10 @@ fn hasher_code() -> Bytes { .append_many([PUSH0, PUSH0, CALLDATACOPY]) .push_number(32_u8) .append_many([PUSH0, PUSH0, CODECOPY]) - .append_many([PUSH0, PUSH0, PUSH0, RETURNDATACOPY]); + .append_many([PUSH0, PUSH0, PUSH0, RETURNDATACOPY]) + .push_number(0xff_u8) + .push_number(3_u8) + .append_many([EXP, POP]); } code.stop().build() } From b0a39c6344583434ef7f8c0ac69d17e9d41211c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 22:01:18 -0700 Subject: [PATCH 167/458] fix(satin): take no signer past nonce 1 with a keyless deployment, and take back only the creation's own bump --- crates/mega-evm/src/system/keyless/mod.rs | 11 +- crates/mega-evm/src/system/keyless/settle.rs | 36 +++-- .../mega-evm/tests/system/keyless/charges.rs | 7 +- .../mega-evm/tests/system/keyless/deploy.rs | 4 +- crates/mega-evm/tests/system/keyless/rules.rs | 150 ++++++++++++++++-- 5 files changed, 169 insertions(+), 39 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index ab164dbff..37c620110 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -18,10 +18,13 @@ //! //! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. //! - 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 that fails keeps the -//! bump only from 0 to 1, which is the replay barrier; from nonce 1 it leaves the nonce at 1, and -//! keeps no record of the bump. The call is permissionless and the signed transaction public, so -//! no number of failing calls, whoever makes them, gets a signer's deployment refused. +//! once the signer's nonce is above 1 (`SignerNonceTooHigh`). A deployment keeps the bump only +//! from 0 to 1, which is the replay barrier; from nonce 1, whether it succeeds or fails, it +//! leaves the nonce at 1 and keeps no record of the bump, as the legacy engine never took a +//! signer past 1. The call is permissionless and the signed transaction public, so no number of +//! failing calls, whoever makes them, gets a signer's deployment refused, and a deployment that +//! succeeded answers a resubmission with `ContractAlreadyExists()`. Nonces a delegated signer's +//! own code spends in the constructor stay spent. //! - 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, diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 841b06d3f..ce3a57667 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -55,10 +55,14 @@ pub(crate) fn give_back_history( /// back too. The creation's lane was popped when it returned, or is popped here when it never /// ran. /// -/// A deployment that failed keeps the signer's nonce bump only when it took the signer from 0 to -/// 1: a failed deployment from nonce 1 leaves it at 1 ([`keep_no_second_bump`]). 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. +/// A deployment keeps the creation's nonce bump only when it took the signer from 0 to 1: a +/// deployment from nonce 1, whether it succeeded or failed, leaves the nonce at 1 +/// ([`take_back_bump`]), as the legacy engine did. 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`. Only the creation's own bump is +/// taken back: the nonces a delegated signer's code spent in the constructor, creating accounts at +/// them, stay spent, so the nonce never goes back below an account the signer created. /// /// Then the call answers, as a frame that resumes after its child returned would: /// @@ -97,13 +101,15 @@ where // 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 bumped = account_nonce(ctx, call.signer) != call.signer_nonce; - if !bumped { + let nonce = account_nonce(ctx, call.signer); + if nonce == call.signer_nonce { call.gas.refill_reservoir(call.signer_account_charge); } - // A deployment that failed from nonce 1 keeps no bump: the address stays deployable. - if bumped && call.signer_nonce > 0 && !holds_code(ctx, call.deploy_address) { - keep_no_second_bump(ctx, &mut call, result)?; + // 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; any further one the signer's own code spent. + if call.signer_nonce > 0 && nonce == call.signer_nonce + 1 { + take_back_bump(ctx, &mut call, result)?; } let (status, output) = match ctx.additional_limit.stop_before_run() { @@ -176,14 +182,14 @@ fn holds_code( }) } -/// Takes back the nonce bump of a failed deployment by 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 fail. +/// 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, having deployed no code. A creation that failed took -/// its value transfer back with the rest of its writes. -fn keep_no_second_bump( +/// 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, call: &mut KeylessCall, result: &FrameResult, diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 507b507eb..1d9a64c95 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -280,7 +280,8 @@ fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { /// 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. +/// and the signer, an account already, is charged nothing for it. The transaction's own bump took +/// it to nonce 1, and a deployment takes no signer past 1. #[test] fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); @@ -293,8 +294,8 @@ fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { .execute_transaction(tx) .expect("a valid transaction"); assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); - // The transaction bumped its sender from 0 to 1, and the creation from 1 to 2. - assert_eq!(nonce(&outcome, deployment.signer), 2); + // 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); diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 83c97afa9..71b1bce92 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -123,7 +123,7 @@ fn test_keyless_deploy_increments_nonce_from_zero() { } /// A signer at nonce 1 still deploys at its Nick's-Method address, which is its first creation's -/// and not its nonce's, and ends at nonce 2: the creation bumps the real nonce. +/// and not its nonce's, and stays at nonce 1: a deployment takes no signer past 1. #[test] fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { for gas_limit in GAS_LIMITS { @@ -131,7 +131,7 @@ fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { let db = system_db().account_nonce(deployment.signer, 1); let outcome = deploy(db, &deployment, gas_limit); assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 2); + assert_eq!(nonce(&outcome, deployment.signer), 1); } } diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index d3acebdb5..27af5f9f3 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -5,9 +5,9 @@ //! 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 that succeeds bumps the signer's nonce as -//! any creation does, and one that fails keeps the bump only from 0 to 1. A signer at nonce 1 -//! stays there however often its deployment fails, whoever submits it. +//! rule 4, which now counts real nonces: a deployment keeps the creation's bump only from 0 to 1, +//! and takes no signer past 1, as the legacy engine did. A signer at nonce 1 stays there however +//! often its deployment fails, whoever submits it, and once it deploys. use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ @@ -25,7 +25,7 @@ use mega_evm::{ MegaSpecId, MegaTransactionError, TestExternalEnvs, }; use revm::{ - bytecode::opcode::{INVALID, MSTORE, PUSH0, REVERT}, + bytecode::opcode::{CALL, CALLER, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, REVERT, STOP}, context::{result::EVMError, CfgEnv}, context_interface::cfg::GasId, state::{AccountInfo, Bytecode}, @@ -388,18 +388,21 @@ fn test_a_signer_at_nonce_one_stays_there_however_often_it_fails() { } } +/// 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: 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() { - // Signed for chains that charge no state gas for deployed code: without a reservoir, the - // signed gas limit does not cover the code a canonical deployment deposits. for deploying_at in GAS_LIMITS { - for (tx, signed, signer, address) in [ - (CREATE2_FACTORY_TX, 100_000, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_CONTRACT), - (EIP1820_TX, 800_000, EIP1820_DEPLOYER, EIP1820_CONTRACT), - ] { + for (tx, signed, signer, address) in CANONICAL { fail_then_deploy(tx, signed, signer, address, GAS_LIMITS[0], deploying_at); } } @@ -425,7 +428,8 @@ fn test_failing_attempts_by_anybody_leave_the_address_deployable() { /// 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`. +/// 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, @@ -433,7 +437,7 @@ fn fail_then_deploy( address: Address, failing_at: u64, deploying_at: u64, -) { +) -> MemoryDatabase { let mut db = system_db(); for attempt in 0..3 { let outcome = run_nth( @@ -451,14 +455,68 @@ fn fail_then_deploy( db.commit(outcome.result_and_state.state); } let deployed = run_nth( - db, + 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), 2, "a deployment that succeeds bumps the nonce"); + assert_eq!(nonce(&deployed, signer), 1, "a deployment takes no signer past 1"); + 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() { + for deploying_at in GAS_LIMITS { + for (tx, signed, signer, address) in CANONICAL { + 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, @@ -634,7 +692,69 @@ fn test_a_delegated_signer_deploys() { ); let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 2); + 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 — the settlement takes back the creation's own bump and nothing +/// else — so the nonce never goes back below an account the signer created, and the signer's +/// next creations land at fresh addresses. A creation that reverts takes the delegation's +/// creations back with it, and the signer ends at 1. +#[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]), 4), + ("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 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}"); + } + } } } From 13a170be6edb0e3ac1f84e7b56592b85d0dc4bd0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 22:01:54 -0700 Subject: [PATCH 168/458] docs: say a keyless deployment takes no signer past nonce 1 --- AGENTS.md | 5 +++-- crates/mega-evm/README.md | 3 ++- crates/mega-evm/src/system/AGENTS.md | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 185f518a9..946c16afd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -186,8 +186,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` — or, inspected, `inspect_execution` just before it — settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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: a deployment that succeeds spends the signer's nonce, and one that fails spends it only from 0 to 1. - From nonce 1 a failed deployment leaves the nonce at 1 and takes the bump's write record and its history back, so no number of failing calls — the call is permissionless and the signed transaction public — gets the signer's deployment refused. + Rule 4 (signer nonce at most 1) counts real nonces, and a keyless deployment never takes a signer past nonce 1, as the legacy engine did: the creation's bump stands only from 0 to 1, which is the replay barrier. + From nonce 1 the settlement sets the nonce back and takes the bump's write record and its history back, whether the deployment succeeded or failed, so 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()`. + Only the creation's own bump is taken back: nonces a delegated signer's code spends in the constructor stay spent, so the nonce never goes back below an account the signer created. `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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 and limit-check protocol 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 a6ff919bd..0dfdc9c41 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -75,7 +75,8 @@ It then starts the creation as the signer, below it, with `gasLimitOverride` cap 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 transaction limit the deployment crosses stops the transaction and takes the deployment back whole. A signer is refused once its nonce is above 1. -A deployment that succeeds spends the signer's nonce, and one that fails spends it only from 0 to 1: a signer at nonce 1 stays there however often its deployment fails, so nobody can use up its attempts. +A deployment spends the signer's nonce from 0 to 1 and takes no signer past 1, as the legacy engine did. +A signer at nonce 1 stays there however often its deployment fails, so nobody can use up its attempts, and once it deploys, so a resubmission finds the address taken (`ContractAlreadyExists()`). A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. 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. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index f648fffe5..310a8c36d 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -24,7 +24,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 charges nothing: the frame starts as it was built. - A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context); it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped; the inspected path settles it in `inspect_execution` just before, and tells the inspector the call ended. -- What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps the signer's spent nonce, 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 that failed from nonce 1 keeps no bump: the settlement sets the nonce back and takes the record and its history back, so a signer's failures stop at nonce 1 and nobody can use up its attempts. +- 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, whether it deployed or failed: the settlement sets the nonce back and takes the record and its history back, so no deployment takes a signer past nonce 1, nobody can use up its attempts, and a resubmission of one that deployed is refused `ContractAlreadyExists()`, as in the legacy engine. It takes back the creation's own bump alone, the one just above the nonce the call started from: nonces a delegated signer's code spent in the constructor stay spent. - 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. From 55d474a5976de2d42c88521065233c1147fab78c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 22:02:56 -0700 Subject: [PATCH 169/458] test(satin): pin that a keyless call carrying value is refused for it before its arguments decode --- .../tests/system/keyless/precedence.rs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index fb2e3a596..d2ea3e3d1 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -8,6 +8,10 @@ //! 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}, @@ -135,6 +139,36 @@ fn test_a_call_two_rules_refuse_reports_the_first_the_legacy_engine_checked() { } } +/// 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 From e5ef5177353051f79f5d20b8c291a53501894051 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:04:00 -0700 Subject: [PATCH 170/458] test(access): pin that a halt burns what its frame had when it halted A callee that hashes, works through 260,000 gas and then hits an invalid opcode burns what it had at the invalid opcode, not what it had after the hash. The stop its caller reaches bills that burn beside the limit, to the gas. --- crates/mega-evm/tests/satin/withheld_gas.rs | 26 +++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index ae970bb7f..b1b06e390 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -555,6 +555,32 @@ fn test_the_stop_reports_the_limit_whatever_a_callee_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 the limit, 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))); + let burned = run.outcome.gas.regular - intrinsic(gas_limit) - limit; + 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. From 7d0197a304155ae9704209878e6049f4cca5b994 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:54:11 -0700 Subject: [PATCH 171/458] test(satin): pin the transfer logs where gas detention meets them A value call to a precompile after a read, priced within and past the allowance and sent by the beneficiary; a value call its caller cannot fund after a read; a SELFDESTRUCT whose frame the cap stops, in the transaction's own frame and in a child; and every detained frame start, with and without an inspector. Each transaction keeps the data size of the transfer logs its receipt carries, and the debug-build frame-start check runs on every path. --- .../tests/satin/detained_transfers.rs | 510 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/withheld_gas.rs | 4 +- 3 files changed, 513 insertions(+), 2 deletions(-) create mode 100644 crates/mega-evm/tests/satin/detained_transfers.rs 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..998d367c3 --- /dev/null +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -0,0 +1,510 @@ +//! 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 transaction the cap stops keeps its body alone. 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, interpreter::InstructionResult}; + +use crate::{ + detention::{ + assert_stopped, context, intrinsic, op, run_on, spin, Calls, 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 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 runs out of the allowance without +/// computing, the frame's checkpoint takes the move and the log back, and the transaction stops +/// at the limit, billed its intrinsic gas and the limit and keeping its body alone. 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 and runs on the cap: priced past it, the same stop, 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); + assert_stopped(&detained, intrinsic_with(&above, gas_limit)); + // The answer is the stop, having spent the allowance it ran on. + let (result, allowance) = ended(&calls, MODEXP); + assert_eq!(result, InstructionResult::Revert); + assert!(allowance < detained.limit.unwrap(), "{allowance}"); + 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, CAP)); + assert_stopped(&detained, plain.outcome.gas.regular - price); + 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 of 2,600, which revm charges after it journaled the move and its transfer log. +const DESTRUCT_AFTER_READ: u64 = 2 + 3 + 5_000 + 2_600; + +/// 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 - 2_600 - 1] { + let stopped = run_own(TIMESTAMP, cap); + assert_stopped(&stopped, intrinsic(gas_limit)); + 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; + assert_stopped(&stopped, intrinsic(gas_limit)); + 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, + /// Whether the cap stops the transaction. + stops: bool, +} + +/// 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. +#[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: false, + }, + Start { + name: "a value call to a contract the cap then stops", + code: |first| calls_with_value(first, CHILD, None), + input: none, + held: VALUE, + stops: true, + }, + Start { + name: "a value call to an account with no code", + code: |first| calls_with_value(first, PAYEE, None), + input: none, + held: VALUE, + stops: false, + }, + 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: false, + }, + 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: false, + }, + 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, + stops: true, + }, + 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: false, + }, + Start { + name: "a value call its caller cannot fund", + code: |first| calls_with_value(first, RECEIVER, None), + input: none, + held: VALUE - 1, + stops: false, + }, + 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: false, + }, + 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: false, + }, + 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: false, + }, + 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: false, + }, + 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: false, + }, + ]; + 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 start.stops { + assert_stopped(&detained, intrinsic_with(&input, gas_limit)); + 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/main.rs b/crates/mega-evm/tests/satin/main.rs index 3ec7ce9f5..3083549b2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -7,6 +7,7 @@ mod data_size; mod data_size_counts; mod db_error; mod deposit_charge; +mod detained_transfers; mod detention; mod equivalence; mod history_bytes; diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index b1b06e390..ac4eb0592 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -814,7 +814,7 @@ fn recording_modexp(runs: &Runs) -> DynPrecompile { /// The calldata of a modexp that is costly to compute: a 1,024-byte base with no zero byte, an /// exponent of `exponent_len` bytes, all ones, and an odd 1,024-byte modulus, then `padding` /// zero bytes the precompile ignores. Its price grows with the exponent, and so does the work. -fn costly_modexp_input(exponent_len: usize, padding: usize) -> Vec { +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_024] { input.extend_from_slice(&U256::from(len).to_be_bytes::<32>()); @@ -860,7 +860,7 @@ fn tx_with(input: &[u8], gas_limit: u64) -> mega_evm::MegaTransaction { } /// What a transaction carrying `input` spends before its first instruction. -fn intrinsic_with(input: &[u8], gas_limit: u64) -> u64 { +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 From 8488000932114bd87e4eea40a95bff1c5410d204 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:54:23 -0700 Subject: [PATCH 172/458] style(satin): format the context's merged imports --- crates/mega-evm/src/evm/context.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 1d9c8f7ed..b6cf6f9d0 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -20,9 +20,8 @@ use crate::{ }, system::{self, MEGA_SYSTEM_ADDRESS}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, Detention, EmptyExternalEnv, - EthSpecId, - EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, - VolatileDataAccess, + EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, + SaltEnv, VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` From 4ebed8a2d54c786302733242f15ef4e6c203daf8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:55:11 -0700 Subject: [PATCH 173/458] docs(access): give the README's precompile residual its condition --- crates/mega-evm/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index a76f07b2b..1cc20a4f0 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -102,7 +102,6 @@ A transaction's state growth is the EIP-8037 state gas it spends, so the state-g It is a limit on gas, so a slot or an account in a crowded SALT bucket reaches it sooner. Every one of these limits is unlimited unless a node sets it. - 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. @@ -111,7 +110,7 @@ Every frame's spendable gas is held to what the limit leaves the transaction, an 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: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. A precompile is run on what the limit leaves its frame, not on all its caller forwarded: one priced past that computes nothing and is the same crossing, as is an interceptor's answer that spent more than it. -A precompile priced past its whole forward is the crossing too, where without the read it would be a failed call its caller survives. +A precompile forwarded more than what the limit leaves its frame, and priced past its whole forward, is the crossing too, where without the read it would be a failed call its caller survives. An interceptor's own charge on a frame is compute whether it answers the call or lets the frame run. 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. From e6e19f27986e0d9d1a620ff4aa7dc915f100042c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:55:16 -0700 Subject: [PATCH 174/458] docs(access): bound a static-charge halt's leftover below the charge's price --- crates/mega-evm/src/access/detention.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index ac1c094f2..453b50fd6 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -69,7 +69,7 @@ struct DetainedFrame { /// /// 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, under the failed charge's price, which is at most 4,999, on +/// 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 From d61b7542e295eebadea870ff389dbf6c5eae4107 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:55:59 -0700 Subject: [PATCH 175/458] docs(access): name a precompile whose input fails past its gas check After a read, a precompile priced between the allowance and its forward whose input fails a check made after its gas check runs out of the allowance before that check and stops the transaction. Without the read the check fails the call, which its caller survives. --- AGENTS.md | 1 + crates/mega-evm/README.md | 1 + crates/mega-evm/src/access/detention.rs | 4 +++- crates/mega-evm/src/access/mod.rs | 8 +++++--- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 492e41efb..b8b7c769c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,6 +232,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 run on the allowance (`hold_precompile` in `MegaEvm::frame_init`), and its answer gets the rest of the forward back (`Detention::restore_forward`). Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. + So is one priced between the allowance and its forward whose input fails a check made after its gas check: it runs out of the allowance before that check, where without the read the check fails the call, which burns its forward and which its caller survives. 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer); an interceptor that charged by taking gas off the frame's limit is settled on the limit the caller forwarded. That charge is compute whether the call is answered or its frame runs (`Detention::charge_crosses`, `on_charged_frame_built`): one the allowance cannot pay is answered and stopped before the frame runs, and the transaction's own frame, which has no caller to hold it, has it added when the frame is built. An answer that halts otherwise burns its whole gas limit. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 1cc20a4f0..f931a1bb9 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -111,6 +111,7 @@ So a transaction that reads runs as it would without the read until a regular ch That charge crossed the cap: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. A precompile is run on what the limit leaves its frame, not on all its caller forwarded: one priced past that computes nothing and is the same crossing, as is an interceptor's answer that spent more than it. A precompile forwarded more than what the limit leaves its frame, and priced past its whole forward, is the crossing too, where without the read it would be a failed call its caller survives. +So is one priced between what the limit leaves its frame and its forward whose input fails a check made after its gas check: without the read, that check fails the call, which its caller survives. An interceptor's own charge on a frame is compute whether it answers the call or lets the frame run. 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 453b50fd6..14263fb33 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -449,7 +449,9 @@ impl Detention { /// and [`on_answer`](Self::on_answer) settles it as the stop. /// /// The precompile's price is not known without running it, so a precompile priced above its - /// whole forward runs out of the allowance as well, and is the stop too. + /// whole forward runs out of the allowance as well, and is the stop too. So is one priced + /// within its forward, past the allowance, whose input fails a check made after its gas check, + /// which without the read fails the call instead. pub(crate) fn restore_forward(result: &mut InterpreterResult, withheld: NonZeroU64) { let forward = result.gas.limit().saturating_add(withheld.get()); result.gas.tracker_mut().set_limit(forward); diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 263d6944a..3191e7052 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -103,9 +103,11 @@ //! answers as it would without the read. Priced past it, it answers out of gas without computing; //! the answer is marked as a crossing, and the same rule stops the transaction. The price is not //! known without running the precompile, so one priced past its whole forward runs out of the -//! allowance too, and is the stop, where without the read it would be a failed call that burns -//! its forward and that its caller survives. A precompile run on the allowance also sees the -//! allowance as its gas limit. +//! allowance too, and is the stop, where without the read it would be a failed call that burns its +//! forward and that its caller survives. So is one priced between the allowance and its forward +//! whose input fails a check made after its gas check: it runs out of the allowance before that +//! check, where without the read the check fails the call, which burns its forward and which its +//! caller survives. A precompile run on the allowance 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 than the allowance the frame would have run on is From fde099aeb6d4ab9386df668870fba52815c23261 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 23 Sep 2026 23:56:42 -0700 Subject: [PATCH 176/458] test(access): run the built-in precompiles past the allowance Modexp priced past the cap through the built-in precompile set stops with intrinsic + limit, as the recording one does. A pairing input with a stray byte, priced between the allowance and its forward, stops under a cap of 100,000 and fails as without the read under the default cap. --- crates/mega-evm/tests/satin/withheld_gas.rs | 42 +++++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index ac4eb0592..e80040067 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -65,6 +65,9 @@ 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"); + /// 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) { @@ -1004,9 +1007,10 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { } /// A modexp priced far above the cap, 58,687,488 and 125,796,352 gas, called after a read with all -/// the gas, is run on the allowance, computes nothing, and the transaction is billed the limit. A -/// transaction the beneficiary sends straight to the precompile is detained from the start, so the -/// precompile runs on the cap itself. The same transaction from another sender computes. +/// the gas, is run on the allowance, computes nothing, and the transaction is billed the limit, in +/// the built-in precompile set the chain runs as in the recording one. A transaction the +/// beneficiary sends straight to the precompile is detained from the start, so the precompile runs +/// on the cap itself. The same transaction from another sender computes. #[test] fn test_a_precompile_priced_past_the_cap_computes_nothing() { for (exponent_len, price) in [(128, 58_687_488), (256, 125_796_352)] { @@ -1027,8 +1031,11 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { for gas_limit in TIERS { let code = calls_precompile(TIMESTAMP, MODEXP, None); let db = MemoryDatabase::default().account_code(CONTRACT, code); - let called = run_precompile(db, MODEXP, recording_modexp, tx_with(&input, gas_limit)); + let called = + run_precompile(db.clone(), MODEXP, recording_modexp, tx_with(&input, gas_limit)); assert_stopped(&called.run, intrinsic_with(&input, gas_limit)); + let built_in = execute(db, tx_with(&input, gas_limit)); + assert_stopped(&built_in, intrinsic_with(&input, gas_limit)); assert!( matches!(called.ran_on[..], [(gas, false)] if gas < CAP), "{:?}", @@ -1045,6 +1052,33 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { } } +/// 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, which checks +/// the input's length after its gas. Under a cap of 100,000 it runs out of the allowance before the +/// length check, and the transaction stops; 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)); + run_on(&mut evm, tx_with(&input, gas_limit)) + }; + let (detained, plain) = (run(TIMESTAMP, 100_000), run(PUSH0, 100_000)); + assert_stopped(&detained, intrinsic_with(&input, gas_limit)); + 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"); + } +} + /// An interceptor that charges its frame by taking gas off the frame's limit charges compute, /// whether it then answers the call or lets the frame run: a `keylessDeploy` call from the /// beneficiary, carrying value (answered, `NoEtherTransfer()`) or not (the frame runs the deployed From 49d54f0b5083d81513a5182d7523ac3bec1bbae1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:25:00 -0700 Subject: [PATCH 177/458] feat(external): read the Oracle's storage through the oracle environment --- crates/mega-evm/src/evm/host.rs | 64 ++- crates/mega-evm/src/external/AGENTS.md | 5 +- crates/mega-evm/src/external/oracle.rs | 5 + crates/mega-evm/tests/_pending/README.md | 15 +- .../tests/_pending/mini_rex/oracle.rs | 222 --------- crates/mega-evm/tests/system/main.rs | 1 + .../mega-evm/tests/system/oracle_storage.rs | 450 ++++++++++++++++++ 7 files changed, 525 insertions(+), 237 deletions(-) create mode 100644 crates/mega-evm/tests/system/oracle_storage.rs diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index f13cf3764..2dc614804 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -30,6 +30,13 @@ //! 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 @@ -68,7 +75,7 @@ use revm::{ }; use crate::{ - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, StagedRecord, + system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, StagedRecord, VolatileDataAccess, }; @@ -155,7 +162,8 @@ impl revm::context_interface::Host self.inner.slot_num() } - /// Loads the slot, marking a read of the Oracle's storage. + /// 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, @@ -163,15 +171,10 @@ impl revm::context_interface::Host key: StorageKey, skip_cold_load: bool, ) -> Result, LoadError> { - let oracle = address == ORACLE_CONTRACT_ADDRESS; - if oracle && self.detention.refuses(VolatileDataAccess::ORACLE) { - return Err(LoadError::ColdLoadSkipped); + if address == ORACLE_CONTRACT_ADDRESS { + return self.oracle_sload(key, skip_cold_load); } - let load = self.inner.sload_skip_cold_load(address, key, skip_cold_load)?; - if oracle { - self.detention.observe(VolatileDataAccess::ORACLE); - } - Ok(load) + self.inner.sload_skip_cold_load(address, key, skip_cold_load) } /// Loads the account, marking a read of the block beneficiary's. @@ -325,6 +328,47 @@ impl MegaContext { self.detention.observe(access); true } + + /// 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 oracle environment answers first ([`OracleEnv::get_oracle_storage`]); a slot it has no + /// value for is read from the database through the journal. 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. + /// + /// The read is always cold, whichever source answered and however often the transaction read + /// the slot before. 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 the price may depend on + /// neither: every read costs the cold access. A frame that could not pay it reads nothing, as + /// revm's own skipped cold load does, and the environment is not asked. + /// + /// 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. + fn oracle_sload( + &mut self, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + if self.detention.refuses(VolatileDataAccess::ORACLE) || skip_cold_load { + return Err(LoadError::ColdLoadSkipped); + } + let value = match self.external_envs().oracle_env.get_oracle_storage(key) { + Some(value) => value, + None => { + revm::context_interface::Host::sload_skip_cold_load( + &mut self.inner, + ORACLE_CONTRACT_ADDRESS, + key, + false, + )? + .data + } + }; + self.detention.observe(VolatileDataAccess::ORACLE); + Ok(StateLoad::new(value, true)) + } } /// Journal reads that observe an account or a slot without warming it. diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 761ee3097..56615b71c 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -15,7 +15,8 @@ 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 is priced cold whichever source answered it, so its price cannot depend on whether the oracle service had a value. - 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 +30,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 service first, the database for a slot it has no value for, 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/oracle.rs b/crates/mega-evm/src/external/oracle.rs index 303638e4d..56c14e7ec 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -24,6 +24,11 @@ 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, and + /// reads the slot from the chain's state when the answer is `None`. A frame that cannot pay + /// the read's cold access, and a frame whose volatile-data access is switched off, read + /// nothing and do not ask. 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/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index d16fd7d4c..8864f17b3 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -31,11 +31,11 @@ Do not add a `_pending/main.rs`. | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | -| the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | +| the oracle and control contracts | 73 | 73 | 0 | 63 | 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** | **246** | **226** | **20** | **159** | **80** | **7** | +| **Total** | **242** | **222** | **20** | **155** | **80** | **7** | ## Tests ported in place @@ -298,6 +298,15 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the | `src/limit/compute_gas.rs` | detention (1) | 1 | `tests/satin/detention.rs` | | **Total** | | **83** | | +## Tests ported by the oracle and control contracts + +These 4 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | +| **Total** | | **4** | | + ## Tests retired after the inventory These 21 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. @@ -354,7 +363,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/access_beneficiary_balance.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `mini_rex/block_env_gas_limit.rs` | 3 | rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `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` | 7 | rewrite 3 (revert-class aborts · D48); keep 4 (the oracle and control contracts) | +| `mini_rex/oracle.rs` | 3 | rewrite 3 (revert-class aborts · D48) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | | `rex2/keyless_deploy.rs` | 36 | 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) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | diff --git a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs index b71b162d6..5227bde08 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -139,228 +139,6 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { ); } -/// 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 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] 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 diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index e8f71296a..c1300aa0f 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -8,4 +8,5 @@ mod dispatch; mod keyless; mod limit_control; mod oracle; +mod oracle_storage; mod system_tx; 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..488fcfd10 --- /dev/null +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -0,0 +1,450 @@ +//! The Oracle's storage, read through the oracle environment: an `SLOAD` in the Oracle's own +//! frame asks the node's oracle service first and the database when the service has no value, +//! 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_primitives::{address, Address, Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::ORACLE_ACCESS_COMPUTE_GAS, + system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + volatile_data_access_disabled_revert_data, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, + MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleEnv, + VolatileDataAccess, +}; +use revm::bytecode::opcode::{ + CALL, DELEGATECALL, DUP2, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, STOP, SUB, SWAP1, +}; + +use crate::common::{block, call_tx, calls_with, split_outcome, system_db, CALLER, CONTRACT}; + +/// 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, and what gas detention made of its reads. +struct Run { + outcome: MegaTransactionOutcome, + accessed: VolatileDataAccess, + limit: Option, +} + +/// 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() } +} + +/// 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 first"); + 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_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_eq!(run.accessed, VolatileDataAccess::empty()); +} + +/// The Oracle's own code answers `getSlot` from the service too: the read is the `SLOAD` in its +/// frame, whatever code runs there. +#[test] +fn test_the_deployed_oracle_reads_through_the_service() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + let run = run(db, &service, call_tx(ORACLE_CONTRACT_ADDRESS, get_slot(SLOT), U256::ZERO)); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(run.outcome.result.output().unwrap()).unwrap(), + B256::from(SERVICE_VALUE), + ); +} From b8734c77c093bab25f8568e044045dc16128393b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:28:49 -0700 Subject: [PATCH 178/458] feat(system): steer gas detention's switch from MegaAccessControl --- crates/mega-evm/src/access/detention.rs | 3 +- crates/mega-evm/src/evm/context.rs | 4 +- crates/mega-evm/src/system/control.rs | 86 +- crates/mega-evm/src/system/intercept.rs | 2 +- crates/mega-evm/tests/_pending/README.md | 10 +- .../tests/_pending/rex4/access_control.rs | 1889 ----------------- crates/mega-evm/tests/_pending/rex4/main.rs | 1 - .../mega-evm/tests/system/access_control.rs | 786 +++++++ crates/mega-evm/tests/system/control.rs | 2 +- crates/mega-evm/tests/system/main.rs | 1 + 10 files changed, 863 insertions(+), 1921 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex4/access_control.rs create mode 100644 crates/mega-evm/tests/system/access_control.rs diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 14263fb33..1477e7038 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -80,7 +80,8 @@ struct DetainedFrame { /// 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. +/// 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. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index b6cf6f9d0..1a0617019 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -245,8 +245,8 @@ impl MegaContext { /// `MegaAccessControl.disableVolatileDataAccess()` before its first instruction. The switch /// turns back on when that frame returns. /// - /// It is test tooling, behind the `test-utils` feature: the contract's interceptor steers the - /// switch once the control contracts' semantics land. + /// 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 fn with_volatile_access_disabled_from(mut self, depth: usize) -> Self { self.detention.set_disabled_from_at_start(Some(depth)); diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 8eb2f8acc..048e6c1f9 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -41,40 +41,84 @@ 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. +/// and the deployed bytecode runs. `depth` is the depth of the frame the call would start. /// -/// # What the three methods do today +/// # The switch /// -/// The switch is gas detention's: [`Detention`](crate::Detention) holds it, the Host consults it -/// before every volatile load, and a refused read reverts its frame with -/// `VolatileDataAccessDisabled`. The interceptor does not steer it yet — that is the control -/// contracts' semantics, which land on their own. 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 switch holds -/// when no call steered it. `DisabledByParent()`, the answer to a frame that re-enables what a -/// frame above it disabled, is what [`Detention::enable_access`](crate::Detention::enable_access) -/// refuses. +/// 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: /// -/// All three take no value: they read or steer execution, and the contract holds no balance. +/// - `disableVolatileDataAccess()` switches volatile-data access off for the caller and every frame +/// below it. 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. +/// +/// 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. +/// +/// 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(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..35bd2bdef 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -123,7 +123,7 @@ pub(crate) fn intercept( 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::AccessControl => crate::system::control::intercept(ctx, inputs, depth), InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), } } diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 8864f17b3..d9732cd8b 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -31,11 +31,11 @@ Do not add a `_pending/main.rs`. | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | -| the oracle and control contracts | 73 | 73 | 0 | 63 | 10 | 0 | +| the oracle and control contracts | 27 | 27 | 0 | 17 | 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** | **242** | **222** | **20** | **155** | **80** | **7** | +| **Total** | **196** | **176** | **20** | **109** | **80** | **7** | ## Tests ported in place @@ -300,12 +300,13 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the oracle and control contracts -These 4 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. +These 50 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | -| **Total** | | **4** | | +| `rex4/access_control.rs` | the oracle and control contracts (46) | 46 | `tests/system/access_control.rs` | +| **Total** | | **50** | | ## Tests retired after the inventory @@ -368,7 +369,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex2/keyless_deploy.rs` | 36 | 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) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | | `rex3/oracle_gas_limit.rs` | 1 | rewrite 1 (revert-class aborts · D48) | -| `rex4/access_control.rs` | 46 | keep 46 (the oracle and control contracts) | | `rex4/beneficiary_detention.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | | `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | 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 d683d9635..000000000 --- a/crates/mega-evm/tests/_pending/rex4/access_control.rs +++ /dev/null @@ -1,1889 +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 -// ============================================================================ - -// ============================================================================ -// 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 -// ============================================================================ - -// ============================================================================ -// 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/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index 5f824b2b2..47862c1b4 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -1,6 +1,5 @@ //! Tests for `Rex4` hardfork features. -mod access_control; mod beneficiary_detention; mod create_safety; mod eip7702_delegation_cycle; 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..90739d364 --- /dev/null +++ b/crates/mega-evm/tests/system/access_control.rs @@ -0,0 +1,786 @@ +//! `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_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + system::{ + IMegaAccessControl, VolatileDataAccessType, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + NON_ZERO_TRANSFER_REVERT_DATA, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + volatile_data_access_disabled_revert_data, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, TestExternalEnvs, VolatileDataAccess, +}; +use revm::{ + bytecode::opcode::*, + context::{ContextTr, TxEnv}, + interpreter::{CallInputs, CallOutcome, InterpreterTypes}, + Inspector, +}; + +use crate::common::{block, system_db, CALLER, 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; +const NOT_INTERCEPTED: [u8; 4] = IMegaAccessControl::NotIntercepted::SELECTOR; + +/* ---------- running a transaction ---------- */ + +/// What a transaction did, and what gas detention made of its reads. +struct Run { + outcome: MegaTransactionOutcome, + accessed: VolatileDataAccess, + limit: Option, +} + +impl Run { + /// The output of the transaction, which must have succeeded. + 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. + fn word(&self) -> U256 { + U256::from_be_slice(&self.output()) + } + + /// The call status the log at `index` carries ([`log_status`]). + 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 + } +} + +/// A transaction from [`CALLER`] to `to` with `data` and `value`, carrying `gas_limit`. +fn tx(to: Address, data: &[u8], value: U256, gas_limit: u64) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::copy_from_slice(data), + value, + gas_limit, + ..Default::default() + })) +} + +/// 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, tx(PARENT, &[], U256::ZERO, GAS_LIMIT)) +} + +/* ---------- code ---------- */ + +/// Appends a `CALL` of `selector` on the access control contract, discarding its status. +fn steer(code: BytecodeBuilder, selector: [u8; 4]) -> BytecodeBuilder { + 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]) +} + +fn disable(code: BytecodeBuilder) -> BytecodeBuilder { + steer(code, DISABLE) +} + +fn enable(code: BytecodeBuilder) -> BytecodeBuilder { + steer(code, ENABLE) +} + +/// Appends a query of `isVolatileDataAccessDisabled()` and returns its answer. +fn query_and_return(code: BytecodeBuilder) -> BytecodeBuilder { + code.mstore(0x0, IS_DISABLED) + .push_number(32_u8) // retSize + .push_number(0x20_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]) + .push_number(32_u8) + .push_number(0x20_u8) + .append(RETURN) +} + +/// 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); +} + +/* ---------- 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. +#[test] +fn test_create_reverts_when_volatile_access_disabled() { + let init_code = + BytecodeBuilder::default().append_many([TIMESTAMP, POP, PUSH0, PUSH0, RETURN]).build(); + let parent = disable(BytecodeBuilder::default()) + .mstore(0x40, &init_code) + .push_number(init_code.len() as u64) + .push_number(0x40_u8) + .push_number(0_u8) + .append(CREATE); + let run = run(&[(PARENT, return_word(parent))]); + assert_eq!(run.word(), U256::ZERO, "the creation failed"); +} + +/// 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"); +} + +/* ---------- 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 query answers `false` where nothing switched access off, `true` in the frame that did, and +/// `true` in a child of it. +#[test] +fn test_query_returns_false_when_not_disabled() { + let run = run(&[(PARENT, query_and_return(BytecodeBuilder::default()).build())]); + assert_eq!(run.word(), U256::ZERO); +} + +/// See [`test_query_returns_false_when_not_disabled`]. +#[test] +fn test_query_returns_true_for_disabling_frame() { + let run = run(&[(PARENT, query_and_return(disable(BytecodeBuilder::default())).build())]); + assert_eq!(run.word(), U256::ONE); +} + +/// See [`test_query_returns_false_when_not_disabled`]. +#[test] +fn test_query_returns_true_when_parent_disabled() { + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = + run(&[(PARENT, parent), (CHILD, query_and_return(BytecodeBuilder::default()).build())]); + assert_eq!(run.word(), U256::ONE); +} + +/// 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. a transaction calling the contract directly ---------- */ + +/// A transaction that calls the contract directly is answered: the switches succeed, the query +/// answers `false`, a value-bearing call is refused with `NonZeroTransfer()`, and a selector the +/// contract does not intercept reverts in its bytecode with `NotIntercepted()`. +#[test] +fn test_direct_tx_disable_volatile_data_access() { + for selector in [DISABLE, ENABLE] { + let run = + execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &selector, U256::ZERO, GAS_LIMIT)); + assert!(run.output().is_empty()); + } +} + +/// See [`test_direct_tx_disable_volatile_data_access`]. +#[test] +fn test_direct_tx_disable_volatile_data_access_with_value_reverts() { + let run = execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &DISABLE, U256::ONE, GAS_LIMIT)); + assert!(!run.outcome.result.is_success()); + assert_eq!( + run.outcome.result.output().cloned().unwrap_or_default(), + Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA) + ); +} + +/// See [`test_direct_tx_disable_volatile_data_access`]. +#[test] +fn test_direct_tx_is_volatile_data_access_disabled() { + let run = execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &IS_DISABLED, U256::ZERO, GAS_LIMIT)); + assert_eq!(run.word(), U256::ZERO); +} + +/// See [`test_direct_tx_disable_volatile_data_access`]. +#[test] +fn test_direct_tx_unknown_selector_falls_through_and_reverts_not_intercepted() { + let run = execute( + system_db(), + tx(ACCESS_CONTROL_ADDRESS, &[0xde, 0xad, 0xbe, 0xef], U256::ZERO, GAS_LIMIT), + ); + assert!(!run.outcome.result.is_success()); + assert_eq!( + run.outcome.result.output().cloned().unwrap_or_default(), + Bytes::from_static(&NOT_INTERCEPTED) + ); +} + +/* ---------- 10. 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"); + } +} + +/* ---------- 11. an inspector sees the answered call ---------- */ + +/// Records the targets of every call an inspector is shown, as it starts and as it ends. +#[derive(Default)] +struct Calls { + starts: Vec
, + ends: Vec
, +} + +impl Inspector for Calls { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + self.starts.push(inputs.target_address); + None + } + + fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.ends.push(inputs.target_address); + } +} + +/// An inspector sees the call the interceptor answered start and end like any other. +#[test] +fn test_inspector_sees_system_contract_call() { + let child = BytecodeBuilder::default().append_many([PUSH0, POP, STOP]).build(); + let db = system_db() + .account_code(PARENT, disables_then_calls_child(CALL)) + .account_code(CHILD, child); + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(Calls::default()); + let outcome = evm.execute_transaction(tx(PARENT, &[], U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(outcome.result.is_success()); + assert_eq!(evm.inspector().starts, vec![PARENT, ACCESS_CONTROL_ADDRESS, CHILD]); + assert_eq!(evm.inspector().ends, vec![ACCESS_CONTROL_ADDRESS, CHILD, PARENT]); +} + +/* ---------- 12. 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, tx(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/control.rs b/crates/mega-evm/tests/system/control.rs index afddd5ce8..7ad958cfa 100644 --- a/crates/mega-evm/tests/system/control.rs +++ b/crates/mega-evm/tests/system/control.rs @@ -29,7 +29,7 @@ fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { } /// 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/main.rs b/crates/mega-evm/tests/system/main.rs index c1300aa0f..c3a98a1ed 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -1,6 +1,7 @@ //! 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 deploy; From 318a5609508aa718d5b9784a5d8aba42e1d81000 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:31:09 -0700 Subject: [PATCH 179/458] feat(system): withhold the hint of a frame whose volatile access is off --- crates/mega-evm/src/system/intercept.rs | 2 +- crates/mega-evm/src/system/oracle.rs | 20 +- crates/mega-evm/tests/_pending/README.md | 10 +- crates/mega-evm/tests/_pending/rex6/main.rs | 1 - .../rex6/oracle_hint_volatile_access.rs | 224 ------------------ crates/mega-evm/tests/system/oracle.rs | 116 +++++++++ 6 files changed, 138 insertions(+), 235 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 35bd2bdef..0c4076ebd 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -121,7 +121,7 @@ pub(crate) fn intercept( depth: usize, ) -> Option { match intercepted_contract(&inputs.target_address)? { - InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs), + InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs, depth), InterceptedContract::KeylessDeploy => crate::system::keyless::intercept(ctx, inputs, depth), InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs, depth), InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index c7fd6f4e6..bc5e76384 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -30,14 +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. /// -/// 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 @@ -51,14 +57,20 @@ pub use mega_system_contracts::oracle::IOracle; /// ([`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. +/// +/// `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; } diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index d9732cd8b..ec3d96a95 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -31,11 +31,11 @@ Do not add a `_pending/main.rs`. | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | -| the oracle and control contracts | 27 | 27 | 0 | 17 | 10 | 0 | +| the oracle and control contracts | 23 | 23 | 0 | 13 | 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** | **196** | **176** | **20** | **109** | **80** | **7** | +| **Total** | **192** | **172** | **20** | **105** | **80** | **7** | ## Tests ported in place @@ -300,13 +300,14 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the oracle and control contracts -These 50 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. +These 54 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | | `rex4/access_control.rs` | the oracle and control contracts (46) | 46 | `tests/system/access_control.rs` | -| **Total** | | **50** | | +| `rex6/oracle_hint_volatile_access.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle.rs` | +| **Total** | | **54** | | ## Tests retired after the inventory @@ -390,7 +391,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `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/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | | `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/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs index 4dac99935..d1cfb90c1 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -7,6 +7,5 @@ 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/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index ed47149fd..85d2d7d86 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -348,3 +348,119 @@ fn test_a_hint_at_the_data_size_limit_is_forwarded() { 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() +} + +/// Appends a `CALL` of `MegaAccessControl` with `selector`, discarding its status. +fn steer(code: BytecodeBuilder, selector: [u8; 4]) -> BytecodeBuilder { + use mega_evm::system::ACCESS_CONTROL_ADDRESS; + use revm::bytecode::opcode::POP; + code.mstore(0x0, selector) + .push_number(0_u8) + .push_number(0_u8) + .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]) +} + +const DISABLE: [u8; 4] = + mega_evm::system::IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; +const ENABLE: [u8; 4] = + mega_evm::system::IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; + +/// 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()); +} From 473371c693f4bb71c230d4b55cfe3fb73d0bfd0b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:31:23 -0700 Subject: [PATCH 180/458] test(system): port the legacy hint rows --- crates/mega-evm/tests/_pending/README.md | 13 +- crates/mega-evm/tests/_pending/rex2/main.rs | 1 - .../tests/_pending/rex2/oracle_hint.rs | 347 ------------------ .../_pending/rex5/oracle_hint_metering.rs | 318 ---------------- crates/mega-evm/tests/system/oracle.rs | 168 +++++++++ 5 files changed, 175 insertions(+), 672 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex2/oracle_hint.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index ec3d96a95..e9468acfd 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -31,11 +31,11 @@ Do not add a `_pending/main.rs`. | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | -| the oracle and control contracts | 23 | 23 | 0 | 13 | 10 | 0 | +| the oracle and control contracts | 9 | 9 | 0 | 0 | 9 | 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** | **192** | **172** | **20** | **105** | **80** | **7** | +| **Total** | **178** | **158** | **20** | **92** | **79** | **7** | ## Tests ported in place @@ -300,14 +300,16 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the oracle and control contracts -These 54 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. +These 68 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | +| `rex2/oracle_hint.rs` | the oracle and control contracts (6) | 6 | `tests/system/oracle.rs` | | `rex4/access_control.rs` | the oracle and control contracts (46) | 46 | `tests/system/access_control.rs` | +| `rex5/oracle_hint_metering.rs` | the oracle and control contracts (8) | 8 | `tests/system/oracle.rs` | | `rex6/oracle_hint_volatile_access.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle.rs` | -| **Total** | | **54** | | +| **Total** | | **68** | | ## Tests retired after the inventory @@ -368,7 +370,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/oracle.rs` | 3 | rewrite 3 (revert-class aborts · D48) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | | `rex2/keyless_deploy.rs` | 36 | 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) | -| `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | | `rex3/oracle_gas_limit.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/beneficiary_detention.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | @@ -385,7 +386,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `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/oracle_hint_metering.rs` | 1 | 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) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | diff --git a/crates/mega-evm/tests/_pending/rex2/main.rs b/crates/mega-evm/tests/_pending/rex2/main.rs index af70245a9..4cac738f1 100644 --- a/crates/mega-evm/tests/_pending/rex2/main.rs +++ b/crates/mega-evm/tests/_pending/rex2/main.rs @@ -1,4 +1,3 @@ //! 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/rex5/oracle_hint_metering.rs b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs index e64e732cd..4ff47b648 100644 --- a/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs +++ b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs @@ -153,51 +153,6 @@ fn run_direct_oracle_tx( 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). @@ -220,48 +175,6 @@ fn test_rex5_data_size_overflow_blocks_forwarding_and_halts_canonically() { ); } -/// 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 { @@ -294,234 +207,3 @@ fn build_oracle_call_with_raw_calldata(calldata: Vec, forward_gas: u64) -> B .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/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 85d2d7d86..43dd43aab 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -395,6 +395,174 @@ const DISABLE: [u8; 4] = 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 transaction that sends value with its `sendHint` forwards nothing: the method is not payable, +/// so the transaction reverts in the bytecode, and its hint would be one it never sent. +#[test] +fn test_a_value_bearing_hint_transaction_forwards_nothing() { + let (result, hints, usage) = run_with_oracle( + system_db(), + call_tx(ORACLE_CONTRACT_ADDRESS, send_hint(b"paid"), U256::ONE), + ); + assert!(!result.result.is_success(), "{:?}", result.result); + assert!(hints.is_empty()); + assert_eq!( + usage.data_size, + mega_evm::TX_BODY_SIZE + send_hint(b"paid").len() as u64, + "the calldata alone: no hint was counted", + ); +} + +/// A hint sent with gas is forwarded, its payload whole, and the calldata of the call is counted +/// on the transaction. +#[test] +fn test_a_hint_with_gas_forwards_and_is_counted() { + let data = send_hint(&[0_u8; 128]); + let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 100_000)); + let (_, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].data.len(), 128); + assert_eq!(usage.data_size, nested_hint(data.len() as u64)); +} + +/// A call of the Oracle with a selector that is not `sendHint` is not a hint, whatever it +/// carries: nothing is forwarded or counted. +#[test] +fn test_an_unknown_selector_to_the_oracle_counts_no_hint() { + let data: Vec = [0xde, 0xad, 0xbe, 0xef].into_iter().chain([0_u8; 256]).collect(); + let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); + let (_, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert!(hints.is_empty()); + assert_eq!(usage.data_size, nested_hint(0)); +} + +/// 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. +#[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_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: nested_hint(total), + frame_local: false, + }), + ); + } +} + +/// Hints add up on the transaction: under a limit that holds one and a half, the first is +/// forwarded and the second stops the transaction. +#[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!(matches!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }) + )); +} + /// A frame that switched its volatile-data access off sends no hint: `sendHint` still runs and /// succeeds, and nothing reaches the service. #[test] From 1fec4f7395f5c976558808663d2b02eb793c3b5e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:35:39 -0700 Subject: [PATCH 181/458] feat(system): answer remainingComputeGas with the compute the caller could spend --- crates/mega-evm/src/evm/execution.rs | 10 +- crates/mega-evm/src/system/intercept.rs | 11 +- crates/mega-evm/src/system/limit_control.rs | 53 +- crates/mega-evm/tests/_pending/README.md | 9 +- .../tests/_pending/rex4/limit_control.rs | 579 ------------------ crates/mega-evm/tests/_pending/rex4/main.rs | 1 - crates/mega-evm/tests/satin/detention.rs | 27 +- .../tests/satin/synthetic_frame_gas.rs | 5 +- crates/mega-evm/tests/system/limit_control.rs | 5 +- crates/mega-evm/tests/system/main.rs | 1 + .../tests/system/remaining_compute_gas.rs | 358 +++++++++++ 11 files changed, 448 insertions(+), 611 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex4/limit_control.rs create mode 100644 crates/mega-evm/tests/system/remaining_compute_gas.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 6aa5ab9a6..19a390ee8 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -960,8 +960,16 @@ impl MegaEvm { return None; } let forwarded = inputs.gas_limit; + // 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, + }; let ctx = &mut self.inner.ctx; - if let Some(answer) = crate::system::intercept(ctx, inputs, frame_init.depth) { + if let Some(answer) = + crate::system::intercept(ctx, inputs, frame_init.depth, caller_remaining) + { return Some(answer); } let charge = forwarded - inputs.gas_limit; diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 0c4076ebd..f5bbf993c 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -82,7 +82,7 @@ pub(crate) enum InterceptedContract { KeylessDeploy, /// `MegaAccessControl`: the volatile-data access switch. AccessControl, - /// `MegaLimitControl`: what the running call has left. + /// `MegaLimitControl`: what the calling frame has left. LimitControl, } @@ -109,7 +109,9 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option( ctx: &mut MegaContext, inputs: &mut CallInputs, depth: usize, + caller_remaining: u64, ) -> Option { match intercepted_contract(&inputs.target_address)? { InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs, depth), InterceptedContract::KeylessDeploy => crate::system::keyless::intercept(ctx, inputs, depth), InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs, depth), - InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), + InterceptedContract::LimitControl => { + crate::system::limit_control::intercept(ctx, inputs, depth, caller_remaining) + } } } diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 608185a75..a3a53bb72 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,44 @@ 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 part before the forward. For a transaction that calls the contract +/// directly, the caller's own gas is the regular gas its frame was given. +/// +/// The figure is taken before the forward, as the legacy engine's was: its compute gas never +/// counted the gas a call forwarded, so its answer did not fall by the forward either. Taken after +/// it, a caller that forwards what `GAS` reports would hear back one sixty-fourth of its gas. +/// +/// 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: gas the +/// caller spends on state or history out of its regular gas, and the stipend a value call hands +/// its callee, are not in it. /// /// 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 +80,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/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e9468acfd..764a31ffc 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -31,11 +31,10 @@ Do not add a `_pending/main.rs`. | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | -| the oracle and control contracts | 9 | 9 | 0 | 0 | 9 | 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** | **178** | **158** | **20** | **92** | **79** | **7** | +| **Total** | **169** | **149** | **20** | **92** | **70** | **7** | ## Tests ported in place @@ -300,16 +299,17 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the oracle and control contracts -These 68 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. +These 77 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | | `rex2/oracle_hint.rs` | the oracle and control contracts (6) | 6 | `tests/system/oracle.rs` | | `rex4/access_control.rs` | the oracle and control contracts (46) | 46 | `tests/system/access_control.rs` | +| `rex4/limit_control.rs` | the oracle and control contracts (9) | 9 | `tests/system/remaining_compute_gas.rs` | | `rex5/oracle_hint_metering.rs` | the oracle and control contracts (8) | 8 | `tests/system/oracle.rs` | | `rex6/oracle_hint_volatile_access.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle.rs` | -| **Total** | | **68** | | +| **Total** | | **77** | | ## Tests retired after the inventory @@ -377,7 +377,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/gas_detention.rs` | 2 | rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 1 | 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)) | | `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) | 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 index 47862c1b4..d9c432fd5 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -7,5 +7,4 @@ 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/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 2616f7636..b6e790cd0 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1218,8 +1218,14 @@ 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 — so what the caller hears from -/// `remainingComputeGas()`, the gas it forwarded, is what it hears after a push of the same price. +/// 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: 2,631. #[test] fn test_an_interceptors_answer_does_not_lift_the_cap() { let calldata = IMegaLimitControl::remainingComputeGasCall {}.abi_encode(); @@ -1246,7 +1252,8 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { ); assert_stopped(&run, intrinsic); - // The answer, read without the loop, after the read and after a push in its place. + // 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) @@ -1258,7 +1265,10 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { .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(); @@ -1267,11 +1277,14 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); - U256::from_be_slice(run.outcome.result.output().unwrap()) + let output = run.outcome.result.output().unwrap().clone(); + (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])) }; - let detained = answer(TIMESTAMP); - assert!(detained > U256::from(CAP), "the whole forward: {detained}"); - assert_eq!(detained, answer(PUSH0), "the forward the call makes without the read"); + 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 - 2_631), "what the cap leaves"); } } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 4e3a9c0f8..ebe1a42b8 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -276,8 +276,9 @@ 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 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. diff --git a/crates/mega-evm/tests/system/limit_control.rs b/crates/mega-evm/tests/system/limit_control.rs index a252b7002..9b8176197 100644 --- a/crates/mega-evm/tests/system/limit_control.rs +++ b/crates/mega-evm/tests/system/limit_control.rs @@ -29,8 +29,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); diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index c3a98a1ed..12c331d16 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -10,4 +10,5 @@ mod keyless; mod limit_control; mod oracle; mod oracle_storage; +mod remaining_compute_gas; mod system_tx; 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..49861b918 --- /dev/null +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -0,0 +1,358 @@ +//! 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_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::*, + context::{BlockEnv, TxEnv}, +}; + +use crate::common::{system_db, CALLER}; + +const CONTRACT: Address = address!("0x0000000000000000000000000000000000300001"); +const CONTRACT2: Address = address!("0x0000000000000000000000000000000000300002"); + +/// 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 { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::copy_from_slice(data), + gas_limit, + ..Default::default() + })) +} + +/// 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 { + assert_eq!(answer, gas_limit - outcome.result.tx_gas_used(), "below the cap"); + } else { + assert_eq!(answer, TX_GAS_LIMIT_CAP - outcome.gas.regular, "above the cap"); + assert!(outcome.gas.history > 0, "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.tx_gas_used()); +} + +/// 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.tx_gas_used()); +} + +/// 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"); +} From 6cd9e5e5d75c294c89e27baa69999251e0ed89b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:39:05 -0700 Subject: [PATCH 182/458] feat(access): name SLOTNUM's access type and decode a refusal as uint8 --- crates/mega-evm/src/access/detention.rs | 86 +++++++++++++++++++ crates/mega-evm/src/access/mod.rs | 11 ++- crates/mega-evm/src/access/volatile.rs | 37 +++++++- crates/mega-evm/src/system/control.rs | 14 +++ crates/mega-evm/tests/satin/detention.rs | 5 ++ .../mega-evm/tests/system/access_control.rs | 15 ++++ 6 files changed, 161 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 1477e7038..90eb4f070 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -561,6 +561,27 @@ pub fn volatile_data_access_disabled_revert_data(access: VolatileDataAccess) -> 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] @@ -890,6 +911,71 @@ mod tests { 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] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 3191e7052..4a1170862 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -135,11 +135,16 @@ //! 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, which the contract's -//! `VolatileDataAccessType` does not declare. +//! 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 use detention::{volatile_data_access_disabled_revert_data, Detention}; +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 index eb50e387d..df8d0b9b9 100644 --- a/crates/mega-evm/src/access/volatile.rs +++ b/crates/mega-evm/src/access/volatile.rs @@ -2,14 +2,15 @@ use core::ops::{BitOr, BitOrAssign}; -use crate::system::VolatileDataAccessType; +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. +/// storage. Bit 12 is the block's slot number, which the contract's enum does not declare +/// ([`SLOT_NUM_ACCESS_TYPE`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct VolatileDataAccess(u16); @@ -40,8 +41,8 @@ impl VolatileDataAccess { 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`). - pub const SLOT_NUM: Self = Self(1 << 12); + /// 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; @@ -107,6 +108,15 @@ impl VolatileDataAccess { Self(self.0 & Self::BLOCK_ENV_MASK) } + /// 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. /// @@ -208,6 +218,25 @@ mod tests { } // 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 diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 048e6c1f9..67d80edeb 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -40,6 +40,20 @@ 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. `depth` is the depth of the frame the call would start. /// diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index b6e790cd0..65a40ecd4 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1176,6 +1176,11 @@ fn test_the_refusal_names_the_access_type() { let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); assert_eq!(&slot_num[..4], IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR.as_slice()); assert_eq!(U256::from_be_slice(&slot_num[4..]), U256::from(12)); + assert_eq!(mega_evm::system::SLOT_NUM_ACCESS_TYPE, 12); + assert_eq!( + mega_evm::decode_volatile_data_access_disabled(&slot_num), + Some(VolatileDataAccess::SLOT_NUM) + ); } /// The switch holds for the frame it is off from and every frame below, and a frame above it diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs index 90739d364..232e7b291 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -261,6 +261,21 @@ fn test_revert_data_contains_error_with_access_type() { 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 From 62d4e076e5828e1c80798787d497a0672b50d476 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:40:30 -0700 Subject: [PATCH 183/458] test(block): take a block's external environments from the factory --- crates/mega-evm/tests/block/external_envs.rs | 117 +++++++++++++++++++ crates/mega-evm/tests/block/main.rs | 1 + 2 files changed, 118 insertions(+) create mode 100644 crates/mega-evm/tests/block/external_envs.rs 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..6860a1cc6 --- /dev/null +++ b/crates/mega-evm/tests/block/external_envs.rs @@ -0,0 +1,117 @@ +//! 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}, + test_utils::BytecodeBuilder, + 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]); + +/// 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)) +} + +/// Code that writes 1 into the slot named by the first byte of its calldata. +fn writer() -> alloy_primitives::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() +} + +/// 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: envs.clone(), asked: asked.clone() }), + ); + + let mut db = common::database(); + db.set_account_code(WRITER, 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(), 1_000_000)); + 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(), 1_000_000)); + 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/main.rs b/crates/mega-evm/tests/block/main.rs index 50d217fe5..c6ba5ef9a 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -7,6 +7,7 @@ mod deploy; mod deposits; mod detention; mod eips; +mod external_envs; mod factory; mod inspector; mod limits; From 1357f78bfe843e27d60c5fab3a1d5f293c2c9679 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:42:14 -0700 Subject: [PATCH 184/458] docs(system): the control contracts' semantics and the Oracle's storage read --- AGENTS.md | 39 ++++++++++++++++++---------- crates/mega-evm/README.md | 10 +++++-- crates/mega-evm/src/lib.rs | 6 +++++ crates/mega-evm/src/system/AGENTS.md | 11 +++++--- 4 files changed, 46 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b8b7c769c..569bc8ee2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,17 +100,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 (detention's hooks and its hold on answered frames included), 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, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | -| `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/` | 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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 (`detention.rs`) | the control contracts steering the switch | -| `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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | the oracle and control contracts (steering the detention switch, the 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 default detention caps) | 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | +| `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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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`); 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`); the deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`) | 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 default detention caps) | 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`, `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`) | — | ### How Satin executes today @@ -190,7 +190,14 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. 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 the control contracts' semantics fill them in — steering detention's switch and answering with the compute ledger — 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. + `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, 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. + `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 part before the forward; a transaction that calls the contract directly hears its own frame's regular gas. + The figure is taken before the forward, as the legacy engine's was, and 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 `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) asks `OracleEnv::get_oracle_storage` first and reads the database through the journal when it answers `None`; `EmptyExternalEnv` always answers `None`. + Every such read is priced as a cold access, whichever source answered and however often the slot was read, because a replaying node cannot tell which source the building node read; a frame that cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either. + 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. - 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 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). @@ -241,9 +248,13 @@ Detention caps how much a transaction may still compute once it read such data ( 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` can switch volatile-data access off for a frame and every frame below it (the state is `Detention`'s; the interceptor steers it once the control contracts' semantics land, and `MegaContext::with_volatile_access_disabled_from` is the test helper). + `MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, 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, which the contract's enum does not declare. + `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 diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index f931a1bb9..aca000a5b 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -69,8 +69,13 @@ The six system contracts live at their fixed `0x6342…` addresses and are deplo 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, 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 the control contracts' semantics fill them in: steering gas detention's switch, and answering with the compute ledger. -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. +`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. +The Oracle forwards a `sendHint` payload to the node's oracle service, unless the calling frame's volatile-data access is off, 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 Oracle's storage is read through the node's oracle service: an `SLOAD` in the Oracle's own frame asks `OracleEnv` first and reads the chain's state for a slot the service has no value for. +Every such read is priced as a cold access, whichever source answered, so a replaying node that cannot tell which one the building node read prices it the same. 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. @@ -115,6 +120,7 @@ So is one priced between what the limit leaves its frame and its forward whose i An interceptor's own charge on a frame is compute whether it answers the call or lets the frame run. 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. diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index f00364f84..903994b16 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -3,6 +3,12 @@ //! 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. +//! +//! 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)] diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index a9dbd1896..6c8eea471 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -4,11 +4,11 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory. ## 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. +- `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, and the [`SequencerRegistryConfig`] that seeds it. No interceptor. - `deploy.rs`: the declarative spec, `transact_deploy`, the EIP-7997 factory, and the list of seven predeploys. - `intercept.rs`: the dispatch — the address test, the selector peek, the value policy and the shape of an answer. @@ -22,7 +22,10 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 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 is not forwarded is not counted. +- 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. +- `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 part before the forward, the figure the legacy engine answered before the forward too. +- `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. - 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. From 625f9817abb6bce042946d352c21f8c9510e4df3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:45:13 -0700 Subject: [PATCH 185/458] bench(system): remainingComputeGas queries and the Oracle's storage reads --- crates/mega-evm/benches/transact.rs | 65 ++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 790d8d3c0..f50b47268 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -17,6 +17,11 @@ //! 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 asks +//! the oracle service, finds nothing, reads the database 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. @@ -40,6 +45,9 @@ //! written (`satin`); and under a state-gas limit one gas short, so the last slot crosses and the //! transaction is stopped (`stopped`). Its op-revm baseline is `data_size_limit/op_revm`. //! +//! `oracle_reads` runs once more through `MegaEvm` alone (`/service`), against an oracle service +//! that answers all 200 slots, so no load reaches the database. +//! //! 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 @@ -64,7 +72,8 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, system::{ - IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, + 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, @@ -99,6 +108,7 @@ 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 block beneficiary of the benchmark's block, `BlockEnv`'s default. const BENEFICIARY: Address = Address::ZERO; @@ -106,6 +116,8 @@ 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; @@ -297,8 +309,9 @@ 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 { let mut code = BytecodeBuilder::default().mstore(0x0, selector); for _ in 0..REPEAT { code = code @@ -306,7 +319,7 @@ fn system_caller_code(selector: [u8; 4]) -> Bytes { .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); @@ -357,8 +370,9 @@ 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(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(LIMITED, limited_code()) .account_balance(VALUE_CALLER, U256::from(REPEAT)) .account_code(VALUE_CALLER, value_caller_code()) @@ -366,7 +380,8 @@ fn bench_transact(c: &mut Criterion) { .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(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); let cfg = mega_context(db.clone()).cfg().clone(); let mut depth = [0u8; 32]; @@ -380,10 +395,12 @@ fn bench_transact(c: &mut Criterion) { ("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"); @@ -391,10 +408,13 @@ fn bench_transact(c: &mut Criterion) { 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); - // Only the volatile workload reads what detention caps, and it must read every kind it is - // here to measure. + // 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 == "volatile_reads" { + 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 | @@ -556,6 +576,31 @@ fn bench_transact(c: &mut Criterion) { }); } + // The Oracle's storage answered by the oracle service, every slot of it: no load reaches the + // database, and each is priced as the database's would be. + 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 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 = [ From 137ac409c00e18ed32610387fa294fb753c445e9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:54:41 -0700 Subject: [PATCH 186/458] style(test): drop a redundant clone in the factory test --- crates/mega-evm/tests/block/external_envs.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/block/external_envs.rs b/crates/mega-evm/tests/block/external_envs.rs index 6860a1cc6..2a2e9cfda 100644 --- a/crates/mega-evm/tests/block/external_envs.rs +++ b/crates/mega-evm/tests/block/external_envs.rs @@ -76,8 +76,7 @@ fn test_a_blocks_environments_come_from_the_factory() { let factory = MegaBlockExecutorFactory::new( OpAlloyReceiptBuilder::default(), common::chain_spec(), - MegaEvmFactory::new() - .with_external_env_factory(Factory { envs: envs.clone(), asked: asked.clone() }), + MegaEvmFactory::new().with_external_env_factory(Factory { envs, asked: asked.clone() }), ); let mut db = common::database(); From c9ee99a0b6e4e5da80c37f7b7e1e440b24881b83 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 00:55:06 -0700 Subject: [PATCH 187/458] docs(system): what remainingComputeGas leaves out --- crates/mega-evm/src/system/limit_control.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index a3a53bb72..ab33c6405 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -61,9 +61,10 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// it, a caller that forwards what `GAS` reports would hear back one sixty-fourth of its gas. /// /// 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: gas the -/// caller spends on state or history out of its regular gas, and the stipend a value call hands -/// its callee, are not in it. +/// 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, so an +/// undetained one hears it counted. /// /// The method reads and takes no value. pub(crate) fn intercept( From 5791f2331e7ac264170f4ff4812bfd78ca4c95bf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 01:47:50 -0700 Subject: [PATCH 188/458] test(block): give the factory test room at any byte price --- crates/mega-evm/tests/block/external_envs.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/block/external_envs.rs b/crates/mega-evm/tests/block/external_envs.rs index 2a2e9cfda..1df735b70 100644 --- a/crates/mega-evm/tests/block/external_envs.rs +++ b/crates/mega-evm/tests/block/external_envs.rs @@ -30,6 +30,10 @@ const WRITER: Address = address!("0x1000000000000000000000000000000000000abc"); 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 { @@ -91,7 +95,7 @@ fn test_a_blocks_environments_come_from_the_factory() { 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(), 1_000_000)); + 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}"); @@ -104,7 +108,7 @@ fn test_a_blocks_environments_come_from_the_factory() { ); let read = IOracle::getSlotCall { slot: ORACLE_SLOT }.abi_encode(); - let tx = common::recovered(common::tx(3, ORACLE_CONTRACT_ADDRESS, read.into(), 1_000_000)); + 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(), From 9c838c763a47c7af5befddd6363740e3fa9758e0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:25:42 -0700 Subject: [PATCH 189/458] fix(external): load an Oracle slot through the journal whichever source answers A read the oracle service answered left the slot unloaded, while the database fallback loaded it warm: a later SSTORE to the slot cost the cold access only when the service answered, and the slot never reached the transaction's state a stateless witness is built from. The read now loads the slot through the journal on both paths and returns the service's value when it has one, still priced cold. --- crates/mega-evm/benches/transact.rs | 14 +- crates/mega-evm/src/evm/host.rs | 45 +++--- .../mega-evm/tests/system/oracle_storage.rs | 146 ++++++++++++++++-- 3 files changed, 169 insertions(+), 36 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index f50b47268..ecf54a9f7 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -19,9 +19,10 @@ //! 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 asks -//! the oracle service, finds nothing, reads the database and is priced cold, and gas detention -//! marks and commits it. op-revm reads the same 200 slots from the database. +//! - `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. @@ -46,7 +47,8 @@ //! transaction is stopped (`stopped`). Its op-revm baseline is `data_size_limit/op_revm`. //! //! `oracle_reads` runs once more through `MegaEvm` alone (`/service`), against an oracle service -//! that answers all 200 slots, so no load reaches the database. +//! 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 @@ -576,8 +578,8 @@ fn bench_transact(c: &mut Criterion) { }); } - // The Oracle's storage answered by the oracle service, every slot of it: no load reaches the - // database, and each is priced as the database's would be. + // 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) }); diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 2dc614804..5108a4c3c 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -333,16 +333,23 @@ impl MegaContext { /// 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 oracle environment answers first ([`OracleEnv::get_oracle_storage`]); a slot it has no - /// value for is read from the database through the journal. 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. + /// 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. /// - /// The read is always cold, whichever source answered and however often the transaction read - /// the slot before. 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 the price may depend on - /// neither: every read costs the cold access. A frame that could not pay it reads nothing, as - /// revm's own skipped cold load does, and the environment is not asked. + /// 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 frame that could not pay the cold access reads nothing, as revm's own skipped cold load + /// does, and the environment is not asked. /// /// 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. @@ -354,18 +361,14 @@ impl MegaContext { if self.detention.refuses(VolatileDataAccess::ORACLE) || skip_cold_load { return Err(LoadError::ColdLoadSkipped); } - let value = match self.external_envs().oracle_env.get_oracle_storage(key) { - Some(value) => value, - None => { - revm::context_interface::Host::sload_skip_cold_load( - &mut self.inner, - ORACLE_CONTRACT_ADDRESS, - key, - false, - )? - .data - } - }; + let loaded = revm::context_interface::Host::sload_skip_cold_load( + &mut self.inner, + ORACLE_CONTRACT_ADDRESS, + key, + false, + )? + .data; + let value = self.external_envs().oracle_env.get_oracle_storage(key).unwrap_or(loaded); self.detention.observe(VolatileDataAccess::ORACLE); Ok(StateLoad::new(value, true)) } diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 488fcfd10..4437b2b7a 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -1,24 +1,31 @@ //! The Oracle's storage, read through the oracle environment: an `SLOAD` in the Oracle's own -//! frame asks the node's oracle service first and the database when the service has no value, -//! is always priced as a cold access, and is a read of volatile data for gas detention. +//! 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_primitives::{address, Address, Bytes, B256, U256}; +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, + constants::{ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, - test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, volatile_data_access_disabled_revert_data, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleEnv, VolatileDataAccess, }; -use revm::bytecode::opcode::{ - CALL, DELEGATECALL, DUP2, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, STOP, SUB, SWAP1, +use revm::{ + bytecode::opcode::{ + CALL, DELEGATECALL, DUP2, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, SSTORE, STOP, SUB, SWAP1, + }, + context::TxEnv, }; -use crate::common::{block, call_tx, calls_with, split_outcome, system_db, CALLER, CONTRACT}; +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"); @@ -182,7 +189,7 @@ fn test_oracle_storage_sload_fallback_to_database() { ); assert_eq!(returned_word(&run), STATE_VALUE); - assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "the service was asked first"); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "the service was asked"); assert_eq!(run.accessed, VolatileDataAccess::ORACLE); } @@ -448,3 +455,124 @@ fn test_the_deployed_oracle_reads_through_the_service() { B256::from(SERVICE_VALUE), ); } + +/* ---------- 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}"); + } +} From 2be4b00891280674465fe09cef11be722da0d761 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:26:10 -0700 Subject: [PATCH 190/458] docs(external): why an Oracle read loads its slot whichever source answers A node that replays a block without the oracle service must price and witness it as the node that built it did. State that rule where the Oracle's storage read is described, and that the service's value is returned even over a value the Oracle's frame stored earlier. --- AGENTS.md | 5 +++-- crates/mega-evm/README.md | 4 ++-- crates/mega-evm/src/external/AGENTS.md | 5 +++-- crates/mega-evm/src/external/oracle.rs | 12 ++++++++---- crates/mega-evm/src/system/oracle.rs | 6 ++++++ 5 files changed, 22 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 569bc8ee2..d5cbbfc58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -195,8 +195,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat That is the caller's spendable part before the forward; a transaction that calls the contract directly hears its own frame's regular gas. The figure is taken before the forward, as the legacy engine's was, and 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 `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) asks `OracleEnv::get_oracle_storage` first and reads the database through the journal when it answers `None`; `EmptyExternalEnv` always answers `None`. - Every such read is priced as a cold access, whichever source answered and however often the slot was read, because a replaying node cannot tell which source the building node read; a frame that cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either. +- 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 that cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either. 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. - 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 limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index aca000a5b..a980f5189 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -74,8 +74,8 @@ A method that takes no value answers a value-bearing call with `NonZeroTransfer( It is regular gas only, so a transaction above the execution cap hears at most the cap's share. The Oracle forwards a `sendHint` payload to the node's oracle service, unless the calling frame's volatile-data access is off, 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 Oracle's storage is read through the node's oracle service: an `SLOAD` in the Oracle's own frame asks `OracleEnv` first and reads the chain's state for a slot the service has no value for. -Every such read is priced as a cold access, whichever source answered, so a replaying node that cannot tell which one the building node read prices it the same. +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. 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. diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 56615b71c..00cdc0d94 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -16,7 +16,8 @@ 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. It answers no oracle slot, so the Oracle's storage is read from the database. -- A read of the Oracle's storage is priced cold whichever source answered it, so its price cannot depend on whether the oracle service had a value. +- 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. @@ -30,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 reads through them in `evm/host.rs` (`oracle_sload`): the service first, the database for a slot it has no value for, always priced cold. +- 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/oracle.rs b/crates/mega-evm/src/external/oracle.rs index 56c14e7ec..52c7af9fc 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -25,10 +25,14 @@ 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, and - /// reads the slot from the chain's state when the answer is `None`. A frame that cannot pay - /// the read's cold access, and a frame whose volatile-data access is switched off, read - /// nothing and do not ask. + /// 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 that cannot pay the read's cold access, and a frame whose volatile-data access is + /// switched off, read nothing and do not ask. 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/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index bc5e76384..e8b03e963 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -4,6 +4,12 @@ //! 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}; From e9faae94d6e37e4c71fc8b744fab2f3984421c00 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:26:23 -0700 Subject: [PATCH 191/458] docs(external): a detained frame that may not spend the cold access still asks The skipped cold load is decided on the frame's regular gas, the part gas detention withholds included, so a detained frame that holds the gas but may not spend it reads and asks the oracle service, and the read's charge then stops the transaction at the compute limit. Say so where the docs said such a frame asks nothing. --- AGENTS.md | 2 +- crates/mega-evm/src/evm/host.rs | 6 ++++-- crates/mega-evm/src/external/oracle.rs | 6 ++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d5cbbfc58..5182d9908 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -197,7 +197,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 that cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either. + 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 the transaction 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. - 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 limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 5108a4c3c..1c2ab7398 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -348,8 +348,10 @@ impl MegaContext { /// 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 frame that could not pay the cold access reads nothing, as revm's own skipped cold load - /// does, and the environment is not asked. + /// 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. diff --git a/crates/mega-evm/src/external/oracle.rs b/crates/mega-evm/src/external/oracle.rs index 52c7af9fc..feebdf38e 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -31,8 +31,10 @@ pub trait OracleEnv: Debug + Unpin { /// 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 that cannot pay the read's cold access, and a frame whose volatile-data access is - /// switched off, read nothing and do not ask. + /// 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 the transaction 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 From 4dd1c930f6f46208175fad4b106cbc9b13f80c11 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:26:38 -0700 Subject: [PATCH 192/458] test(external): pin Oracle reads after a write, in a nested frame and under detention A read after the Oracle's frame wrote the slot answers the service's value and is priced cold; every read of a nested Oracle frame is cold and asks; a detained frame that holds the cold access but may not spend it asks and is stopped at the compute limit. --- .../mega-evm/tests/system/oracle_storage.rs | 144 +++++++++++++++++- 1 file changed, 141 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 4437b2b7a..00ec6f37e 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -13,14 +13,17 @@ use mega_evm::{ system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, volatile_data_access_disabled_revert_data, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, - MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleEnv, - VolatileDataAccess, + LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, OracleEnv, VolatileDataAccess, }; use revm::{ bytecode::opcode::{ - CALL, DELEGATECALL, DUP2, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, SSTORE, STOP, SUB, SWAP1, + 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::{ @@ -456,6 +459,36 @@ fn test_the_deployed_oracle_reads_through_the_service() { ); } +/// 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. @@ -576,3 +609,108 @@ fn test_the_read_slot_is_in_the_transactions_state_whichever_source_answered() { 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]); + } +} From 53b15578891ef9ac3e33793f39a29fafdf7b1126 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:27:26 -0700 Subject: [PATCH 193/458] docs(system): a detained callee hears its stipend counted too Detention takes a value call's whole gas limit, stipend included, off its caller's compute, so the allowance carries the stipend as the callee's own gas does: the callee hears it counted whether or not it is detained. --- crates/mega-evm/src/system/limit_control.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index ab33c6405..57e80bf21 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -63,8 +63,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, so an -/// undetained one hears it counted. +/// 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( From e0f1ca093b7789af09438d41e1e92ef467a9ece5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:28:02 -0700 Subject: [PATCH 194/458] docs(system): what remainingComputeGas keeps of the legacy answer Only one property carries over from the legacy engine: forwarded gas is not counted. The legacy figure came from a separate compute ledger and could exceed the caller's gas; this one is the caller's spendable regular gas before the forward, which detention caps. A transaction whose sender is the block beneficiary is detained from its start, so a direct call hears the cap. --- AGENTS.md | 5 +++-- crates/mega-evm/README.md | 1 + crates/mega-evm/src/system/AGENTS.md | 4 ++-- crates/mega-evm/src/system/limit_control.rs | 16 +++++++++++----- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5182d9908..1a88fbb0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -192,8 +192,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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` steers detention's switch for the frame that calls it (see Gas detention), `MegaLimitControl.remainingComputeGas()` answers the compute the calling frame could still spend, 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. `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 part before the forward; a transaction that calls the contract directly hears its own frame's regular gas. - The figure is taken before the forward, as the legacy engine's was, and is regular gas only: the reservoir is not in it, so a transaction above the execution cap hears at most the cap's share. + 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index a980f5189..f66b7622a 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -72,6 +72,7 @@ A method that takes no value answers a value-bearing call with `NonZeroTransfer( `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, 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 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. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 6c8eea471..c6ab9848a 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -23,8 +23,8 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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, 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 is not forwarded is not counted. -- 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. -- `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 part before the forward, the figure the legacy engine answered before the forward too. +- 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. - 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. diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 57e80bf21..10276934a 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -53,12 +53,18 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// 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 part before the forward. For a transaction that calls the contract -/// directly, the caller's own gas is the regular gas its frame was given. +/// 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, as the legacy engine's was: its compute gas never -/// counted the gas a call forwarded, so its answer did not fall by the forward either. Taken after -/// it, a caller that forwards what `GAS` reports would hear back one sixty-fourth of its gas. +/// 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 From e018c740d1ca72a37225f75756ad1151ecfdfc27 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:29:28 -0700 Subject: [PATCH 195/458] test(system): pin the access switch clearing on a halt and between transactions A child that switched volatile-data access off and then halted, on an invalid opcode or out of gas, leaves its sibling free to read; a switch set in one transaction does not carry into the next on the same EVM. --- .../mega-evm/tests/system/access_control.rs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs index 232e7b291..a43fcce69 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -509,6 +509,63 @@ fn test_disable_in_reverted_child_does_not_affect_sibling() { 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(tx(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(tx(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. From 12b40c4b9ca2a8090dd86a26e021d5468f4dfe12 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:30:35 -0700 Subject: [PATCH 196/458] test(system): pin remainingComputeGas to the gas its caller resumes with The answer equals the spendable regular gas the caller resumes with, undetained, detained by its own read, by a child's read, as a value-called callee, as a beneficiary sender and after an Oracle read, below and above the execution cap; a caller that acts on it can spend it and is stopped at the compute limit past it. --- .../tests/system/remaining_compute_gas.rs | 242 +++++++++++++++++- 1 file changed, 240 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index 49861b918..26fc7cb88 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -12,19 +12,23 @@ use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use alloy_sol_types::SolCall; use mega_evm::{ constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, - system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS}, + system::{IMegaLimitControl, IOracle, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, }; use revm::{ bytecode::opcode::*, context::{BlockEnv, TxEnv}, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, + Inspector, }; use crate::common::{system_db, 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; @@ -356,3 +360,237 @@ fn test_a_childs_read_binds_its_callers_answer() { 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 ---------- */ + +/// Records every answer a query returns, next to the spendable regular gas its caller resumes +/// with: what a regular charge of the caller could draw at its next instruction. +#[derive(Debug, Default)] +struct AnswerAndResume { + pending: Option, + 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::()); + } + } +} + +/// 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 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 + ); + } + } +} From 93da3fbe980476ee9ae2257d34c4a53c783b1ac4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 08:30:49 -0700 Subject: [PATCH 197/458] test(system): pin the stipend a value-called callee hears The callee hears the stipend more than the same callee a call without value started, and the same answer whether or not the transaction is detained. --- .../tests/system/remaining_compute_gas.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index 26fc7cb88..2e6b11f0c 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -548,6 +548,34 @@ 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. +#[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. From 9ee48c69190778dbf8d3f580193e87c4841b29ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 13:03:03 -0700 Subject: [PATCH 198/458] refactor(block): exempt a deposit from the packing budgets in one place The execution-gas, data-size and KV budgets each carried their own deposit guard. They are checked together at the end of the pre-execution check, so one early return for a deposit covers all three. --- crates/mega-evm/src/block/limit.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index b70faf498..5418870ec 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -394,10 +394,15 @@ impl BlockLimiter { } } - // 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. A deposit is not the - // builder's to refuse on the execution ledger; it still counts, in `post_execution_update`. - if !is_deposit && self.gas.execution >= self.limits.block_execution_gas_limit { + // The packing budgets: 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 — never a deposit, which is not the builder's to refuse. Every committed + // transaction counts towards them, a deposit included, in `post_execution_update`. + if is_deposit { + return Ok(()); + } + + if self.gas.execution >= self.limits.block_execution_gas_limit { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::ExecutionGasLimit { @@ -407,10 +412,7 @@ impl BlockLimiter { )); } - // Every committed transaction counts, a deposit included, in `post_execution_update`. The - // transaction that crossed is already packed, so what is refused here is the next one — - // never a deposit, which is not the builder's to refuse. - if !is_deposit && self.usage.data_size >= self.limits.block_txs_data_limit { + if self.usage.data_size >= self.limits.block_txs_data_limit { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::TransactionDataLimit { @@ -420,8 +422,8 @@ impl BlockLimiter { )); } - // The same for the write records, the block's KV count. - if !is_deposit && self.usage.write_records >= self.limits.block_kv_update_limit { + // The block's KV count. + if self.usage.write_records >= self.limits.block_kv_update_limit { return Err(invalid_tx( tx_hash, MegaBlockLimitExceededError::KVUpdateLimit { From c0882c7867f41607bcf4b872ce6f7b7e9f9521c9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 24 Sep 2026 13:08:55 -0700 Subject: [PATCH 199/458] fix(access): detain a transaction whose recipient delegates to the beneficiary A contract's call to an EIP-7702 delegator of the block beneficiary loads the delegate through the Host, which marks the read. The transaction's own frame resolves its delegate through the journal instead, so a transaction sent straight to such a delegator ran the beneficiary's code undetained. Once revm has prepared the first frame, the recipient's delegation is read from the journal as it stands and marked the same way. --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 4 +-- crates/mega-evm/src/access/mod.rs | 2 +- crates/mega-evm/src/evm/context.rs | 22 ++++++++++++++ crates/mega-evm/src/evm/execution.rs | 1 + .../mega-evm/tests/satin/volatile_access.rs | 29 +++++++++++++++++++ 6 files changed, 56 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1a88fbb0d..18a5459bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -211,7 +211,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 and an applied EIP-7702 authority that is; the Oracle's storage, through `SLOAD` in the Oracle's own frame. + 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, and an applied EIP-7702 authority that is; 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 90eb4f070..0073501b4 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -264,8 +264,8 @@ impl Detention { } /// Records a read the transaction makes by being what it is, before any frame: a sender or a - /// recipient that is the block beneficiary, or an EIP-7702 authority that is. No compute has - /// been spent, so the limit is the read's cap. + /// 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; diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 4a1170862..50106c22e 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -12,7 +12,7 @@ //! | 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, and an applied EIP-7702 authority that is | [`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, and an applied EIP-7702 authority 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)): the spec's, diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 1a0617019..32052d8f4 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -369,6 +369,28 @@ impl MegaContext { } } + /// 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. /// diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 19a390ee8..529a9b8c4 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -247,6 +247,7 @@ where } let frame = self.op.first_frame_input(evm, gas)?; evm.ctx_mut().additional_limit.on_state_gas_before_frames(gas.state_gas_spent()); + evm.ctx_mut().mark_beneficiary_delegate(); Ok(frame) } diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 6ca34df6a..704f7369d 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -658,6 +658,35 @@ fn test_an_applied_authority_that_is_the_beneficiary_detains() { } } +/// 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 From 6a45c7c100394643895570ea8e74ebccce2ffb93 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 01:31:27 -0700 Subject: [PATCH 200/458] fix(access): count no spilled state gas in an answer's compute --- crates/mega-evm/src/access/detention.rs | 26 +++++++++++++---- crates/mega-evm/tests/satin/withheld_gas.rs | 32 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index a62c2dc84..6811e65e5 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -400,9 +400,11 @@ impl Detention { /// ([`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: it is answered out of gas and marked as a crossing of what the - /// frame would have had withheld. A crossing is settled by the same rule as a frame that ran - /// ([`stop`](Self::stop)). Returns the limit when it crossed. + /// 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 of what the frame would have had withheld. A crossing is + /// settled by the same rule as a frame that ran ([`stop`](Self::stop)). Returns the limit + /// when it crossed. pub(crate) fn on_answer( &mut self, result: &mut InterpreterResult, @@ -418,7 +420,12 @@ impl Detention { return None; } let allowance = self.allowance(depth, gas_limit)?; - if gas_limit.saturating_sub(result.gas.remaining()) <= allowance { + // 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 @@ -757,8 +764,9 @@ mod tests { } } - /// An answer that halts burns the gas limit; one that spent more than the frame's allowance is - /// answered out of gas and stops at the limit, with what the frame would have had withheld. + /// 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 what the frame would have had + /// withheld. 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(); @@ -777,6 +785,12 @@ mod tests { 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); diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 0bb805c87..57a803f3e 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1182,6 +1182,38 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { } } +/// 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 { From b0e99984279c20364d62452633e7c5c9e76114b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 01:34:15 -0700 Subject: [PATCH 201/458] fix(access): detain a keyless deployment whose signer is the beneficiary --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 29 +++++ crates/mega-evm/src/access/mod.rs | 7 +- .../mega-evm/src/system/keyless/dispatch.rs | 11 +- .../tests/system/keyless/detention.rs | 109 ++++++++++++++++++ crates/mega-evm/tests/system/keyless/mod.rs | 1 + 6 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 crates/mega-evm/tests/system/keyless/detention.rs diff --git a/AGENTS.md b/AGENTS.md index 2a07ffd81..ca65f2de7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -224,7 +224,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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, and an applied EIP-7702 authority that is; the Oracle's storage, through `SLOAD` in the Oracle's own frame. + 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 6811e65e5..1a01af9b7 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -351,6 +351,17 @@ impl Detention { self.frames.push(DetainedFrame { at_suspension: regular_spent(gas), contribution: 0 }); } + /// 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) { + if self.detains { + 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. /// @@ -874,6 +885,24 @@ mod tests { assert_eq!(detention.allowance(2, 0), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS - 132_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); + assert!(call.record_regular_cost(100_000)); + 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); + 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] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index e2b8897b4..ab42ed483 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -12,7 +12,7 @@ //! | 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, and an applied EIP-7702 authority that is | [`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)): the spec's, @@ -119,7 +119,10 @@ //! regular gas — on gas held to the limit as a running 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 is kept as a frame suspended on it, and its charges are compute as a -//! caller's are; a call a rule refuses is an answer held by the rule above. +//! caller's are; a call a rule refuses is 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 //! diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 8fd73cd88..1835e60c1 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -36,6 +36,7 @@ use crate::{ }, }, untouched_call_gas, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, MegaContext, + VolatileDataAccess, }; /// What the keyless rewrite made of a frame about to start. @@ -110,7 +111,9 @@ pub(crate) struct KeylessCall { /// 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`). +/// 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 @@ -350,6 +353,12 @@ fn prepare( let checks_code = !ctx.cfg().is_eip3607_disabled(); let signer_info = ctx.journal_mut().inspect_account(signer, checks_code)?.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. + if signer == ctx.block().beneficiary { + ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas); + } if signer_info.nonce > 1 { refuse!(KeylessDeployError::SignerNonceTooHigh { signer_nonce: signer_info.nonce }); } 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..715a9f4a3 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -0,0 +1,109 @@ +//! 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 transaction with the deployment taken +//! back whole. + +use alloy_sol_types::SolError; +use mega_evm::{ + constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, + LimitCheck, LimitKind, MegaLimitExceeded, VolatileDataAccess, +}; +use revm::{context::BlockEnv, primitives::KECCAK_EMPTY}; + +use super::*; +use crate::common::{call_tx, context}; + +/// 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; + +/// What a transaction did, and what gas detention made of it. +struct Run { + outcome: MegaTransactionOutcome, + limit: Option, + accessed: VolatileDataAccess, +} + +/// 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 { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let ctx = + context(db).with_block(BlockEnv { beneficiary, ..block() }).with_tx_runtime_limits(limits); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(ctx); + 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() } +} + +/// Asserts `run` of `deployment` at `gas_limit` was stopped by gas detention, having computed +/// exactly its limit past its intrinsic gas, and kept nothing of the deployment. +fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: 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 }, + ); + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false, + }), + ); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!( + run.outcome.gas.regular, + reference.gas.regular + limit, + "the transaction computed up to its limit and not one unit past it, 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)); +} + +/// 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. +/// 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); + } +} diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index dc1898cb1..ada705d2a 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -8,6 +8,7 @@ mod charges; mod deploy; +mod detention; mod dispatch; mod inspector; mod limits; From 2a79677f18cd85fe6a252a0a516aef0cda919f9a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 01:41:08 -0700 Subject: [PATCH 202/458] test(system): pin a keyless deployment under detention, transfer logs and limits --- .../mega-evm/tests/system/keyless/deploy.rs | 123 ++++++ .../tests/system/keyless/detention.rs | 402 +++++++++++++++++- .../mega-evm/tests/system/keyless/limits.rs | 67 +++ 3 files changed, 578 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 71b1bce92..a82729a75 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -761,3 +761,126 @@ fn test_a_failed_keyless_transaction_leaves_nothing_for_the_next() { 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"); + } +} + +/// A `keylessDeploy` call carrying value is refused before anything moves: it logs nothing and +/// counts what a transaction carrying the same calldata to an account with no code counts, its +/// body alone. +#[test] +fn test_a_call_carrying_value_moves_and_logs_nothing() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::from(1)); + tx.0.base.gas_limit = gas_limit; + let refused = MegaEvm::new(context(system_db())) + .execute_transaction(tx) + .expect("a valid transaction"); + assert_eq!(refusal(&refused), KeylessDeployError::NoEtherTransfer); + assert!(refused.result.logs().is_empty()); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!(refused.usage, reference.usage, "the body alone, at {gas_limit}"); + } +} + +/// 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 index 715a9f4a3..e250a9004 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -4,18 +4,39 @@ //! 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 transaction with the deployment taken -//! back whole. +//! its charges count as compute, a crossing stops the transaction with the deployment taken back +//! whole, 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_sol_types::SolError; +use alloy_primitives::TxKind; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, - LimitCheck, LimitKind, MegaLimitExceeded, VolatileDataAccess, + 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::{ + CALL, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, POP, PUSH0, SSTORE, STATICCALL, SUB, SWAP1, + TIMESTAMP, + }, + context::{BlockEnv, TxEnv}, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, + primitives::KECCAK_EMPTY, + Inspector, }; -use revm::{context::BlockEnv, primitives::KECCAK_EMPTY}; use super::*; -use crate::common::{call_tx, context}; +use crate::common::{call_tx, context, CALLER as RELAYER}; /// The block beneficiary of the cases where nobody in the transaction is the beneficiary. const BENEFICIARY: Address = address!("0x0000000000000000000000000000000000beef02"); @@ -30,21 +51,79 @@ struct Run { accessed: VolatileDataAccess, } -/// 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 { - let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); - let ctx = - context(db).with_block(BlockEnv { beneficiary, ..block() }).with_tx_runtime_limits(limits); +/// 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) +} + +/// The `keylessDeploy` transaction `data` from the relayer at `gas_limit`. +fn keyless_tx(data: Bytes, gas_limit: u64) -> MegaTransaction { let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); tx.0.base.gas_limit = gas_limit; + tx +} + +/// 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 /// exactly its limit past its intrinsic gas, and kept nothing of the deployment. fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: u64) { @@ -76,6 +155,48 @@ fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: u64) { 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. +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") +} + +/* ---------- 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 @@ -107,3 +228,256 @@ fn test_a_signer_that_is_the_beneficiary_detains_its_deployment() { assert_stopped(&stopped, &deployment, gas_limit); } } + +/* ---------- 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 limit: the call reverts with the stop, and the deployment +/// is taken back whole. 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)); + assert_stopped(&stopped, &reads, gas_limit); + 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 constructor's last charge crosses. +#[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_stopped(&short, &deployment, gas_limit); + } +} + +/* ---------- 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())); + } +} + +/// Records every answer `remainingComputeGas()` gives, next to the spendable regular gas its +/// caller resumes with: what a regular charge of the caller could draw at its next instruction. +#[derive(Debug, Default)] +struct AnswerAndResume { + pending: Option, + 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::()); + } + } +} + +/// `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}"), + } + } + } +} + +/* ---------- 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 the cap, the constructor stops at the limit, and the +/// deployment is taken back whole. +#[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()); + + let stopped = run_tx(oracle_context(db(), service.clone(), 1_000), tx(), true); + assert_stopped(&stopped, &deployment, gas_limit); + assert_eq!(stopped.accessed, VolatileDataAccess::ORACLE); + } +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index f6b57ae15..68d709a39 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -450,3 +450,70 @@ fn test_a_deployment_is_counted_but_not_stopped_under_the_exemption() { } use revm::primitives::KECCAK_EMPTY; + +/// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit` under `limits`, with the +/// signer's SALT bucket at `m_signer` times the minimum and the deploy address's at `m_address`. +fn crowded_run( + db: MemoryDatabase, + deployment: &Deployment, + gas_limit: u64, + limits: EvmTxRuntimeLimits, + (m_signer, m_address): (u64, u64), +) -> Outcome { + let envs = crowded(TestExternalEnvs::new(), deployment.signer, m_signer); + let envs = crowded(envs, deployment.address, m_address); + 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()) + .with_tx_runtime_limits(limits); + 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 state-gas limit holds each upfront charge of a deployment once, at the price its bucket +/// sets: the signer's account the call pays for, and the created account the creation's start +/// holds, as the frame-start hold holds any `CREATE`'s. With the signer's bucket at twice the +/// minimum and the deploy address's at four times, a deployment holds `2 ×` the new account, `4 ×` +/// the created account and `4 ×` its deposited byte. A limit of exactly that deploys, as without a +/// limit; one gas less stops the transaction. A signer that has an account pays for none, and the +/// limit that holds the rest deploys it. +#[test] +fn test_the_upfront_charges_are_held_once_at_their_bucket_prices() { + let deployment = Deployment::new(deploying(&runtime(1))); + assert_ne!(bucket(deployment.signer), bucket(deployment.address)); + let created = entry(GasId::create_state_gas()) + satin_gas_params().code_deposit_state_gas(1); + let held = 2 * entry(GasId::new_account_state_gas()) + 4 * created; + let limited = |db: MemoryDatabase, gas_limit, limit| { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit); + crowded_run(db, &deployment, gas_limit, limits, (2, 4)) + }; + for gas_limit in GAS_LIMITS { + let unlimited = crowded_run( + system_db(), + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits(), + (2, 4), + ); + assert_eq!(unlimited.gas.state, held, "at {gas_limit}"); + + let exact = limited(system_db(), gas_limit, held); + assert_eq!(returned(&exact).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(exact.gas, unlimited.gas); + let short = limited(system_db(), gas_limit, held - 1); + assert_eq!(stop(&short), MegaLimitExceeded { kind: 3, limit: held - 1 }); + assert_stopped_whole(&short, &deployment, gas_limit); + + let funded = db_for(&deployment, U256::from(1)); + let exact = limited(funded.clone(), gas_limit, 4 * created); + assert_eq!(returned(&exact).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(exact.gas.state, 4 * created); + let short = limited(funded, gas_limit, 4 * created - 1); + assert_eq!(stop(&short), MegaLimitExceeded { kind: 3, limit: 4 * created - 1 }); + } +} From 8c7fc20a72ada995ab92e3cc321d1a3557564692 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 01:42:04 -0700 Subject: [PATCH 203/458] test(system): port the six parked rows of a keyless deployment's volatile reads --- crates/mega-evm/tests/_pending/README.md | 15 +- crates/mega-evm/tests/_pending/rex5/main.rs | 1 - .../tests/_pending/rex5/sandbox_accounting.rs | 690 ------------------ .../tests/system/keyless/detention.rs | 75 +- 4 files changed, 77 insertions(+), 704 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index b7d1bd540..4e3e1fe1e 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,13 +28,12 @@ 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 | -| detention | 6 | 6 | 0 | 0 | 6 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **100** | **82** | **18** | **63** | **30** | **7** | +| **Total** | **94** | **76** | **18** | **63** | **24** | **7** | ## Tests ported in place @@ -275,7 +274,7 @@ These 54 rows run in a real test target now, adapted to the Satin API: the state ## Tests ported by detention -These 83 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. +These 89 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -290,12 +289,13 @@ These 83 rows run in a real test target now, adapted to the Satin API and to the | `rex4/access_control.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex4/beneficiary_detention.rs` | detention (12) | 12 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex4/gas_detention.rs` | detention (3) | 3 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | +| `rex5/sandbox_accounting.rs` | detention (6) | 6 | `tests/system/keyless/detention.rs` | | `rex5/selfdestruct_beneficiary.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex6/beneficiary_detention.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | | `rex6/eip7702_authority_accounting.rs` | detention (2) | 2 | `tests/satin/volatile_access.rs` | | `src/access/volatile.rs` | detention (4) | 4 | `crates/mega-evm/src/access/volatile.rs` | | `src/limit/compute_gas.rs` | detention (1) | 1 | `tests/satin/detention.rs` | -| **Total** | | **83** | | +| **Total** | | **89** | | ## Tests ported by the oracle and control contracts @@ -372,12 +372,6 @@ They are not counted above. | `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | | `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_beneficiary_balance_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_block_env_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_coinbase_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_oracle_access_merged_into_parent_volatile_tracker` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_volatile_bitmap_survives_residual_overflow_halt` | detention | a keyless deployment a transaction limit stops still reports the volatile data its creation read, and the stop stays the limit's | -| `rex5/sandbox_accounting.rs` | `test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code` | detention | a keyless deployment's volatile-data access is its creation frame's, as any frame's is; the tracker that sees it is detention's | ## Files @@ -404,7 +398,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `rex5/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | -| `rex5/sandbox_accounting.rs` | 6 | rewrite 6 (detention · native sub-frame: parent tracker sees child directly) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 1e88eb46b..f0ba19ba8 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -7,6 +7,5 @@ mod create2_resize_gas_metering; mod eip7702_metering; mod oracle_hint_metering; mod pre_block_system_calls; -mod sandbox_accounting; mod sstore_storage_gas_error; mod stipend_accounting; 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 fc5f2c784..000000000 --- a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs +++ /dev/null @@ -1,690 +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 -// ============================================================================ - -/// 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: 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/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index e250a9004..cc8305f29 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -26,10 +26,11 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, POP, PUSH0, SSTORE, STATICCALL, SUB, SWAP1, - TIMESTAMP, + BALANCE, CALL, COINBASE, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, POP, PUSH0, SSTORE, STATICCALL, + STOP, SUB, SWAP1, TIMESTAMP, }, context::{BlockEnv, TxEnv}, + context_interface::cfg::GasId, interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, primitives::KECCAK_EMPTY, Inspector, @@ -481,3 +482,73 @@ fn test_a_constructor_reads_the_oracle_as_any_frame_does() { assert_eq!(stopped.accessed, VolatileDataAccess::ORACLE); } } + +/* ---------- 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 state-gas limit has no +/// room for stops the transaction on state growth, not on compute. +#[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))); + let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); + let limit = upfront + entry(GasId::sstore_set_state_gas()) - 1; + for gas_limit in GAS_LIMITS { + let run = run_both(&deployment, gas_limit, capped(CAP).with_tx_state_gas_limit(limit)); + let ExecutionResult::Revert { output, .. } = &run.outcome.result else { + panic!("expected the state-gas stop, got {:?}", run.outcome.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(output).unwrap(), + MegaLimitExceeded { kind: LimitKind::StateGrowth.as_u8(), limit }, + ); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); + assert!(run.limit.is_some()); + assert_eq!(nonce(&run.outcome, deployment.signer), 0, "the deployment is taken back"); + } +} From dd64719b62c3125f5a2aba5c25a36b10f61f42b5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:30:55 -0700 Subject: [PATCH 204/458] fix(access): withhold an answer's spill once when it is settled as the stop An answer that spends past the allowance is marked as a crossing of what the frame would have had withheld. State and history gas that spilled onto its regular gas would have drawn the withheld part first, and the revert that settles the stop credits the spill back, so the crossing now leaves the spill out rather than returning it twice. --- crates/mega-evm/src/access/detention.rs | 10 +++- crates/mega-evm/tests/satin/withheld_gas.rs | 51 +++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 1a01af9b7..3d2ec060c 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -443,7 +443,15 @@ impl Detention { // gas limit is above the allowance and the frame would have had the rest withheld. An // answer built on less than the frame was forwarded is settled on what it was // forwarded. - let withheld = NonZeroU64::new(gas_limit - allowance)?; + // + // State and history gas that spilled onto regular gas would have drawn the withheld + // part first, and the revert that settles the stop credits the spill back, so the + // crossing withholds what is left once the spill is taken out, as the tracker's own + // record of a running frame does. The spill is below `gas_limit - allowance`, since + // the regular gas the answer spent past it exceeds the allowance. + let withheld = NonZeroU64::new( + (gas_limit - allowance).saturating_sub(result.gas.state_gas_spilled()), + )?; result.result = InstructionResult::OutOfGas; result.gas.tracker_mut().set_limit(gas_limit); result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 57a803f3e..9fcb7e2c8 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1247,3 +1247,54 @@ fn test_a_slotnum_refusal_is_past_the_enum() { VolatileDataAccessType::BlockHash ); } + +/// 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 and the limit, whatever state +/// or history gas the answer charged: below the execution cap that gas spills onto regular gas and +/// the stop's revert gives it back, so the stop withholds none of it a second time. Above the cap +/// the reservoir pays it and nothing spills. +#[test] +fn test_an_answer_past_the_allowance_with_a_spill_is_billed_the_limit() { + 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.gas.regular, intrinsic + CAP, "{gas_limit}, history {history}"); + } + } +} From 4959e33daa97f8114db9676ece98b3da52b18351 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:46:55 -0700 Subject: [PATCH 205/458] feat(evm): place a system call's gas above 30M in its state-gas reservoir --- crates/mega-evm/src/evm/context.rs | 21 +++++++++++++------- crates/mega-evm/src/test_utils/neutral.rs | 10 ++++++++++ crates/mega-evm/tests/satin/equivalence.rs | 23 +++++++++++++++------- 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index ae5db7e71..21986ff16 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -442,8 +442,13 @@ 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). /// -/// The system-call reservoir margin is set off rather than left alone: it belongs to the -/// system-call reservoir split. +/// 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. fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.gas_params = satin_gas_params(); cfg.enable_amsterdam_eip8037 = true; @@ -451,7 +456,7 @@ 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 = false; + cfg.system_call_state_gas_margin_in_reservoir = true; cfg.limit_contract_code_size = Some(constants::MAX_CONTRACT_SIZE); cfg.limit_contract_initcode_size = Some(constants::MAX_INITCODE_SIZE); cfg @@ -537,7 +542,7 @@ 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, "the system-call reservoir margin stays off"); + assert!(cfg.margin, "a system call's gas above 30M must be its reservoir"); 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"); @@ -598,7 +603,7 @@ 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 = true; + cfg.system_call_state_gas_margin_in_reservoir = 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); @@ -632,8 +637,10 @@ mod tests { } #[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)); + fn test_the_system_call_reservoir_margin_stays_on() { + assert_satin_cfg(&context_with(|cfg| { + cfg.system_call_state_gas_margin_in_reservoir = false; + })); } #[test] diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index d6de5c13b..39e98aad8 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -48,6 +48,12 @@ use crate::{EthSpecId, ExternalEnvTypes, MegaEvm, MegaSpecId}; /// 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 { @@ -147,6 +153,8 @@ 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()); } /// Amsterdam's configuration carries what revm's runner derives from the Amsterdam spec id, @@ -163,6 +171,8 @@ 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()); } /// Neither configuration is Satin's, and both run Satin's spec. diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index cba87adbb..b8dbf9526 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -172,9 +172,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 the -/// system-call reservoir margin off. So op-revm journals the same transfer logs, and the logs of -/// the two are compared as they are. +/// 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()); @@ -185,7 +186,7 @@ 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); + assert!(cfg.system_call_state_gas_margin_in_reservoir); } #[test] @@ -396,16 +397,24 @@ fn test_refund_matches_op_revm() { 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 - SLOT_STATE_GAS, + ); assert_same(&mega_outcome, &op_outcome); } From 75612b50c9eecc407ff1cf2e9cd6e9fac11e20a5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:48:51 -0700 Subject: [PATCH 206/458] feat(evm): run a system call on an explicit gas limit --- crates/mega-evm/src/evm/mod.rs | 106 ++++++++++++++++- crates/mega-evm/tests/_pending/README.md | 14 ++- crates/mega-evm/tests/_pending/src/evm/mod.rs | 111 ------------------ 3 files changed, 113 insertions(+), 118 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/src/evm/mod.rs diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8f11c4446..1624bef63 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -354,13 +354,48 @@ 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 mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); + tx.0.base.gas_limit = 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) } } @@ -458,8 +493,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}; @@ -577,6 +613,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/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4e3e1fe1e..e50796b04 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,11 +29,11 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | +| the pre-block system calls | 31 | 22 | 9 | 27 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **94** | **76** | **18** | **63** | **24** | **7** | +| **Total** | **91** | **76** | **15** | **60** | **24** | **7** | ## Tests ported in place @@ -329,6 +329,15 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless | `src/sandbox/execution.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/rules.rs` | | **Total** | | **69** | | +## Tests ported by the pre-block system calls + +These 3 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | +| **Total** | | **3** | | + ## Tests retired after the inventory These 21 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. @@ -401,5 +410,4 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | | `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | 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]))); - } -} From 5179e918a2463a7028b3c293848eebd8d3155546 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:52:54 -0700 Subject: [PATCH 207/458] feat(block): refuse a block whose EIP-2935 or EIP-4788 call fails --- crates/mega-evm/src/block/eips.rs | 125 +++- crates/mega-evm/src/block/executor.rs | 4 +- crates/mega-evm/tests/_pending/README.md | 10 +- .../_pending/rex5/pre_block_system_calls.rs | 672 ------------------ crates/mega-evm/tests/block/eips.rs | 343 ++++++++- 5 files changed, 416 insertions(+), 738 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 8b3a2ef09..77c68cb6e 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -3,72 +3,121 @@ //! 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. +//! +//! 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. #[cfg(not(feature = "std"))] use alloc as std; -use std::{boxed::Box, string::ToString}; +use std::{boxed::Box, format, 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 op_revm::OpHaltReason; use revm::{ - context::{result::ResultAndState, Block}, + context::{result::ResultAndState, Block, ContextTr}, database::State, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{Account, EvmState}, Database, }; +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 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, and its +/// state is handed to nobody. 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 gas_limit = pre_block_call_gas_limit(block.gas_limit()); + let outcome = evm + .transact_system_call_with_gas_limit( + SYSTEM_ADDRESS, + HISTORY_STORAGE_ADDRESS, + parent_block_hash.0.into(), + gas_limit, + ) + .map_err(|e| BlockValidationError::BlockHashContractCall { message: e.to_string() })?; + if !outcome.result.is_success() { + return Err(BlockValidationError::BlockHashContractCall { + message: format!("the EIP-2935 pre-block call did not succeed: {:?}", outcome.result), + } + .into()); + } + Ok(Some(outcome)) } /// 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, and its state is handed to nobody. 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,19 +127,27 @@ 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| { - BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: e.to_string(), - } - .into() - }) + let gas_limit = pre_block_call_gas_limit(block.gas_limit()); + let refused = |message: std::string::String| BlockValidationError::BeaconRootContractCall { + parent_beacon_block_root: Box::new(parent_beacon_block_root), + message, + }; + let outcome = evm + .transact_system_call_with_gas_limit( + SYSTEM_ADDRESS, + BEACON_ROOTS_ADDRESS, + parent_beacon_block_root.0.into(), + gas_limit, + ) + .map_err(|e| refused(e.to_string()))?; + if !outcome.result.is_success() { + return Err(refused(format!( + "the EIP-4788 pre-block call did not succeed: {:?}", + outcome.result + )) + .into()); + } + Ok(Some(outcome)) } /// The state that applying `balances` to `db` would produce. Nothing is committed. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 95a1db133..d99035948 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -531,7 +531,9 @@ where /// The EIP-2935 and EIP-4788 calls run before the deploy. 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 deploy that follows. + /// the deploy 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 reaches the observer. /// /// The pre-block system calls that apply a due `SequencerRegistry` change are still an empty /// hook after the deploy. diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e50796b04..ebd82b26b 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,11 +29,11 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 31 | 22 | 9 | 27 | 4 | 0 | +| the pre-block system calls | 20 | 11 | 9 | 16 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **91** | **76** | **15** | **60** | **24** | **7** | +| **Total** | **80** | **65** | **15** | **49** | **24** | **7** | ## Tests ported in place @@ -331,12 +331,13 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 3 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. +These 14 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | | `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | -| **Total** | | **3** | | +| **Total** | | **14** | | ## Tests retired after the inventory @@ -406,7 +407,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/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | -| `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | 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/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 0b4a3ebe7..45341b870 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -2,26 +2,41 @@ //! //! 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 +//! reaches neither the observer nor the database. +//! +//! 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, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaHardforkConfig, MegaSpecId, + constants::SLOT_STATE_GAS, + pre_block_call_gas_limit, + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, + MegaHardforkConfig, MegaSpecId, PreBlockStateSource, }; 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, executor_with_env, executor_with_env_and_spec, pre_block_states, record_pre_block, + BLOCK_NUMBER, +}; /// The parent hash the EIP-2935 call records. const PARENT_HASH: B256 = B256::repeat_byte(0xab); @@ -94,6 +109,68 @@ fn pre_block_calls( recorded(&mut state) } +/// The pre-block calls a block at `number` on the chain `spec` describes handed to the observer, +/// in order, and whether the block started. +fn observed_calls( + spec: MegaHardforkConfig, + number: u64, + ctx: MegaBlockExecutionCtx, +) -> (Vec, Result<(), BlockExecutionError>) { + let mut state = state_with_recorders(); + let mut executor = executor_with_env_and_spec(&mut state, ctx, env_at_block(number), spec); + let log = record_pre_block(&mut executor); + let started = executor.apply_pre_execution_changes(); + let calls = pre_block_states(&log) + .into_iter() + .map(|(source, _)| source) + .filter(|source| { + matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) + }) + .collect(); + (calls, 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 pre-block calls the +/// observer received, 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 mut executor = executor_with_env(&mut state, ctx(), env); + let log = record_pre_block(&mut executor); + let started = executor.apply_pre_execution_changes(); + let calls = pre_block_states(&log) + .into_iter() + .map(|(source, _)| source) + .filter(|source| { + matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) + }) + .collect(); + (calls, 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] @@ -133,10 +210,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) = observed_calls(before_prague, BLOCK_NUMBER, ctx()); + started.expect("a block before Prague starts"); + assert_eq!(calls, [PreBlockStateSource::Eip4788], "no block hashes call reached the observer"); } /// A chain that has not reached Cancun makes no beacon root call, and needs no root; the block @@ -146,10 +227,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) = observed_calls(before_cancun, BLOCK_NUMBER, ctx_without_beacon_root()); + started.expect("a block before Cancun starts"); + assert_eq!(calls, [PreBlockStateSource::Eip2935], "no beacon root call reached the observer"); } /// The genesis block makes neither call: it has no parent to record. Its parent beacon root is @@ -164,22 +249,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) = observed_calls(common::chain_spec(), 0, genesis); + started.expect("the genesis block starts"); + assert!(calls.is_empty(), "no pre-block call reached the observer: {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 nothing reached the observer. #[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) = observed_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!( @@ -194,16 +280,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) = + observed_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, [PreBlockStateSource::Eip2935]); assert!( matches!( @@ -213,3 +297,210 @@ fn test_a_block_without_a_parent_beacon_root_is_refused() { "{err}" ); } + +/// With the contracts' own code, both calls succeed, reach the observer in order and are +/// committed: 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 mut executor = executor_with_env(&mut state, ctx(), env_at_block(BLOCK_NUMBER)); + let log = record_pre_block(&mut executor); + executor.apply_pre_execution_changes().expect("both calls succeed"); + let calls: Vec<_> = pre_block_states(&log).into_iter().map(|(source, _)| source).collect(); + assert_eq!(&calls[..2], [PreBlockStateSource::Eip2935, PreBlockStateSource::Eip4788]); + 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 +/// reaches neither the observer nor the database; 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, [PreBlockStateSource::Eip2935]); +} + +/// A pre-block call that reverts refuses the block just as one that halts does. +#[test] +fn test_a_block_is_refused_when_a_pre_block_call_reverts() { + let reverts = BytecodeBuilder::default().revert().build(); + + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, reverts.clone()); + let (calls, started) = start_block(db, common::evm_env()); + let err = started.expect_err("a reverted block hashes call refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) + if message.contains("Revert") + ), + "{err}" + ); + assert!(calls.is_empty(), "{calls:?}"); + + let mut db = common::database(); + db.set_account_code(BEACON_ROOTS_ADDRESS, reverts); + let (calls, started) = start_block(db, common::evm_env()); + let err = started.expect_err("a reverted beacon root call refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { .. }) + ), + "{err}" + ); + assert_eq!(calls, [PreBlockStateSource::Eip2935]); +} + +/// 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!(u64::from(SLOTS) * SLOT_STATE_GAS > SYSTEM_CALL_REGULAR_GAS_LIMIT); + 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); + + 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 mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); + let log = record_pre_block(&mut executor); + executor.apply_pre_execution_changes().expect("a 250M block holds both calls"); + let states = pre_block_states(&log); + assert_eq!(states[0].0, PreBlockStateSource::Eip2935); + assert_eq!(states[0].1[&HISTORY_STORAGE_ADDRESS].storage.len(), usize::from(SLOTS)); + assert_eq!(states[1].0, PreBlockStateSource::Eip4788); + assert_eq!(states[1].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 refuses the block with the EIP-2935 error, carrying +/// the database's message. +#[test] +fn test_blockhashes_pre_block_call_db_error_returns_validation_error() { + let err = start_block_over(failing_on(HISTORY_STORAGE_ADDRESS)) + .expect_err("a failed read refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) + if message.contains("injected basic() error") + ), + "{err}" + ); +} + +/// A database error in the beacon root call refuses the block with the EIP-4788 error; the block +/// hashes call before it read what it needed. +#[test] +fn test_beacon_root_pre_block_call_db_error_returns_validation_error() { + let err = start_block_over(failing_on(BEACON_ROOTS_ADDRESS)) + .expect_err("a failed read refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { + message, + .. + }) if message.contains("injected basic() error") + ), + "{err}" + ); +} From 9312df765e067346bb249862d56c22b17b7c79d3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:54:15 -0700 Subject: [PATCH 208/458] test(satin): pin the revert-class stop as a matrix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every transaction-level limit — data size, KV updates, state gas and gas detention's compute limit — crossed by the transaction's own frame and by a frame three calls below it, below the execution cap and above it, without an inspector and under one that rewrites every frame result into a success. Each cell checks the receipt, the latched stop, the bill on every ledger against a twin that reverts where the stop crossed, that nothing written or logged is kept, and that no frame ran on after the crossing. Beside the matrix: a frame budget crossed three calls down reverts that frame alone and its callers run on, and a real out-of-gas or a precompile given less than its price still halts and burns what its frame was given. --- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/stops.rs | 614 +++++++++++++++++++++++++++ 2 files changed, 615 insertions(+) create mode 100644 crates/mega-evm/tests/satin/stops.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 3083549b2..c07948d7f 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -31,6 +31,7 @@ mod schedule; mod state; mod state_gas_limit; mod static_callee; +mod stops; mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs new file mode 100644 index 000000000..91ee7acb0 --- /dev/null +++ b/crates/mega-evm/tests/satin/stops.rs @@ -0,0 +1,614 @@ +//! The revert-class stop, pinned as a matrix. +//! +//! A transaction-level limit — data size, KV updates, state gas, or gas detention's compute limit — +//! stops the transaction with a revert. The frame that crosses it reverts with +//! `MegaLimitExceeded(kind, limit)`, the transaction is latched, and every frame above returns the +//! same revert without running another instruction, whatever produced its result. The transaction +//! 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 reverts its frame alone, and its caller runs on. 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, without an inspector and under one that rewrites every frame result into a success, below +//! the execution cap and above it, where a reservoir pays the body first. What ran is read off a +//! twin of each transaction: the same frames, each reverting where the stopped one crossed its +//! limit or would have resumed. The twin runs without limits and revm settles its reverts itself, +//! so it bills exactly what the stop should, plus the two pushes each of its reverts costs. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, + MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, + LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, + SSTORE, TIMESTAMP, + }, + context::result::ExecutionResult, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::{ + common::{call, call_with_data}, + detention::{context, work}, +}; + +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 call or 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 each of the twin's reverts cost. +const TWIN_REVERT: u64 = 4; + +/// A transaction-level limit the matrix crosses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Limit { + DataSize, + KvUpdates, + StateGas, + Compute, +} + +impl Limit { + const ALL: [Self; 4] = [Self::DataSize, Self::KvUpdates, Self::StateGas, Self::Compute]; + + const fn kind(self) -> LimitKind { + match self { + Self::DataSize => LimitKind::DataSize, + Self::KvUpdates => LimitKind::KVUpdate, + Self::StateGas => LimitKind::StateGrowth, + 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. The +/// frame at `crossing` then crosses the limit — a fresh slot's write, or a read of the block's +/// timestamp and more compute than the cap — and every frame above it calls the next. The stopped +/// transaction's frames then write [`MARKER`] and log again; the twin's frames revert instead. +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)); + } + } + code = if depth < crossing { + let code = call_all(code, CHAIN[depth + 1]); + if twin { + code + } else { + code.append(POP) + } + } else { + match limit { + Limit::Compute if twin => code.append(TIMESTAMP), + Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), + _ => 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 +} + +/// The state gas of one fresh slot of `A`, at the price the engine runs. +fn one_slot() -> u64 { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); + let db = MemoryDatabase::default().account_code(A, code); + let outcome = execute(db, EvmTxRuntimeLimits::no_limits(), BELOW); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome.gas.state +} + +/// 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 the steps and the result of every frame it sees end, then rewrites that result into a +/// success with no output: a tool's inspector the latch must see through. +#[derive(Clone, Default)] +struct Rewriter { + /// The frame and opcode of the last step, and the slot it named when it was an `SSTORE`. + last: Option<(Address, u8, Option)>, + /// How many writes of [`MARKER`] ran. + marker_writes: usize, + /// The frames that ended, deepest first, with the result each had before the rewrite. + ended: Vec<(Address, InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for Rewriter { + 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.marker_writes += usize::from(slot == Some(MARKER)); + self.last = Some((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())); + result.result = InstructionResult::Stop; + result.output = Bytes::new(); + } +} + +/// 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 a [`Rewriter`]. +fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { + let row = format!("{limit:?} at depth {crossing}, gas limit {gas_limit}"); + let frames = crossing as u64 + 1; + let intrinsic = intrinsic(gas_limit); + + // The twin: the same frames, reverting where the stopped ones crossed or would resume. + let twin = execute(chain(limit, crossing, true), EvmTxRuntimeLimits::no_limits(), gas_limit); + assert!( + matches!(&twin.result, ExecutionResult::Revert { output, .. } if output.is_empty()), + "{row}: the twin reverts: {:?}", + twin.result + ); + assert_eq!(twin.limit_exceeded, None, "{row}"); + assert_eq!( + (twin.gas.state, twin.gas.history, twin.gas.reservoir_remaining), + (0, intrinsic.gas.history, intrinsic.gas.reservoir_remaining), + "{row}: a revert keeps nothing but the body", + ); + // 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 * frames; + + // The limit crossed, and the usage that crossed it: one more byte, record or unit of state gas + // than the limit. The compute limit is set by the read, at the compute it ran to plus the cap, + // and the stop reports it as what was used. + let (configured, value) = limits_of(limit, crossing, slot); + let (value, used) = match value { + Some(value) => (value, value + 1), + None => (before_crossing + CAP, before_crossing + CAP), + }; + let stop = + LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local: false }; + // What ran: up to the crossing, and for the compute limit the cap past the read. + let ran = if limit == Limit::Compute { value } 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(Rewriter::default()); + let rewritten = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + let rewriter = evm.inspector(); + + for (column, outcome) in [("plain", &plain), ("rewritten", &rewritten)] { + let cell = format!("{row}, {column}"); + // 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}"); + + // The bill: intrinsic gas plus what ran, on the regular ledger alone. + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); + 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 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"); + + // Nothing the stopped frames wrote or logged is kept; the body is all the transaction + // keeps. + assert!(outcome.result.logs().is_empty(), "{cell}: no log is kept"); + for account in &CHAIN[..=crossing] { + let kept = outcome + .state + .get(account) + .is_some_and(|account| account.storage.values().any(|slot| slot.is_changed())); + assert!(!kept, "{cell}: {account} kept a write"); + } + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + "{cell}: the body stays" + ); + } + // No instruction ran after the crossing: the bill above has no marker's write in it, and under + // the inspector none ran at all. Every frame returned the stop, and the rewrites into successes + // did not reach a caller: the inspector changed nothing the transaction reports. + assert_eq!(rewritten.gas, plain.gas, "{row}"); + assert_eq!(rewriter.marker_writes, 0, "{row}: no frame ran on after the crossing"); + if limit != Limit::Compute { + assert_eq!( + rewriter.last, + Some((CHAIN[crossing], SSTORE, Some(CROSSING_SLOT))), + "{row}: the crossing write was the last step" + ); + } + let ended: Vec<_> = CHAIN[..=crossing] + .iter() + .rev() + .map(|frame| (*frame, InstructionResult::Revert, stop.revert_data())) + .collect(); + assert_eq!(rewriter.ended, ended, "{row}: every frame returned the stop, deepest first"); +} + +/// Every transaction-level limit, crossed by the transaction's own frame and by a frame three calls +/// below it, stops the transaction the same way — below the execution cap and above it, with and +/// without an inspector that rewrites every frame result into a success. +#[test] +fn test_every_limit_stops_the_transaction_at_every_depth_and_tier() { + let slot = one_slot(); + for limit in Limit::ALL { + for crossing in [0, 3] { + for gas_limit in TIERS { + assert_cell(limit, crossing, gas_limit, slot); + } + } + } +} + +/// 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, slot: u64) -> (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::KvUpdates => { + (EvmTxRuntimeLimits::default().with_tx_kv_update_limit(OWN_SLOTS), Some(OWN_SLOTS)) + } + Limit::StateGas => { + let value = (OWN_SLOTS + 1) * slot - 1; + (EvmTxRuntimeLimits::default().with_tx_state_gas_limit(value), Some(value)) + } + Limit::Compute => (EvmTxRuntimeLimits::default(), None), + } +} + +/* ---------- 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 budget — in data size or in +/// write records — reverts alone with `MegaLimitExceeded(kind, budget)`, where the budget is what +/// the shares left it. Its caller resumes and reads the stop, every frame above runs on, nothing is +/// latched and the transaction 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 data_budget = share(share(share(ROOM - LOG_BASE_SIZE) - LOG_BASE_SIZE) - LOG_BASE_SIZE); + const RECORDS: u64 = 100; + let record_budget = share(share(share(RECORDS))); + let rows = [ + ( + LimitKind::DataSize, + EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + ROOM), + data_budget, + // D's log and its writes cross its budget long before the transaction's limit. + writer(data_budget / WRITE_RECORD_SIZE + 1), + ), + ( + LimitKind::KVUpdate, + EvmTxRuntimeLimits::default().with_tx_kv_update_limit(RECORDS), + record_budget, + writer(record_budget + 1), + ), + ]; + for (kind, limits, budget, d) in rows { + for gas_limit in TIERS { + let case = format!("{kind:?}, 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 latches nothing"); + + // 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) + .with_tx_kv_update_limit(1_000) + .with_tx_state_gas_limit(TX_GAS_LIMIT_CAP) +} + +/// A loop that never ends. +fn spin() -> Bytes { + BytecodeBuilder::default().append(JUMPDEST).append_many([PUSH0, JUMP]).build() +} + +/// 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" + ); + } +} From aaa49cd633f57e51ae7ce47c84b53736a97ce2f8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:55:42 -0700 Subject: [PATCH 209/458] fix(limit): latch a halt an inspector made into the stop Under the latch every frame result was rewritten to the stop unless it was a halt. No frame runs an instruction once the transaction is latched, so the only halt that can reach the latch is one an inspector wrote, and an inspector that rewrote the frames' results into halts turned the stop into a halt that burned the transaction's regular gas while the outcome still named the limit. The latch now rewrites a halt too, as it does a success. --- crates/mega-evm/src/limit/limit.rs | 19 ++++++---- crates/mega-evm/tests/satin/stops.rs | 56 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 41f04f3a5..b3ce68c66 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -216,15 +216,19 @@ impl AdditionalLimit { self.latched().copied().or(resume_stop) } - /// 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. + /// Rewrites `result` to the latched stop, when the transaction is latched: a success, a revert + /// or a halt becomes the latched revert, on the gas the result carries. + /// + /// No frame runs an instruction once the transaction is latched, so no out-of-gas can happen + /// after the latch: the frame that crossed returns the stop, and every frame above it returns + /// it again without running. A halt that reaches here under the latch was made by an + /// inspector's rewrite, which cannot turn the stop into a halt any more than into a success. + /// A real halt before the latch is left alone: it was returned before the latch was set. pub(crate) 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(); - } + 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 @@ -793,7 +797,8 @@ impl AdditionalLimit { /// 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. + /// whatever produced it (an interceptor, an inspector's rewrite), so neither a success nor a + /// halt passes it. /// /// Then the caller is held to its limits with what it now holds, and a crossing is the stop /// it returns before it runs on ([`stop_before_run`](Self::stop_before_run)): its own diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 91ee7acb0..bc63fcb4f 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -332,6 +332,62 @@ fn test_every_limit_stops_the_transaction_at_every_depth_and_tier() { } } +/// Rewrites every frame 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 cannot turn a stop into a halt either: +/// under the latch every result is the stop, whatever produced it, so the transaction reports the +/// stop and bills what ran, as it does without the inspector, rather than burning its gas. +#[test] +fn test_an_inspector_cannot_turn_a_stop_into_a_halt() { + let slot = one_slot(); + 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, slot); + let plain = execute(chain(limit, crossing, false), configured, gas_limit); + 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!( + matches!(&halted.result, ExecutionResult::Revert { .. }), + "{case}: {:?}", + halted.result + ); + assert_eq!(halted.result.output(), plain.result.output(), "{case}"); + assert_eq!(halted.limit_exceeded, plain.limit_exceeded, "{case}"); + assert_eq!(halted.gas, plain.gas, "{case}"); + assert_eq!(halted.usage, plain.usage, "{case}"); + } + } + } + } +} + /// 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, slot: u64) -> (EvmTxRuntimeLimits, Option) { From 9a0063a6cf7164cb1e98bf98fd67878903b9a1c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:56:41 -0700 Subject: [PATCH 210/458] test(satin): pin that a detained callee's stop does not burn its callers' gas A callee one or three calls down that reads the block's timestamp and then computes past the cap stops the transaction, and the stop bills the intrinsic gas plus the limit the read set, the same at every gas limit, below the execution cap and above it: nothing of what the callers held is burned. --- crates/mega-evm/tests/satin/stops.rs | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index bc63fcb4f..0593433cb 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -409,6 +409,63 @@ fn limits_of(limit: Limit, crossing: usize, slot: u64) -> (EvmTxRuntimeLimits, O } } +/* ---------- a detained callee does not burn its callers' gas ---------- */ + +/// A callee at `depth` that reads the block's timestamp and then computes past the cap, below +/// callers that forward it all their gas and would write [`MARKER`] once it returned. +fn detained_callee_at(depth: usize) -> MemoryDatabase { + let callee = work(log(BytecodeBuilder::default()).append_many([TIMESTAMP, POP]), ROUNDS); + let callee = callee.sstore(MARKER, U256::from(1)).stop().build(); + (0..depth) + .fold(MemoryDatabase::default(), |db, caller| { + let code = call_all(BytecodeBuilder::default(), CHAIN[caller + 1]).append(POP); + db.account_code(CHAIN[caller], code.sstore(MARKER, U256::from(1)).stop().build()) + }) + .account_code(CHAIN[depth], callee) +} + +/// A callee that reads the block's timestamp and then computes past the cap does not make its +/// callers burn their gas: the stop bills the transaction its intrinsic gas plus the limit the read +/// set — its compute at the read plus the cap — and nothing of what the callers held, whatever the +/// gas limit, one call down or three, below the execution cap and above it. +#[test] +fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_gas() { + for depth in [1, 3] { + let bills: Vec<_> = [BELOW, ABOVE, 1_000_000_000] + .into_iter() + .map(|gas_limit| { + let case = format!("depth {depth}, gas limit {gas_limit}"); + let intrinsic = intrinsic(gas_limit); + let mut evm = MegaEvm::new(context(detained_callee_at(depth))); + 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"); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false, + }; + assert_eq!(outcome.result.output(), Some(&stop.revert_data()), "{case}"); + assert!(!outcome.result.is_halt(), "{case}"); + assert_eq!(outcome.limit_exceeded, Some(stop), "{case}"); + // The read came after the callers' calls and the callee's log: its compute then is + // theirs alone, a sliver of the cap. + assert!(limit - CAP < 50_000, "{case}: compute at the read {}", limit - CAP); + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + limit, "{case}"); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + limit, "{case}"); + assert_eq!( + outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, + "{case}: the reservoir comes back" + ); + assert!(outcome.result.logs().is_empty(), "{case}"); + (outcome.gas.gas_used, outcome.gas.regular, outcome.gas.state, outcome.gas.history) + }) + .collect(); + assert!(bills.windows(2).all(|pair| pair[0] == pair[1]), "depth {depth}: {bills:?}"); + } +} + /* ---------- frame budgets ---------- */ /// The slot a frame stores its call's status in. From 0f9c555a4fa24eeb9d823ede96cb6cdf0e9a81c4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 02:59:35 -0700 Subject: [PATCH 211/458] feat(block): apply a due SequencerRegistry change before the block's transactions --- crates/mega-evm/src/block/executor.rs | 56 ++- .../mega-evm/src/system/sequencer_registry.rs | 331 ++++++++++++++- crates/mega-evm/tests/_pending/README.md | 23 +- .../rex5/apply_pending_changes_gas_budget.rs | 60 --- .../_pending/src/system/sequencer_registry.rs | 381 ------------------ crates/mega-evm/tests/block/deploy.rs | 12 +- crates/mega-evm/tests/block/main.rs | 1 + .../tests/block/sequencer_registry.rs | 229 +++++++++++ 8 files changed, 614 insertions(+), 479 deletions(-) create mode 100644 crates/mega-evm/tests/block/sequencer_registry.rs diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index d99035948..714b39a61 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -51,7 +51,8 @@ //! //! # The pre-block observer //! -//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, and every system-contract deploy — +//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, every system-contract deploy, the +//! read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` call — //! produces an [`EvmState`] that this executor commits. alloy-evm 0.36 re-exports revm's //! `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on [`BlockExecutor`] and no //! source tag, so this crate names the step ([`PreBlockStateSource`]) and carries an optional @@ -60,16 +61,18 @@ //! drops untouched accounts from the committed transition, so a caller that only saw the //! database after the commit would miss the read-only deploy entries of a later block. //! -//! # What later mechanisms fill in +//! # The pre-block system calls //! -//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) deploys the -//! system contracts and the EIP-7997 factory every block (idempotent). The pre-block system -//! calls that apply a due `SequencerRegistry` change are still an empty hook after that deploy. +//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 +//! and EIP-4788 calls, deploys the system contracts and the EIP-7997 factory (idempotent), 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. #[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}; @@ -103,7 +106,8 @@ use crate::{ block::eips, estimated_da_size, system::{ - system_contract_specs, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, + is_apply_pending_changes_due, system_contract_specs, transact_apply_pending_changes, + transact_deploy, SequencerRegistryConfig, SystemContractDeployError, }, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, @@ -195,6 +199,12 @@ pub enum MegaBlockExecutionError { /// The nonce already on the account. nonce: u64, }, + /// 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, + }, } impl fmt::Display for MegaBlockExecutionError { @@ -230,6 +240,10 @@ impl fmt::Display for MegaBlockExecutionError { f, "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" ), + Self::ApplyPendingChangesFailed { message } => write!( + f, + "the SequencerRegistry applyPendingChanges() pre-block call reverted or halted: {message}" + ), } } } @@ -254,6 +268,11 @@ pub enum PreBlockStateSource { Eip4788, /// A system-contract or factory deploy at this address. SystemContract(Address), + /// The reads of the `SequencerRegistry`'s pending role changes that decide whether the + /// block makes the `applyPendingChanges()` call. + PendingChanges, + /// The `SequencerRegistry.applyPendingChanges()` system call. + ApplyPendingChanges, } /// Receives each pre-block [`EvmState`] before the executor commits it. @@ -518,10 +537,10 @@ where /// Runs what a block does before its transactions. /// /// In order: the admission gate, the reset of the block-hash record, the EIP-2935 and - /// EIP-4788 pre-block calls, and the system-contract deploys. Each step's state is handed to - /// the pre-block observer and then committed here rather than inside its helper, so a - /// witness generator sees every step's read and write set. The sequence the observer - /// receives is the witness a stateless client needs. + /// EIP-4788 pre-block calls, the system-contract deploys, and the `SequencerRegistry`'s due + /// role changes. Each step's state is handed to the pre-block observer and then committed + /// here rather than inside its helper, so a witness generator sees every step's read and + /// write set. The sequence the observer receives is the witness a stateless client needs. /// /// 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 @@ -535,8 +554,10 @@ where /// ([`pre_block_call_gas_limit`](eips::pre_block_call_gas_limit)), and one that does not /// succeed refuses the block before its state reaches the observer. /// - /// The pre-block system calls that apply a due `SequencerRegistry` change are still an empty - /// hook after the deploy. + /// The registry's role changes come after the deploy, which is what puts the registry in + /// state on the chain's first block. Its pending slots are read and handed on 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. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; @@ -586,7 +607,14 @@ where self.deliver_pre_block(PreBlockStateSource::SystemContract(spec.address), state); } - // Hook point: the pre-block system calls. + 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.deliver_pre_block(PreBlockStateSource::PendingChanges, reads); + if due { + let ResultAndState { state, .. } = transact_apply_pending_changes(&mut self.evm)?; + self.deliver_pre_block(PreBlockStateSource::ApplyPendingChanges, state); + } Ok(()) } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 0608f076f..f55457f52 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -6,14 +6,34 @@ //! `crates/system-contracts/contracts/SequencerRegistry.sol`. //! //! The contract is deployed by [`transact_deploy`](crate::system::transact_deploy) with the -//! bootstrap slots [`SequencerRegistryConfig`] names. Reading the rotated system address out of -//! its storage, and the pre-block call that applies a due change, belong to the pre-block -//! system calls. +//! bootstrap slots [`SequencerRegistryConfig`] names, before every block. 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. -use alloy_primitives::{address, Address}; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::format; + +use alloy_evm::block::BlockExecutionError; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use op_revm::OpHaltReason; +use revm::{ + context::{result::ResultAndState, Block, ContextTr}, + state::{Account, EvmState, EvmStorageSlot, TransactionId}, +}; use super::MEGA_SYSTEM_ADDRESS; -use crate::{HardforkParams, HardforkParamsError, MegaHardfork}; +use crate::{ + pre_block_call_gas_limit, ExternalEnvTypes, HardforkParams, HardforkParamsError, + MegaBlockExecutionError, MegaEvm, MegaHardfork, +}; +use storage_slots::{ + 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 = @@ -99,3 +119,304 @@ impl HardforkParams for SequencerRegistryConfig { Ok(()) } } + +/// 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 hands on 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. +/// +/// # 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`]): 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 stops it: a change the registry scheduled for this block must be applied in it. +pub fn transact_apply_pending_changes( + evm: &mut MegaEvm, +) -> Result, BlockExecutionError> +where + DB: alloy_evm::Database, + ExtEnvs: ExternalEnvTypes, +{ + let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); + let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit()); + let failed = |message| MegaBlockExecutionError::ApplyPendingChangesFailed { message }; + let outcome = evm + .transact_system_call_with_gas_limit( + alloy_eips::eip4788::SYSTEM_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + Bytes::from(calldata), + gas_limit, + ) + .map_err(|error| failed(format!("{error}")))?; + if !outcome.result.is_success() { + return Err(failed(format!("{:?}", outcome.result)).into()); + } + Ok(outcome) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MegaContext, MegaSpecId}; + use alloy_primitives::address; + use revm::{ + context::{BlockEnv, Transaction}, + database::{InMemoryDB, State}, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, + state::{AccountInfo, Bytecode}, + Database, DatabaseCommit, + }; + use storage_slots::{CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS}; + + 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 registry whose code reverts fails the call, and the block with it. + #[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"); + assert!(err.to_string().contains("reverted or halted"), "{err}"); + } +} diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index ebd82b26b..449649428 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,11 +29,11 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 20 | 11 | 9 | 16 | 4 | 0 | +| the pre-block system calls | 10 | 10 | 0 | 7 | 3 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **80** | **65** | **15** | **49** | **24** | **7** | +| **Total** | **70** | **64** | **6** | **40** | **23** | **7** | ## Tests ported in place @@ -331,13 +331,15 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 14 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. +These 24 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (1) | 1 | `tests/block/sequencer_registry.rs` | | `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | | `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | -| **Total** | | **14** | | +| `src/system/sequencer_registry.rs` | the pre-block system calls (9) | 9 | `src/system/sequencer_registry.rs` | +| **Total** | | **24** | | ## Tests retired after the inventory @@ -366,15 +368,6 @@ They are not counted above. | File | Test | Parked under | Reason | |---|---|---|---| -| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_no_pending` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_no_registry` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_sequencer_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_is_apply_pending_changes_due_system_address_due` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_errors_when_registry_reverts` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_respects_30m_floor` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_updates_and_clears_due_roles` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | -| `src/system/sequencer_registry.rs` | `test_transact_apply_pending_changes_uses_block_gas_limit` | the pre-block system calls | the pre-block system calls own transact_apply_pending_changes | | `block_executor/sequencer_registry.rs` | `test_admin_handoff_via_block_executor` | the pre-block system calls | the pre-block system calls own the two-step admin handoff | | `block_executor/sequencer_registry.rs` | `test_bootstrap_block_resolves_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | | `block_executor/sequencer_registry.rs` | `test_dual_change_in_same_block` | the pre-block system calls | the pre-block system calls own applying a pending rotation | @@ -403,11 +396,11 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/gas_detention.rs` | 2 | rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 1 | rewrite 1 (inspector support · D41) | -| `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/apply_pending_changes_gas_budget.rs` | 3 | rewrite 3 (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/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `src/system/sequencer_registry.rs` | 15 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes); keep 9 (the pre-block system calls · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/sequencer_registry.rs` | 6 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | 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 index a55e63e9c..b8b361ac7 100644 --- 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 @@ -165,66 +165,6 @@ fn assert_30m_system_call_oog(result: &ExecutionResult, system_c ); } -/// 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 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 dd9fdae11..3fb3c9aa7 100644 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -185,385 +185,4 @@ mod tests { 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/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 336a0fdfa..f2a06d15e 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -51,13 +51,16 @@ fn deploy_sources() -> [PreBlockStateSource; SYSTEM_CONTRACT_DEPLOY_COUNT] { expected_hashes().map(|(address, _)| PreBlockStateSource::SystemContract(address)) } +/// The two EIP calls, the seven deploys, then the read of the registry's pending changes, which +/// finds none due on these blocks. fn assert_pre_block_order(outcomes: &[(PreBlockStateSource, revm::state::EvmState)]) { - assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT); + assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 1); assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); for (i, source) in deploy_sources().iter().enumerate() { assert_eq!(outcomes[2 + i].0, *source); } + assert_eq!(outcomes[2 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::PendingChanges); } fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryConfig) { @@ -105,8 +108,8 @@ fn assert_registry_seed(state: &mut State, config: &SequencerReg } /// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the -/// registry's seeded slots. The executor's own observer sees the two EIP calls and then the -/// seven deploy states, in that order. +/// registry's seeded slots. The executor's own observer sees the two EIP calls, the seven deploy +/// states and the read of the registry's pending changes, in that order. #[test] fn test_the_first_block_deploys_every_system_contract() { let mut state = common::state(); @@ -144,7 +147,8 @@ fn test_the_first_block_deploys_every_system_contract() { } /// A second block changes nothing in the seven deploys: the executor's own observer reports -/// exactly seven read-only account entries, and the two EIP calls still precede them. +/// exactly seven read-only account entries, the two EIP calls still precede them and the read of +/// the registry's pending changes follows them. #[test] fn test_the_second_block_is_seven_read_only_entries() { let mut state = common::state(); diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index c6ba5ef9a..0a7c0f485 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -15,5 +15,6 @@ mod receipts; mod rules; mod salt; mod schedule; +mod sequencer_registry; mod state_gas; mod transfer_logs; 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..c2d9cd4ee --- /dev/null +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -0,0 +1,229 @@ +//! The `SequencerRegistry`'s role changes, applied before a block's transactions. +//! +//! The registry is deployed before every block. After the deploy, the executor reads whether a +//! role change is due in the block and, when one is, makes the `applyPendingChanges()` system +//! call. Each step's state reaches the pre-block observer before it is committed. + +use std::sync::{Arc, Mutex}; + +use alloy_evm::{block::BlockExecutor, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use mega_evm::{ + system::{ + storage_slots::{ + CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, + }, + MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + }, + test_utils::MemoryDatabase, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, MegaEvmFactory, + MegaHardforkConfig, PreBlockStateSource, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{database::State, inspector::NoOpInspector, state::EvmState, Database}; + +use crate::common::{self, pre_block_states, PreBlockLog, BLOCK_NUMBER}; + +/// 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, +>; + +fn word(address: Address) -> U256 { + U256::from_be_bytes(address.into_word().0) +} + +/// A database holding a deployed registry with `slots` on top of the bootstrap roles, and the +/// accounts the tests' transactions come from. +fn registry_with(slots: &[(U256, U256)]) -> MemoryDatabase { + let mut db = common::database(); + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE); + db.set_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + word(MEGA_SYSTEM_ADDRESS), + ); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER, word(common::SEQUENCER)); + 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, 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, 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<'_> { + 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, common::chain_spec(), OpAlloyReceiptBuilder::default()) +} + +/// Installs a recording observer on `executor` and returns the log it writes. +fn record(executor: &mut Executor<'_>) -> PreBlockLog { + let log = Arc::new(Mutex::new(Vec::new())); + let captured = Arc::clone(&log); + executor.set_pre_block_observer(Some(Box::new( + move |source: PreBlockStateSource, state: &EvmState| { + captured.lock().expect("pre-block observer").push((source, state.clone())); + }, + ))); + log +} + +/// The registry's own steps the observer received, in order: the deploy of it, the read of its +/// pending changes and the call that applies them. +fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { + pre_block_states(log) + .into_iter() + .filter(|(source, _)| { + matches!( + source, + PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS) | + PreBlockStateSource::PendingChanges | + PreBlockStateSource::ApplyPendingChanges + ) + }) + .collect() +} + +/// Starts a block at [`BLOCK_NUMBER`] over `state` and answers the registry's steps the observer +/// received. +fn start_block( + state: &mut State, + envs: Envs, + gas_limit: u64, +) -> Vec<(PreBlockStateSource, EvmState)> { + let mut executor = executor(state, envs, gas_limit); + let log = record(&mut executor); + executor.apply_pre_execution_changes().expect("the block starts"); + registry_steps(&log) +} + +/// 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") +} + +fn sources(steps: &[(PreBlockStateSource, EvmState)]) -> Vec { + steps.iter().map(|(source, _)| *source).collect() +} + +/// 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 observer receives +/// 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!( + sources(&steps), + [ + PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), + PreBlockStateSource::PendingChanges, + PreBlockStateSource::ApplyPendingChanges, + ] + ); + assert_eq!(envs.total_bucket_queries(), 0, "no pre-block step read a capacity"); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), 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 observer receives the read that found nothing +/// due, both pending slots and nothing else, read-only. On the chain's first block that read +/// finds the registry the deploy before it just created. +#[test] +fn test_a_block_with_nothing_due_makes_no_call() { + for db in [common::database(), registry_with(&[])] { + let mut state = State::builder().with_database(db).build(); + let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + assert_eq!( + sources(&steps), + [ + PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), + PreBlockStateSource::PendingChanges + ] + ); + let registry = &steps[1].1[&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_eq!(sources(&steps).last(), Some(&PreBlockStateSource::PendingChanges)); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), word(MEGA_SYSTEM_ADDRESS)); + assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), 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_eq!(sources(&steps).last(), Some(&PreBlockStateSource::ApplyPendingChanges)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), 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), word(MEGA_SYSTEM_ADDRESS)); +} From 88b8e899d030f707901816e11955d4daae140360 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:00:44 -0700 Subject: [PATCH 212/458] test: port the seventeen parked rows of the revert-class stop The legacy engine halted a transaction a limit stopped and rescued the gas it had left. The rows keep their scenarios and now expect the stop: a revert carrying MegaLimitExceeded, billed the intrinsic gas plus what ran, where a read of volatile data caps the compute, a body, a write or a hint crosses the data size, or a frame crosses its own budget alone. A read whose limit the transaction's gas cannot reach leaves an ordinary out-of-gas a halt. --- crates/mega-evm/tests/_pending/README.md | 29 +- .../mini_rex/access_beneficiary_balance.rs | 148 ------- .../_pending/mini_rex/block_env_gas_limit.rs | 239 ----------- .../mega-evm/tests/_pending/mini_rex/main.rs | 4 - .../tests/_pending/mini_rex/oracle.rs | 239 ----------- .../mini_rex/tx_data_and_kv_update_limit.rs | 375 ----------------- crates/mega-evm/tests/_pending/rex3/main.rs | 1 - .../tests/_pending/rex3/oracle_gas_limit.rs | 128 ------ .../_pending/rex4/beneficiary_detention.rs | 327 --------------- .../tests/_pending/rex4/frame_limits.rs | 205 ---------- .../tests/_pending/rex4/gas_detention.rs | 182 --------- crates/mega-evm/tests/_pending/rex4/main.rs | 3 - crates/mega-evm/tests/_pending/rex5/main.rs | 1 - .../_pending/rex5/oracle_hint_metering.rs | 209 ---------- crates/mega-evm/tests/satin/stops.rs | 378 +++++++++++++++++- crates/mega-evm/tests/system/oracle.rs | 32 ++ 16 files changed, 424 insertions(+), 2076 deletions(-) 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_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/oracle.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/rex3/oracle_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/beneficiary_detention.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/rex5/oracle_hint_metering.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4e3e1fe1e..e79a8807e 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,12 +28,11 @@ 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 | -| revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 34 | 22 | 12 | 30 | 4 | 0 | | system contract deployment | 11 | 5 | 6 | 11 | 0 | 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** | **94** | **76** | **18** | **63** | **24** | **7** | +| **Total** | **77** | **59** | **18** | **63** | **7** | **7** | ## Tests ported in place @@ -329,6 +328,23 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless | `src/sandbox/execution.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/rules.rs` | | **Total** | | **69** | | +## Tests ported by revert-class aborts + +These 17 rows run in a real test target now, adapted to the Satin API: a transaction-level limit — data size, KV updates, state gas or gas detention's compute limit — stops the transaction with a revert carrying `MegaLimitExceeded`, which settles like an EIP-8037 revert, where the legacy engine halted and rescued the remaining gas; a frame budget reverts its frame alone. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `mini_rex/access_beneficiary_balance.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | +| `mini_rex/block_env_gas_limit.rs` | revert-class aborts (3) | 3 | `tests/satin/stops.rs` | +| `mini_rex/oracle.rs` | revert-class aborts (3) | 3 | `tests/satin/stops.rs` | +| `mini_rex/tx_data_and_kv_update_limit.rs` | revert-class aborts (4) | 4 | `tests/satin/stops.rs` | +| `rex3/oracle_gas_limit.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | +| `rex4/beneficiary_detention.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | +| `rex4/frame_limits.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | +| `rex4/gas_detention.rs` | revert-class aborts (2) | 2 | `tests/satin/stops.rs` | +| `rex5/oracle_hint_metering.rs` | revert-class aborts (1) | 1 | `tests/system/oracle.rs` | +| **Total** | | **17** | | + ## Tests retired after the inventory These 21 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. @@ -382,21 +398,12 @@ 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` | 7 | keep 7 (the pre-block system calls) | | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | -| `mini_rex/access_beneficiary_balance.rs` | 1 | rewrite 1 (revert-class aborts · D48) | -| `mini_rex/block_env_gas_limit.rs` | 3 | rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `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` | 3 | rewrite 3 (revert-class aborts · D48) | -| `mini_rex/tx_data_and_kv_update_limit.rs` | 4 | rewrite 4 (revert-class aborts · D48) | -| `rex3/oracle_gas_limit.rs` | 1 | rewrite 1 (revert-class aborts · D48) | -| `rex4/beneficiary_detention.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | -| `rex4/gas_detention.rs` | 2 | rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 1 | rewrite 1 (inspector support · D41) | | `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/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | 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 6d6250f1c..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs +++ /dev/null @@ -1,148 +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 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_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs deleted file mode 100644 index 5ddbd3ab9..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs +++ /dev/null @@ -1,239 +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_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_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_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/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs index e90c00b83..9033fa5b9 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -1,9 +1,5 @@ //! 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 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 5227bde08..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ /dev/null @@ -1,239 +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] -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 - ); -} 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 f4fce5a89..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs +++ /dev/null @@ -1,375 +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() -} - -// ============================================================================ -// SPEC COMPARISON TESTS -// ============================================================================ - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -/// 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 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)); -} - -// ============================================================================ -// STORAGE DEDUPLICATION TESTS -// ============================================================================ - -// ============================================================================ -// 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))); -} - -// ============================================================================ -// GAS PRESERVATION TESTS -// ============================================================================ - -// ============================================================================ -// TRACKER MIGRATION COVERAGE TESTS -// ============================================================================ - -/// 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/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs index e197703b0..edb4e4298 100644 --- a/crates/mega-evm/tests/_pending/rex3/main.rs +++ b/crates/mega-evm/tests/_pending/rex3/main.rs @@ -1,4 +1,3 @@ //! 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 c9c6e66a5..000000000 --- a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs +++ /dev/null @@ -1,128 +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 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"); -} - -// ============================================================================= -// Rex3: Additional oracle SLOAD detention tests -// ============================================================================= 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 827ee74a4..000000000 --- a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs +++ /dev/null @@ -1,327 +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 -// ============================================================================ - -// ============================================================================ -// TEST 1b: CALL to beneficiary where child reverts — detention persists -// ============================================================================ - -// ============================================================================ -// TEST 2: STATICCALL to beneficiary triggers detention -// ============================================================================ - -// ============================================================================ -// TEST 3: DELEGATECALL to beneficiary triggers detention -// ============================================================================ - -// ============================================================================ -// TEST 4: CALLCODE to beneficiary triggers detention -// ============================================================================ - -// ============================================================================ -// TEST 5: Caller is beneficiary — eager detention from TX start -// ============================================================================ - -// ============================================================================ -// TEST 5b: Caller is beneficiary — pre-REX4 no eager detention -// ============================================================================ - -// ============================================================================ -// TEST 6: Recipient is beneficiary — eager detention from TX start -// ============================================================================ - -// ============================================================================ -// TEST 6b: Recipient is beneficiary — pre-REX4 no eager detention -// ============================================================================ - -// ============================================================================ -// TEST 7: SELFBALANCE in beneficiary contract triggers detention (integration) -// ============================================================================ - -// ============================================================================ -// TEST 8: CALL to non-beneficiary does NOT trigger detention -// ============================================================================ - -// ============================================================================ -// TEST 9: SELFBALANCE in non-beneficiary contract does NOT trigger detention -// ============================================================================ - -// ============================================================================ -// TEST 10: disableVolatileDataAccess + SELFBALANCE at beneficiary reverts -// ============================================================================ - -// ============================================================================ -// 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 -// ============================================================================ 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 717345d49..000000000 --- a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs +++ /dev/null @@ -1,205 +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_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"); -} - -// ============================================================================ -// KV UPDATE PER-FRAME LIMITS -// ============================================================================ - -// ============================================================================ -// 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 49bfec00e..000000000 --- a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs +++ /dev/null @@ -1,182 +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 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: 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" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index d8b53b49b..e62746d5f 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -1,9 +1,6 @@ //! Tests for `Rex4` hardfork features. -mod beneficiary_detention; mod create_safety; mod eip7702_delegation_cycle; -mod frame_limits; -mod gas_detention; mod intrinsic_limit_bypass; mod storage_call_stipend; diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index f0ba19ba8..1136abb13 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 eip7702_metering; -mod oracle_hint_metering; mod pre_block_system_calls; 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 4ff47b648..000000000 --- a/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs +++ /dev/null @@ -1,209 +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 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", - ); -} - -/// 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() -} diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 0593433cb..2f4105902 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -18,7 +18,10 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP}, + 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, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, @@ -26,8 +29,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, - SSTORE, TIMESTAMP, + ADD, BALANCE, CALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, + RETURNDATASIZE, REVERT, SLOAD, SSTORE, TIMESTAMP, }, context::result::ExecutionResult, interpreter::{ @@ -39,7 +42,7 @@ use revm::{ use crate::{ common::{call, call_with_data}, - detention::{context, work}, + detention::{context, work, BENEFICIARY}, }; const CALLER: Address = address!("0000000000000000000000000000000000500000"); @@ -725,3 +728,370 @@ fn test_the_transactions_own_frame_that_halts_burns_its_regular_gas() { ); } } + +/* ---------- 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 a thousand fresh slots, so the +/// writes spend nothing but compute from the frame's regular gas. +const ROOMY: u64 = 1_000_000_000; + +/// Appends writes of the fresh slots `1..=1,000`: 22,100,000 of compute, past the cap. +fn thousand_writes(code: BytecodeBuilder) -> BytecodeBuilder { + (1..=1_000_u64).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: a revert +/// carrying `MegaLimitExceeded(2, limit)` for the limit the reads set, billed the intrinsic gas +/// plus that limit and nothing of the gas the transaction had left. Returns the limit and what the +/// transaction read. +fn assert_detention_stop( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, +) -> (u64, mega_evm::VolatileDataAccess) { + let intrinsic = intrinsic(ROOMY); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, ROOMY)).unwrap(); + let detention = evm.ctx().detention(); + let limit = detention.compute_limit().expect("a read set a limit"); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false, + }; + assert!(!outcome.result.is_halt(), "a revert, not a halt: {:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + limit); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + limit); + assert_eq!(outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining); + assert!(outcome.result.logs().is_empty()); + (limit, detention.accessed()) +} + +/// A frame that reads the block's timestamp and then writes a thousand fresh slots stops at the +/// limit the read set, and bills that limit: the transaction's own frame, a child whose caller +/// never runs on, 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 = thousand_writes(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + 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 a thousand fresh slots stops the +/// transaction: its caller's code after the call never runs. +#[test] +fn test_nested_call_block_env_access_child_oog() { + let child = thousand_writes(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()); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + 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 a +/// thousand 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, thousand_writes(parent).stop().build()) + .account_code(B, child.stop().build()); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); +} + +/// A call to the Oracle that reads its storage, then a thousand fresh slots: the transaction stops +/// at the compute at the read plus the Oracle's cap, the spec's 20,000,000, and bills it. +#[test] +fn test_an_oracle_read_holds_the_transaction_to_its_cap() { + let code = thousand_writes(call_oracle(BytecodeBuilder::default(), None)); + let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + 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 limit, not the gas limit. +#[test] +fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { + let code = thousand_writes(call_oracle(BytecodeBuilder::default(), Some(0xffff))); + let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); + assert_detention_stop(db, EvmTxRuntimeLimits::default()); +} + +/// A contract that calls one that reads the Oracle's storage and then writes a thousand fresh +/// slots: the stop reaches the outer contract, whose reads after the call never run. +#[test] +fn test_parent_runs_out_of_gas_after_oracle_access() { + let middle = thousand_writes(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()); + let (_, accessed) = assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default()); + 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 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, thousand_writes(code).stop().build()); + let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); + let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits); + 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 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 (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + 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, "{}", detained.gas.gas_used); +} + +/// A body over the transaction's data-size limit stops the transaction before its first frame: a +/// revert carrying the stop, not a halt, billed the intrinsic gas alone. +#[test] +fn test_data_limit_just_exceed() { + let limit = TX_BODY_SIZE - 1; + let db = || MemoryDatabase::default().account_code(A, writer(1)); + let outcome = + execute(db(), EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit), BELOW); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: TX_BODY_SIZE, + frame_local: false, + }; + assert!(!outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert_eq!(outcome.gas.gas_used, intrinsic(BELOW).gas.gas_used, "nothing ran"); +} + +/// A library's write, one call down, crosses a limit one byte above the body: the stop is a +/// revert, and the transaction is billed what ran. +#[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); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: TX_BODY_SIZE + WRITE_RECORD_SIZE, + frame_local: false, + }; + assert!(!outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert!(outcome.gas.gas_used < 200_000, "the stop burns nothing: {}", outcome.gas.gas_used); +} + +/// 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(); + assert!(!outcome.result.is_halt(), "{:?}", outcome.result); + assert!(matches!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, frame_local: false, .. }) + )); + 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"); +} + +/// Data size is held before write records: a body that crosses the data-size limit is its stop +/// whatever the KV limit, and so is a write that crosses both. +#[test] +fn test_check_limit_priority_data_size_before_kv_update() { + let db = || MemoryDatabase::default().account_code(A, writer(1)); + let both = |data_size: u64| { + EvmTxRuntimeLimits::default().with_tx_data_size_limit(data_size).with_tx_kv_update_limit(0) + }; + for (data_size, used) in [ + (1, TX_BODY_SIZE), + (TX_BODY_SIZE + LOG_BASE_SIZE, TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE), + ] { + let outcome = execute(db(), both(data_size), BELOW); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: data_size, + used, + frame_local: false, + }), + "data size {data_size}" + ); + } +} + +/// A transaction detained from its start — its sender is the block's beneficiary — whose body +/// crosses the data-size limit is the data-size stop, billed its intrinsic gas: detention adds +/// nothing to what it pays. +#[test] +fn test_detention_plus_intrinsic_data_size_overflow() { + let db = + || MemoryDatabase::default().account_code(A, BytecodeBuilder::default().stop().build()); + let run = |limits| { + MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(call(BENEFICIARY, A, U256::ZERO, ROOMY)) + .unwrap() + }; + let unlimited = run(EvmTxRuntimeLimits::default()); + let stopped = run(EvmTxRuntimeLimits::default().with_tx_data_size_limit(100)); + assert!(!stopped.result.is_halt(), "{:?}", stopped.result); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: TX_BODY_SIZE, + frame_local: false, + }) + ); + assert_eq!(stopped.gas, unlimited.gas, "the intrinsic gas alone, the reservoir back"); +} + +/// The transaction's own frame crossing its frame budget — a frame cap of a hundred records' bytes, +/// crossed by the 101st write — reverts it alone: a revert, not a halt, and no latch. The body is +/// all the transaction keeps. +#[test] +fn test_data_size_top_level_exceed_is_frame_local_revert() { + let cap = 100 * WRITE_RECORD_SIZE; + let code = (1..=101_u64).fold(BytecodeBuilder::default(), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + let outcome = execute(db, EvmTxRuntimeLimits::default().with_frame_data_size_limit(cap), BELOW); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: cap, + used: 0, + frame_local: true, + }; + assert!(!outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); +} diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 43dd43aab..ef6d32c0c 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -563,6 +563,38 @@ fn test_consecutive_hints_add_up_on_the_transaction() { )); } +/// A contract's hint whose payload crosses the transaction's data-size limit is not forwarded, and +/// the crossing stops the transaction with a revert carrying the stop, not a halt: the contract +/// never runs on to return its 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_transaction() { + const LIMIT: u64 = 2_048; + let data = send_hint(&[0_u8; 4_096]); + let code = return_status(call_oracle(BytecodeBuilder::default(), &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(LIMIT), + ); + + assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: LIMIT, + used: nested_hint(data.len() as u64), + frame_local: false, + }; + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert!(!outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&stop.revert_data()), "the stop, not the status"); + assert!( + outcome.gas.gas_used < crate::common::GAS_LIMIT / 10, + "the stop burns nothing: {}", + outcome.gas.gas_used + ); +} + /// A frame that switched its volatile-data access off sends no hint: `sendHint` still runs and /// succeeds, and nothing reaches the service. #[test] From bed0112cd7229835ca871d00b0da8db7c5bf59e6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:01:55 -0700 Subject: [PATCH 213/458] docs: say how a stop unwinds whatever produced a frame's result The latch rewrites every result above the crossing, an inspector's halt included, and nothing is rescued on a stop because nothing was taken. The crate README states the stop the four limits share, and the module table no longer lists the revert-class stop as a mechanism still to come. --- AGENTS.md | 5 ++++- crates/mega-evm/README.md | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index ca65f2de7..ada9a783f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,7 +102,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 (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; inspector support | +| `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 rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | | `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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | @@ -302,6 +302,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer The state-gas limit's entry of what is held outside each frame is pushed and popped with the lane. - **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. + The rewrite takes every result, whatever produced it — revm, an interceptor, or an inspector that turned it into a success or a halt (`AdditionalLimit::apply_latch`): no frame runs an instruction under the latch, so a halt there can only be an inspector's. + 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 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 state gas or records would cross it are taken back before the first frame. The one exception is the state gas an opcode charges upfront for the account the frame it starts adds: revm gives it back for a frame it refuses, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts. @@ -310,6 +312,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. 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. + `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result. - **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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 1010f233b..890ad772b 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -137,6 +137,13 @@ 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 transaction-level limit — data size, KV updates, state gas, gas detention's compute limit — stops a transaction the same way. +The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, and every frame above returns the same revert without running another instruction, whatever produced its result: revm, an interceptor, or an inspector that rewrites it into a success or a halt. +The transaction settles like any EIP-8037 revert: it 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. +A frame budget reverts its frame alone, and its caller runs on; 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 at the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result. + ## Quick start ```rust,ignore From 9f2f291868167999a3822813384a443209143d20 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:05:16 -0700 Subject: [PATCH 214/458] feat(block): read the live system address out of the SequencerRegistry --- crates/mega-evm/src/block/executor.rs | 69 +- crates/mega-evm/src/evm/context.rs | 22 +- crates/mega-evm/src/evm/execution.rs | 9 +- .../mega-evm/src/system/sequencer_registry.rs | 131 +++- crates/mega-evm/src/system/tx.rs | 13 +- crates/mega-evm/tests/_pending/README.md | 22 +- .../block_executor/sequencer_registry.rs | 620 ------------------ .../_pending/src/system/sequencer_registry.rs | 188 ------ crates/mega-evm/tests/block/deploy.rs | 11 +- .../tests/block/sequencer_registry.rs | 245 ++++++- 10 files changed, 457 insertions(+), 873 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 714b39a61..8a6ab5b8e 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -52,22 +52,23 @@ //! # The pre-block observer //! //! Each pre-block step — the EIP-2935 call, the EIP-4788 call, every system-contract deploy, the -//! read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` call — -//! produces an [`EvmState`] that this executor commits. alloy-evm 0.36 re-exports revm's -//! `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on [`BlockExecutor`] and no -//! source tag, so this crate names the step ([`PreBlockStateSource`]) and carries an optional -//! [`PreBlockStateObserver`]. Every pre-block state is handed to the observer **before** it is -//! committed, in execution order. The sequence is the witness a stateless client needs: revm -//! drops untouched accounts from the committed transition, so a caller that only saw the -//! database after the commit would miss the read-only deploy entries of a later block. +//! read of the `SequencerRegistry`'s pending changes, the `applyPendingChanges()` call and the read +//! of the live system address — produces an [`EvmState`] that this executor commits. alloy-evm 0.36 +//! re-exports revm's `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on +//! [`BlockExecutor`] and no source tag, so this crate names the step ([`PreBlockStateSource`]) and +//! carries an optional [`PreBlockStateObserver`]. Every pre-block state is handed to the observer +//! **before** it is committed, in execution order. The sequence is the witness a stateless client +//! needs: revm drops untouched accounts from the committed transition, so a caller that only saw +//! the database after the commit would miss the read-only deploy entries of a later block. //! //! # The pre-block system calls //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 //! and EIP-4788 calls, deploys the system contracts and the EIP-7997 factory (idempotent), 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. +//! applies a role change the `SequencerRegistry` has due in this block and reads the live system +//! address out of it ([`MegaContext::system_address`]). 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. #[cfg(not(feature = "std"))] use alloc as std; @@ -106,8 +107,9 @@ use crate::{ block::eips, estimated_da_size, system::{ - is_apply_pending_changes_due, system_contract_specs, transact_apply_pending_changes, - transact_deploy, SequencerRegistryConfig, SystemContractDeployError, + is_apply_pending_changes_due, resolve_system_address, system_contract_specs, + transact_apply_pending_changes, transact_deploy, SequencerRegistryConfig, + SystemContractDeployError, }, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, @@ -205,6 +207,18 @@ pub enum MegaBlockExecutionError { /// What the call ended with: its result, or the error that stopped it. message: String, }, + /// The live system address cannot be read: the `SequencerRegistry` has no account. + MissingSequencerRegistry, + /// The live system address cannot be read: the `SequencerRegistry` holds other code than + /// the contract this engine deploys. + SequencerRegistryCodeMismatch { + /// The hash this engine deploys. + expected: B256, + /// The hash in state. + found: B256, + }, + /// The `SequencerRegistry` holds a zero system address. + ZeroSystemAddress, } impl fmt::Display for MegaBlockExecutionError { @@ -244,6 +258,16 @@ impl fmt::Display for MegaBlockExecutionError { f, "the SequencerRegistry applyPendingChanges() pre-block call reverted or halted: {message}" ), + Self::MissingSequencerRegistry => { + f.write_str("the SequencerRegistry does not exist; the system address cannot be read") + } + Self::SequencerRegistryCodeMismatch { expected, found } => write!( + f, + "SequencerRegistry code hash mismatch: expected {expected}, found {found}; the system address cannot be read" + ), + Self::ZeroSystemAddress => { + f.write_str("the SequencerRegistry holds a zero system address") + } } } } @@ -273,6 +297,8 @@ pub enum PreBlockStateSource { PendingChanges, /// The `SequencerRegistry.applyPendingChanges()` system call. ApplyPendingChanges, + /// The read of the live system address out of the `SequencerRegistry`. + SystemAddress, } /// Receives each pre-block [`EvmState`] before the executor commits it. @@ -537,10 +563,11 @@ where /// Runs what a block does before its transactions. /// /// In order: the admission gate, the reset of the block-hash record, the EIP-2935 and - /// EIP-4788 pre-block calls, the system-contract deploys, and the `SequencerRegistry`'s due - /// role changes. Each step's state is handed to the pre-block observer and then committed - /// here rather than inside its helper, so a witness generator sees every step's read and - /// write set. The sequence the observer receives is the witness a stateless client needs. + /// EIP-4788 pre-block calls, the system-contract deploys, the `SequencerRegistry`'s due role + /// changes, and the read of the live system address. Each step's state is handed to the + /// pre-block observer and then committed here rather than inside its helper, so a witness + /// generator sees every step's read and write set. The sequence the observer receives is + /// the witness a stateless client needs. /// /// 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 @@ -557,7 +584,9 @@ where /// The registry's role changes come after the deploy, which is what puts the registry in /// state on the chain's first block. Its pending slots are read and handed on 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. + /// the same pre-block budget, refusing the block if it does not succeed. The system address + /// is read last, so a rotation due in this block governs this block's system-address + /// transactions; the EVM holds it for every transaction the block runs. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; @@ -616,6 +645,10 @@ where self.deliver_pre_block(PreBlockStateSource::ApplyPendingChanges, state); } + let (system_address, read) = resolve_system_address(self.evm.db_mut())?; + self.deliver_pre_block(PreBlockStateSource::SystemAddress, read); + self.evm.ctx_mut().set_system_address(system_address); + Ok(()) } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 21986ff16..473b7ace6 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -59,6 +59,8 @@ pub struct MegaContext MegaContext { bucket_multipliers: BucketMultipliers::default(), system_originated: false, prices_history: true, + system_address: MEGA_SYSTEM_ADDRESS, keyless_call: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, @@ -296,6 +299,23 @@ impl MegaContext { self.system_originated } + /// The address a system-address transaction must be sent from: a legacy call from it to a + /// whitelisted contract is the protocol's own, promoted to a deposit (see the + /// [`system`](crate::system) module). + /// + /// Block execution reads it out of the `SequencerRegistry` before every block's transactions, + /// once a rotation due in the block has been applied, so it is the live one for the block. A + /// context no block has been started on uses [`MEGA_SYSTEM_ADDRESS`]. + pub const fn system_address(&self) -> Address { + self.system_address + } + + /// Sets the address system-address transactions come from, for every transaction from now + /// on. Block execution sets the one it read out of the `SequencerRegistry`. + pub(crate) const fn set_system_address(&mut self, address: Address) { + self.system_address = address; + } + /// Whether the running (or last) transaction pays history gas for the bytes it appends. /// /// Three kinds of transaction pay none: a deposit, a transaction the protocol itself produced @@ -316,7 +336,7 @@ impl MegaContext { /// Prepares the common execution layer for a new transaction. Every transaction entry point /// of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. pub(crate) fn on_new_tx(&mut self) { - let system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); + let system_originated = system::is_system_originated(&self.inner.tx, self.system_address); self.prepare(system_originated); } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index c3ef2ed06..4696a0009 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -52,7 +52,6 @@ use crate::{ system::{ is_deposit_like_transaction, keyless::{self, Rewrite}, - MEGA_SYSTEM_ADDRESS, }, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, @@ -159,10 +158,8 @@ where /// 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, - )?; + let system_address = evm.ctx_ref().system_address(); + crate::system::validate_and_promote::<_, _, Self::Error>(evm.ctx_mut(), system_address)?; self.op.validate_env(evm) } @@ -1270,7 +1267,7 @@ fn unbuilt_first_frame( fn deposit_creates_caller( ctx: &mut MegaContext, ) -> Result { - if !is_deposit_like_transaction(ctx.tx(), MEGA_SYSTEM_ADDRESS) { + if !is_deposit_like_transaction(ctx.tx(), ctx.system_address()) { return Ok(false); } let caller = ctx.tx().caller(); diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index f55457f52..597e84384 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -11,6 +11,8 @@ //! 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. +//! Then it reads the live system address out of the registry ([`resolve_system_address`]), which +//! the block's system-address transactions must come from. #[cfg(not(feature = "std"))] use alloc as std; @@ -31,7 +33,7 @@ use crate::{ MegaBlockExecutionError, MegaEvm, MegaHardfork, }; use storage_slots::{ - PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, + CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }; @@ -56,7 +58,7 @@ pub const PLACEHOLDER_MIN_ROTATION_DELAY: u64 = 10; /// Bootstrap configuration for the `SequencerRegistry`, attached to Satin via [`HardforkParams`]. /// /// These values seed the registry's storage on a fresh deploy. After that the live roles are -/// whatever the contract holds; rotating them is a later pre-block system call. The contract +/// whatever the contract holds, rotated by the `applyPendingChanges()` pre-block call. The contract /// has no setter for `_minRotationDelay`, so a matching-code registry cannot be repaired later /// through this helper: the delay must be seeded here, and it must not be zero. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -215,6 +217,45 @@ where Ok(outcome) } +/// Reads the live system address out of the registry: the address a system-address transaction +/// must be sent from in the block. Also answers the read, as a read-only entry of the registry's +/// account, which the caller hands on as a witness. +/// +/// It is read once the block's pre-block changes are committed — the registry deployed and a due +/// rotation applied — so a rotation takes effect at its activation block. +/// +/// # Errors +/// +/// The deploy before it guarantees what is checked here, so each of these is a state no Satin +/// block leaves behind, and the block is refused rather than run against the wrong authority: +/// [`MegaBlockExecutionError::MissingSequencerRegistry`] when the registry has no account, +/// [`MegaBlockExecutionError::SequencerRegistryCodeMismatch`] when it holds other code than +/// [`SEQUENCER_REGISTRY_CODE`], and [`MegaBlockExecutionError::ZeroSystemAddress`] when its +/// `_currentSystemAddress` is zero. A database error is the database's. +pub fn resolve_system_address( + db: &mut DB, +) -> Result<(Address, EvmState), BlockExecutionError> { + let info = db + .basic(SEQUENCER_REGISTRY_ADDRESS) + .map_err(BlockExecutionError::other)? + .ok_or(MegaBlockExecutionError::MissingSequencerRegistry)?; + if info.code_hash != SEQUENCER_REGISTRY_CODE_HASH { + return Err(MegaBlockExecutionError::SequencerRegistryCodeMismatch { + expected: SEQUENCER_REGISTRY_CODE_HASH, + found: info.code_hash, + } + .into()); + } + let mut registry = Account::from(info); + let current = + read_slot(db, &mut registry, CURRENT_SYSTEM_ADDRESS).map_err(BlockExecutionError::other)?; + if current.is_zero() { + return Err(MegaBlockExecutionError::ZeroSystemAddress.into()); + } + let address = Address::from_word(current.into()); + Ok((address, EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)]))) +} + #[cfg(test)] mod tests { use super::*; @@ -227,7 +268,7 @@ mod tests { state::{AccountInfo, Bytecode}, Database, DatabaseCommit, }; - use storage_slots::{CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS}; + use storage_slots::CURRENT_SEQUENCER; const NEXT_SYSTEM_ADDRESS: Address = address!("0x1111111111111111111111111111111111111111"); const NEXT_SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); @@ -419,4 +460,88 @@ mod tests { .expect_err("a reverting registry fails closed"); assert!(err.to_string().contains("reverted or halted"), "{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 + } + + fn resolve(db: &mut InMemoryDB) -> Result<(Address, EvmState), BlockExecutionError> { + resolve_system_address(&mut State::builder().with_database(db).build()) + } + + /// A registry holding the code this engine deploys resolves to the address it stores. + #[test] + fn test_resolve_expects_the_deployed_code_hash() { + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let (address, _) = resolve(&mut db).expect("the deployed registry resolves"); + assert_eq!(address, NEXT_SYSTEM_ADDRESS); + } + + /// A registry still holding the legacy engine's first bytecode is not the one this engine + /// deploys, and the read refuses it. + #[test] + fn test_resolve_rejects_the_v1_code_hash() { + use mega_system_contracts::sequencer_registry::{V1_0_0_CODE, V1_0_0_CODE_HASH}; + let mut db = registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let err = resolve(&mut db).expect_err("the v1 registry fails closed"); + assert!(err.to_string().contains("code hash mismatch"), "{err}"); + assert!(err.to_string().contains(&V1_0_0_CODE_HASH.to_string()), "{err}"); + } + + /// The read answers the stored address and a witness holding the registry's account and the + /// one slot it read, read-only. + #[test] + fn test_resolve_returns_stored_system_address_with_witness() { + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let (address, witness) = resolve(&mut db).unwrap(); + assert_eq!(address, NEXT_SYSTEM_ADDRESS); + + assert_eq!(witness.len(), 1); + let registry = &witness[&SEQUENCER_REGISTRY_ADDRESS]; + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + 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_changed()); + assert_eq!(slot.present_value(), word(NEXT_SYSTEM_ADDRESS)); + assert_eq!(slot.original_value(), slot.present_value()); + } + + /// A registry whose system address is zero is refused. + #[test] + fn test_resolve_zero_slot_errors() { + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, None); + let err = resolve(&mut db).expect_err("a zero system address fails closed"); + assert!(err.to_string().contains("zero system address"), "{err}"); + } + + /// A registry with no account is refused. + #[test] + fn test_resolve_missing_registry_errors() { + let err = resolve(&mut InMemoryDB::default()).expect_err("no registry fails closed"); + assert!(err.to_string().contains("does not exist"), "{err}"); + } + + /// A registry holding foreign code is refused, whatever it stores. + #[test] + fn test_resolve_wrong_code_hash_errors() { + let mut db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); + let err = resolve(&mut db).expect_err("foreign code fails closed"); + assert!(err.to_string().contains("code hash mismatch"), "{err}"); + } } diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index 6a0427ce3..f7368a689 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -36,12 +36,15 @@ use crate::{ MegaContext, }; -/// The address the sequencer sends the protocol's own transactions from. +/// The address the sequencer sends the protocol's own transactions from, until the +/// `SequencerRegistry` says otherwise. /// -/// 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 transaction from the system address is executed as a deposit: no signature, no nonce check +/// of op-revm's own and no fee. Which address that is can be rotated through the registry, and +/// block execution reads the live one out of it before every block +/// ([`MegaContext::system_address`](crate::MegaContext::system_address)). This is the address a +/// context uses before any block has been started on it, and the one the unknown-chain +/// placeholder schedule seeds the registry with. pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); /// The contracts a system-address transaction may call. It may call nothing else and create diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 449649428..4e643902b 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,11 +29,11 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 10 | 10 | 0 | 7 | 3 | 0 | -| system contract deployment | 11 | 5 | 6 | 11 | 0 | 0 | +| the pre-block system calls | 3 | 3 | 0 | 0 | 3 | 0 | +| system contract deployment | 5 | 5 | 0 | 5 | 0 | 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** | **70** | **64** | **6** | **40** | **23** | **7** | +| **Total** | **57** | **57** | **0** | **27** | **23** | **7** | ## Tests ported in place @@ -331,15 +331,16 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 24 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. +These 37 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `block_executor/sequencer_registry.rs` | the pre-block system calls (7) | 7 | `tests/block/sequencer_registry.rs` | | `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (1) | 1 | `tests/block/sequencer_registry.rs` | | `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | | `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | -| `src/system/sequencer_registry.rs` | the pre-block system calls (9) | 9 | `src/system/sequencer_registry.rs` | -| **Total** | | **24** | | +| `src/system/sequencer_registry.rs` | the pre-block system calls (9), system contract deployment (6) | 15 | `src/system/sequencer_registry.rs` | +| **Total** | | **37** | | ## Tests retired after the inventory @@ -368,13 +369,6 @@ They are not counted above. | File | Test | Parked under | Reason | |---|---|---|---| -| `block_executor/sequencer_registry.rs` | `test_admin_handoff_via_block_executor` | the pre-block system calls | the pre-block system calls own the two-step admin handoff | -| `block_executor/sequencer_registry.rs` | `test_bootstrap_block_resolves_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | -| `block_executor/sequencer_registry.rs` | `test_dual_change_in_same_block` | the pre-block system calls | the pre-block system calls own applying a pending rotation | -| `block_executor/sequencer_registry.rs` | `test_pending_not_yet_due_is_noop` | the pre-block system calls | the pre-block system calls own applying a pending rotation | -| `block_executor/sequencer_registry.rs` | `test_sequencer_change_does_not_affect_system_address` | the pre-block system calls | the pre-block system calls own applying a pending rotation | -| `block_executor/sequencer_registry.rs` | `test_system_address_change` | the pre-block system calls | the pre-block system calls own applying a pending rotation | -| `block_executor/sequencer_registry.rs` | `test_system_tx_uses_resolved_system_address` | the pre-block system calls | the pre-block system calls own resolving the live system address | ## Files @@ -383,7 +377,6 @@ Each cell lists `disposition count (mechanism · decision)`. | File | Tests | Owners | |---|---:|---| | `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | -| `block_executor/sequencer_registry.rs` | 7 | keep 7 (the pre-block system calls) | | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | | `mini_rex/access_beneficiary_balance.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `mini_rex/block_env_gas_limit.rs` | 3 | rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | @@ -403,4 +396,3 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `src/system/sequencer_registry.rs` | 6 | keep 6 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | 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/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs deleted file mode 100644 index 3fb3c9aa7..000000000 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ /dev/null @@ -1,188 +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()) - } - - #[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")); - } -} diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index f2a06d15e..898cd6f18 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -52,15 +52,16 @@ fn deploy_sources() -> [PreBlockStateSource; SYSTEM_CONTRACT_DEPLOY_COUNT] { } /// The two EIP calls, the seven deploys, then the read of the registry's pending changes, which -/// finds none due on these blocks. +/// finds none due on these blocks, and the read of the system address. fn assert_pre_block_order(outcomes: &[(PreBlockStateSource, revm::state::EvmState)]) { - assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 1); + assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 2); assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); for (i, source) in deploy_sources().iter().enumerate() { assert_eq!(outcomes[2 + i].0, *source); } assert_eq!(outcomes[2 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::PendingChanges); + assert_eq!(outcomes[3 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::SystemAddress); } fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryConfig) { @@ -109,7 +110,7 @@ fn assert_registry_seed(state: &mut State, config: &SequencerReg /// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the /// registry's seeded slots. The executor's own observer sees the two EIP calls, the seven deploy -/// states and the read of the registry's pending changes, in that order. +/// states and the two reads of the registry, in that order. #[test] fn test_the_first_block_deploys_every_system_contract() { let mut state = common::state(); @@ -147,8 +148,8 @@ fn test_the_first_block_deploys_every_system_contract() { } /// A second block changes nothing in the seven deploys: the executor's own observer reports -/// exactly seven read-only account entries, the two EIP calls still precede them and the read of -/// the registry's pending changes follows them. +/// exactly seven read-only account entries, the two EIP calls still precede them and the two +/// reads of the registry follow them. #[test] fn test_the_second_block_is_seven_read_only_entries() { let mut state = common::state(); diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index c2d9cd4ee..cd21cc2e4 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -1,25 +1,30 @@ -//! The `SequencerRegistry`'s role changes, applied before a block's transactions. +//! The `SequencerRegistry`'s role changes, applied before a block's transactions, and the live +//! system address read out of it. //! //! The registry is deployed before every block. After the deploy, the executor reads whether a //! role change is due in the block and, when one is, makes the `applyPendingChanges()` system -//! call. Each step's state reaches the pre-block observer before it is committed. +//! call; then it reads the system address the block's system-address transactions must come +//! from. Each step's state reaches the pre-block observer before it is committed. use std::sync::{Arc, Mutex}; +use alloy_consensus::transaction::Recovered; use alloy_evm::{block::BlockExecutor, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{address, Address, Bytes, B256, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ system::{ storage_slots::{ - CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_ADMIN, PENDING_SEQUENCER, + PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }, - MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + IOracle, ISequencerRegistry, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, }, test_utils::MemoryDatabase, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, MegaEvmFactory, - MegaHardforkConfig, PreBlockStateSource, TestExternalEnvs, MIN_BUCKET_SIZE, + MegaHardforkConfig, MegaTxEnvelope, PreBlockStateSource, TestExternalEnvs, MIN_BUCKET_SIZE, }; use revm::{database::State, inspector::NoOpInspector, state::EvmState, Database}; @@ -93,6 +98,16 @@ fn envs_at(m: u64) -> Envs { /// 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); @@ -102,7 +117,7 @@ fn executor(state: &mut State, envs: Envs, gas_limit: u64) -> Ex Bytes::new(), BlockLimits::no_limits(), ); - MegaBlockExecutor::new(evm, ctx, common::chain_spec(), OpAlloyReceiptBuilder::default()) + MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } /// Installs a recording observer on `executor` and returns the log it writes. @@ -118,7 +133,7 @@ fn record(executor: &mut Executor<'_>) -> PreBlockLog { } /// The registry's own steps the observer received, in order: the deploy of it, the read of its -/// pending changes and the call that applies them. +/// pending changes, the call that applies them and the read of the system address. fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { pre_block_states(log) .into_iter() @@ -127,7 +142,8 @@ fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { source, PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS) | PreBlockStateSource::PendingChanges | - PreBlockStateSource::ApplyPendingChanges + PreBlockStateSource::ApplyPendingChanges | + PreBlockStateSource::SystemAddress ) }) .collect() @@ -143,9 +159,24 @@ fn start_block( let mut executor = executor(state, envs, gas_limit); let log = record(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!( + executor.evm().ctx().system_address(), + Address::from_word(slot_of(®istry_steps(&log), CURRENT_SYSTEM_ADDRESS).into()), + "the EVM holds the system address the registry read found", + ); registry_steps(&log) } +/// The value the last registry step read or wrote for `slot`. +fn slot_of(steps: &[(PreBlockStateSource, EvmState)], slot: U256) -> U256 { + steps + .iter() + .rev() + .find_map(|(_, state)| state.get(&SEQUENCER_REGISTRY_ADDRESS)?.storage.get(&slot)) + .map(|slot| slot.present_value()) + .expect("a registry step touched the slot") +} + /// 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") @@ -172,6 +203,7 @@ fn test_a_due_change_is_applied_under_a_crowded_bucket() { PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), PreBlockStateSource::PendingChanges, PreBlockStateSource::ApplyPendingChanges, + PreBlockStateSource::SystemAddress, ] ); assert_eq!(envs.total_bucket_queries(), 0, "no pre-block step read a capacity"); @@ -192,7 +224,8 @@ fn test_a_block_with_nothing_due_makes_no_call() { sources(&steps), [ PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), - PreBlockStateSource::PendingChanges + PreBlockStateSource::PendingChanges, + PreBlockStateSource::SystemAddress, ] ); let registry = &steps[1].1[&SEQUENCER_REGISTRY_ADDRESS]; @@ -209,7 +242,7 @@ 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_eq!(sources(&steps).last(), Some(&PreBlockStateSource::PendingChanges)); + assert!(!sources(&steps).contains(&PreBlockStateSource::ApplyPendingChanges)); assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), word(MEGA_SYSTEM_ADDRESS)); assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), word(NEXT_SYSTEM_ADDRESS)); } @@ -221,9 +254,197 @@ 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_eq!(sources(&steps).last(), Some(&PreBlockStateSource::ApplyPendingChanges)); + assert!(sources(&steps).contains(&PreBlockStateSource::ApplyPendingChanges)); assert_eq!(slot(&mut state, CURRENT_SEQUENCER), 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), word(MEGA_SYSTEM_ADDRESS)); } + +/// The system address a chain's schedule seeds the registry with, distinct from +/// [`MEGA_SYSTEM_ADDRESS`], so a test can tell the one read out of the registry from the default. +const GENESIS_SYSTEM_ADDRESS: Address = address!("0x5000000000000000000000000000000000000005"); + +/// The admin a handoff moves the registry to. +const NEXT_ADMIN: Address = address!("0x6000000000000000000000000000000000000006"); + +/// A Satin-at-genesis schedule whose registry is seeded with [`GENESIS_SYSTEM_ADDRESS`]. +fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { + MegaHardforkConfig::default().with_all_activated().with_params(SequencerRegistryConfig { + initial_system_address: GENESIS_SYSTEM_ADDRESS, + ..common::registry_config() + }) +} + +/// A legacy call from `sender` to the Oracle's `getSlot(0)`: a system-address transaction when +/// `sender` is the block's system address, an ordinary one otherwise. It carries a gas price, so +/// an ordinary one needs a balance its sender does not have here. +fn oracle_call_from(sender: Address, nonce: u64) -> Recovered { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + Recovered::new_unchecked( + common::tx(nonce, ORACLE_CONTRACT_ADDRESS, input.into(), 1_000_000), + sender, + ) +} + +/// A transaction from `sender` to the registry carrying `input`. +fn registry_call_from(sender: Address, input: Vec) -> Recovered { + Recovered::new_unchecked( + common::tx(0, SEQUENCER_REGISTRY_ADDRESS, input.into(), 1_000_000), + 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. +fn assert_is_the_system_address(executor: &mut Executor<'_>, sender: Address) { + assert_eq!(executor.evm().ctx().system_address(), sender); + 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"); +} + +/// 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) { + assert_ne!(executor.evm().ctx().system_address(), sender); + 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}"); +} + +/// A fresh chain's first block deploys the registry and reads the system address its schedule +/// seeded it with: the registry's, not the engine's default. The read reaches the observer as a +/// read-only entry of the one slot. +#[test] +fn test_bootstrap_block_resolves_system_address() { + let mut state = common::state(); + let mut executor = executor_on( + &mut state, + envs_at(1), + common::BLOCK_GAS_LIMIT, + chain_seeding_genesis_system_address(), + ); + let log = record(&mut executor); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(executor.evm().ctx().system_address(), GENESIS_SYSTEM_ADDRESS); + + let steps = registry_steps(&log); + let (source, read) = steps.last().expect("the read reached the observer"); + assert_eq!(*source, PreBlockStateSource::SystemAddress); + let registry = &read[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "a read-only entry"); + assert_eq!(registry.storage.len(), 1); + assert_eq!( + registry.storage[&CURRENT_SYSTEM_ADDRESS].present_value(), + word(GENESIS_SYSTEM_ADDRESS) + ); + + drop(executor); + + // The default schedule seeds the engine's default address, and the read finds it. + let mut state = common::state(); + let mut default = self::executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + default.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(default.evm().ctx().system_address(), MEGA_SYSTEM_ADDRESS); +} + +/// 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 mut state = common::state(); + let mut executor = executor_on( + &mut state, + envs_at(1), + common::BLOCK_GAS_LIMIT, + chain_seeding_genesis_system_address(), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_is_the_system_address(&mut executor, GENESIS_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); +} + +/// A system-address rotation due in this block governs this block: the new address sends the +/// protocol's transactions, and the old one no longer can. +#[test] +fn test_system_address_change() { + let mut state = + State::builder().with_database(registry_with(&system_address_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, NEXT_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); +} + +/// 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), word(NEXT_SEQUENCER)); +} + +/// A rotation scheduled for a later block leaves this block's system address as it was. +#[test] +fn test_pending_not_yet_due_is_noop() { + let mut state = State::builder() + .with_database(registry_with(&system_address_change(BLOCK_NUMBER + 8_999))) + .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_SYSTEM_ADDRESS); +} + +/// 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(&[(ADMIN, word(common::ADMIN))]); + 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), word(NEXT_ADMIN)); + assert_eq!(slot(&mut state, PENDING_ADMIN), U256::ZERO); +} From 6f07407f18f797ed0213ba4bd44772136598d492 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:09:40 -0700 Subject: [PATCH 215/458] test(evm): pin how a system call's gas settles against op-revm --- crates/mega-evm/tests/_pending/README.md | 10 +- .../rex5/apply_pending_changes_gas_budget.rs | 265 ---------- crates/mega-evm/tests/block/eips.rs | 66 +++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/system_call.rs | 465 ++++++++++++++++++ 5 files changed, 536 insertions(+), 271 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs create mode 100644 crates/mega-evm/tests/satin/system_call.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4e643902b..035849672 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,11 +29,10 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 3 | 3 | 0 | 0 | 3 | 0 | | system contract deployment | 5 | 5 | 0 | 5 | 0 | 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** | **57** | **57** | **0** | **27** | **23** | **7** | +| **Total** | **54** | **54** | **0** | **27** | **20** | **7** | ## Tests ported in place @@ -331,16 +330,16 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 37 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. 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: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `block_executor/sequencer_registry.rs` | the pre-block system calls (7) | 7 | `tests/block/sequencer_registry.rs` | -| `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (1) | 1 | `tests/block/sequencer_registry.rs` | +| `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (4) | 4 | `tests/block/sequencer_registry.rs`, `tests/satin/system_call.rs` | | `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | | `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | | `src/system/sequencer_registry.rs` | the pre-block system calls (9), system contract deployment (6) | 15 | `src/system/sequencer_registry.rs` | -| **Total** | | **37** | | +| **Total** | | **40** | | ## Tests retired after the inventory @@ -389,7 +388,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/frame_limits.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex4/gas_detention.rs` | 2 | rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 1 | rewrite 1 (inspector support · D41) | -| `rex5/apply_pending_changes_gas_budget.rs` | 3 | rewrite 3 (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/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | 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 b8b361ac7..000000000 --- a/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs +++ /dev/null @@ -1,265 +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:?}", - ); -} - -/// 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/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 45341b870..9f9608bff 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -504,3 +504,69 @@ fn test_beacon_root_pre_block_call_db_error_returns_validation_error() { "{err}" ); } + +/// What the observer receives 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_the_observer_receives_a_pre_block_call_as_op_revm_runs_it() { + 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 mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); + let log = record_pre_block(&mut executor); + executor.apply_pre_execution_changes().expect("the block starts"); + let (source, delivered) = pre_block_states(&log).into_iter().next().expect("a first step"); + assert_eq!(source, PreBlockStateSource::Eip2935); + 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 observer sees 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/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 3083549b2..12be8c56a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -34,6 +34,7 @@ mod static_callee; mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; +mod system_call; mod transfer_logs; mod volatile_access; mod withheld_gas; 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..01e528833 --- /dev/null +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -0,0 +1,465 @@ +//! 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}, + 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, + }, + handler::{ + EthFrame, ExecuteEvm, Handler, SystemCallTx, SYSTEM_CALL_GAS_LIMIT, + SYSTEM_CALL_REGULAR_GAS_LIMIT, + }, + inspector::NoOpInspector, + interpreter::interpreter::EthInterpreter, + state::EvmState, + Journal, +}; + +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; + +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_STATE_GAS); + 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_STATE_GAS, + "the excess, less the one slot it paid for", + ); + assert_same(&mega, &op); + } +} + +/// The default reservoir holds sixteen fresh slots at Satin's price. Sixteen writes empty it and +/// spend no regular gas on state; a seventeenth spills its state gas onto the regular budget. +/// `GAS`, read after the writes, shows the spill: the regular gas the seventeenth write took is +/// its own regular cost, which the sixteenth write's shows, plus one slot of state gas. +#[test] +fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { + assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); + // 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 (mega, op) = + run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), SYSTEM_CALL_GAS_LIMIT); + assert!(mega.result.is_success(), "{:?}", mega.result); + assert_eq!(mega.result.gas().state_gas_spent_final(), writes * SLOT_STATE_GAS); + assert_same(&mega, &op); + let reading = mega.state[&CONTRACT].storage[&U256::from(READING)].present_value(); + (reading.to::(), mega.result.gas().reservoir_remaining()) + }; + + let (after_15, reservoir_15) = run(15); + let (after_16, reservoir_16) = run(16); + let (after_17, reservoir_17) = run(17); + assert_eq!(reservoir_15, SLOT_STATE_GAS); + assert_eq!(reservoir_16, 0, "sixteen slots empty the reservoir"); + assert_eq!(reservoir_17, 0); + let one_write = after_15 - after_16; + assert!(one_write < SLOT_STATE_GAS, "the sixteenth write took regular gas for itself alone"); + assert_eq!(after_16 - after_17, one_write + SLOT_STATE_GAS, "the seventeenth 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() { + for writes in [0, 1, 5] { + 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_STATE_GAS, + "{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_tx_kv_update_limit(0) + .with_frame_kv_update_limit(0) + .with_tx_state_gas_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_STATE_GAS, "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); + assert!(mega.result.gas().state_gas_spent_final() > 0, "the change wrote fresh slots"); + assert_eq!(mega.result.gas().state_gas_spent_final() % SLOT_STATE_GAS, 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_STATE_GAS, + ); + 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. +#[test] +fn test_a_system_address_transaction_is_split_by_the_execution_cap() { + for (gas_limit, reservoir) in [(1_000_000, 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); + 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}"); + assert_same(&mega_outcome.result_and_state, &op_outcome); + } +} From c49e3cfa7c84a65da46a58f1bfb1135618c35af0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:12:19 -0700 Subject: [PATCH 216/458] test(block): port the registry rotation rows the pre-block calls unblock --- crates/mega-evm/tests/_pending/README.md | 9 +- .../rex6/sequencer_registry_rotation.rs | 398 ------------------ crates/mega-evm/tests/block/eips.rs | 8 +- .../tests/block/sequencer_registry.rs | 152 ++++++- 4 files changed, 157 insertions(+), 410 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 035849672..7e6374753 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -29,10 +29,9 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| system contract deployment | 5 | 5 | 0 | 5 | 0 | 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** | **54** | **54** | **0** | **27** | **20** | **7** | +| **Total** | **49** | **49** | **0** | **22** | **20** | **7** | ## Tests ported in place @@ -330,16 +329,17 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 40 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. 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: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. The counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `block_executor/sequencer_registry.rs` | the pre-block system calls (7) | 7 | `tests/block/sequencer_registry.rs` | | `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (4) | 4 | `tests/block/sequencer_registry.rs`, `tests/satin/system_call.rs` | | `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | +| `rex6/sequencer_registry_rotation.rs` | system contract deployment (5) | 5 | `tests/block/eips.rs`, `tests/block/sequencer_registry.rs` | | `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | | `src/system/sequencer_registry.rs` | the pre-block system calls (9), system contract deployment (6) | 15 | `src/system/sequencer_registry.rs` | -| **Total** | | **40** | | +| **Total** | | **45** | | ## Tests retired after the inventory @@ -393,4 +393,3 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/oracle_hint_metering.rs` | 1 | rewrite 1 (revert-class aborts · D48) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | -| `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | 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/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 9f9608bff..76d14ffb8 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -388,7 +388,8 @@ fn test_a_block_is_refused_when_a_pre_block_call_reverts() { matches!( &err, BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) - if message.contains("Revert") + if message.contains("EIP-2935 pre-block call did not succeed") + && message.contains("Revert") ), "{err}" ); @@ -401,7 +402,10 @@ fn test_a_block_is_refused_when_a_pre_block_call_reverts() { assert!( matches!( &err, - BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { .. }) + BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { + message, + .. + }) if message.contains("EIP-4788 pre-block call did not succeed") ), "{err}" ); diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index cd21cc2e4..a219fac03 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -11,16 +11,18 @@ use std::sync::{Arc, Mutex}; use alloy_consensus::transaction::Recovered; use alloy_evm::{block::BlockExecutor, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use alloy_sol_types::SolCall; +use alloy_primitives::{address, keccak256, Address, Bytes, 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, + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_ADMIN, + PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, }, IOracle, ISequencerRegistry, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + SEQUENCER_REGISTRY_CODE_HASH, }, test_utils::MemoryDatabase, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, MegaEvmFactory, @@ -342,9 +344,20 @@ fn test_bootstrap_block_resolves_system_address() { registry.storage[&CURRENT_SYSTEM_ADDRESS].present_value(), word(GENESIS_SYSTEM_ADDRESS) ); - + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH, "the deployed code"); drop(executor); + // The registry is the one this engine ships, seeded with the schedule's roles and delay. + assert_eq!( + state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, + SEQUENCER_REGISTRY_CODE_HASH, + ); + assert_eq!( + slot(&mut state, MIN_ROTATION_DELAY), + U256::from(common::registry_config().min_rotation_delay) + ); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(common::SEQUENCER)); + // The default schedule seeds the engine's default address, and the read finds it. let mut state = common::state(); let mut default = self::executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); @@ -448,3 +461,132 @@ fn test_admin_handoff_via_block_executor() { assert_eq!(slot(&mut state, ADMIN), 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 whose registry the first block deploys, 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_config().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), 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), word(common::SEQUENCER), "not before"); + + drop(started_block_at(&mut state, activation)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(next), "applied at its block"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO); +} + +/// 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_config().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); +} From 811cc4694303ab357061f54a65021a1c49af3870 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:14:48 -0700 Subject: [PATCH 217/458] docs: describe the system calls, their budgets and the live system address --- AGENTS.md | 50 +++++++++++++++++++++++++++------------ crates/mega-evm/README.md | 14 +++++++++-- 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ca65f2de7..9992ab206 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,23 +100,23 @@ 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 (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch the spec fixes on (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`) | revert-class policy aborts, the system-call reservoir split; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); the system-contract deploy and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls (the remaining hook point of `apply_pre_execution_changes`) | -| `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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and the live system address (`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`) | revert-class policy aborts; 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the live system address, and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read, its `applyPendingChanges()` pre-block call and the live system address read (`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 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`, `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`) | — | ### 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 on and not disabled, 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 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 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. @@ -172,7 +172,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. -- 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 EIP-2935 and EIP-4788 pre-block calls among them — run under the sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. +- 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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 them, a system transaction being promoted to a deposit. A user's deposit is not system-originated and is held to every per-transaction limit. @@ -186,7 +186,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. 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`. Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; the pre-block system calls that apply a due `SequencerRegistry` change remain an empty hook after that deploy. + It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block and reads the live system address out of it (see the system calls below). - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. Three of the six system contracts answer calls through their interceptors (`system/`), and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless rewrite 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. @@ -214,6 +214,26 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Only the creation's own bump is taken back: nonces a delegated signer's code spends in the constructor stay spent, so the nonce never goes back below an account the signer created. `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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. + Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS`. + A registry that is missing, holds other code or holds a zero address refuses the block (`system::resolve_system_address`). +- 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 reaches the observer. + - 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. @@ -449,7 +469,7 @@ When the agent is requested to implement a new feature or bug fix, it should con 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. + `block/eips.rs` holds the EIP-2935 and EIP-4788 calls and the post-block balance increments, `system/sequencer_registry.rs` the registry's due-change read, its `applyPendingChanges()` call and the system-address 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, ...};`. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 1010f233b..34b5ff985 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -57,7 +57,16 @@ The execution figure a block counts for a transaction is its regular ledger — A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. 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` deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, hands each pre-block state (the two EIP calls and the seven deploys) to an optional observer before it commits — that sequence is the witness a stateless client needs — and leaves one hook point empty: the pre-block system calls. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call, and reads the live system address out of the registry. +It hands each pre-block state — the two EIP calls, the seven deploys, the registry's two reads and its call — to an optional observer before it commits; that sequence is the witness a stateless client needs. + +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. +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. @@ -90,7 +99,8 @@ A deployment spends the signer's nonce from 0 to 1 and takes no signer past 1, a A signer at nonce 1 stays there however often its deployment fails, so nobody can use up its attempts, and once it deploys, so a resubmission finds the address taken (`ContractAlreadyExists()`). A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. -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 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. +It is the address the `SequencerRegistry` holds, which block execution reads before each block's transactions, once a rotation due in the block has been applied (`MegaContext::system_address`); a context no block has been started on uses `MEGA_SYSTEM_ADDRESS`. The account such a transaction creates for its caller is charged the account-creation state gas exactly once. 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. From 068407f2f0890193bdffcfd210382b633a4a2ae5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:27:35 -0700 Subject: [PATCH 218/458] test(evm): read a slot's state gas off the schedule in the system-call tests --- crates/mega-evm/tests/satin/equivalence.rs | 4 +- crates/mega-evm/tests/satin/system_call.rs | 62 ++++++++++++++-------- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index b8dbf9526..9d42f7f45 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -413,7 +413,9 @@ fn test_system_call_matches_op_revm() { assert!(mega_outcome.result.is_success()); assert_eq!( mega_outcome.result.gas().reservoir_remaining(), - SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - SLOT_STATE_GAS, + SYSTEM_CALL_GAS_LIMIT - + SYSTEM_CALL_REGULAR_GAS_LIMIT - + satin_gas_params().get(GasId::sstore_set_state_gas()), ); assert_same(&mega_outcome, &op_outcome); } diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 01e528833..c1a94e9e4 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -19,6 +19,7 @@ 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, @@ -41,6 +42,7 @@ use revm::{ 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, @@ -51,6 +53,8 @@ use revm::{ Journal, }; +use crate::common::runs_at_measurement_prices; + const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CONTRACT: Address = address!("0x5000000000000000000000000000000000000001"); @@ -60,6 +64,12 @@ 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, @@ -193,7 +203,7 @@ fn test_a_system_call_within_30m_has_no_reservoir() { 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_STATE_GAS); + 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); } @@ -213,20 +223,24 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { 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_STATE_GAS, + 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. Sixteen writes empty it and -/// spend no regular gas on state; a seventeenth spills its state gas onto the regular budget. -/// `GAS`, read after the writes, shows the spill: the regular gas the seventeenth write took is -/// its own regular cost, which the sixteenth write's shows, plus one slot of state gas. +/// 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 write before it shows, plus the part of its slot the +/// reservoir did not hold. #[test] fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { - assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); + if !runs_at_measurement_prices() { + assert_eq!(SLOT_STATE_GAS, slot()); + assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); + } // The reading is stored into a slot that already holds a value, which writes no new state. const READING: u64 = 0xff; let run = |writes| { @@ -237,21 +251,27 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), SYSTEM_CALL_GAS_LIMIT); assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().state_gas_spent_final(), writes * SLOT_STATE_GAS); + 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 (after_15, reservoir_15) = run(15); - let (after_16, reservoir_16) = run(16); - let (after_17, reservoir_17) = run(17); - assert_eq!(reservoir_15, SLOT_STATE_GAS); - assert_eq!(reservoir_16, 0, "sixteen slots empty the reservoir"); - assert_eq!(reservoir_17, 0); - let one_write = after_15 - after_16; - assert!(one_write < SLOT_STATE_GAS, "the sixteenth write took regular gas for itself alone"); - assert_eq!(after_16 - after_17, one_write + SLOT_STATE_GAS, "the seventeenth spilled"); + // The most slots the reservoir holds, and what the one after them spills. + let held = DEFAULT_RESERVOIR / slot(); + let spill = (held + 1) * slot() - DEFAULT_RESERVOIR; + let (before, reservoir_before) = run(held - 1); + let (at, reservoir_at) = run(held); + let (after, reservoir_after) = run(held + 1); + assert_eq!(reservoir_before, DEFAULT_RESERVOIR - (held - 1) * slot()); + assert_eq!(reservoir_at, DEFAULT_RESERVOIR - held * slot(), "empty at Satin's price"); + assert_eq!(reservoir_after, 0); + let one_write = before - at; + assert!( + one_write < slot(), + "the last write the reservoir held took regular gas for itself alone" + ); + assert_eq!(at - after, one_write + spill, "the next one spilled"); } /// What is left of the reservoir is reported, slot by slot, and a call that writes nothing @@ -269,7 +289,7 @@ fn test_reservoir_remaining_is_what_the_writes_left() { ); assert_eq!( mega.result.gas().reservoir_remaining(), - DEFAULT_RESERVOIR - writes * SLOT_STATE_GAS, + DEFAULT_RESERVOIR - writes * slot(), "{writes} writes", ); assert_same(&mega, &op); @@ -336,7 +356,7 @@ fn test_a_system_call_with_a_reservoir_stays_exempt() { 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_STATE_GAS, "m = 1"); + 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); } @@ -378,7 +398,7 @@ fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { assert!(mega.result.is_success(), "{:?}", mega.result); assert_eq!(mega.result.gas().reservoir_remaining(), 0); assert!(mega.result.gas().state_gas_spent_final() > 0, "the change wrote fresh slots"); - assert_eq!(mega.result.gas().state_gas_spent_final() % SLOT_STATE_GAS, 0, "at m = 1"); + assert_eq!(mega.result.gas().state_gas_spent_final() % slot(), 0, "at m = 1"); assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega, &op); } @@ -417,7 +437,7 @@ fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_reg 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_STATE_GAS, + DEFAULT_RESERVOIR - slots * slot(), ); assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega_outcome, &op_outcome); From 5ec9a5abe5748367aebfe5b7d3e08d212aeac257 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:43:26 -0700 Subject: [PATCH 219/458] fix(system): report a database error in the applyPendingChanges call as the database's --- .../mega-evm/src/system/sequencer_registry.rs | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 597e84384..017781b71 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -23,7 +23,10 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use op_revm::OpHaltReason; use revm::{ - context::{result::ResultAndState, Block, ContextTr}, + context::{ + result::{EVMError, ResultAndState}, + Block, ContextTr, + }, state::{Account, EvmState, EvmStorageSlot, TransactionId}, }; @@ -192,7 +195,8 @@ fn read_slot( /// # Errors /// /// [`MegaBlockExecutionError::ApplyPendingChangesFailed`] when the call reverts or halts, or an -/// error stops it: a change the registry scheduled for this block must be applied in it. +/// error other than the database's stops it: a change the registry scheduled for this block must +/// be applied in it. A database error is the database's. pub fn transact_apply_pending_changes( evm: &mut MegaEvm, ) -> Result, BlockExecutionError> @@ -203,14 +207,18 @@ where let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit()); let failed = |message| MegaBlockExecutionError::ApplyPendingChangesFailed { message }; - let outcome = evm - .transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - gas_limit, - ) - .map_err(|error| failed(format!("{error}")))?; + let outcome = match evm.transact_system_call_with_gas_limit( + alloy_eips::eip4788::SYSTEM_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + Bytes::from(calldata), + gas_limit, + ) { + Ok(outcome) => outcome, + // A read the database could not serve says nothing about the block, as for the registry + // reads on either side of the call. + Err(EVMError::Database(error)) => return Err(BlockExecutionError::other(error)), + Err(error) => return Err(failed(format!("{error}")).into()), + }; if !outcome.result.is_success() { return Err(failed(format!("{:?}", outcome.result)).into()); } @@ -447,6 +455,21 @@ mod tests { 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. #[test] fn test_transact_apply_pending_changes_errors_when_registry_reverts() { From 5bdf0e3a90bc045caef945d568d3f3fe3433479c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 03:43:26 -0700 Subject: [PATCH 220/458] test(block): hold the pre-block budget and spill tests at any byte price --- crates/mega-evm/tests/block/eips.rs | 6 +++++- crates/mega-evm/tests/satin/system_call.rs | 21 ++++++++++----------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 76d14ffb8..b093916f1 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -419,9 +419,13 @@ fn test_a_block_is_refused_when_a_pre_block_call_reverts() { #[test] fn test_the_block_aware_budget_accepts_a_pre_block_call_above_30m() { const SLOTS: u16 = 400; - assert!(u64::from(SLOTS) * SLOT_STATE_GAS > SYSTEM_CALL_REGULAR_GAS_LIMIT); 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(); diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index c1a94e9e4..4055c79aa 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -233,7 +233,7 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { /// 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 write before it shows, plus the part of its slot the +/// took is its own regular cost, which the writes before it show, plus the part of its slot the /// reservoir did not hold. #[test] fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { @@ -260,18 +260,17 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { // The most slots the reservoir holds, and what the one after them spills. let held = DEFAULT_RESERVOIR / slot(); let spill = (held + 1) * slot() - DEFAULT_RESERVOIR; - let (before, reservoir_before) = run(held - 1); + let (two_short, _) = run(held - 2); + let (one_short, reservoir_one_short) = run(held - 1); let (at, reservoir_at) = run(held); - let (after, reservoir_after) = run(held + 1); - assert_eq!(reservoir_before, DEFAULT_RESERVOIR - (held - 1) * slot()); + let (past, reservoir_past) = run(held + 1); + assert_eq!(reservoir_one_short, DEFAULT_RESERVOIR - (held - 1) * slot()); assert_eq!(reservoir_at, DEFAULT_RESERVOIR - held * slot(), "empty at Satin's price"); - assert_eq!(reservoir_after, 0); - let one_write = before - at; - assert!( - one_write < slot(), - "the last write the reservoir held took regular gas for itself alone" - ); - assert_eq!(at - after, one_write + spill, "the next one spilled"); + 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 From f0419e9c14f7bf44d337cb7a78cc99362ff9e151 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:16:57 -0700 Subject: [PATCH 221/458] docs(system): name the SequencerRegistry's pre-block helpers in the module guide --- crates/mega-evm/src/system/AGENTS.md | 6 +++--- crates/mega-evm/src/system/tx.rs | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 34847b394..1a3ca29c7 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## OVERVIEW -The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory. +The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory, and the `SequencerRegistry`'s pre-block steps: the due-change read, the `applyPendingChanges()` system call and the read of the live system address. ## STRUCTURE - `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. @@ -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 overhead, the nine rules, the charges of the creation's start and the rewrite into a creation (`dispatch.rs`); the settlement of the creation into its call and the ABI answer (`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, and the [`SequencerRegistryConfig`] that seeds it. No interceptor. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, the [`SequencerRegistryConfig`] that seeds it, and its three pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) and `resolve_system_address` (fail-closed read of `_currentSystemAddress`). No interceptor. - `deploy.rs`: the declarative spec, `transact_deploy`, the EIP-7997 factory, and the list of seven predeploys. - `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. @@ -72,4 +72,4 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. - Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list, delivers each witness to the pre-block observer, and commits. -- Read the rotated system address, or run `applyPendingChanges`: the pre-block system calls own those. +- Change when a role change is applied or how the live system address is read: `sequencer_registry.rs`, whose three helpers `block/executor.rs::apply_pre_execution_changes` calls after the deploys, in that order; the result lives on the context (`MegaContext::system_address`). diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index f7368a689..886d139e6 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -1,10 +1,11 @@ //! 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 +//! ([`MegaContext::system_address`](crate::MegaContext::system_address); [`MEGA_SYSTEM_ADDRESS`] +//! until a block has read it). 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`]): From 8e679174f1565a3eba834b6da85b00008760db90 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:17:18 -0700 Subject: [PATCH 222/458] test(evm): pin a system-address transaction between 30M and the execution cap --- crates/mega-evm/tests/satin/system_call.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 4055c79aa..827123b0d 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -462,10 +462,16 @@ fn system_address_transaction(gas_limit: u64) -> (TxEnv, OpTransaction) { /// 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. +/// deposit op-revm runs for it — never the system call's 30M split, which the rows between 30M and +/// the cap would see. #[test] fn test_a_system_address_transaction_is_split_by_the_execution_cap() { - for (gas_limit, reservoir) in [(1_000_000, 0), (TX_GAS_LIMIT_CAP + 5_000_000, 5_000_000)] { + 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); From 483b48ab0116d4b558f54a68f6b1eb8fffd245c1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:20:21 -0700 Subject: [PATCH 223/458] test(satin): pin that no caller resumes after a compute stop --- crates/mega-evm/tests/satin/detention.rs | 10 ++- crates/mega-evm/tests/satin/stops.rs | 82 ++++++++++++++++++++---- 2 files changed, 77 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 65a40ecd4..f8122f625 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -810,7 +810,7 @@ fn test_a_childs_read_caps_its_caller() { } /// When a child crosses the cap, no caller resumes: the caller's code after the call — a write -/// and a log — never runs, and every frame returns the stop. +/// and a log — never runs, the child runs the last step, and every frame returns the stop. #[test] fn test_no_caller_resumes_after_the_stop() { let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); @@ -837,6 +837,9 @@ fn test_no_caller_resumes_after_the_stop() { ] ); assert!(!evm.inspector().opcodes.contains(&SSTORE), "the caller did not resume"); + // A caller that resumed would fail its first charge on the withheld part, before its + // write, and report the same stop on the same bill: only its step shows it ran. + assert_eq!(evm.inspector().last_frame, Some(CHILD), "the child ran the last step"); } } @@ -1018,11 +1021,13 @@ fn test_an_inspectors_reads_are_not_the_transactions() { /* ---------- refused reads ---------- */ -/// Records every call's result and the gas it spent, and every opcode that ran. +/// 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 { @@ -1036,6 +1041,7 @@ 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( diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 2f4105902..223344532 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -305,6 +305,13 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { // did not reach a caller: the inspector changed nothing the transaction reports. assert_eq!(rewritten.gas, plain.gas, "{row}"); assert_eq!(rewriter.marker_writes, 0, "{row}: no frame ran on after the crossing"); + // A caller that resumed after a compute stop would fail its first charge on the withheld part + // and report the same stop on the same bill: only its step shows it ran. + assert_eq!( + rewriter.last.map(|(frame, ..)| frame), + Some(CHAIN[crossing]), + "{row}: the last step ran in the crossing frame" + ); if limit != Limit::Compute { assert_eq!( rewriter.last, @@ -414,6 +421,33 @@ fn limits_of(limit: Limit, crossing: usize, slot: u64) -> (EvmTxRuntimeLimits, O /* ---------- a detained callee does not burn its callers' gas ---------- */ +/// Records the frame the last step ran in. +/// +/// After a compute stop the transaction's compute sits at the limit, so a caller that resumed +/// would fail its first charge on the withheld part and be stopped the same way, on the same bill: +/// the frame of the last step is what tells it ran. +#[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) +} + /// A callee at `depth` that reads the block's timestamp and then computes past the cap, below /// callers that forward it all their gas and would write [`MARKER`] once it returned. fn detained_callee_at(depth: usize) -> MemoryDatabase { @@ -430,7 +464,8 @@ fn detained_callee_at(depth: usize) -> MemoryDatabase { /// A callee that reads the block's timestamp and then computes past the cap does not make its /// callers burn their gas: the stop bills the transaction its intrinsic gas plus the limit the read /// set — its compute at the read plus the cap — and nothing of what the callers held, whatever the -/// gas limit, one call down or three, below the execution cap and above it. +/// gas limit, one call down or three, below the execution cap and above it. No caller resumes: the +/// callee runs the last step. #[test] fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_gas() { for depth in [1, 3] { @@ -439,10 +474,21 @@ fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_g .map(|gas_limit| { let case = format!("depth {depth}, gas limit {gas_limit}"); let intrinsic = intrinsic(gas_limit); + let tx = || call(CALLER, A, U256::ZERO, gas_limit); let mut evm = MegaEvm::new(context(detained_callee_at(depth))); - let outcome = - evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + let outcome = evm.execute_transaction(tx()).unwrap(); let limit = evm.ctx().detention().compute_limit().expect("the read set a limit"); + let (recorded, last) = run_recording_steps( + detained_callee_at(depth), + EvmTxRuntimeLimits::default(), + tx(), + ); + assert_eq!(last, Some(CHAIN[depth]), "{case}: the last step ran in the callee"); + assert_eq!( + (&recorded.result, recorded.gas), + (&outcome.result, outcome.gas), + "{case}: the recorder changes nothing" + ); let stop = LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, limit, @@ -767,15 +813,24 @@ fn with_oracle_read(db: MemoryDatabase) -> MemoryDatabase { /// Runs `db`'s `A` under `limits` with [`ROOMY`] gas and asserts the detention stop: a revert /// carrying `MegaLimitExceeded(2, limit)` for the limit the reads set, billed the intrinsic gas -/// plus that limit and nothing of the gas the transaction had left. Returns the limit and what the -/// transaction read. +/// plus that limit and nothing of the gas the transaction had left. The frame `crossing` crossed +/// it, and ran the last step: no caller resumed. Returns the limit and what the transaction read. fn assert_detention_stop( db: MemoryDatabase, limits: EvmTxRuntimeLimits, + crossing: Address, ) -> (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(crossing), "the last step ran in the crossing 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 stop = LimitCheck::ExceedsLimit { @@ -801,7 +856,7 @@ fn assert_detention_stop( fn test_volatile_data_access_oog_does_not_consume_all_gas() { let code = thousand_writes(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); let db = MemoryDatabase::default().account_code(A, code.stop().build()); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); } @@ -815,7 +870,7 @@ fn test_nested_call_block_env_access_child_oog() { let db = MemoryDatabase::default() .account_code(A, parent.stop().build()) .account_code(B, child.stop().build()); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), B); assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); } @@ -829,7 +884,7 @@ fn test_parent_block_env_access_oog_after_nested_call() { let db = MemoryDatabase::default() .account_code(A, thousand_writes(parent).stop().build()) .account_code(B, child.stop().build()); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); } @@ -839,7 +894,7 @@ fn test_parent_block_env_access_oog_after_nested_call() { fn test_an_oracle_read_holds_the_transaction_to_its_cap() { let code = thousand_writes(call_oracle(BytecodeBuilder::default(), None)); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); assert!(limit - ORACLE_ACCESS_COMPUTE_GAS < 10_000, "{}", limit - ORACLE_ACCESS_COMPUTE_GAS); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -849,7 +904,7 @@ fn test_an_oracle_read_holds_the_transaction_to_its_cap() { fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { let code = thousand_writes(call_oracle(BytecodeBuilder::default(), Some(0xffff))); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); - assert_detention_stop(db, EvmTxRuntimeLimits::default()); + assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); } /// A contract that calls one that reads the Oracle's storage and then writes a thousand fresh @@ -862,7 +917,8 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { let db = MemoryDatabase::default() .account_code(A, outer.stop().build()) .account_code(B, middle.stop().build()); - let (_, accessed) = assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default()); + let (_, accessed) = + assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), B); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -874,7 +930,7 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { let code = call_oracle(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), Some(0xffff)); let db = MemoryDatabase::default().account_code(A, thousand_writes(code).stop().build()); let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); - let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits); + let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, A); assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); assert_eq!( accessed, @@ -888,7 +944,7 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { 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 (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default()); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); assert!(limit - CAP < 1_000, "{}", limit - CAP); } From 4a289d693dbe39142e7bc239a0c6d9d7a5a8f72f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:21:13 -0700 Subject: [PATCH 224/458] feat(evm): let a node set the live system address on an EVM it builds --- AGENTS.md | 3 +- crates/mega-evm/README.md | 3 +- crates/mega-evm/src/evm/context.rs | 20 +++++- crates/mega-evm/src/system/tx.rs | 11 +-- .../tests/block/sequencer_registry.rs | 70 ++++++++++++++++++- 5 files changed, 94 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9992ab206..228708e42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -214,7 +214,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Only the creation's own bump is taken back: nonces a delegated signer's code spends in the constructor stay spent, so the nonce never goes back below an account the signer created. `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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. - Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS`. + Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. + An EVM a node builds outside block execution — an RPC call, the replay of a block's transactions for a trace — starts no block, so the node reads the live address from the registry and sets it (`MegaContext::set_system_address`, or `with_system_address` on a context it builds); otherwise, once the address is rotated, that EVM runs the rotated address's transactions as ordinary ones. A registry that is missing, holds other code or holds a zero address refuses the block (`system::resolve_system_address`). - 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 34b5ff985..6463797d7 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -100,7 +100,8 @@ A signer at nonce 1 stays there however often its deployment fails, so nobody ca 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 whitelist, 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, which block execution reads before each block's transactions, once a rotation due in the block has been applied (`MegaContext::system_address`); a context no block has been started on uses `MEGA_SYSTEM_ADDRESS`. +It is the address the `SequencerRegistry` holds, which block execution reads before each block's transactions, once a rotation due in the block has been applied (`MegaContext::system_address`); a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. +A node that builds an EVM outside block execution — an RPC call, the replay of a block's transactions for a trace — reads the live address from the registry itself and sets it (`MegaContext::set_system_address`, `MegaContext::with_system_address`). The account such a transaction creates for its caller is charged the account-creation state gas exactly once. 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. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 473b7ace6..7e38f36db 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -305,17 +305,31 @@ impl MegaContext { /// /// Block execution reads it out of the `SequencerRegistry` before every block's transactions, /// once a rotation due in the block has been applied, so it is the live one for the block. A - /// context no block has been started on uses [`MEGA_SYSTEM_ADDRESS`]. + /// context no block has been started on uses [`MEGA_SYSTEM_ADDRESS`] unless its builder set + /// another ([`set_system_address`](Self::set_system_address)). pub const fn system_address(&self) -> Address { self.system_address } /// Sets the address system-address transactions come from, for every transaction from now - /// on. Block execution sets the one it read out of the `SequencerRegistry`. - pub(crate) const fn set_system_address(&mut self, address: Address) { + /// on. + /// + /// The block executor sets it itself, to the address it read out of the `SequencerRegistry` + /// before the block's transactions. An EVM a node builds outside block execution — an RPC + /// call, or the replay of a block's transactions for a trace — has no block to read it, so + /// the node reads the live address from the `SequencerRegistry` in the state the EVM runs on + /// and sets it here; otherwise, once the address has been rotated, that EVM runs the rotated + /// address's transactions as ordinary ones. + pub const fn set_system_address(&mut self, address: Address) { self.system_address = address; } + /// [`set_system_address`](Self::set_system_address), as a builder. + pub const fn with_system_address(mut self, address: Address) -> Self { + self.system_address = address; + self + } + /// Whether the running (or last) transaction pays history gas for the bytes it appends. /// /// Three kinds of transaction pay none: a deposit, a transaction the protocol itself produced diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index 886d139e6..36e9c3f8e 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -3,9 +3,10 @@ //! The sequencer writes what the protocol owes the chain — the oracle values it served, for one //! — through transactions sent from the system address the `SequencerRegistry` names //! ([`MegaContext::system_address`](crate::MegaContext::system_address); [`MEGA_SYSTEM_ADDRESS`] -//! until a block has read it). 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. +//! until a block has read it or the context is given one). 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`]): @@ -44,8 +45,8 @@ use crate::{ /// of op-revm's own and no fee. Which address that is can be rotated through the registry, and /// block execution reads the live one out of it before every block /// ([`MegaContext::system_address`](crate::MegaContext::system_address)). This is the address a -/// context uses before any block has been started on it, and the one the unknown-chain -/// placeholder schedule seeds the registry with. +/// context uses before any block has been started on it, unless it is given another, and the one +/// the unknown-chain placeholder schedule seeds the registry with. pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); /// The contracts a system-address transaction may call. It may call nothing else and create diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index a219fac03..56046b000 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex}; use alloy_consensus::transaction::Recovered; -use alloy_evm::{block::BlockExecutor, EvmFactory}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory, ToTxEnv}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::{SolCall, SolValue}; @@ -25,8 +25,9 @@ use mega_evm::{ SEQUENCER_REGISTRY_CODE_HASH, }, test_utils::MemoryDatabase, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, MegaEvmFactory, - MegaHardforkConfig, MegaTxEnvelope, PreBlockStateSource, TestExternalEnvs, MIN_BUCKET_SIZE, + BlockLimits, ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaContext, + MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, PreBlockStateSource, + TestExternalEnvs, MIN_BUCKET_SIZE, }; use revm::{database::State, inspector::NoOpInspector, state::EvmState, Database}; @@ -394,6 +395,69 @@ fn test_system_address_change() { assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); } +/// 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, so it reads no registry. +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 — reads no registry, so the node sets the address it read there +/// itself. Given the rotated address, through the context's builder or the setter on a factory's +/// EVM, it promotes that address's Oracle transaction exactly as the block executor does: the same +/// result, state, gas and usage. Without it, it runs the transaction as an ordinary one, which the +/// empty sender cannot pay for. +#[test] +fn test_a_context_built_with_the_rotated_address_promotes_as_the_block_does() { + 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 = executor.run_transaction(&tx).expect("the block promotes it").inner; + drop(executor); + assert!(in_block.result.is_success(), "{:?}", in_block.result); + assert_eq!(in_block.gas.history, 0, "the protocol's own transaction pays no history"); + + // 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<'_>| { + assert_eq!(evm.ctx().system_address(), NEXT_SYSTEM_ADDRESS); + 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); + }; + assert_as_in_block(&mut MegaEvm::new( + context_outside_block(&mut state, &envs).with_system_address(NEXT_SYSTEM_ADDRESS), + )); + let mut evm = MegaEvmFactory::new() + .with_external_env_factory(envs.clone()) + .create_evm(&mut state, common::evm_env()); + evm.ctx_mut().set_system_address(NEXT_SYSTEM_ADDRESS); + assert_as_in_block(&mut evm); + + let mut evm = MegaEvm::new(context_outside_block(&mut state, &envs)); + assert_eq!(evm.ctx().system_address(), MEGA_SYSTEM_ADDRESS); + let err = evm + .execute_transaction(tx.to_tx_env()) + .expect_err("an ordinary transaction from an empty account is refused"); + assert!(err.to_string().contains("lack of funds"), "{err}"); +} + /// A sequencer rotation leaves the system address as it was. #[test] fn test_sequencer_change_does_not_affect_system_address() { From ecd066fef00842b1e63c142166391f863b4f6f83 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:27:40 -0700 Subject: [PATCH 225/458] fix(inspector): leave a revived creation to the latch once the transaction is stopped --- AGENTS.md | 6 +- crates/mega-evm/src/evm/inspector.rs | 35 +++-- crates/mega-evm/tests/satin/inspector.rs | 49 +++++++ crates/mega-evm/tests/satin/stops.rs | 167 ++++++++++++++++++++++- 4 files changed, 239 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ada9a783f..48ffc2840 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -303,6 +303,7 @@ 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. The rewrite takes every result, whatever produced it — revm, an interceptor, or an inspector that turned it into a success or a halt (`AdditionalLimit::apply_latch`): no frame runs an instruction under the latch, so a halt there can only be an inspector's. + A stopped creation an inspector revived is one of them: the creation-revival refusal puts it back and leaves a latched transaction to the latch rather than failing it. 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 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 state gas or records would cross it are taken back before the first frame. @@ -312,7 +313,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. 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. - `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result. + `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result, and a column of stopped creations that inspector revives. - **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. @@ -322,7 +323,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`), unless the transaction is latched: the creation is put back, and the latch reports the stop. + A creation stopped by its own frame budget latches nothing, and its revival is refused. 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. diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index eb255511e..b8e58f489 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -20,7 +20,10 @@ //! 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. +//! was rolled back. A transaction a limit stopped is the exception: once it is latched, every +//! frame's result is the stop whatever produced it, so a revived creation is put back and reports +//! the stop, and the transaction does not fail. A creation stopped by its own frame budget +//! latches nothing, and its revival is refused. Every other rewrite is the tool's business. #[cfg(not(feature = "std"))] use alloc as std; @@ -35,9 +38,11 @@ use revm::{ Interpreter, InterpreterTypes, }, primitives::{Address, Log, U256}, - Inspector, + Database, Inspector, }; +use crate::{ExternalEnvTypes, MegaContext}; + /// 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. @@ -325,30 +330,36 @@ 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`]. +/// [`FORBIDDEN_CREATE_REVIVAL`] — unless the transaction is latched, where the creation is put back +/// and reports the stop, which the latch writes over every result. /// /// 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. +/// with a success itself is no revival: nothing failed. The latch is read after the hooks that can +/// set it — the frame's run, detention's classification of its end, the hold on a start's upfront +/// state gas, and the answer before building — have run, so a creation the latch stopped is never +/// refused. #[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, ) 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); } -/// Puts a revived creation back to `before` and records the refusal as the context's error. -fn refuse_create_revival( - context: &mut CTX, +/// Puts a revived creation back to `before` and, unless the transaction is latched, records the +/// refusal as the context's error. +fn refuse_create_revival( + context: &mut MegaContext, before: InstructionResult, result: &mut FrameResult, ) { @@ -357,7 +368,7 @@ fn refuse_create_revival( return; } outcome.result.result = before; - if context.error().is_ok() { + if context.additional_limit.latched().is_none() && context.error().is_ok() { let message: String = format!("{FORBIDDEN_CREATE_REVIVAL}: {before:?}"); *context.error() = Err(ContextError::Custom(message)); } diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index b80a5ad8c..c12d2a997 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -249,6 +249,55 @@ fn test_create_revival_is_refused() { .is_success()); } +/// A creation its own frame budget stops is refused its revival too: the stop is the creation's +/// alone and latches nothing, so the creation failed as any failed creation does. Under a KV limit +/// of three, the creation's start makes two records, and the write in its init code is a third one +/// over its budget of 98% of the three, which the transaction's limit still holds; under a limit +/// of four the budget holds it, and the same creation succeeds. +#[test] +fn test_a_creation_its_frame_budget_stops_is_refused_its_revival() { + // 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 = + |records: u64| mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(records); + let plain = |records: u64| { + MegaEvm::new(context(db()).with_tx_runtime_limits(under(records))) + .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) + .unwrap() + }; + 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(4); + 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(3); + assert!(stopped.result.is_success(), "{:?}", stopped.result); + assert_eq!(stopped.limit_exceeded, None, "a frame budget latches nothing"); + assert!(!created(&stopped), "the creation failed"); + + let limits = under(3); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }); + match evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)) { + Err(EVMError::Custom(message)) => { + assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") + } + other => panic!("expected the refusal, got {other:?}"), + } +} + /// A declared observer that writes back fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 223344532..661c622c9 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -15,6 +15,9 @@ //! twin of each transaction: the same frames, each reverting where the stopped one crossed its //! limit or would have resumed. The twin runs without limits and revm settles its reverts itself, //! so it bills exactly what the stop should, plus the two pushes each of its reverts costs. +//! +//! A column of creations holds the same under that inspector, which revives a stopped creation: +//! once the transaction is latched the revival is not refused, and the creation reports the stop. use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ @@ -35,13 +38,13 @@ use revm::{ context::result::ExecutionResult, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, - InstructionResult, Interpreter, + CreateInputs, CreateOutcome, InstructionResult, Interpreter, }, Database, Inspector, }; use crate::{ - common::{call, call_with_data}, + common::{call, call_with_data, create}, detention::{context, work, BENEFICIARY}, }; @@ -187,15 +190,18 @@ fn execute( } /// Records the steps and the result of every frame it sees end, then rewrites that result into a -/// success with no output: a tool's inspector the latch must see through. +/// success with no output — a creation's too, which revives a creation that failed: a tool's +/// inspector the latch must see through. #[derive(Clone, Default)] struct Rewriter { /// The frame and opcode of the last step, and the slot it named when it was an `SSTORE`. last: Option<(Address, u8, Option)>, /// How many writes of [`MARKER`] ran. marker_writes: usize, - /// The frames that ended, deepest first, with the result each had before the rewrite. + /// The calls that ended, deepest first, with the result each had before the rewrite. ended: Vec<(Address, InstructionResult, Bytes)>, + /// The creations that ended, with the result each had before the rewrite. + created: Vec<(InstructionResult, Bytes)>, } impl Inspector, EthInterpreter> for Rewriter { @@ -217,6 +223,18 @@ impl Inspector, EthInterpreter> for Rewriter { 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())); + result.result = InstructionResult::Return; + result.output = Bytes::new(); + } } /// One row of the matrix, both columns: `limit` crossed by the frame at `crossing` of a @@ -419,6 +437,147 @@ fn limits_of(limit: Limit, crossing: usize, slot: u64) -> (EvmTxRuntimeLimits, O } } +/* ---------- 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 let Creation::NestedStart = creation { + return match limit { + Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), + Limit::KvUpdates => limits.with_tx_kv_update_limit(0), + Limit::StateGas => limits.with_tx_state_gas_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::KvUpdates => limits.with_tx_kv_update_limit(unlimited.usage.write_records - 1), + Limit::StateGas => limits.with_tx_state_gas_limit(unlimited.gas.state - 1), + Limit::Compute => limits, + } +} + +/// Under the latch a revived creation reports the stop, as a revived call does: an inspector that +/// rewrites a stopped creation into a success is not refused, because once the transaction is +/// stopped every frame's result is the stop, whatever produced it. 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 report the stop on the bill they have without the inspector, +/// below the execution cap and above it. +/// +/// A nested creation's init code cannot be the first to cross the KV limit. A record is one unit, +/// so the record that crosses the transaction's limit comes when the creation already holds all +/// the transaction had left, and its budget — 98% of that, rounded down — is less unless nothing +/// was left, when the start's own records cross: the budget stops the creation alone first. +#[test] +fn test_a_revived_creation_reports_the_stop() { + let cases = [ + (Creation::Transaction, Limit::ALL.as_slice()), + (Creation::Nested, [Limit::DataSize, Limit::StateGas, Limit::Compute].as_slice()), + (Creation::NestedStart, [Limit::DataSize, Limit::KvUpdates, Limit::StateGas].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 plain = MegaEvm::new(context(db.clone()).with_tx_runtime_limits(configured)) + .execute_transaction(tx.clone()) + .expect("the transaction is valid"); + let stop = plain.limit_exceeded.expect("the transaction is stopped"); + assert!( + matches!( + stop, + LimitCheck::ExceedsLimit { kind, frame_local: false, .. } + if kind == limit.kind() + ), + "{case}: {stop:?}" + ); + assert!( + matches!(&plain.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{case}: {:?}", + plain.result + ); + + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(configured)) + .with_inspector(Rewriter::default()); + let revived = evm.execute_transaction(tx).expect("the revival is not refused"); + assert_eq!(revived.result, plain.result, "{case}: the stop"); + assert_eq!(revived.limit_exceeded, plain.limit_exceeded, "{case}"); + assert_eq!(revived.gas, plain.gas, "{case}: the plain run's bill"); + assert_eq!(revived.usage, plain.usage, "{case}"); + let rewriter = evm.inspector(); + assert_eq!( + rewriter.created, + [(InstructionResult::Revert, stop.revert_data())], + "{case}: the creation ended with the stop before its revival" + ); + let ended = match creation { + Creation::Transaction => vec![], + Creation::Nested | Creation::NestedStart => { + vec![(A, InstructionResult::Revert, stop.revert_data())] + } + }; + assert_eq!(rewriter.ended, ended, "{case}: its creator returned the stop"); + } + } + } +} + /* ---------- a detained callee does not burn its callers' gas ---------- */ /// Records the frame the last step ran in. From 29e9dccf340b4c728744b669c693a223ae352502 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:29:49 -0700 Subject: [PATCH 226/458] test: assert a revert where a stopped row means one --- crates/mega-evm/tests/satin/stops.rs | 98 ++++++++++++++++++-------- crates/mega-evm/tests/system/oracle.rs | 26 +++++-- 2 files changed, 86 insertions(+), 38 deletions(-) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 661c622c9..6dcf2f4c0 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -654,8 +654,12 @@ fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_g used: limit, frame_local: false, }; - assert_eq!(outcome.result.output(), Some(&stop.revert_data()), "{case}"); - assert!(!outcome.result.is_halt(), "{case}"); + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{case}: {:?}", + outcome.result + ); assert_eq!(outcome.limit_exceeded, Some(stop), "{case}"); // The read came after the callers' calls and the callee's log: its compute then is // theirs alone, a sliver of the cap. @@ -998,8 +1002,12 @@ fn assert_detention_stop( used: limit, frame_local: false, }; - assert!(!outcome.result.is_halt(), "a revert, not a halt: {:?}", outcome.result); - assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + 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 + limit); assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + limit); @@ -1184,8 +1192,12 @@ fn test_data_limit_just_exceed() { used: TX_BODY_SIZE, frame_local: false, }; - assert!(!outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{:?}", + outcome.result + ); assert_eq!(outcome.limit_exceeded, Some(stop)); assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); assert_eq!(outcome.gas.gas_used, intrinsic(BELOW).gas.gas_used, "nothing ran"); @@ -1207,8 +1219,12 @@ fn test_data_limit_exceed_in_nested_call() { used: TX_BODY_SIZE + WRITE_RECORD_SIZE, frame_local: false, }; - assert!(!outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{:?}", + outcome.result + ); assert_eq!(outcome.limit_exceeded, Some(stop)); assert!(outcome.gas.gas_used < 200_000, "the stop burns nothing: {}", outcome.gas.gas_used); } @@ -1225,11 +1241,21 @@ fn test_state_revert_when_exceeding_limit() { )) .execute_transaction(call(CALLER, A, U256::from(100), BELOW)) .unwrap(); - assert!(!outcome.result.is_halt(), "{:?}", outcome.result); - assert!(matches!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, frame_local: false, .. }) - )); + 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"); @@ -1263,29 +1289,35 @@ fn test_check_limit_priority_data_size_before_kv_update() { /// A transaction detained from its start — its sender is the block's beneficiary — whose body /// crosses the data-size limit is the data-size stop, billed its intrinsic gas: detention adds -/// nothing to what it pays. +/// nothing to what it pays, which is what the same transaction pays within the limits. #[test] fn test_detention_plus_intrinsic_data_size_overflow() { let db = || MemoryDatabase::default().account_code(A, BytecodeBuilder::default().stop().build()); let run = |limits| { - MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) - .execute_transaction(call(BENEFICIARY, A, U256::ZERO, ROOMY)) - .unwrap() + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)); + let outcome = evm.execute_transaction(call(BENEFICIARY, A, U256::ZERO, ROOMY)).unwrap(); + (outcome, evm.ctx().detention().compute_limit()) }; - let unlimited = run(EvmTxRuntimeLimits::default()); - let stopped = run(EvmTxRuntimeLimits::default().with_tx_data_size_limit(100)); - assert!(!stopped.result.is_halt(), "{:?}", stopped.result); - assert_eq!( - stopped.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: TX_BODY_SIZE, - frame_local: false, - }) + let (within_limits, detained) = run(EvmTxRuntimeLimits::default()); + assert_eq!(detained, Some(CAP), "the beneficiary's transaction is detained from its start"); + assert!(within_limits.result.is_success(), "{:?}", within_limits.result); + let (stopped, detained) = run(EvmTxRuntimeLimits::default().with_tx_data_size_limit(100)); + assert_eq!(detained, Some(CAP), "the stopped one too"); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: TX_BODY_SIZE, + frame_local: false, + }; + assert!( + matches!(&stopped.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{:?}", + stopped.result ); - assert_eq!(stopped.gas, unlimited.gas, "the intrinsic gas alone, the reservoir back"); + assert_eq!(stopped.limit_exceeded, Some(stop)); + assert_eq!(stopped.gas, within_limits.gas, "the intrinsic gas alone, the reservoir back"); } /// The transaction's own frame crossing its frame budget — a frame cap of a hundred records' bytes, @@ -1305,8 +1337,12 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { used: 0, frame_local: true, }; - assert!(!outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.result.output(), Some(&stop.revert_data())); + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{:?}", + outcome.result + ); assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); } diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index ef6d32c0c..7490f6aad 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -569,11 +569,13 @@ fn test_consecutive_hints_add_up_on_the_transaction() { /// its gas limit. #[test] fn test_data_size_overflow_blocks_forwarding_and_stops_the_transaction() { + use revm::context::result::ExecutionResult; + const LIMIT: u64 = 2_048; let data = send_hint(&[0_u8; 4_096]); - let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); + let call = || call_oracle(BytecodeBuilder::default(), &data, 1_000_000); let (outcome, hints) = run_with_oracle_under( - with_contract(code), + with_contract(return_status(call())), call_tx(CONTRACT, [], U256::ZERO), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(LIMIT), ); @@ -586,13 +588,23 @@ fn test_data_size_overflow_blocks_forwarding_and_stops_the_transaction() { frame_local: false, }; assert_eq!(outcome.limit_exceeded, Some(stop)); - assert!(!outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.result.output(), Some(&stop.revert_data()), "the stop, not the status"); assert!( - outcome.gas.gas_used < crate::common::GAS_LIMIT / 10, - "the stop burns nothing: {}", - outcome.gas.gas_used + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "the stop, not the status: {:?}", + outcome.result + ); + + // What ran is the contract's code up to its call, which the stop answered at the Oracle's + // start, handing back what it forwarded: the same code stopping after a call to an Oracle with + // no code, without limits, runs exactly that. + let (ran, _) = run_with_oracle_under( + with_contract(call().stop().build()).account_code(ORACLE_CONTRACT_ADDRESS, Bytes::new()), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits(), ); + assert!(ran.result.is_success(), "{:?}", ran.result); + 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 From e31c378535ef84d0bad1b56a6eaf08b930dcb565 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 04:31:35 -0700 Subject: [PATCH 227/458] style(satin): match the creation column's start case with matches! --- crates/mega-evm/tests/satin/stops.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 6dcf2f4c0..5cad22ca0 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -488,7 +488,7 @@ fn creation_run( /// 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 let Creation::NestedStart = creation { + if matches!(creation, Creation::NestedStart) { return match limit { Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), Limit::KvUpdates => limits.with_tx_kv_update_limit(0), From 102376c977a250b00131580f02f45b1511bf195b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:22:51 -0700 Subject: [PATCH 228/458] test(keyless): pin the detention hold before the call's charges --- .../tests/system/keyless/detention.rs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index cc8305f29..4eec018d7 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -289,6 +289,26 @@ fn test_a_sender_that_is_the_beneficiary_holds_the_whole_deployment_to_the_cap() } } +/// 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 at the cap having computed exactly the cap. 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); + } + } +} + /* ---------- the control contracts ---------- */ /// A deployment in a subtree where volatile-data access is switched off keeps the refusal. With From aa37301cee49c27ee04355c0dd6a3e8b82ec04dc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:25:02 -0700 Subject: [PATCH 229/458] docs(keyless): take the creation's bump back only when it is the last --- AGENTS.md | 6 +-- crates/mega-evm/README.md | 5 ++- crates/mega-evm/src/system/AGENTS.md | 2 +- crates/mega-evm/src/system/keyless/mod.rs | 17 ++++---- crates/mega-evm/src/system/keyless/settle.rs | 20 +++++----- .../mega-evm/tests/system/keyless/charges.rs | 2 +- .../mega-evm/tests/system/keyless/deploy.rs | 2 +- crates/mega-evm/tests/system/keyless/rules.rs | 39 +++++++++++++++---- 8 files changed, 61 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 09f1816de..0aef9e805 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -209,9 +209,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` — or, inspected, `inspect_execution` just before it — settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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, and a keyless deployment never takes a signer past nonce 1, as the legacy engine did: the creation's bump stands only from 0 to 1, which is the replay barrier. - From nonce 1 the settlement sets the nonce back and takes the bump's write record and its history back, whether the deployment succeeded or failed, so 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()`. - Only the creation's own bump is taken back: nonces a delegated signer's code spends in the constructor stay spent, so the nonce never goes back below an account the signer created. + 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 and takes the bump's write record and its history back, whether the deployment succeeded or failed, when the 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()`. + A delegated signer whose code creates accounts in the constructor spends nonces after the bump; those stay spent and so does the bump, because the nonce never goes back below an account the signer created, so that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` stay in the ABI with no producer: 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. - 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. Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 9d1d38c07..be73874b4 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -95,8 +95,9 @@ It then starts the creation as the signer, below it, with `gasLimitOverride` cap 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 transaction limit the deployment crosses stops the transaction 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 and takes no signer past 1, as the legacy engine did. -A signer at nonce 1 stays there however often its deployment fails, so nobody can use up its attempts, and once it deploys, so a resubmission finds the address taken (`ContractAlreadyExists()`). +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 exception is a delegated signer whose code creates accounts in the constructor: the nonces it spends stay spent, and so does the creation's bump below them, so it 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 whitelist, the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 1a3ca29c7..571ac7a90 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -24,7 +24,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 charges nothing: the frame starts as it was built. - A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context), which gas detention holds as a running frame's before the call charges anything; it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1, kept by detention as the frame suspended on it. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped; the inspected path settles it in `inspect_execution` just before, and tells the inspector the call ended. -- 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, whether it deployed or failed: the settlement sets the nonce back and takes the record and its history back, so no deployment takes a signer past nonce 1, nobody can use up its attempts, and a resubmission of one that deployed is refused `ContractAlreadyExists()`, as in the legacy engine. It takes back the creation's own bump alone, the one just above the nonce the call started from: nonces a delegated signer's code spent in the constructor stay spent. +- 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 and takes the record and its history 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. A delegated signer whose code creates accounts in the constructor spends nonces after the bump; those stay spent and so does the bump, because the nonce cannot go back below an account the signer created, so 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 is not forwarded is not counted. - 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. diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 37c620110..aa97bd643 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -18,13 +18,16 @@ //! //! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. //! - 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 keeps the bump only -//! from 0 to 1, which is the replay barrier; from nonce 1, whether it succeeds or fails, it -//! leaves the nonce at 1 and keeps no record of the bump, as the legacy engine never took a -//! signer past 1. The call is permissionless and the signed transaction public, so no number of -//! failing calls, whoever makes them, gets a signer's deployment refused, and a deployment that -//! succeeded answers a resubmission with `ContractAlreadyExists()`. Nonces a delegated signer's -//! own code spends in the constructor stay spent. +//! once the signer's nonce is above 1 (`SignerNonceTooHigh`). A deployment from nonce 0 keeps the +//! bump, which is the replay barrier. A deployment from nonce 1 takes the bump back, with its +//! record, whether it succeeds or fails, when the bump 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()`. A delegated signer whose code creates accounts in the constructor +//! spends further nonces after the bump; those stay spent, and so does the bump, because the +//! nonce cannot go back below an account the signer created. Such a signer ends above 1, and +//! every later deployment of it is refused `SignerNonceTooHigh`. //! - 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, diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index ce3a57667..380c3ed75 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -55,14 +55,15 @@ pub(crate) fn give_back_history( /// back too. The creation's lane was popped when it returned, or is popped here when it never /// ran. /// -/// A deployment keeps the creation's nonce bump only when it took the signer from 0 to 1: a -/// deployment from nonce 1, whether it succeeded or failed, leaves the nonce at 1 -/// ([`take_back_bump`]), as the legacy engine did. 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`. Only the creation's own bump is -/// taken back: the nonces a delegated signer's code spent in the constructor, creating accounts at -/// them, stay spent, so the nonce never goes back below an account the signer created. +/// A deployment from nonce 0 keeps the creation's nonce bump. A deployment from nonce 1, whether +/// it succeeded or failed, takes the bump back when it is the last nonce change the deployment +/// made ([`take_back_bump`]), leaving the nonce at 1, as the legacy engine did. 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 a delegated signer's code spent further nonces in the constructor, creating accounts at +/// them, nothing is taken back: the nonce cannot go back below an account the signer created. That +/// signer ends above 1, and a resubmission is refused `SignerNonceTooHigh`. /// /// Then the call answers, as a frame that resumes after its child returned would: /// @@ -107,7 +108,8 @@ where } // 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; any further one the signer's own code spent. + // the call started from, and it is taken back only when it is the last one: a further bump + // the signer's own code made holds an account at the nonce below it. if call.signer_nonce > 0 && nonce == call.signer_nonce + 1 { take_back_bump(ctx, &mut call, result)?; } diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 1d9a64c95..7920816cb 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -281,7 +281,7 @@ fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { /// 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 a deployment takes no signer past 1. +/// it to nonce 1, and the creation's bump from there is taken back. #[test] fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index a82729a75..548680449 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -123,7 +123,7 @@ fn test_keyless_deploy_increments_nonce_from_zero() { } /// A signer at nonce 1 still deploys at its Nick's-Method address, which is its first creation's -/// and not its nonce's, and stays at nonce 1: a deployment takes no signer past 1. +/// and not its nonce's, and stays at nonce 1: the creation's bump from 1 is taken back. #[test] fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { for gas_limit in GAS_LIMITS { diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 27af5f9f3..816c29cb1 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -5,9 +5,11 @@ //! 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 only from 0 to 1, -//! and takes no signer past 1, as the legacy engine did. A signer at nonce 1 stays there however -//! often its deployment fails, whoever submits it, and once it deploys. +//! 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 that creates accounts in its constructor ends above +//! 1, and is refused thereafter. use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ @@ -462,7 +464,7 @@ fn fail_then_deploy( 3, ); assert_eq!(returned(&deployed).deployedAddress, address, "at {deploying_at}"); - assert_eq!(nonce(&deployed, signer), 1, "a deployment takes no signer past 1"); + assert_eq!(nonce(&deployed, signer), 1, "the creation's bump from 1 is taken back"); db.commit(deployed.result_and_state.state); db } @@ -698,10 +700,12 @@ fn test_a_delegated_signer_deploys() { /// 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 — the settlement takes back the creation's own bump and nothing -/// else — so the nonce never goes back below an account the signer created, and the signer's -/// next creations land at fresh addresses. A creation that reverts takes the delegation's -/// creations back with it, and the signer ends at 1. +/// 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: 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"); @@ -739,6 +743,25 @@ fn test_nonces_a_delegated_signer_spends_in_its_deployment_stay_spent() { } 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); + assert!( + matches!(error, KeylessDeployError::ExecutionReverted { .. }), + "{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 { From 7e8688131a02e1724cd6ff0a3ebab136050bd7f7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:25:36 -0700 Subject: [PATCH 230/458] test(keyless): say what the transaction data-size stop's limit admits --- crates/mega-evm/tests/system/keyless/limits.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 68d709a39..7c99ac512 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -110,7 +110,9 @@ fn test_a_transaction_latched_by_its_body_deploys_nothing() { } } -/// A log that crosses the transaction's data-size limit stops the transaction: the call reverts +/// A log that crosses the transaction's data-size limit stops the transaction. The limit holds the +/// body, the two records of the creation's start and 100 bytes more, so the body passes and the +/// creation starts, and the constructor's `LOG0` of 2,000 bytes is what crosses: the call reverts /// with the stop, and the deployment is taken back whole. #[test] fn test_a_deployment_crossing_the_transaction_data_size_limit_stops_it() { From 26b5f96c1a2b0ae9333994758f0bc756eb1e49cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:29:22 -0700 Subject: [PATCH 231/458] fix(block): run the three pre-block calls through one helper and one error rule --- AGENTS.md | 1 + crates/mega-evm/README.md | 2 +- crates/mega-evm/src/block/eips.rs | 110 +++++++++++------- .../mega-evm/src/system/sequencer_registry.rs | 45 ++----- crates/mega-evm/tests/block/eips.rs | 38 ++---- 5 files changed, 93 insertions(+), 103 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0aef9e805..ecf1b0777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,6 +234,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 reaches the observer. + One helper runs all three pre-block calls and holds one rule for them (`block/eips.rs`, `transact_pre_block_call`): a database error during the call 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 — 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`). - 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). diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index be73874b4..d602cafde 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -64,7 +64,7 @@ A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is re 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. +A pre-block call that does not succeed refuses the block with the call's own validation error; a database error during it is an internal error instead, since it says nothing about the block. 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. diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 77c68cb6e..3efd75d02 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -7,19 +7,28 @@ //! 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. +//! chain can build on. A database error 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. #[cfg(not(feature = "std"))] use alloc as std; -use std::{boxed::Box, format, 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}; use alloy_hardforks::EthereumHardforks; -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, Bytes, B256, U256}; use op_revm::OpHaltReason; use revm::{ - context::{result::ResultAndState, Block, ContextTr}, + context::{ + result::{EVMError, ResultAndState}, + Block, ContextTr, + }, database::State, handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{Account, EvmState}, @@ -47,11 +56,49 @@ 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: +/// +/// - a database error 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: an EVM error other than the database's, and an outcome that is not a success, whether +/// the call reverted or halted. +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)) => 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. A call that does not succeed refuses the block, and its -/// state is handed to nobody. 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 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( @@ -74,29 +121,18 @@ where return Ok(None); } - let gas_limit = pre_block_call_gas_limit(block.gas_limit()); - let outcome = evm - .transact_system_call_with_gas_limit( - SYSTEM_ADDRESS, - HISTORY_STORAGE_ADDRESS, - parent_block_hash.0.into(), - gas_limit, - ) - .map_err(|e| BlockValidationError::BlockHashContractCall { message: e.to_string() })?; - if !outcome.result.is_success() { - return Err(BlockValidationError::BlockHashContractCall { - message: format!("the EIP-2935 pre-block call did not succeed: {:?}", outcome.result), - } - .into()); - } - Ok(Some(outcome)) + 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. A call that does not succeed -/// refuses the block, and its state is handed to nobody. The state is not committed. +/// refuses the block with [`BlockValidationError::BeaconRootContractCall`], and its state is +/// handed to nobody; a 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( @@ -127,27 +163,15 @@ where return Ok(None); } - let gas_limit = pre_block_call_gas_limit(block.gas_limit()); - let refused = |message: std::string::String| BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message, + let refused = |message| { + BlockValidationError::BeaconRootContractCall { + parent_beacon_block_root: Box::new(parent_beacon_block_root), + message, + } + .into() }; - let outcome = evm - .transact_system_call_with_gas_limit( - SYSTEM_ADDRESS, - BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - gas_limit, - ) - .map_err(|e| refused(e.to_string()))?; - if !outcome.result.is_success() { - return Err(refused(format!( - "the EIP-4788 pre-block call did not succeed: {:?}", - outcome.result - )) - .into()); - } - Ok(Some(outcome)) + 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. diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 017781b71..7ae069c50 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -14,25 +14,18 @@ //! Then it reads the live system address out of the registry ([`resolve_system_address`]), which //! the block's system-address transactions must come from. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::format; - use alloy_evm::block::BlockExecutionError; use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use op_revm::OpHaltReason; use revm::{ - context::{ - result::{EVMError, ResultAndState}, - Block, ContextTr, - }, + context::result::ResultAndState, state::{Account, EvmState, EvmStorageSlot, TransactionId}, }; use super::MEGA_SYSTEM_ADDRESS; use crate::{ - pre_block_call_gas_limit, ExternalEnvTypes, HardforkParams, HardforkParamsError, + transact_pre_block_call, ExternalEnvTypes, HardforkParams, HardforkParamsError, MegaBlockExecutionError, MegaEvm, MegaHardfork, }; use storage_slots::{ @@ -188,15 +181,17 @@ 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`]): 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. +/// ([`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 the database's stops it: a change the registry scheduled for this block must -/// be applied in it. A database error is the database's. +/// be applied in it. A 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> @@ -204,25 +199,9 @@ where DB: alloy_evm::Database, ExtEnvs: ExternalEnvTypes, { - let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); - let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit()); - let failed = |message| MegaBlockExecutionError::ApplyPendingChangesFailed { message }; - let outcome = match evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - gas_limit, - ) { - Ok(outcome) => outcome, - // A read the database could not serve says nothing about the block, as for the registry - // reads on either side of the call. - Err(EVMError::Database(error)) => return Err(BlockExecutionError::other(error)), - Err(error) => return Err(failed(format!("{error}")).into()), - }; - if !outcome.result.is_success() { - return Err(failed(format!("{:?}", outcome.result)).into()); - } - Ok(outcome) + 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) } /// Reads the live system address out of the registry: the address a system-address transaction @@ -270,7 +249,7 @@ mod tests { use crate::{MegaContext, MegaSpecId}; use alloy_primitives::address; use revm::{ - context::{BlockEnv, Transaction}, + context::{BlockEnv, ContextTr, Transaction}, database::{InMemoryDB, State}, handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{AccountInfo, Bytecode}, diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index b093916f1..4ade89b4c 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -479,38 +479,24 @@ fn failing_on(address: Address) -> ErrorInjectingDatabase { db } -/// A database error in the block hashes call refuses the block with the EIP-2935 error, carrying -/// the database's message. +/// 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_blockhashes_pre_block_call_db_error_returns_validation_error() { +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 refuses the block"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) - if message.contains("injected basic() error") - ), - "{err}" - ); + .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 refuses the block with the EIP-4788 error; the block -/// hashes call before it read what it needed. +/// 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_beacon_root_pre_block_call_db_error_returns_validation_error() { +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 refuses the block"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { - message, - .. - }) if message.contains("injected basic() error") - ), - "{err}" - ); + .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 observer receives for a pre-block call is the state op-revm's own system call From 2871ff59f30ca21b3aa113d77ea3292496f77a1c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:32:04 -0700 Subject: [PATCH 232/458] refactor(evm): answer a frame nothing may start before the keyless rewrite on both paths --- crates/mega-evm/src/evm/execution.rs | 45 +++++++++++++++---- .../mega-evm/src/system/keyless/dispatch.rs | 7 ++- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 4696a0009..4232305f1 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -475,15 +475,7 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - // The state gas the caller holds is held outside the frame it starts. The caller is the - // frame on top of the stack, suspended on this frame's input; the transaction's own frame - // has none, and starts on what was charged before it. - if self.inner.frame_stack.index().is_some() { - let held = self.inner.frame_stack.get().interpreter.gas.state_gas_spent(); - self.inner.ctx.additional_limit.note_caller_state_gas(held); - } - 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)); } let answer = match keyless::rewrite(&mut self.inner.ctx, &mut frame_init)? { @@ -662,6 +654,10 @@ where /// call's end once the creation is settled into it /// ([`inspect_execution`](InspectorHandler::inspect_execution)). A `keylessDeploy` call the /// rewrite answers is seen as the call it is, `call` and `call_end` paired around the answer. + /// + /// A frame nothing may start — a latched transaction's, one past the call-stack limit — is + /// answered after the inspector's `frame_start` and before the keyless rewrite, at the point + /// the plain path answers it ([`EvmTr::frame_init`]), and the inspector is told it ended. #[inline] fn inspect_frame_init( &mut self, @@ -672,6 +668,12 @@ where return answered_by_inspector(ctx, inspector, &frame_init, output) .map(ItemOrResult::Result); } + if let Some(mut output) = self.answered_before_building(&frame_init)? { + let (ctx, inspector) = self.ctx_inspector(); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); + return Ok(ItemOrResult::Result(output)); + } + let (ctx, inspector) = self.ctx_inspector(); match keyless::rewrite(ctx, &mut frame_init)? { Rewrite::NotKeyless => {} Rewrite::Answered(output) => { @@ -1022,6 +1024,31 @@ impl MegaEvm { }; crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth, caller_remaining) } + + /// Steps 1 and 2 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may + /// start ([`answer_before_building`]), with the empty lane that stands in for it. Both paths + /// make it before the keyless rewrite, so the rewrite never sees a latched transaction; on the + /// inspected path it comes after the inspector's `frame_start`, and the check `frame_init` + /// makes again finds nothing to answer. + /// + /// Before it, the state gas the caller holds is noted: it is held outside the frame it starts. + /// The caller is the frame on top of the stack, suspended on this frame's input; the + /// transaction's own frame has none, and starts on what was charged before it. + #[inline] + fn answered_before_building( + &mut self, + frame_init: &FrameInit, + ) -> Result, ContextDbError>> { + if self.inner.frame_stack.index().is_some() { + let held = self.inner.frame_stack.get().interpreter.gas.state_gas_spent(); + self.inner.ctx.additional_limit.note_caller_state_gas(held); + } + let answer = answer_before_building(&mut self.inner.ctx, frame_init)?; + if answer.is_some() { + self.inner.ctx.additional_limit.push_empty_frame(); + } + Ok(answer) + } } /// Holds the state gas the caller was charged upfront for the frame that is starting — the new diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 1835e60c1..ff47fd98e 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -96,7 +96,8 @@ pub(crate) struct KeylessCall { /// 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. A transaction the latch already -/// stopped is not dispatched either: its frame is answered with the stop. +/// stopped never reaches the rewrite: both frame-start paths answer its frame with the stop before +/// the rewrite runs. /// /// # What the call pays, and what it is held to /// @@ -224,8 +225,7 @@ fn rewrite_dispatched( } /// Whether `inputs` is a `keylessDeploy` call the rewrite takes: a `CALL` at `depth` 0 to -/// [`KEYLESS_DEPLOY_ADDRESS`] carrying the `keylessDeploy` selector, in a transaction the latch -/// has not stopped. +/// [`KEYLESS_DEPLOY_ADDRESS`] carrying the `keylessDeploy` selector. /// /// The depth is tested first: every frame below the transaction's own leaves after one /// comparison. @@ -238,7 +238,6 @@ fn is_dispatched( depth == 0 && inputs.target_address == KEYLESS_DEPLOY_ADDRESS && inputs.scheme == CallScheme::Call && - ctx.additional_limit.latched().is_none() && peek_selector(&inputs.input, ctx) == Some(IKeylessDeploy::keylessDeployCall::SELECTOR) } From dfcaa6abab226382227a448db4c0d2fbc1e38dc2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:33:21 -0700 Subject: [PATCH 233/458] docs(evm): name the refused keyless call as the answer that spends gas, and the creation's depth --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 10 ++++++---- crates/mega-evm/src/system/keyless/mod.rs | 6 ++++++ 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ecf1b0777..35c0e7b7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -277,7 +277,7 @@ Detention caps how much a transaction may still compute once it read such data ( Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. So is one priced between the allowance and its forward whose input fails a check made after its gas check: it runs out of the allowance before that check, where without the read the check fails the call, which burns its forward and which its caller survives. - 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer, or on a refused `keylessDeploy` call, in `inspect_frame_init`); an answer built on less than its caller forwarded is settled on the limit the caller forwarded. + 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer, or on a refused `keylessDeploy` call, in `inspect_frame_init`); the one answer of the engine's own that spends regular gas is a refused `keylessDeploy` call's, built on the whole forward, 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 a running frame: its gas is held to what the limit leaves it before it charges anything (`keyless::rewrite`), 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 the answer's settlement stops, whether a rule would then have refused the call or its creation would have run. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 3d2ec060c..8b853cd18 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -404,8 +404,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, an inspector's, or revm's for a - /// call it did not start. + /// `result` is the answer: a precompile's, an interceptor's, a refused `keylessDeploy` call's, + /// an inspector's, or revm's for a call it did not start. /// /// An answer marked as a crossing — a precompile that ran out of the allowance it was held to /// ([`restore_forward`](Self::restore_forward)) — crossed the limit. Otherwise, an answer that @@ -440,8 +440,10 @@ impl Detention { 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. An - // answer built on less than the frame was forwarded is settled on what it was + // 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 a refused `keylessDeploy` + // call's, built on the whole forward; 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. // // State and history gas that spilled onto regular gas would have drawn the withheld diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index aa97bd643..72a073f60 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -17,6 +17,12 @@ //! What the native frame means for a deployment: //! //! - `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, and `remainingComputeGas()` and `disableVolatileDataAccess()`, which act for the +//! frame one level above the one a call would start, see the keyless call as the frame above the +//! constructor: volatile-data access switched off from the call's depth covers the constructor, +//! and the call's charges are compute a detained constructor has already spent. //! - 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. A deployment from nonce 1 takes the bump back, with its From dccd083da1e78e3b15397b1ef32b7ede66e90eb2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:40:41 -0700 Subject: [PATCH 234/458] test(keyless): pin the stop as a column of the matrix --- .../tests/system/keyless/detention.rs | 2 +- .../mega-evm/tests/system/keyless/limits.rs | 217 +++++++++++++++++- 2 files changed, 210 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index 4eec018d7..0585cba89 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -170,7 +170,7 @@ fn burn(code: BytecodeBuilder, rounds: u16) -> BytecodeBuilder { /// 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. -fn reads_then_burns(first: u8, rounds: u16) -> Bytes { +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)) } diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 7c99ac512..4c4347564 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -8,6 +8,10 @@ //! 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 stop is pinned as a column of the matrix: every transaction-level 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 rewrites every frame result into a success. +//! //! 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. @@ -17,9 +21,16 @@ use mega_evm::{ constants::TX_GAS_LIMIT_CAP, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, LimitCheck, LimitKind, MegaLimitExceeded, }; -use revm::bytecode::opcode::{LOG0, PUSH0, REVERT}; +use revm::{ + bytecode::opcode::{LOG0, PUSH0, REVERT, TIMESTAMP}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + InstructionResult, + }, + Database, Inspector, +}; -use super::*; +use super::{detention::reads_then_burns, *}; use crate::common::context; /// Init code that logs `len` bytes of data and deploys a one-byte runtime. @@ -74,18 +85,34 @@ fn creation_stop(outcome: &Outcome) -> MegaLimitExceeded { /// 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); - assert_eq!(nonce(outcome, deployment.signer), 0, "the signer's nonce is taken back"); - assert!(code_hash(outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + 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], "at {gas_limit}"); - assert!(regular >= KEYLESS_DEPLOY_OVERHEAD_GAS, "the overhead stays spent"); - assert_eq!(outcome.usage.write_records, 0, "no record is kept"); + 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(), - "the reservoir comes back", + "{case}: the reservoir comes back", ); } } @@ -430,6 +457,180 @@ fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { } } +/* ---------- the stop, as a column of the matrix ---------- */ + +/// A transaction-level 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 slot the constructor fills crosses the state-gas limit. + StateGas, + /// 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; 3] = [Self::DataSize, Self::StateGas, Self::Compute]; + + /// The init code whose run crosses the limit. + fn init_code(self) -> Bytes { + match self { + Self::DataSize => logging(2_000), + Self::StateGas => filling_a_slot(), + Self::Compute => reads_then_burns(TIMESTAMP, 1_000), + } + } + + /// The limits under which a deployment of `deployment`, by a signer at `signer_nonce`, + /// crosses the limit, with the kind and the limit of the stop it reports. + fn limits( + self, + deployment: &Deployment, + signer_nonce: u64, + ) -> (EvmTxRuntimeLimits, LimitKind, u64) { + let limits = EvmTxRuntimeLimits::no_limits(); + match self { + Self::DataSize => { + // The body, the two records of the creation's start and 100 bytes more. + let limit = body_bytes(deployment) + 2 * 40 + 100; + (limits.with_tx_data_size_limit(limit), LimitKind::DataSize, limit) + } + Self::StateGas => { + // The signer's account when the bump creates it, the created account, and one + // gas short of the slot. + let signer = + if signer_nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; + let limit = signer + + entry(GasId::create_state_gas()) + + entry(GasId::sstore_set_state_gas()) - + 1; + (limits.with_tx_state_gas_limit(limit), LimitKind::StateGrowth, limit) + } + Self::Compute => { + // Read at the call's charges and the read's own two gas. + let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(self.init_code().len()); + let limit = charges + 2 + COMPUTE_CAP; + let limits = limits.with_block_env_access_compute_gas_limit(COMPUTE_CAP); + (limits, LimitKind::ComputeGas, limit) + } + } + } +} + +/// Records the result of every frame it sees end, then rewrites it into a success with no output +/// — a creation's too, whose address it revives: a tool's inspector the stop must see through. +#[derive(Default)] +struct Rewriter { + /// The frames that ended, deepest first: whether each was a creation, and its result before + /// the rewrite. + ended: Vec<(bool, InstructionResult)>, +} + +impl Inspector, EthInterpreter> for Rewriter { + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + self.ended.push((false, outcome.result.result)); + outcome.result.result = InstructionResult::Stop; + outcome.result.output = Bytes::new(); + } + + fn create_end( + &mut self, + _: &mut MegaContext, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.ended.push((true, outcome.result.result)); + outcome.result.result = InstructionResult::Return; + outcome.result.output = Bytes::new(); + outcome.address = Some(inputs.created_address(1)); + } +} + +/// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit` under `limits`, without an +/// inspector and under a [`Rewriter`]: both outcomes, and the frames the rewriter saw end. +fn plain_and_rewritten( + 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(Rewriter::default()); + let rewritten = evm.execute_transaction(tx).expect("the transaction is valid"); + let ended = evm.inspector().ended.clone(); + (plain, rewritten, ended) +} + +/// The stop, as a column of the matrix: each transaction-level limit a deployment's creation can +/// cross — data size, state gas, 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 rewrites every frame result into a success and revives the creation. +/// +/// Every run reverts with the stop and keeps nothing of the deployment: the signer's nonce is +/// where it was, neither spent from 0 nor left at 2 from 1; no code, no record, and no state or +/// history gas beyond the transaction's body; above the cap the reservoir comes back. A compute +/// stop bills exactly its limit past the body: the call's charges, the read and the cap. The +/// inspector sees the creation end with the stop, then the call, and changes nothing the +/// transaction reports. +#[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, kind, limit) = crossing.limits(&deployment, signer_nonce); + 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, rewritten, ended) = + plain_and_rewritten(db.clone(), &deployment, gas_limit, limits); + for (column, outcome) in [("plain", &plain), ("rewritten", &rewritten)] { + let cell = format!("{row}, {column}"); + assert_eq!( + stop(outcome), + MegaLimitExceeded { kind: kind.as_u8(), limit }, + "{cell}" + ); + assert!( + matches!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: stopped, limit: at, frame_local: false, .. + }) if stopped == kind && at == limit + ), + "{cell}: {:?}", + outcome.limit_exceeded + ); + assert_nothing_kept(outcome, &deployment, gas_limit, signer_nonce, &cell); + if kind == LimitKind::ComputeGas { + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [_, regular, ..] = beyond(outcome, &reference); + assert_eq!(regular, limit, "{cell}: computed up to the limit exactly"); + } + } + assert_eq!( + ended, + [(true, InstructionResult::Revert), (false, InstructionResult::Revert)], + "{row}: the creation, then the call, each ended with the stop", + ); + assert_eq!(rewritten.result_and_state, plain.result_and_state, "{row}"); + assert_eq!(rewritten.gas, plain.gas, "{row}"); + assert_eq!(rewritten.usage, plain.usage, "{row}"); + assert_eq!(rewritten.limit_exceeded, plain.limit_exceeded, "{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] From f4f6e4a3c7f17fbea42f89e23a150cadbbd1635d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:43:19 -0700 Subject: [PATCH 235/458] test(satin): pin frames answered without running three calls down as cells of the matrix --- crates/mega-evm/tests/satin/stops.rs | 287 +++++++++++++++++++- crates/mega-evm/tests/satin/withheld_gas.rs | 6 +- 2 files changed, 288 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 5cad22ca0..465a6e061 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -18,6 +18,11 @@ //! //! A column of creations holds the same under that inspector, which revives a stopped creation: //! once the transaction is latched the revival is not refused, and the creation reports the 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, a value call +//! whose new account crosses the state-gas limit, and a start whose records cross the data-size +//! limit before the frame is built — and settle the same way. use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ @@ -28,7 +33,7 @@ use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, - LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_BASE_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -38,14 +43,16 @@ use revm::{ context::result::ExecutionResult, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, - CreateInputs, CreateOutcome, InstructionResult, Interpreter, + CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, }, + primitives::HashMap, Database, Inspector, }; use crate::{ common::{call, call_with_data, create}, detention::{context, work, BENEFICIARY}, + withheld_gas::{priced, Runs, PRICED}, }; const CALLER: Address = address!("0000000000000000000000000000000000500000"); @@ -1346,3 +1353,279 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); } + +/* ---------- 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 transaction-level +/// 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`], which revm answers without running: the account it adds + /// crosses the state-gas limit. + NewAccount, + /// `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::NewAccount | Self::StartRecords => EMPTY, + } + } +} + +/// The chain `A` → `B` → `C` → the answered frame, stopped or its twin. `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 the stopped transaction's frames +/// drop the status and stop, and the twin's revert. +fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { + let end = |code: BytecodeBuilder| { + if twin { + revert(code).build() + } else { + 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::NewAccount | 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 limits `answered`'s chain crosses its limit under, and the stop it reports. The compute +/// limit is set by `A`'s read, at the read's own two gas plus the cap. +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 + CAP)) + } + Answered::NewAccount => { + let unlimited = + execute(answered_chain(answered, false), EvmTxRuntimeLimits::no_limits(), BELOW); + assert!(unlimited.result.is_success(), "{:?}", unlimited.result); + let account = unlimited.gas.state; + ( + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), + stop(LimitKind::StateGrowth, account - 1, account), + ) + } + 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 [`Rewriter`] 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, false)).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(Rewriter::default()); + 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. +/// +/// A compute stop bills exactly its limit past the intrinsic gas. Any other stop bills what ran, +/// read off the twin: the same frames without limits, each reverting once its call returned, which +/// bills what the stopped frames ran plus the two pushes of each revert. +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, limit, .. } = stop else { unreachable!() }; + let ran = if kind == LimitKind::ComputeGas { + limit + } else { + let twin = + execute(answered_chain(answered, true), EvmTxRuntimeLimits::no_limits(), gas_limit); + assert!( + matches!(&twin.result, ExecutionResult::Revert { output, .. } if output.is_empty()), + "{row}: the twin reverts: {:?}", + twin.result + ); + twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT * 3 + }; + + 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; + 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.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); + 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 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!( + outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero()), + "{cell}: no value moved" + ); + if answered == Answered::Precompile { + let [(allowance, false)] = run.ran_on[..] else { + panic!("{cell}: the precompile ran on {:?}", run.ran_on) + }; + assert!(allowance < CAP, "{cell}: run on the allowance, {allowance}"); + } + } + assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); + assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + let ended: Vec<_> = [answered.target(), C, B, A] + .into_iter() + .map(|frame| (frame, InstructionResult::Revert, stop.revert_data())) + .collect(); + assert_eq!( + rewritten.ended, ended, + "{row}: the answered frame, then every caller, ended stopped" + ); +} + +/// A frame three calls down that is answered without running, and whose answer crosses a limit, +/// stops the transaction as a frame that ran there does: an answer past what the compute limit +/// leaves the frame, a precompile run on that allowance and priced past it, and a value call to +/// an empty account whose new account crosses the state-gas limit. 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, every caller returns it without running on, and the transaction settles +/// like any stop: it bills what ran, keeps the body's history and nothing else, and gets its +/// reservoir back. +#[test] +fn test_an_answer_three_calls_down_stops_the_transaction_at_either_tier() { + for answered in [Answered::PastTheAllowance, Answered::Precompile, Answered::NewAccount] { + 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. The +/// transaction settles like any 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/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 9fcb7e2c8..ebfc84cf1 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -786,14 +786,14 @@ fn test_a_call_that_reads_the_beneficiary_costs_what_a_warm_account_costs() { /* ---------- answers ---------- */ /// A precompile that charges the price its input names, as one big-endian word. -const PRICED: Address = address!("0000000000000000000000000000000000d00013"); +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. -type Runs = Arc>>; +pub(crate) type Runs = Arc>>; /// The precompile at [`PRICED`], recording what it runs on into `runs`. -fn priced(runs: &Runs) -> DynPrecompile { +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::(); From 879208d99692206465606ecc521397defe4f9a3e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 11:45:03 -0700 Subject: [PATCH 236/458] refactor(evm): assert in debug that no frame returns a halt under the latch --- crates/mega-evm/src/evm/execution.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 4232305f1..72d6ffbe4 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -571,6 +571,16 @@ impl EvmTr for MegaEvm Date: Fri, 25 Sep 2026 12:26:07 -0700 Subject: [PATCH 237/458] test(system): pin the registry's refusal as a validation error --- crates/mega-evm/src/system/sequencer_registry.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 7ae069c50..bdb0c01b3 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -449,7 +449,8 @@ mod tests { assert!(err.to_string().contains("injected basic() error"), "{err}"); } - /// A registry whose code reverts fails the call, and the block with it. + /// 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])); @@ -460,6 +461,18 @@ mod tests { ); 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().contains("reverted or halted"), "{err}"); } From 648d4ffcd0355175dc8b1455a3ce8efc3442be0a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:27:54 -0700 Subject: [PATCH 238/458] fix(block): state the registry refusal's cause once --- crates/mega-evm/src/block/executor.rs | 7 +++---- crates/mega-evm/src/system/sequencer_registry.rs | 8 +++++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 8a6ab5b8e..f3a69be86 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -254,10 +254,9 @@ impl fmt::Display for MegaBlockExecutionError { f, "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" ), - Self::ApplyPendingChangesFailed { message } => write!( - f, - "the SequencerRegistry applyPendingChanges() pre-block call reverted or halted: {message}" - ), + Self::ApplyPendingChangesFailed { message } => { + write!(f, "the SequencerRegistry's pending changes could not be applied: {message}") + } Self::MissingSequencerRegistry => { f.write_str("the SequencerRegistry does not exist; the system address cannot be read") } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index bdb0c01b3..b8027e37a 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -473,7 +473,13 @@ mod tests { ), "{err:?}" ); - assert!(err.to_string().contains("reverted or halted"), "{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. From d9a26ddc4935d8a46d4a05f35352fa569c5272f8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:30:04 -0700 Subject: [PATCH 239/458] fix(block): classify a pre-block call's database error by is_fatal, as a transaction's --- AGENTS.md | 3 +- crates/mega-evm/README.md | 3 +- crates/mega-evm/src/block/eips.rs | 124 +++++++++++++++--- .../mega-evm/src/system/sequencer_registry.rs | 6 +- 4 files changed, 115 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 35c0e7b7f..c44f138ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,7 +234,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 reaches the observer. - One helper runs all three pre-block calls and holds one rule for them (`block/eips.rs`, `transact_pre_block_call`): a database error during the call 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 — 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`). + 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). diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index d602cafde..fc2961430 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -64,7 +64,8 @@ A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is re 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 during it is an internal error instead, since it says nothing about the block. +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. diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 3efd75d02..f895346ca 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -7,9 +7,9 @@ //! 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 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. +//! 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. #[cfg(not(feature = "std"))] use alloc as std; @@ -27,7 +27,7 @@ use op_revm::OpHaltReason; use revm::{ context::{ result::{EVMError, ResultAndState}, - Block, ContextTr, + Block, ContextTr, DBErrorMarker, }, database::State, handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, @@ -60,14 +60,17 @@ pub fn pre_block_call_gas_limit(block_gas_limit: u64) -> u64 { /// 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: +/// 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 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; +/// - 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: an EVM error other than the database's, and an outcome that is not a success, whether -/// the call reverted or halted. +/// 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, @@ -83,7 +86,9 @@ where let outcome = match evm.transact_system_call_with_gas_limit(SYSTEM_ADDRESS, target, data, gas_limit) { Ok(outcome) => outcome, - Err(EVMError::Database(error)) => return Err(BlockExecutionError::other(error)), + 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() { @@ -97,8 +102,8 @@ where /// /// Answers `None`, having run nothing, when Prague is not active or the block is the genesis /// 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 database -/// error is an internal error, as for every pre-block call. The state is not committed. +/// [`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( @@ -131,8 +136,8 @@ where /// 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. A call that does not succeed /// refuses the block with [`BlockValidationError::BeaconRootContractCall`], and its state is -/// handed to nobody; a database error is an internal error, as for every pre-block call. The -/// state is not committed. +/// 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( @@ -203,8 +208,17 @@ pub fn transact_balance_increments( #[cfg(test)] mod tests { use super::*; + use crate::{ + test_utils::{ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, + MegaContext, MegaSpecId, + }; use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; + use revm::{ + context::BlockEnv, + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + DatabaseCommit, + }; use std::vec; #[test] @@ -288,4 +302,82 @@ mod tests { assert!(produced.is_empty()); } + + /// 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) + } + } + + impl core::error::Error for NotFatal {} + + impl DBErrorMarker for NotFatal { + fn is_fatal(&self) -> bool { + false + } + } + + /// An [`ErrorInjectingDatabase`] whose errors are not fatal. + #[derive(Debug)] + struct NotFatalDb(ErrorInjectingDatabase); + + 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 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_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/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index b8027e37a..01c8e0764 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -189,9 +189,9 @@ fn read_slot( /// # Errors /// /// [`MegaBlockExecutionError::ApplyPendingChangesFailed`] when the call reverts or halts, or an -/// error other than the database's stops it: a change the registry scheduled for this block must -/// be applied in it. A database error is an internal error, as for every pre-block call: it says -/// nothing about the block. +/// 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> From eb7bc8614e4e1af6902dcbe58570be02bf4dc60f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:31:58 -0700 Subject: [PATCH 240/458] test(keyless): pin where each limit of the stop column is crossed --- .../mega-evm/tests/system/keyless/limits.rs | 117 ++++++++++++------ 1 file changed, 77 insertions(+), 40 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 4c4347564..2a23c4eac 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -19,7 +19,7 @@ use alloy_sol_types::SolError; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, LimitCheck, - LimitKind, MegaLimitExceeded, + LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{LOG0, PUSH0, REVERT, TIMESTAMP}, @@ -139,12 +139,15 @@ fn test_a_transaction_latched_by_its_body_deploys_nothing() { /// A log that crosses the transaction's data-size limit stops the transaction. The limit holds the /// body, the two records of the creation's start and 100 bytes more, so the body passes and the -/// creation starts, and the constructor's `LOG0` of 2,000 bytes is what crosses: the call reverts -/// with the stop, and the deployment is taken back whole. +/// creation starts, and the constructor's `LOG0` of 2,000 bytes is what crosses: the stop reports +/// the body, the two records and the whole log as used, the call reverts with the stop, and the +/// deployment is taken back whole. #[test] fn test_a_deployment_crossing_the_transaction_data_size_limit_stops_it() { let deployment = Deployment::new(logging(2_000)); - let limit = body_bytes(&deployment) + 2 * 40 + 100; + let start = body_bytes(&deployment) + 2 * WRITE_RECORD_SIZE; + let limit = start + 100; + let used = start + LOG_BASE_SIZE + 2_000; for gas_limit in GAS_LIMITS { let outcome = limited( &deployment, @@ -152,10 +155,16 @@ fn test_a_deployment_crossing_the_transaction_data_size_limit_stops_it() { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit }, "at {gas_limit}"); - assert!(matches!( + assert_eq!( outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, frame_local: false, .. }) - )); + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used, + frame_local: false + }), + "at {gas_limit}: the constructor's log crosses" + ); assert_stopped_whole(&outcome, &deployment, gas_limit); } } @@ -486,41 +495,70 @@ impl Crossing { } /// The limits under which a deployment of `deployment`, by a signer at `signer_nonce`, - /// crosses the limit, with the kind and the limit of the stop it reports. - fn limits( - self, - deployment: &Deployment, - signer_nonce: u64, - ) -> (EvmTxRuntimeLimits, LimitKind, u64) { + /// crosses the limit, with the stop it reports: its kind, its limit, and what it counts as + /// used where the constructor crosses. + fn limits(self, deployment: &Deployment, signer_nonce: u64) -> (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. - let limit = body_bytes(deployment) + 2 * 40 + 100; - (limits.with_tx_data_size_limit(limit), LimitKind::DataSize, limit) + // 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::StateGas => { - // The signer's account when the bump creates it, the created account, and one - // gas short of the slot. + // The signer's account when the bump creates it, the created account, and the + // slot, which crosses a limit one gas short of it. let signer = if signer_nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; - let limit = signer + + let used = signer + entry(GasId::create_state_gas()) + - entry(GasId::sstore_set_state_gas()) - - 1; - (limits.with_tx_state_gas_limit(limit), LimitKind::StateGrowth, limit) + entry(GasId::sstore_set_state_gas()); + let limit = used - 1; + let stop = Crossed::new(LimitKind::StateGrowth, limit, used); + (limits.with_tx_state_gas_limit(limit), stop) } Self::Compute => { - // Read at the call's charges and the read's own two gas. + // Read at the call's charges and the read's own two gas; the stop brings the + // compute to the limit exactly. let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(self.init_code().len()); let limit = charges + 2 + COMPUTE_CAP; let limits = limits.with_block_env_access_compute_gas_limit(COMPUTE_CAP); - (limits, LimitKind::ComputeGas, limit) + (limits, Crossed::new(LimitKind::ComputeGas, limit, limit)) } } } } +/// 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 } + } + + /// The limit check the transaction's outcome reports for the stop. + const fn check(self) -> LimitCheck { + LimitCheck::ExceedsLimit { + kind: self.kind, + limit: self.limit, + used: self.used, + frame_local: false, + } + } +} + /// Records the result of every frame it sees end, then rewrites it into a success with no output /// — a creation's too, whose address it revives: a tool's inspector the stop must see through. #[derive(Default)] @@ -573,18 +611,22 @@ fn plain_and_rewritten( /// nonce 0 and at nonce 1, below the execution cap and above it, without an inspector and under /// one that rewrites every frame result into a success and revives the creation. /// -/// Every run reverts with the stop and keeps nothing of the deployment: the signer's nonce is -/// where it was, neither spent from 0 nor left at 2 from 1; no code, no record, and no state or -/// history gas beyond the transaction's body; above the cap the reservoir comes back. A compute -/// stop bills exactly its limit past the body: the call's charges, the read and the cap. The -/// inspector sees the creation end with the stop, then the call, and changes nothing the -/// transaction reports. +/// Every run reverts with the stop, and the stop counts as used what the constructor's crossing +/// brings the transaction to: the body, the start's two records and the whole log; the accounts +/// the deployment adds and the slot; the compute up to the limit. So the crossing is the +/// constructor's, not the creation's start or the call's charges. Every run keeps nothing of the +/// deployment: the signer's nonce is where it was, neither spent from 0 nor left at 2 from 1; no +/// code, no record, and no state or history gas beyond the transaction's body; above the cap the +/// reservoir comes back. A compute stop bills exactly its limit past the body: the call's +/// charges, the read and the cap. The inspector sees the creation end with the stop, then the +/// call, and changes nothing the transaction reports. #[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, kind, limit) = crossing.limits(&deployment, signer_nonce); + let (limits, expected) = crossing.limits(&deployment, signer_nonce); + let Crossed { kind, limit, .. } = expected; let db = match signer_nonce { 0 => system_db(), nonce => system_db().account_nonce(deployment.signer, nonce), @@ -600,15 +642,10 @@ fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { MegaLimitExceeded { kind: kind.as_u8(), limit }, "{cell}" ); - assert!( - matches!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: stopped, limit: at, frame_local: false, .. - }) if stopped == kind && at == limit - ), - "{cell}: {:?}", - outcome.limit_exceeded + assert_eq!( + outcome.limit_exceeded, + Some(expected.check()), + "{cell}: the constructor crosses" ); assert_nothing_kept(outcome, &deployment, gas_limit, signer_nonce, &cell); if kind == LimitKind::ComputeGas { From a18074bfa97f271e0b75e36ea56a6a6a90a389f9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:33:17 -0700 Subject: [PATCH 241/458] test(satin): derive the answered new account's limit from the schedule and check both inspector columns --- crates/mega-evm/tests/satin/stops.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 465a6e061..d913651ff 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -29,6 +29,7 @@ use mega_evm::{ constants::{ BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, }, + satin_gas_params, system::ORACLE_CONTRACT_ADDRESS, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, @@ -41,6 +42,7 @@ use revm::{ 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, @@ -1425,7 +1427,8 @@ fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { } /// The limits `answered`'s chain crosses its limit under, and the stop it reports. The compute -/// limit is set by `A`'s read, at the read's own two gas plus the cap. +/// limit is set by `A`'s read, at the read's own two gas plus the cap; the state-gas limit is one +/// gas short of the schedule's new account, which the test database prices at the minimum bucket. fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { let stop = |kind, limit, used| LimitCheck::ExceedsLimit { kind, limit, used, frame_local: false }; @@ -1434,10 +1437,7 @@ fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { (EvmTxRuntimeLimits::default(), stop(LimitKind::ComputeGas, 2 + CAP, 2 + CAP)) } Answered::NewAccount => { - let unlimited = - execute(answered_chain(answered, false), EvmTxRuntimeLimits::no_limits(), BELOW); - assert!(unlimited.result.is_success(), "{:?}", unlimited.result); - let account = unlimited.gas.state; + let account = satin_gas_params().get(GasId::new_account_state_gas()); ( EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), stop(LimitKind::StateGrowth, account - 1, account), @@ -1533,7 +1533,9 @@ fn run_answered( /// /// A compute stop bills exactly its limit past the intrinsic gas. Any other stop bills what ran, /// read off the twin: the same frames without limits, each reverting once its call returned, which -/// bills what the stopped frames ran plus the two pushes of each revert. +/// bills what the stopped frames ran plus the two pushes of each revert. The twin runs on the same +/// engine, so that 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); @@ -1600,6 +1602,13 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { rewritten.ended, ended, "{row}: the answered frame, then every caller, ended stopped" ); + 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, then every caller, ended stopped" + ); + } } /// A frame three calls down that is answered without running, and whose answer crosses a limit, From 625e1247cdca43fb941037011ae1710ed5ee03a6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:35:17 -0700 Subject: [PATCH 242/458] test(keyless): pin a delegated signer whose creation reverts in its deployment --- crates/mega-evm/tests/system/keyless/rules.rs | 60 ++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 816c29cb1..610cc714d 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -27,9 +27,12 @@ use mega_evm::{ MegaSpecId, MegaTransactionError, TestExternalEnvs, }; use revm::{ - bytecode::opcode::{CALL, CALLER, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, REVERT, STOP}, + 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, }; @@ -781,6 +784,61 @@ fn test_nonces_a_delegated_signer_spends_in_its_deployment_stay_spent() { } } +/// 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. #[test] fn test_keyless_deploy_contract_already_exists() { From db9dbd326e8753ff97df07ecdeb37843ea407f9d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:36:48 -0700 Subject: [PATCH 243/458] docs(keyless): state the take-back rule as the settlement applies it --- AGENTS.md | 6 +++-- crates/mega-evm/README.md | 3 ++- crates/mega-evm/src/system/AGENTS.md | 2 +- crates/mega-evm/src/system/keyless/mod.rs | 22 +++++++++------- crates/mega-evm/src/system/keyless/settle.rs | 25 +++++++++++-------- crates/mega-evm/tests/system/keyless/rules.rs | 4 +-- 6 files changed, 36 insertions(+), 26 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c44f138ce..4aa76d914 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -210,8 +210,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A stop the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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 and takes the bump's write record and its history back, whether the deployment succeeded or failed, when the 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()`. - A delegated signer whose code creates accounts in the constructor spends nonces after the bump; those stay spent and so does the bump, because the nonce never goes back below an account the signer created, so that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. + 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` stay in the ABI with no producer: 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. - 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. Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index fc2961430..918fed374 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -98,7 +98,8 @@ Once the creation returns the call answers in the contract's ABI — the deploye 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 exception is a delegated signer whose code creates accounts in the constructor: the nonces it spends stay spent, and so does the creation's bump below them, so it ends above 1 and every later deployment of it is refused. +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 whitelist, the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 571ac7a90..01415889a 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -24,7 +24,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 charges nothing: the frame starts as it was built. - A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context), which gas detention holds as a running frame's before the call charges anything; it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1, kept by detention as the frame suspended on it. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped; the inspected path settles it in `inspect_execution` just before, and tells the inspector the call ended. -- 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 and takes the record and its history 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. A delegated signer whose code creates accounts in the constructor spends nonces after the bump; those stay spent and so does the bump, because the nonce cannot go back below an account the signer created, so that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. +- 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 is not forwarded is not counted. - 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. diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 72a073f60..74e9882b1 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -25,15 +25,19 @@ //! and the call's charges are compute a detained constructor has already spent. //! - 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. A deployment from nonce 1 takes the bump back, with its -//! record, whether it succeeds or fails, when the bump 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()`. A delegated signer whose code creates accounts in the constructor -//! spends further nonces after the bump; those stay spent, and so does the bump, because the -//! nonce cannot go back below an account the signer created. Such a signer ends above 1, and -//! every later deployment of it is refused `SignerNonceTooHigh`. +//! 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 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, diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 380c3ed75..d36385614 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -55,15 +55,18 @@ pub(crate) fn give_back_history( /// back too. The creation's lane was popped when it returned, or is popped here when it never /// ran. /// -/// A deployment from nonce 0 keeps the creation's nonce bump. A deployment from nonce 1, whether -/// it succeeded or failed, takes the bump back when it is the last nonce change the deployment -/// made ([`take_back_bump`]), leaving the nonce at 1, as the legacy engine did. 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 a delegated signer's code spent further nonces in the constructor, creating accounts at -/// them, nothing is taken back: the nonce cannot go back below an account the signer created. That -/// signer ends above 1, and a resubmission is refused `SignerNonceTooHigh`. +/// A deployment from nonce 0 keeps the creation's nonce bump. 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`. /// /// Then the call answers, as a frame that resumes after its child returned would: /// @@ -108,8 +111,8 @@ where } // 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 further bump - // the signer's own code made holds an account at the nonce below it. + // 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 call.signer_nonce > 0 && nonce == call.signer_nonce + 1 { take_back_bump(ctx, &mut call, result)?; } diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 610cc714d..62f8e2d69 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -8,8 +8,8 @@ //! 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 that creates accounts in its constructor ends above -//! 1, and is refused thereafter. +//! 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::{ From 4b05d25c79f65fb55a5f45ca090b07829a85fba2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:36:55 -0700 Subject: [PATCH 244/458] docs(keyless): say what the creation's depth means on chain --- crates/mega-evm/src/system/keyless/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 74e9882b1..85e619570 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -19,10 +19,10 @@ //! - `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, and `remainingComputeGas()` and `disableVolatileDataAccess()`, which act for the -//! frame one level above the one a call would start, see the keyless call as the frame above the -//! constructor: volatile-data access switched off from the call's depth covers the constructor, -//! and the call's charges are compute a detained constructor has already spent. +//! 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 From 165a117384cc842cbc09415b72d9a2dedd43eb1d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 12:59:10 -0700 Subject: [PATCH 245/458] refactor(host): read a slot without loading its account's code --- crates/mega-evm/src/evm/host.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 1c2ab7398..9650ac6be 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -402,7 +402,8 @@ pub trait JournalInspectTr { /// 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. + /// is zero without a database read. Never loads the account's code: a slot read needs only + /// the account and the slot in a witness, not its bytecode. fn inspect_storage( &mut self, address: Address, @@ -467,8 +468,9 @@ impl JournalInspectTr for Journal { key: StorageKey, ) -> Result<&EvmStorageSlot, DB::Error> { let transaction_id = self.transaction_id; - let is_newly_created = self.inspect_account(address, true)?.is_created(); + self.inspect_account_code_hash(address)?; let account = self.inner.state.get_mut(&address).expect("inspected above"); + let is_newly_created = account.is_created(); match account.storage.entry(key) { Entry::Occupied(entry) => Ok(entry.into_mut()), Entry::Vacant(entry) => { @@ -856,6 +858,25 @@ mod tests { ); } + /// `inspect_storage` reads the slot without hydrating the account's code, on either branch, + /// so a slot read leaves no bytecode in a stateless witness. + #[test] + fn test_inspect_storage_never_hydrates_code() { + const ADDR: Address = address!("00000000000000000000000000000000000000ee"); + let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + let code_is_loaded = + |journal: &Journal| journal.inner.state[&ADDR].info.code.is_some(); + + journal.inspect_storage(ADDR, U256::from(1)).expect("vacant read must succeed"); + assert!(!code_is_loaded(&journal), "the vacant branch must not hydrate info.code"); + + journal.inspect_storage(ADDR, U256::from(2)).expect("occupied read must succeed"); + assert!(!code_is_loaded(&journal), "the occupied branch must not hydrate info.code"); + assert!(journal.inner.state[&ADDR].is_cold_transaction_id(journal.transaction_id)); + } + /// The Host stages what each state-writing call observed and counts nothing: counting is the /// opcode wrapper's, after the opcode completed. #[test] From 6dc052ca560da11ef248c8c071522daef932f976 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:01:50 -0700 Subject: [PATCH 246/458] perf(limit): compute a child frame's share of its parent's budget in u64 --- crates/mega-evm/src/limit/limit.rs | 34 ++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index b3ce68c66..fee1d4b1a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -863,14 +863,18 @@ impl AdditionalLimit { } } -/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`]. +/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`], rounded down. /// -/// The product is taken in `u128`, so a remaining budget near `u64::MAX` does not wrap. +/// 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 { - let remaining = remaining as u128; - let numerator = FRAME_DATA_SHARE_NUMERATOR as u128; - let denominator = FRAME_DATA_SHARE_DENOMINATOR as u128; - ((remaining * numerator) / denominator) as u64 + const N: u64 = FRAME_DATA_SHARE_NUMERATOR; + const D: u64 = FRAME_DATA_SHARE_DENOMINATOR; + const _: () = assert!(N < D && D % (D - N) == 0); + const K: u64 = D / (D - N); + remaining - remaining.div_ceil(K) } /// Whether starting `input` moves value from one account to another, which is what revm journals @@ -942,6 +946,24 @@ mod tests { 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()), From ed76ddd21d3b8a2a451ac6e994215f69125bab44 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:02:41 -0700 Subject: [PATCH 247/458] perf(limit): inline the pop of a returning frame's lane --- crates/mega-evm/src/limit/frame_limit.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index f8241ba49..dd604620c 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -307,6 +307,7 @@ impl FrameLimitTracker { /// 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 { From 1f62ef14388b435834a85b77f68c29d44fc2373d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:03:53 -0700 Subject: [PATCH 248/458] test(keyless): add a differential record of keyless deployments --- .../tests/system/keyless/differential.rs | 1078 +++++++++++++++++ crates/mega-evm/tests/system/keyless/mod.rs | 1 + 2 files changed, 1079 insertions(+) create mode 100644 crates/mega-evm/tests/system/keyless/differential.rs 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..8416acf59 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -0,0 +1,1078 @@ +//! 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. +//! +//! The record is the way to hold a change to the engine's frame lifecycle to what it changes: +//! when `MEGA_KEYLESS_RECORD` names a file, the record is written there, and the records of two +//! builds can be compared line by line. The test itself 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 +//! latched body; 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, LOG0, 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, and the record is +/// written where `MEGA_KEYLESS_RECORD` says. +#[test] +fn test_keyless_differential_record() { + let mut record = String::new(); + for scenario in scenarios() { + 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(); + } + if let Ok(path) = std::env::var(RECORD_PATH) { + std::fs::write(&path, record).expect("the record is written"); + } +} + +/* ---------- 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 logs `len` bytes of data and deploys a one-byte runtime. +fn logging(len: u64) -> Bytes { + let prefix = + BytecodeBuilder::default().push_number(len).push_number(0_u64).append(LOG0).build_vec(); + constructor(&prefix, &runtime(1)) +} + +/// 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 slot = Deployment::new(filling_a_slot()); + 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)), + ); + let signer = if nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; + let used = + signer + entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()); + all.push( + Scenario::deploying( + format!("limit: state gas, nonce {nonce}"), + db(&slot), + &slot, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(used - 1)), + ); + 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: tx KV, nonce {nonce}"), + db(&slot), + &slot, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2)), + ); + all.push( + Scenario::deploying( + format!("limit: frame KV, nonce {nonce}"), + db(&slot), + &slot, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(3)), + ); + 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)), + ); + let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); + all.push( + Scenario::deploying( + format!("limit: upfront state gas, nonce {nonce}"), + db(&small), + &small, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1)), + ); + } + all.push( + Scenario::deploying("limit: a latched body", 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("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/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index ada705d2a..e54aac7bb 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -9,6 +9,7 @@ mod charges; mod deploy; mod detention; +mod differential; mod dispatch; mod inspector; mod limits; From 614441e100582994958cb1e5a5b46b45f99643d0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:10:32 -0700 Subject: [PATCH 249/458] feat(system)!: read the live system address inside the EVM A transaction of the system shape (a legacy call to a whitelisted contract) reads the SequencerRegistry's current system address from the journal, without warming it, when it is validated. Every other transaction reads nothing and is never a system-address transaction. The block executor no longer reads or plumbs the address. Removed: MegaContext::{system_address, set_system_address, with_system_address}, system::resolve_system_address, system::sent_from_system_address, PreBlockStateSource::SystemAddress and the three MegaBlockExecutionError variants only that read produced. A transaction from the system address of another shape now runs as an ordinary transaction instead of being refused. --- crates/mega-evm/src/block/executor.rs | 59 ++---- crates/mega-evm/src/evm/context.rs | 79 +++---- crates/mega-evm/src/evm/execution.rs | 34 ++- crates/mega-evm/src/evm/mod.rs | 3 - crates/mega-evm/src/external/gas.rs | 5 +- .../mega-evm/src/system/sequencer_registry.rs | 176 +++++++++------- crates/mega-evm/src/system/tx.rs | 178 +++++++++------- crates/mega-evm/src/test_utils/database.rs | 15 ++ crates/mega-evm/tests/block/deploy.rs | 6 +- .../tests/block/sequencer_registry.rs | 185 +++++++++------- crates/mega-evm/tests/satin/equivalence.rs | 15 +- .../mega-evm/tests/satin/history_exemption.rs | 1 + .../mega-evm/tests/satin/limit_exemption.rs | 1 + crates/mega-evm/tests/satin/system_call.rs | 12 +- crates/mega-evm/tests/satin/transfer_logs.rs | 1 + .../mega-evm/tests/satin/volatile_access.rs | 6 +- crates/mega-evm/tests/system/dispatch.rs | 75 ++++--- crates/mega-evm/tests/system/system_tx.rs | 199 ++++++++++++++---- 18 files changed, 636 insertions(+), 414 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index f3a69be86..eaa158406 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -52,8 +52,8 @@ //! # The pre-block observer //! //! Each pre-block step — the EIP-2935 call, the EIP-4788 call, every system-contract deploy, the -//! read of the `SequencerRegistry`'s pending changes, the `applyPendingChanges()` call and the read -//! of the live system address — produces an [`EvmState`] that this executor commits. alloy-evm 0.36 +//! read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` call — +//! produces an [`EvmState`] that this executor commits. alloy-evm 0.36 //! re-exports revm's `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on //! [`BlockExecutor`] and no source tag, so this crate names the step ([`PreBlockStateSource`]) and //! carries an optional [`PreBlockStateObserver`]. Every pre-block state is handed to the observer @@ -65,10 +65,13 @@ //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 //! and EIP-4788 calls, deploys the system contracts and the EIP-7997 factory (idempotent), then -//! applies a role change the `SequencerRegistry` has due in this block and reads the live system -//! address out of it ([`MegaContext::system_address`]). 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. +//! 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. +//! +//! The executor does not read the live system address: a transaction of the system shape reads it +//! out of the registry itself when it is validated, and the pre-block step is what leaves the +//! registry naming this block's address. #[cfg(not(feature = "std"))] use alloc as std; @@ -107,9 +110,8 @@ use crate::{ block::eips, estimated_da_size, system::{ - is_apply_pending_changes_due, resolve_system_address, system_contract_specs, - transact_apply_pending_changes, transact_deploy, SequencerRegistryConfig, - SystemContractDeployError, + is_apply_pending_changes_due, system_contract_specs, transact_apply_pending_changes, + transact_deploy, SequencerRegistryConfig, SystemContractDeployError, }, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, @@ -207,18 +209,6 @@ pub enum MegaBlockExecutionError { /// What the call ended with: its result, or the error that stopped it. message: String, }, - /// The live system address cannot be read: the `SequencerRegistry` has no account. - MissingSequencerRegistry, - /// The live system address cannot be read: the `SequencerRegistry` holds other code than - /// the contract this engine deploys. - SequencerRegistryCodeMismatch { - /// The hash this engine deploys. - expected: B256, - /// The hash in state. - found: B256, - }, - /// The `SequencerRegistry` holds a zero system address. - ZeroSystemAddress, } impl fmt::Display for MegaBlockExecutionError { @@ -257,16 +247,6 @@ impl fmt::Display for MegaBlockExecutionError { Self::ApplyPendingChangesFailed { message } => { write!(f, "the SequencerRegistry's pending changes could not be applied: {message}") } - Self::MissingSequencerRegistry => { - f.write_str("the SequencerRegistry does not exist; the system address cannot be read") - } - Self::SequencerRegistryCodeMismatch { expected, found } => write!( - f, - "SequencerRegistry code hash mismatch: expected {expected}, found {found}; the system address cannot be read" - ), - Self::ZeroSystemAddress => { - f.write_str("the SequencerRegistry holds a zero system address") - } } } } @@ -296,8 +276,6 @@ pub enum PreBlockStateSource { PendingChanges, /// The `SequencerRegistry.applyPendingChanges()` system call. ApplyPendingChanges, - /// The read of the live system address out of the `SequencerRegistry`. - SystemAddress, } /// Receives each pre-block [`EvmState`] before the executor commits it. @@ -562,8 +540,8 @@ where /// Runs what a block does before its transactions. /// /// In order: the admission gate, the reset of the block-hash record, the EIP-2935 and - /// EIP-4788 pre-block calls, the system-contract deploys, the `SequencerRegistry`'s due role - /// changes, and the read of the live system address. Each step's state is handed to the + /// EIP-4788 pre-block calls, the system-contract deploys and the `SequencerRegistry`'s due + /// role changes. Each step's state is handed to the /// pre-block observer and then committed here rather than inside its helper, so a witness /// generator sees every step's read and write set. The sequence the observer receives is /// the witness a stateless client needs. @@ -583,9 +561,10 @@ where /// The registry's role changes come after the deploy, which is what puts the registry in /// state on the chain's first block. Its pending slots are read and handed on 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. The system address - /// is read last, so a rotation due in this block governs this block's system-address - /// transactions; the EVM holds it for every transaction the block runs. + /// 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()?; @@ -644,10 +623,6 @@ where self.deliver_pre_block(PreBlockStateSource::ApplyPendingChanges, state); } - let (system_address, read) = resolve_system_address(self.evm.db_mut())?; - self.deliver_pre_block(PreBlockStateSource::SystemAddress, read); - self.evm.ctx_mut().set_system_address(system_address); - Ok(()) } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 7e38f36db..7807e8139 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -18,7 +18,7 @@ use crate::{ history::transaction_body_bytes, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{self, keyless::KeylessCall, MEGA_SYSTEM_ADDRESS}, + system::{self, keyless::KeylessCall}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, VolatileDataAccess, @@ -54,13 +54,11 @@ pub struct MegaContext MegaContext { bucket_multipliers: BucketMultipliers::default(), system_originated: false, prices_history: true, - system_address: MEGA_SYSTEM_ADDRESS, keyless_call: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, @@ -293,43 +290,17 @@ impl MegaContext { } /// Whether the running (or last) transaction is system-originated, and so prices every - /// EIP-8037 state gas charge at the minimum bucket and is held to no per-transaction limit. - /// 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 } - /// The address a system-address transaction must be sent from: a legacy call from it to a - /// whitelisted contract is the protocol's own, promoted to a deposit (see the - /// [`system`](crate::system) module). - /// - /// Block execution reads it out of the `SequencerRegistry` before every block's transactions, - /// once a rotation due in the block has been applied, so it is the live one for the block. A - /// context no block has been started on uses [`MEGA_SYSTEM_ADDRESS`] unless its builder set - /// another ([`set_system_address`](Self::set_system_address)). - pub const fn system_address(&self) -> Address { - self.system_address - } - - /// Sets the address system-address transactions come from, for every transaction from now - /// on. - /// - /// The block executor sets it itself, to the address it read out of the `SequencerRegistry` - /// before the block's transactions. An EVM a node builds outside block execution — an RPC - /// call, or the replay of a block's transactions for a trace — has no block to read it, so - /// the node reads the live address from the `SequencerRegistry` in the state the EVM runs on - /// and sets it here; otherwise, once the address has been rotated, that EVM runs the rotated - /// address's transactions as ordinary ones. - pub const fn set_system_address(&mut self, address: Address) { - self.system_address = address; - } - - /// [`set_system_address`](Self::set_system_address), as a builder. - pub const fn with_system_address(mut self, address: Address) -> Self { - self.system_address = address; - self - } - /// Whether the running (or last) transaction pays history gas for the bytes it appends. /// /// Three kinds of transaction pay none: a deposit, a transaction the protocol itself produced @@ -347,15 +318,17 @@ impl MegaContext { self.prices_history } - /// Prepares the common execution layer for a new transaction. Every transaction entry point - /// of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. - pub(crate) fn on_new_tx(&mut self) { - let system_originated = system::is_system_originated(&self.inner.tx, self.system_address); - self.prepare(system_originated); + /// 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 for a transaction of the system shape, 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)); } /// 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. @@ -744,7 +717,7 @@ 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"); @@ -849,7 +822,7 @@ mod tests { MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg.clone()); ctx.set_tx(call_from(Address::repeat_byte(0x11))); - ctx.on_new_tx(); + ctx.on_new_tx(false); assert!(!ctx.prices_history(), "a user's transaction pays no history"); assert_cfg_is(&ctx, &cfg); @@ -861,13 +834,13 @@ mod tests { 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(); + 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(); + ctx.on_new_tx(false); assert!(!ctx.prices_history()); assert_cfg_is(&ctx, &cfg); } @@ -883,7 +856,7 @@ mod tests { assert!(!ctx.is_neutral()); assert_satin_cfg(&ctx); ctx.set_tx(call_from(Address::repeat_byte(0x11))); - ctx.on_new_tx(); + ctx.on_new_tx(false); assert!(ctx.prices_history()); assert_satin_cfg(&ctx); } @@ -906,7 +879,7 @@ mod tests { 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(); + ctx.on_new_tx(false); assert_eq!( ctx.additional_limit.frame_start_transfer_log(&endowed_creation), emits_transfer_logs(ctx.cfg()), @@ -930,7 +903,7 @@ mod tests { cfg.amsterdam_eip7708_disabled = true; }); ctx.set_tx(call_from(Address::repeat_byte(0x11))); - ctx.on_new_tx(); + ctx.on_new_tx(false); assert!(ctx.additional_limit.frame_start_transfer_log(&endowed_creation)); } @@ -940,7 +913,7 @@ mod tests { 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(); + 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 72d6ffbe4..abe7b2efd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -10,6 +10,7 @@ use core::{cell::Cell, num::NonZeroU64}; use op_revm::{ handler::{IsTxError, OpHandler}, + transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; use std::{boxed::Box, vec::Vec}; @@ -49,10 +50,7 @@ use revm::{ use crate::{ evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, - system::{ - is_deposit_like_transaction, - keyless::{self, Rewrite}, - }, + system::keyless::{self, Rewrite}, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, }; @@ -155,11 +153,23 @@ 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. + /// 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. Only a transaction of the + /// system shape reads the live system address, from the journal and without warming it; every + /// other transaction pays the shape test, a comparison or two on its own fields. fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { - let system_address = evm.ctx_ref().system_address(); - crate::system::validate_and_promote::<_, _, Self::Error>(evm.ctx_mut(), system_address)?; + let ctx = evm.ctx_mut(); + let system_transaction = crate::system::is_live_system_transaction(ctx)?; + ctx.on_new_tx(system_transaction); + if system_transaction { + crate::system::validate_and_promote::<_, _, Self::Error>(ctx)?; + } self.op.validate_env(evm) } @@ -1296,15 +1306,17 @@ fn unbuilt_first_frame( /// 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. fn deposit_creates_caller( ctx: &mut MegaContext, ) -> Result { - if !is_deposit_like_transaction(ctx.tx(), ctx.system_address()) { + if ctx.tx().tx_type() != DEPOSIT_TRANSACTION_TYPE { return Ok(false); } let caller = ctx.tx().caller(); diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 1624bef63..bfc4c3c57 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -295,7 +295,6 @@ impl ExecuteEvm for MegaEvm Result { self.inner.ctx.set_tx(tx); - self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().run(self) } @@ -306,7 +305,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())) } @@ -334,7 +332,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) } } diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs index f09362e17..9c85e62ff 100644 --- a/crates/mega-evm/src/external/gas.rs +++ b/crates/mega-evm/src/external/gas.rs @@ -59,8 +59,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. diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 01c8e0764..253b12c4d 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -11,8 +11,15 @@ //! 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. -//! Then it reads the live system address out of the registry ([`resolve_system_address`]), which -//! the block's system-address transactions must come from. +//! +//! The live system address, which a system-address transaction must be sent from, is read out of +//! the registry by the transaction itself, and only by a transaction that has the system shape +//! ([`has_system_transaction_shape`](crate::system::has_system_transaction_shape)): validation +//! reads `_currentSystemAddress` from the journal without warming it ([`inspect_system_address`]) +//! and compares it with the caller. 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, U256}; @@ -26,7 +33,7 @@ use revm::{ use super::MEGA_SYSTEM_ADDRESS; use crate::{ transact_pre_block_call, ExternalEnvTypes, HardforkParams, HardforkParamsError, - MegaBlockExecutionError, MegaEvm, MegaHardfork, + JournalInspectTr, MegaBlockExecutionError, MegaEvm, MegaHardfork, }; use storage_slots::{ CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, @@ -204,43 +211,34 @@ where transact_pre_block_call(evm, "applyPendingChanges()", SEQUENCER_REGISTRY_ADDRESS, data, refused) } -/// Reads the live system address out of the registry: the address a system-address transaction -/// must be sent from in the block. Also answers the read, as a read-only entry of the registry's -/// account, which the caller hands on as a witness. +/// 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. +/// +/// `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. Block execution +/// never leaves such a registry behind — the pre-block deploy puts this code there or refuses the +/// block, and the contract writes no zero address — so these are states an EVM run outside block +/// execution may meet, and in none of them is any transaction a system-address transaction. /// -/// It is read once the block's pre-block changes are committed — the registry deployed and a due -/// rotation applied — so a rotation takes effect at its activation block. +/// The registry's account and the one slot are loaded cold and without the code: they are in the +/// transaction's state, so a stateless witness carries the read, and the transaction's own access +/// to either pays what it would have paid without it. /// /// # Errors /// -/// The deploy before it guarantees what is checked here, so each of these is a state no Satin -/// block leaves behind, and the block is refused rather than run against the wrong authority: -/// [`MegaBlockExecutionError::MissingSequencerRegistry`] when the registry has no account, -/// [`MegaBlockExecutionError::SequencerRegistryCodeMismatch`] when it holds other code than -/// [`SEQUENCER_REGISTRY_CODE`], and [`MegaBlockExecutionError::ZeroSystemAddress`] when its -/// `_currentSystemAddress` is zero. A database error is the database's. -pub fn resolve_system_address( - db: &mut DB, -) -> Result<(Address, EvmState), BlockExecutionError> { - let info = db - .basic(SEQUENCER_REGISTRY_ADDRESS) - .map_err(BlockExecutionError::other)? - .ok_or(MegaBlockExecutionError::MissingSequencerRegistry)?; - if info.code_hash != SEQUENCER_REGISTRY_CODE_HASH { - return Err(MegaBlockExecutionError::SequencerRegistryCodeMismatch { - expected: SEQUENCER_REGISTRY_CODE_HASH, - found: info.code_hash, - } - .into()); - } - let mut registry = Account::from(info); - let current = - read_slot(db, &mut registry, CURRENT_SYSTEM_ADDRESS).map_err(BlockExecutionError::other)?; - if current.is_zero() { - return Err(MegaBlockExecutionError::ZeroSystemAddress.into()); +/// The database's, when the account or the slot cannot be read. +pub(crate) fn inspect_system_address( + journal: &mut J, +) -> Result, J::DBError> { + if journal.inspect_account_code_hash(SEQUENCER_REGISTRY_ADDRESS)? != + SEQUENCER_REGISTRY_CODE_HASH + { + return Ok(None); } - let address = Address::from_word(current.into()); - Ok((address, EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)]))) + let current = journal + .inspect_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)? + .present_value(); + Ok((!current.is_zero()).then(|| Address::from_word(current.into()))) } #[cfg(test)] @@ -249,7 +247,7 @@ mod tests { use crate::{MegaContext, MegaSpecId}; use alloy_primitives::address; use revm::{ - context::{BlockEnv, ContextTr, Transaction}, + context::{BlockEnv, ContextTr, JournalTr, Transaction}, database::{InMemoryDB, State}, handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{AccountInfo, Bytecode}, @@ -501,68 +499,86 @@ mod tests { db } - fn resolve(db: &mut InMemoryDB) -> Result<(Address, EvmState), BlockExecutionError> { - resolve_system_address(&mut State::builder().with_database(db).build()) + /// Reads the live system address out of `db` through a fresh journal, and answers it with the + /// journal the read left behind. + fn inspect(db: InMemoryDB) -> (Option
, revm::Journal) { + let mut journal = revm::Journal::new(db); + let address = inspect_system_address(&mut journal).expect("the read succeeds"); + (address, journal) } - /// A registry holding the code this engine deploys resolves to the address it stores. + /// A registry holding the code this engine deploys names the address it stores. The read + /// leaves the registry's account and the one slot it read in the journal, cold, untouched and + /// unchanged: a witness of the read, and nothing a later access would find warm. #[test] - fn test_resolve_expects_the_deployed_code_hash() { - let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); - let (address, _) = resolve(&mut db).expect("the deployed registry resolves"); - assert_eq!(address, NEXT_SYSTEM_ADDRESS); - } - - /// A registry still holding the legacy engine's first bytecode is not the one this engine - /// deploys, and the read refuses it. - #[test] - fn test_resolve_rejects_the_v1_code_hash() { - use mega_system_contracts::sequencer_registry::{V1_0_0_CODE, V1_0_0_CODE_HASH}; - let mut db = registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS)); - let err = resolve(&mut db).expect_err("the v1 registry fails closed"); - assert!(err.to_string().contains("code hash mismatch"), "{err}"); - assert!(err.to_string().contains(&V1_0_0_CODE_HASH.to_string()), "{err}"); - } + fn test_inspect_answers_the_stored_system_address_and_warms_nothing() { + let db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let (address, journal) = inspect(db); + assert_eq!(address, Some(NEXT_SYSTEM_ADDRESS)); - /// The read answers the stored address and a witness holding the registry's account and the - /// one slot it read, read-only. - #[test] - fn test_resolve_returns_stored_system_address_with_witness() { - let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); - let (address, witness) = resolve(&mut db).unwrap(); - assert_eq!(address, NEXT_SYSTEM_ADDRESS); - - assert_eq!(witness.len(), 1); - let registry = &witness[&SEQUENCER_REGISTRY_ADDRESS]; + let registry = &journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert!(registry.is_cold_transaction_id(journal.transaction_id), "the account stays cold"); 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 stays cold"); assert!(!slot.is_changed()); assert_eq!(slot.present_value(), word(NEXT_SYSTEM_ADDRESS)); - assert_eq!(slot.original_value(), slot.present_value()); + assert!(journal.inner.journal.is_empty(), "the read leaves no journal entry"); + } + + /// A registry still holding the legacy engine's first bytecode is not the one this engine + /// deploys: it names no address, and its slot is not read. + #[test] + fn test_inspect_refuses_the_v1_code_hash() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let (address, journal) = inspect(registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS))); + assert_eq!(address, None); + assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].storage.is_empty()); } - /// A registry whose system address is zero is refused. + /// A registry holding foreign code names no address, whatever it stores. #[test] - fn test_resolve_zero_slot_errors() { - let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, None); - let err = resolve(&mut db).expect_err("a zero system address fails closed"); - assert!(err.to_string().contains("zero system address"), "{err}"); + fn test_inspect_refuses_foreign_code() { + let db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); + let (address, journal) = inspect(db); + assert_eq!(address, None); + assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].storage.is_empty()); } - /// A registry with no account is refused. + /// 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_resolve_missing_registry_errors() { - let err = resolve(&mut InMemoryDB::default()).expect_err("no registry fails closed"); - assert!(err.to_string().contains("does not exist"), "{err}"); + fn test_inspect_answers_no_address_for_a_zero_slot() { + let (address, journal) = inspect(registry_holding(SEQUENCER_REGISTRY_CODE, None)); + assert_eq!(address, None); + assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS] + .storage + .contains_key(&CURRENT_SYSTEM_ADDRESS)); } - /// A registry holding foreign code is refused, whatever it stores. + /// A state without the registry names no address, and the read records the account's + /// absence. #[test] - fn test_resolve_wrong_code_hash_errors() { - let mut db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); - let err = resolve(&mut db).expect_err("foreign code fails closed"); - assert!(err.to_string().contains("code hash mismatch"), "{err}"); + fn test_inspect_answers_no_address_without_a_registry() { + let (address, journal) = inspect(InMemoryDB::default()); + assert_eq!(address, None); + let registry = &journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(registry.is_loaded_as_not_existing()); + assert!(registry.storage.is_empty()); + } + + /// A read the database cannot serve is the database's error, not an absent address. + #[test] + fn test_inspect_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 err = inspect_system_address(&mut revm::Journal::new(db)).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 36e9c3f8e..da6f1aa29 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -1,17 +1,22 @@ //! 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 the system address the `SequencerRegistry` names -//! ([`MegaContext::system_address`](crate::MegaContext::system_address); [`MEGA_SYSTEM_ADDRESS`] -//! until a block has read it or the context is given one). 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`]. Validation tests the shape first, on the transaction's own +//! fields, and only a transaction that has it reads the live system address out of the registry +//! and compares it with its caller ([`is_live_system_transaction`]). A transaction of any other +//! shape reads nothing and is never a system-address transaction, whoever sent it: one from the +//! system address is an ordinary transaction, validated and charged as a user's is. //! //! 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). @@ -20,33 +25,27 @@ //! (`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::{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, + system::{inspect_system_address, ORACLE_CONTRACT_ADDRESS}, + types::MegaTransaction, + ExternalEnvTypes, JournalInspectTr, MegaContext, }; -/// The address the sequencer sends the protocol's own transactions from, until the -/// `SequencerRegistry` says otherwise. +/// The system address the unknown-chain placeholder schedule seeds the `SequencerRegistry` with. /// -/// A transaction from the system address is executed as a deposit: no signature, no nonce check -/// of op-revm's own and no fee. Which address that is can be rotated through the registry, and -/// block execution reads the live one out of it before every block -/// ([`MegaContext::system_address`](crate::MegaContext::system_address)). This is the address a -/// context uses before any block has been started on it, unless it is given another, and the one -/// the unknown-chain placeholder schedule seeds the registry with. +/// 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 of the +/// system shape ([`has_system_transaction_shape`]), 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 @@ -61,36 +60,63 @@ 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 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 decides whether a transaction reads the live system address at all, so it looks at the +/// transaction's own fields only: the type, then the destination against the one-entry whitelist. +/// A transaction that fails it, which is almost every transaction, reads nothing. +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 the running transaction is a system-address transaction: it has the system shape +/// ([`has_system_transaction_shape`]) and its caller is the live system address, read out of the +/// `SequencerRegistry` in the journal without warming it. +/// +/// A transaction of any other shape reads nothing. The registry cannot change its system address +/// inside a block after the pre-block step — 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 same address, the +/// one the block's pre-block step left, and an EVM run outside block execution reads the one in +/// the state it runs on. A registry that names no trusted address (see the registry's reader) +/// makes no transaction a system-address transaction. +/// +/// # Errors +/// +/// The database's, when the registry's account or its slot cannot be read. +pub(crate) fn is_live_system_transaction( + ctx: &mut MegaContext, +) -> Result { + let tx = ctx.tx(); + if !has_system_transaction_shape(tx.tx_type(), tx.kind()) { + return Ok(false); } + let caller = tx.caller(); + Ok(inspect_system_address(ctx.journal_mut())? == Some(caller)) } /// Whether `tx` is executed on the deposit path: a deposit transaction, or a system-address @@ -99,7 +125,8 @@ pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address 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. +/// 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 @@ -109,47 +136,35 @@ pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address /// /// 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, and no per-transaction limit stops it, so -/// the protocol's maintenance cannot fail on a resource limit. The mechanisms that meter read it -/// as they land. +/// 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)) } -/// 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. +/// [`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 || + tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH +} + +/// Validates a system-address transaction and promotes it to a deposit. /// -/// 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. +/// Called for the running transaction once [`is_live_system_transaction`] said 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), each under the configuration switch a user transaction +/// obeys. pub(crate) fn validate_and_promote( ctx: &mut MegaContext, - system_address: Address, ) -> 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 (eip3607_disabled, nonce_check_disabled) = @@ -166,7 +181,7 @@ where // 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 (system_address, tx_nonce) = (ctx.tx().caller(), ctx.tx().nonce()); let account = ctx.journal_mut().inspect_account(system_address, true)?; validate_account_nonce_and_code( &account.info, @@ -288,6 +303,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/database.rs b/crates/mega-evm/src/test_utils/database.rs index 47afb46ca..27ba51acd 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -8,6 +8,10 @@ use revm::{ state::{AccountInfo, Bytecode, EvmState}, }; +use crate::system::{ + storage_slots::CURRENT_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, +}; + /// A memory database for testing purposes. #[derive(Debug, Default, Clone, derive_more::Deref, derive_more::DerefMut)] pub struct MemoryDatabase { @@ -98,6 +102,17 @@ impl MemoryDatabase { self.set_account_storage(address, storage_key, value); self } + + /// Installs the `SequencerRegistry` this engine deploys, naming `system_address` the live + /// system address: a legacy call from it to a whitelisted contract is then a system-address + /// transaction, as it is on a chain whose registry names it. + pub fn sequencer_registry(self, system_address: Address) -> Self { + self.account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE).account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + U256::from_be_bytes(system_address.into_word().0), + ) + } } impl revm::Database for MemoryDatabase { diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 898cd6f18..7ef966bd1 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -52,16 +52,16 @@ fn deploy_sources() -> [PreBlockStateSource; SYSTEM_CONTRACT_DEPLOY_COUNT] { } /// The two EIP calls, the seven deploys, then the read of the registry's pending changes, which -/// finds none due on these blocks, and the read of the system address. +/// finds none due on these blocks. The live system address is not read before the block: a +/// system-address transaction reads it itself. fn assert_pre_block_order(outcomes: &[(PreBlockStateSource, revm::state::EvmState)]) { - assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 2); + assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 1); assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); for (i, source) in deploy_sources().iter().enumerate() { assert_eq!(outcomes[2 + i].0, *source); } assert_eq!(outcomes[2 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::PendingChanges); - assert_eq!(outcomes[3 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::SystemAddress); } fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryConfig) { diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 56046b000..473819e12 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -3,8 +3,10 @@ //! //! The registry is deployed before every block. After the deploy, the executor reads whether a //! role change is due in the block and, when one is, makes the `applyPendingChanges()` system -//! call; then it reads the system address the block's system-address transactions must come -//! from. Each step's state reaches the pre-block observer before it is committed. +//! call. Each step's state reaches the pre-block observer before it is committed. The executor +//! does not read the system address: a transaction of the system shape 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 std::sync::{Arc, Mutex}; @@ -33,6 +35,9 @@ use revm::{database::State, inspector::NoOpInspector, state::EvmState, Database} use crate::common::{self, pre_block_states, PreBlockLog, 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"); @@ -136,7 +141,7 @@ fn record(executor: &mut Executor<'_>) -> PreBlockLog { } /// The registry's own steps the observer received, in order: the deploy of it, the read of its -/// pending changes, the call that applies them and the read of the system address. +/// pending changes and the call that applies them. fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { pre_block_states(log) .into_iter() @@ -145,8 +150,7 @@ fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { source, PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS) | PreBlockStateSource::PendingChanges | - PreBlockStateSource::ApplyPendingChanges | - PreBlockStateSource::SystemAddress + PreBlockStateSource::ApplyPendingChanges ) }) .collect() @@ -162,24 +166,9 @@ fn start_block( let mut executor = executor(state, envs, gas_limit); let log = record(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); - assert_eq!( - executor.evm().ctx().system_address(), - Address::from_word(slot_of(®istry_steps(&log), CURRENT_SYSTEM_ADDRESS).into()), - "the EVM holds the system address the registry read found", - ); registry_steps(&log) } -/// The value the last registry step read or wrote for `slot`. -fn slot_of(steps: &[(PreBlockStateSource, EvmState)], slot: U256) -> U256 { - steps - .iter() - .rev() - .find_map(|(_, state)| state.get(&SEQUENCER_REGISTRY_ADDRESS)?.storage.get(&slot)) - .map(|slot| slot.present_value()) - .expect("a registry step touched the slot") -} - /// 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") @@ -206,7 +195,6 @@ fn test_a_due_change_is_applied_under_a_crowded_bucket() { PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), PreBlockStateSource::PendingChanges, PreBlockStateSource::ApplyPendingChanges, - PreBlockStateSource::SystemAddress, ] ); assert_eq!(envs.total_bucket_queries(), 0, "no pre-block step read a capacity"); @@ -228,7 +216,6 @@ fn test_a_block_with_nothing_due_makes_no_call() { [ PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), PreBlockStateSource::PendingChanges, - PreBlockStateSource::SystemAddress, ] ); let registry = &steps[1].1[&SEQUENCER_REGISTRY_ADDRESS]; @@ -280,8 +267,10 @@ fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { } /// A legacy call from `sender` to the Oracle's `getSlot(0)`: a system-address transaction when -/// `sender` is the block's system address, an ordinary one otherwise. It carries a gas price, so -/// an ordinary one needs a balance its sender does not have here. +/// `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(); Recovered::new_unchecked( @@ -299,31 +288,45 @@ fn registry_call_from(sender: Address, input: Vec) -> Recovered, sender: Address) { - assert_eq!(executor.evm().ctx().system_address(), sender); +/// 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) { - assert_ne!(executor.evm().ctx().system_address(), sender); 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}"); } -/// A fresh chain's first block deploys the registry and reads the system address its schedule -/// seeded it with: the registry's, not the engine's default. The read reaches the observer as a -/// read-only entry of the one slot. +/// 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(), word(system_address)); +} + +/// A fresh chain's first block deploys the registry seeded with the system address its schedule +/// names, and that address is the system address from the block's first transaction: the +/// registry's, not the engine's default. No pre-block step reads it; the system-address +/// transaction does, and its state carries the read. #[test] -fn test_bootstrap_block_resolves_system_address() { +fn test_the_bootstrap_block_promotes_the_seeded_system_address() { let mut state = common::state(); let mut executor = executor_on( &mut state, @@ -333,19 +336,17 @@ fn test_bootstrap_block_resolves_system_address() { ); let log = record(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); - assert_eq!(executor.evm().ctx().system_address(), GENESIS_SYSTEM_ADDRESS); - - let steps = registry_steps(&log); - let (source, read) = steps.last().expect("the read reached the observer"); - assert_eq!(*source, PreBlockStateSource::SystemAddress); - let registry = &read[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_touched(), "a read-only entry"); - assert_eq!(registry.storage.len(), 1); + let sources = sources(®istry_steps(&log)); assert_eq!( - registry.storage[&CURRENT_SYSTEM_ADDRESS].present_value(), - word(GENESIS_SYSTEM_ADDRESS) + sources, + [ + PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), + PreBlockStateSource::PendingChanges, + ] ); - assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH, "the deployed code"); + let outcome = assert_is_the_system_address(&mut executor, GENESIS_SYSTEM_ADDRESS); + assert_carries_the_system_address_read(&outcome.inner.state, GENESIS_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); drop(executor); // The registry is the one this engine ships, seeded with the schedule's roles and delay. @@ -353,17 +354,41 @@ fn test_bootstrap_block_resolves_system_address() { state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, SEQUENCER_REGISTRY_CODE_HASH, ); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), word(GENESIS_SYSTEM_ADDRESS)); assert_eq!( slot(&mut state, MIN_ROTATION_DELAY), U256::from(common::registry_config().min_rotation_delay) ); assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(common::SEQUENCER)); - // The default schedule seeds the engine's default address, and the read finds it. + // The default schedule seeds the engine's default address, and it is the system address. let mut state = common::state(); let mut default = self::executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); default.apply_pre_execution_changes().expect("the block starts"); - assert_eq!(default.evm().ctx().system_address(), MEGA_SYSTEM_ADDRESS); + assert_is_the_system_address(&mut default, MEGA_SYSTEM_ADDRESS); +} + +/// Once the registry is in place, no pre-block step carries the system address's slot: the +/// deploy leaves the registry as a read-only entry without storage, and the read of the pending +/// changes reads the pending slots alone. The slot is in the system-address transaction's own +/// state instead, read-only and cold, 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 mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + let log = record(&mut executor); + executor.apply_pre_execution_changes().expect("the block starts"); + for (source, state) in pre_block_states(&log) { + let slot = state + .get(&SEQUENCER_REGISTRY_ADDRESS) + .and_then(|registry| registry.storage.get(&CURRENT_SYSTEM_ADDRESS)); + assert!(slot.is_none(), "{source:?} 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 left the slot cold"); } /// A system-address transaction is recognised by the address read out of the registry: from it, @@ -395,11 +420,34 @@ fn test_system_address_change() { 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, so it reads no registry. +/// 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, @@ -411,13 +459,13 @@ fn context_outside_block<'a>( } /// An EVM a node builds outside block execution — for an RPC call, or to replay a block's -/// transactions for a trace — reads no registry, so the node sets the address it read there -/// itself. Given the rotated address, through the context's builder or the setter on a factory's -/// EVM, it promotes that address's Oracle transaction exactly as the block executor does: the same -/// result, state, gas and usage. Without it, it runs the transaction as an ordinary one, which the -/// empty sender cannot pay for. +/// 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_a_context_built_with_the_rotated_address_promotes_as_the_block_does() { +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(); @@ -425,14 +473,11 @@ fn test_a_context_built_with_the_rotated_address_promotes_as_the_block_does() { let mut executor = executor(&mut state, envs.clone(), common::BLOCK_GAS_LIMIT); executor.apply_pre_execution_changes().expect("the block starts"); - let in_block = executor.run_transaction(&tx).expect("the block promotes it").inner; + let in_block = assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS).inner; drop(executor); - assert!(in_block.result.is_success(), "{:?}", in_block.result); - assert_eq!(in_block.gas.history, 0, "the protocol's own transaction pays no history"); // 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<'_>| { - assert_eq!(evm.ctx().system_address(), NEXT_SYSTEM_ADDRESS); 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); @@ -440,22 +485,20 @@ fn test_a_context_built_with_the_rotated_address_promotes_as_the_block_does() { 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).with_system_address(NEXT_SYSTEM_ADDRESS), - )); - let mut evm = MegaEvmFactory::new() - .with_external_env_factory(envs.clone()) - .create_evm(&mut state, common::evm_env()); - evm.ctx_mut().set_system_address(NEXT_SYSTEM_ADDRESS); - assert_as_in_block(&mut evm); - - let mut evm = MegaEvm::new(context_outside_block(&mut state, &envs)); - assert_eq!(evm.ctx().system_address(), MEGA_SYSTEM_ADDRESS); - let err = evm - .execute_transaction(tx.to_tx_env()) - .expect_err("an ordinary transaction from an empty account is refused"); - assert!(err.to_string().contains("lack of funds"), "{err}"); + 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 sequencer rotation leaves the system address as it was. diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 9d42f7f45..ae05781b4 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -486,13 +486,18 @@ 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), @@ -515,6 +520,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:?}"); diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index ae4a43d35..a3adcc7d5 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -79,6 +79,7 @@ fn db() -> MemoryDatabase { .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`. diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index f02294075..6d5dae83e 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -64,6 +64,7 @@ fn db() -> MemoryDatabase { .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`. diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 827123b0d..2694bc5c7 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -464,6 +464,9 @@ fn system_address_transaction(gas_limit: u64) -> (TxEnv, OpTransaction) { /// 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 [ @@ -474,7 +477,8 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { ] { let db = MemoryDatabase::default() .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + .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); @@ -485,6 +489,10 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { 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}"); - assert_same(&mega_outcome.result_and_state, &op_outcome); + 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 index 266953dec..27dadd869 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -901,6 +901,7 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { 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 { diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 704f7369d..f25b0676f 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -349,7 +349,11 @@ 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()); + 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, 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/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 8b756fdf5..c84cc39a0 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -10,12 +10,17 @@ use mega_evm::{ MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, }, - test_utils::{op_transaction, MemoryDatabase}, + test_utils::{op_transaction, ErrorInjectingDatabase, GasInspector, MemoryDatabase}, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, }; use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; use revm::{ - context::{result::ExecutionResult, CfgEnv, TxEnv}, + bytecode::opcode::{SLOAD, STOP}, + context::{ + result::{EVMError, ExecutionResult}, + transaction::{AccessList, AccessListItem}, + CfgEnv, TxEnv, + }, database::State, DatabaseCommit, }; @@ -28,23 +33,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. @@ -218,33 +217,139 @@ 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 system address that does not have the system shape — off the +/// whitelist, a creation, another type than legacy — is an ordinary transaction: it is not +/// promoted, so an empty system address cannot pay its fee, and a funded one pays its fee and +/// its history like any sender. #[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_system_address_is_an_ordinary_transaction() { + let db = || chain_db().account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])); + for (shape, tx) in other_shapes(MEGA_SYSTEM_ADDRESS) { + let refused = rejection(db(), tx.clone()); + assert!(refused.contains("LackOfFundForMaxFee"), "{shape}: {refused}"); + + let mut evm = MegaEvm::new(chain_context( + db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS)), + )); + let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); + assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); + assert!(!evm.ctx().is_system_originated(), "{shape}"); + assert!(outcome.state[&MEGA_SYSTEM_ADDRESS].info.balance < U256::from(FUNDS), "{shape}"); + assert!(outcome.gas.history > 0, "{shape} pays history"); + } +} - 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}"); +/// A transaction without the system shape never reads the registry, whoever sends it: a database +/// that cannot serve the registry's account does not stop it, and its state holds nothing of the +/// registry. A legacy call to the Oracle has the shape, and its validation reads the registry, +/// here into the database's error. +#[test] +fn test_a_transaction_of_another_shape_never_reads_the_registry() { + let db = || { + let mut db = ErrorInjectingDatabase::new( + chain_db() + .account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS)) + .account_balance(CALLER, U256::from(FUNDS)), + ); + db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + db + }; + for caller in [MEGA_SYSTEM_ADDRESS, CALLER] { + for (shape, tx) in other_shapes(caller) { + let outcome = MegaEvm::new(chain_context(db())) + .execute_transaction(tx) + .expect("the registry is never read"); + assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); + assert!(!outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "{shape}"); + } + } + + let shaped = legacy_tx(CALLER, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 0); + let error = MegaEvm::new(chain_context(db())) + .execute_transaction(shaped) + .expect_err("the shaped transaction reads the registry"); + assert!(matches!(error, EVMError::Database(_)), "{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. +/// The read of the live system address warms nothing. A user's legacy call to the Oracle's +/// `setSlots` has the system shape, so its validation reads the registry's slot and finds the +/// caller is not the system address; the Oracle then asks the registry for the system address +/// itself, and that `SLOAD` pays the cold price, as it does for the same call as an EIP-2930 +/// transaction, which reads nothing at validation: the two spend the same gas on every ledger. +/// Only an access list that names the slot makes the `SLOAD` warm. #[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_the_read_leaves_the_slot_and_the_registry_cold() { + 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 (shaped, cold) = run(write()); + assert!( + shaped.state[&SEQUENCER_REGISTRY_ADDRESS].storage.contains_key(&CURRENT_SYSTEM_ADDRESS), + "the shaped transaction read the slot", + ); + let (unshaped, unread) = run(typed(write(), 1)); + assert_eq!(cold, unread, "the SLOAD after the read costs what it costs without one"); + assert_eq!(shaped.gas, unshaped.gas, "and so does the whole transaction"); + + let mut warmed = typed(write(), 1); + warmed.0.base.access_list = AccessList(vec![AccessListItem { + address: SEQUENCER_REGISTRY_ADDRESS, + storage_keys: vec![B256::from(CURRENT_SYSTEM_ADDRESS)], + }]); + let (_, warm) = run(warmed); + assert!(warm < cold, "a warm SLOAD ({warm}) is cheaper than the cold one ({cold})"); } /// The whitelist holds for the system address alone: anyone else may call anything, and pays @@ -659,19 +764,23 @@ fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { ); } -/// 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: it reads nothing of the registry and runs as the deposit it is, as +/// one carrying the hash from any other caller does (see +/// `test_a_deposit_from_another_caller_is_untouched`). 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_runs_as_a_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); - assert!( - refused.contains(NOT_A_SYSTEM_TRANSACTION), - "the refusal names the rule, not the whitelist alone: {refused}", - ); + let mut db = ErrorInjectingDatabase::new(chain_db()); + db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + let outcome = MegaEvm::new(chain_context(db)) + .execute_transaction(tx) + .expect("validation reads nothing of the registry"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); } From 5ebb7d33dbd142ad87a537458f247bc8f9e1a8e2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:11:55 -0700 Subject: [PATCH 250/458] refactor(evm): build a system call's transaction on its gas limit --- crates/mega-evm/src/evm/mod.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index bfc4c3c57..ed3cdfa06 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -344,6 +344,32 @@ where { } +/// The transaction a system call runs, on the gas limit its caller names. +trait SystemCallTxWithGasLimit: SystemCallTx { + /// 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 new_system_tx_with_gas_limit( + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, + ) -> Self; +} + +impl SystemCallTxWithGasLimit for MegaTransaction { + fn new_system_tx_with_gas_limit( + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, + ) -> Self { + let mut tx = Self::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, @@ -378,8 +404,7 @@ impl MegaEvm { data: Bytes, gas_limit: u64, ) -> Result, EVMError> { - let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); - tx.0.base.gas_limit = gas_limit; + let tx = MegaTransaction::new_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))) } From ebc6a112715b4f7b10cdfc2299c67283824d1d4c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:12:44 -0700 Subject: [PATCH 251/458] refactor(keyless): run the keylessDeploy call as a real revm frame --- crates/mega-evm/src/access/detention.rs | 32 +- crates/mega-evm/src/access/mod.rs | 9 +- crates/mega-evm/src/evm/context.rs | 16 +- crates/mega-evm/src/evm/execution.rs | 171 ++++------- crates/mega-evm/src/evm/frame.rs | 7 +- crates/mega-evm/src/limit/limit.rs | 18 +- .../mega-evm/src/system/keyless/dispatch.rs | 274 +++++++++--------- crates/mega-evm/src/system/keyless/mod.rs | 22 +- crates/mega-evm/src/system/keyless/settle.rs | 268 ++++++++--------- .../tests/satin/synthetic_frame_gas.rs | 18 +- 10 files changed, 388 insertions(+), 447 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 8b853cd18..361867fc9 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -55,10 +55,9 @@ struct DetainedFrame { /// /// 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 a running frame's is, then -/// starts its creation. It is kept as a frame suspended on the creation -/// ([`on_call_rewritten`](Self::on_call_rewritten)), so its charges are compute as a caller's -/// are, whether a rule then refuses the call or its creation runs. +/// `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 @@ -338,19 +337,6 @@ impl Detention { } } - /// The transaction's own frame, a keyless deployment's call whose gas is `gas`, was rewritten - /// into the creation it starts, without running: it is kept as the frame at depth 0, - /// suspended on the creation with the regular gas it spent — its own charges and the gas it - /// forwarded — so the creation's first run adds the charges to the transaction's compute, as - /// a caller's work before a `CREATE` is added. - /// - /// The call's charges were held to the limit as they were made: its gas was held as a - /// running frame's is ([`hold`](Self::hold)) before it charged anything. - pub(crate) fn on_call_rewritten(&mut self, gas: &Gas) { - debug_assert!(self.frames.is_empty(), "the call is the transaction's own frame"); - self.frames.push(DetainedFrame { at_suspension: regular_spent(gas), contribution: 0 }); - } - /// 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 @@ -404,8 +390,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 refused `keylessDeploy` call's, - /// an inspector's, or revm's for a call it did not start. + /// `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 that ran out of the allowance it was held to /// ([`restore_forward`](Self::restore_forward)) — crossed the limit. Otherwise, an answer that @@ -441,8 +427,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 a refused `keylessDeploy` - // call's, built on the whole forward; the limit is set to the forward all the same, so + // 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. // @@ -882,12 +868,12 @@ mod tests { let mut detention = detaining(); detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); let mut call = gas(100_000_000, 0); - detention.hold(&mut call); + detention.on_frame_run(&mut call, 0); assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); assert!(call.record_regular_cost(132_000)); assert!(call.record_withheld_first_cost(50_000_000)); - detention.on_call_rewritten(&call); + 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), 132_000, "the charges, not the forward"); diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index ab42ed483..16a825539 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -116,10 +116,11 @@ //! //! 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 gas held to the limit as a running 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 is kept as a frame suspended on it, and its charges are compute as a -//! caller's are; a call a rule refuses is an answer held by the rule above. The call reads its +//! 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. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 7e38f36db..41b793db5 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -18,7 +18,7 @@ use crate::{ history::transaction_body_bytes, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{self, keyless::KeylessCall, MEGA_SYSTEM_ADDRESS}, + system::{self, keyless::KeylessFrame, MEGA_SYSTEM_ADDRESS}, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, VolatileDataAccess, @@ -61,10 +61,9 @@ pub struct MegaContext, + /// 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, @@ -97,7 +96,7 @@ impl MegaContext { system_originated: false, prices_history: true, system_address: MEGA_SYSTEM_ADDRESS, - keyless_call: None, + keyless_frame: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -378,8 +377,9 @@ impl MegaContext { self.additional_limit.reset(); self.additional_limit.set_transfer_logs(emits_transfer_logs(&self.inner.cfg)); self.bucket_multipliers.reset(); - // A transaction that failed with an error left its `keylessDeploy` call unsettled. - self.keyless_call = None; + // 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); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 72d6ffbe4..d0bb2c427 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -23,12 +23,11 @@ use revm::{ }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, + journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, Host, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, - execution::runtime_oog_unwind, instructions::InstructionProvider, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, @@ -49,10 +48,7 @@ use revm::{ use crate::{ evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, - system::{ - is_deposit_like_transaction, - keyless::{self, Rewrite}, - }, + system::{is_deposit_like_transaction, keyless}, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, }; @@ -260,21 +256,12 @@ where /// 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. - /// - /// The outermost frame of a keyless deployment is the creation its `keylessDeploy` call - /// started, and the call is the transaction's own frame: the creation's result is settled into - /// the call first, which answers in the `IKeylessDeploy` ABI ([`keyless::settle`]). The - /// translation is made here, where every first-frame result arrives — a creation answered at - /// its start never returns through the frame lifecycle. The inspected path settles it earlier, - /// to tell the inspector the call ended ([`InspectorHandler::inspect_execution`]), and the - /// settlement here then finds nothing to do. fn last_frame_result( &mut self, evm: &mut Self::Evm, frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - keyless::settle::<_, _, Self::Error>(evm.ctx_mut(), frame_result)?; evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); self.op.last_frame_result(evm, frame_result, parent_gas)?; // The write record the transaction's own frame makes was charged before execution; a @@ -378,33 +365,6 @@ where + IsTxError, { type IT = EthInterpreter; - - /// revm's inspected execution, with the end of a keyless deployment's call reported. - /// - /// The call is the transaction's own frame, which runs no code, and its creation is the - /// outermost frame revm runs: revm's loop tells the inspector the creation ended, and nothing - /// tells it the call did. So the creation is settled into the call here, before - /// [`last_frame_result`](Handler::last_frame_result) would settle it, and the inspector is - /// told the call ended with the answer the settlement made. The rest is revm's. - fn inspect_execution( - &mut self, - evm: &mut Self::Evm, - checkpoint: JournalCheckpoint, - gas: &mut GasTracker, - ) -> Result, Self::Error> { - let Some(first_frame_input) = self.first_frame_input(evm, gas)? else { - unwind_runtime_oog(evm.ctx(), checkpoint)?; - return Ok(None); - }; - evm.ctx().journal_mut().checkpoint_commit(); - let mut frame_result = self.inspect_run_exec_loop(evm, first_frame_input)?; - let (ctx, inspector) = evm.ctx_inspector(); - if let Some(call) = keyless::settle::<_, _, Self::Error>(ctx, &mut frame_result)? { - frame_end_checked(ctx, inspector, &FrameInput::Call(call), &mut frame_result); - } - self.last_frame_result(evm, &mut frame_result, gas)?; - Ok(Some(frame_result)) - } } impl EvmTr for MegaEvm { @@ -437,11 +397,11 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Some(answer), - Rewrite::Rewritten | Rewrite::NotKeyless => self.intercept(&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) }; - // The frame that starts, as its caller forwarded it: the creation, when the rewrite made - // one of a `keylessDeploy` call, and the call itself when the rewrite answered it. 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(); @@ -524,10 +483,14 @@ impl EvmTr for MegaEvm { ctx.additional_limit.set_frame_address(address); hold_upfront_state_gas(ctx, None); + if keyless { + ctx.keyless_frame = Some(keyless::KeylessFrame::Built); + } Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } Err(mut result) => { @@ -548,7 +511,8 @@ impl EvmTr for MegaEvm 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(), @@ -591,21 +556,29 @@ impl EvmTr for MegaEvm Result, ContextDbError> { let refund = self.inner.ctx.additional_limit.on_frame_return(&mut 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: its caller, when it has one, is the `keylessDeploy` call that started it, - // which is settled once the transaction's frames are done. - if returned.is_none() { - self.inner.frame_stack.get().interpreter.gas.refill_history(refund); - } else { - keyless::give_back_history(&mut self.inner.ctx, refund); + // 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) } @@ -657,17 +630,13 @@ where /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it, and its /// answer is held to the state-gas limit as revm's own is ([`hold_upfront_state_gas`]). /// - /// A keyless deployment is seen as the frames it is made of. The inspector is told the - /// transaction's `keylessDeploy` call starts; the keyless rewrite then turns it into its - /// creation, and the inspector is told the creation starts, as the call's child, one journal - /// depth below it. Every step of the init code follows, then the creation's end, and the - /// call's end once the creation is settled into it - /// ([`inspect_execution`](InspectorHandler::inspect_execution)). A `keylessDeploy` call the - /// rewrite answers is seen as the call it is, `call` and `call_end` paired around the answer. - /// /// A frame nothing may start — a latched transaction's, one past the call-stack limit — is - /// answered after the inspector's `frame_start` and before the keyless rewrite, at the point - /// the plain path answers it ([`EvmTr::frame_init`]), and the inspector is told it ended. + /// 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, @@ -678,29 +647,6 @@ where return answered_by_inspector(ctx, inspector, &frame_init, output) .map(ItemOrResult::Result); } - if let Some(mut output) = self.answered_before_building(&frame_init)? { - let (ctx, inspector) = self.ctx_inspector(); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); - return Ok(ItemOrResult::Result(output)); - } - let (ctx, inspector) = self.ctx_inspector(); - match keyless::rewrite(ctx, &mut frame_init)? { - Rewrite::NotKeyless => {} - Rewrite::Answered(output) => { - return Ok(ItemOrResult::Result(answered_without_running( - ctx, - inspector, - &frame_init, - output, - ))); - } - Rewrite::Rewritten => { - if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - return answered_by_inspector(ctx, inspector, &frame_init, output) - .map(ItemOrResult::Result); - } - } - } 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)? { @@ -725,12 +671,15 @@ where 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 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. + /// 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. #[inline] fn inspect_frame_run( &mut self, @@ -738,6 +687,7 @@ 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, @@ -1036,10 +986,9 @@ impl MegaEvm { } /// Steps 1 and 2 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may - /// start ([`answer_before_building`]), with the empty lane that stands in for it. Both paths - /// make it before the keyless rewrite, so the rewrite never sees a latched transaction; on the - /// inspected path it comes after the inspector's `frame_start`, and the check `frame_init` - /// makes again finds nothing to answer. + /// start ([`answer_before_building`]), with the empty lane that stands in for it. It comes + /// before the keyless dispatch, so the dispatch never sees a latched transaction; on the + /// inspected path it comes after the inspector's `frame_start`. /// /// Before it, the state gas the caller holds is noted: it is held outside the frame it starts. /// The caller is the frame on top of the stack, suspended on this frame's input; the @@ -1095,17 +1044,6 @@ fn hold_upfront_state_gas( } } -/// revm's unwinding of a runtime phase that ran out of gas before the first frame. -/// -/// Called through this function rather than directly: the inspector handler's bounds keep the -/// compiler from reading the journal's database error as `DB::Error`, and here nothing does. -fn unwind_runtime_oog( - ctx: &mut MegaContext, - checkpoint: JournalCheckpoint, -) -> Result<(), DB::Error> { - runtime_oog_unwind(ctx, checkpoint) -} - /// Settles `output`, the answer the inspector gave the frame `frame_init` starts in its place. /// 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. @@ -1124,8 +1062,7 @@ where Ok(answered_without_running(ctx, inspector, frame_init, output)) } -/// Settles `output`, the answer the frame `frame_init` starts gets without running on the -/// inspected path — an inspector's, or a `keylessDeploy` call's the rewrite refused — as +/// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as /// [`EvmTr::frame_init`] settles an answer: an empty lane stands in for the frame, and the answer /// is held to the compute limit ([`settle_answer`]) and to the state-gas limit /// ([`hold_upfront_state_gas`]). Then the inspector is told the frame ended. diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 8f6b5b9fa..d981219e2 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -1,7 +1,7 @@ //! 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, the -//! system contract interceptors, a `keylessDeploy` call its rules refuse, and, when it lands, +//! system contract interceptors, a `keylessDeploy` call carrying value, and, when it lands, //! precompile normalisation. 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: //! @@ -15,9 +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 caller itself — a keyless deployment's call, which -//! takes back its creation's result as the frame of a `CREATE` does. +//! [`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/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index b3ce68c66..4e13b3c46 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -693,12 +693,12 @@ impl AdditionalLimit { /// 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 the keyless rewrite, 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: the keyless rewrite runs at the transaction's - /// own frame, which no opcode starts, and charges for the creation it builds itself. A - /// divergence trips here in every debug build rather than mis-charging the caller and - /// mis-splitting the refund its failure gets back. + /// 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, @@ -777,12 +777,6 @@ impl AdditionalLimit { true } - /// The number of frames with a lane: the frames on the call stack, and a `keylessDeploy` call - /// whose creation is running. - pub(crate) fn frame_depth(&self) -> usize { - self.tracker.depth() - } - /// Pushes the lane of a frame answered without running: a result built without an /// interpreter keeps the lanes aligned with the frames revm returns. /// diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ff47fd98e..df0f1daee 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -1,6 +1,5 @@ //! 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 is rewritten -//! into. +//! pays before its creation starts, the rules it is held to, and the creation it starts. #[cfg(not(feature = "std"))] use alloc as std; @@ -10,18 +9,18 @@ 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, Transaction}, context_interface::{ cfg::{GasId, StateGasCharge, StateGasSite}, - journaled_state::JournalCheckpoint, Host, }, - handler::FrameResult, + handler::{EthFrame, FrameResult}, interpreter::{ - interpreter_action::FrameInit, CallInputs, CallScheme, CreateInputs, CreateScheme, - FrameInput, Gas, InstructionResult, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, CallScheme, + CreateInputs, CreateScheme, FrameInput, Gas, InstructionResult, InterpreterAction, }, primitives::KECCAK_EMPTY, + state::Bytecode, }; use crate::{ @@ -31,43 +30,29 @@ use crate::{ intercept::peek_selector, keyless::{ calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, - recover_signer, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, - KEYLESS_DEPLOY_OVERHEAD_GAS, + recover_signer, settle, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, untouched_call_gas, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, MegaContext, VolatileDataAccess, }; -/// What the keyless rewrite made of a frame about to start. +/// 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 Rewrite { - /// The frame is not a keyless deployment; it starts as it is. - NotKeyless, - /// The frame is now the creation the `keylessDeploy` call stands for. The call's lane is - /// pushed and its [`KeylessCall`] is on the context, waiting for the creation's result. - Rewritten, - /// The call is answered without a frame: a rule refused it, or it could not pay for what its - /// creation's start makes. Nothing was written and no lane was pushed for it. - Answered(FrameResult), +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), } -/// A `keylessDeploy` call rewritten into its creation, from the rewrite until the creation's -/// result is settled into it ([`settle`](super::settle)). -/// -/// The call is a frame no code runs in: its lane is pushed and its journal checkpoint taken as -/// any frame's, and its gas holds what it paid before its creation started. The creation is its -/// child, and returns into it as a creation returns into the frame whose `CREATE` started it. +/// What a `keylessDeploy` call's creation is settled into the call with. #[derive(Debug)] -pub(crate) struct KeylessCall { - /// The call's inputs, as the transaction's frame was started with them: what the call - /// returns into, and what an inspector is told the call ended from. - pub(super) inputs: Box, - /// The call's gas: the gas and the reservoir the transaction's frame was forwarded, less the - /// overhead, the upfront charges and the gas forwarded to the creation. - pub(super) gas: Gas, - /// The journal checkpoint taken before the creation's start wrote anything. - pub(super) checkpoint: JournalCheckpoint, +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. @@ -81,31 +66,105 @@ pub(crate) struct KeylessCall { pub(super) signer_record_charge: u64, /// Whether the creation moves value out of the signer's account. pub(super) moves_value: bool, - /// The history the creation's lane gave back for the records the creation did not keep. - pub(super) returned_history: u64, } -/// Turns a `keylessDeploy` call at the transaction's own frame into the creation it stands for, -/// or answers it; any other frame is [`Rewrite::NotKeyless`]. +/// 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. A transaction the latch already stopped never reaches the dispatch: its frame +/// is answered with the stop before. /// -/// # What is dispatched +/// 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 holds it +/// from the fork that deploys it on, before any transaction. +#[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.clone())); + } + 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`]). /// -/// A `CALL` to [`KEYLESS_DEPLOY_ADDRESS`] whose first four bytes are the `keylessDeploy` -/// selector, at depth 0: 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. A transaction the latch already -/// stopped never reaches the rewrite: both frame-start paths answer its frame with the stop before -/// the rewrite runs. +/// A frame with a stop to return — the latch, or its own budget, which the nonce record a failed +/// creation leaves the call can cross — 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. /// /// # What the call pays, and what it is held to /// -/// In this order, each refusal an answer with the call's gas as it stands: +/// In this order, each refusal the frame's return with its gas as it stands: /// /// 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 is answered out of gas. -/// 2. The call carries no value (`NoEtherTransfer()`). +/// 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`). @@ -118,7 +177,7 @@ pub(crate) struct KeylessCall { /// 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 is answered out of gas. +/// 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 cold and without its @@ -128,7 +187,7 @@ pub(crate) struct KeylessCall { /// 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 is answered out of gas. +/// 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`). /// @@ -137,7 +196,7 @@ pub(crate) struct KeylessCall { /// 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 refusal writes nothing, so the answer takes back the state and history gas the call was +/// 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. @@ -145,54 +204,30 @@ pub(crate) struct KeylessCall { /// # The creation /// /// The creation is started as the signer's, at the signer's Nick's-Method address -/// (`CreateScheme::Custom`), at depth 1 below the call: the call's lane is pushed first, as the -/// transaction's own frame's is, and the creation is its child from there on — its share of the -/// data-size and KV budgets, its records, its forward and the reservoir it inherits, the -/// state-gas limit, the latch. The call's journal checkpoint is taken before the creation's -/// start writes the signer's nonce, so a call that is stopped takes that write back with the +/// (`CreateScheme::Custom`), as the call's child: its share of the data-size and KV budgets, its +/// records, its forward and the reservoir it inherits, the state-gas limit, the latch. 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. -#[inline] -pub(crate) fn rewrite( +fn start( ctx: &mut MegaContext, - frame_init: &mut FrameInit, -) -> Result> { - match &frame_init.frame_input { - FrameInput::Call(inputs) if is_dispatched(ctx, inputs, frame_init.depth) => { - rewrite_dispatched(ctx, frame_init) - } - _ => Ok(Rewrite::NotKeyless), - } -} - -/// [`rewrite`] of a call [`is_dispatched`] took. Kept out of line: every frame asks whether it is -/// a keyless deployment, one transaction in a great many is. -#[inline(never)] -fn rewrite_dispatched( - ctx: &mut MegaContext, - frame_init: &mut FrameInit, -) -> Result> { - let FrameInput::Call(inputs) = &frame_init.frame_input else { return Ok(Rewrite::NotKeyless) }; - let mut gas = untouched_call_gas(inputs); - // The call is the transaction's own frame, and gas detention holds it as a running frame - // before it charges anything: its regular charges draw only what the compute limit leaves it. - ctx.detention.hold(&mut gas); - let deployment = match prepare(ctx, inputs, &mut gas)? { + 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) => return Ok(Rewrite::Answered(refusal.answer(inputs, gas))), + Err(refusal) => { + let (result, output) = refusal.result(gas); + return Ok(InterpreterAction::new_return(result, output, *gas)); + } }; - // The call suspends on its creation, with its charges as its compute. - ctx.detention.on_call_rewritten(&gas); - - // The call's own lane, as the transaction's frame pushes it. A call carrying no value makes - // no record, so its start crosses nothing the body did not. - let _ = ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); ctx.additional_limit.set_frame_creator(deployment.signer); - ctx.additional_limit.note_caller_state_gas(gas.state_gas_spent()); if let Some((on_lane, caller)) = deployment.record_charges { ctx.additional_limit.stage_frame_charge(deployment.records, on_lane, caller); } - let checkpoint = ctx.journal_mut().checkpoint(); - let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, @@ -203,42 +238,15 @@ fn rewrite_dispatched( ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); - let FrameInput::Call(inputs) = - core::mem::replace(&mut frame_init.frame_input, FrameInput::Create(Box::new(create))) - else { - unreachable!("the rewrite starts from the call it dispatched") - }; - ctx.keyless_call = Some(KeylessCall { - inputs, - gas, - checkpoint, + 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(), - returned_history: 0, - }); - frame_init.depth += 1; - Ok(Rewrite::Rewritten) -} - -/// Whether `inputs` is a `keylessDeploy` call the rewrite takes: a `CALL` at `depth` 0 to -/// [`KEYLESS_DEPLOY_ADDRESS`] carrying the `keylessDeploy` selector. -/// -/// The depth is tested first: every frame below the transaction's own leaves after one -/// comparison. -#[inline] -fn is_dispatched( - ctx: &MegaContext, - inputs: &CallInputs, - depth: usize, -) -> bool { - depth == 0 && - inputs.target_address == KEYLESS_DEPLOY_ADDRESS && - inputs.scheme == CallScheme::Call && - peek_selector(&inputs.input, ctx) == Some(IKeylessDeploy::keylessDeployCall::SELECTOR) + })); + Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) } /// A creation the call passed every rule for and paid the start of. @@ -261,7 +269,7 @@ struct Deployment { record_charges: Option<(u64, u64)>, } -/// Why a call is answered instead of rewritten. +/// Why a call is refused. enum Refusal { /// A rule refused it: a revert with the rule's error. Rule(KeylessDeployError), @@ -270,16 +278,22 @@ enum Refusal { } impl Refusal { - /// 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) = match self { + /// 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 @@ -287,7 +301,7 @@ impl Refusal { } /// Holds the call `inputs` to the rules and charges `gas` for what the creation's start makes, in -/// the order [`rewrite`] lists; the deployment to start, or why the call is answered. +/// the order [`start`] lists; the deployment to start, or why the call is refused. fn prepare( ctx: &mut MegaContext, inputs: &CallInputs, diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 85e619570..8a78a5ee2 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -4,15 +4,15 @@ //! //! # A native creation //! -//! A `keylessDeploy(bytes,uint256)` call a transaction makes is rewritten into the creation it -//! stands for, before the frame starts and before any interceptor sees it ([`rewrite`]). The call -//! becomes a frame no code runs in: 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. The call then answers in the `IKeylessDeploy` ABI -//! ([`settle`]). An inspector sees both frames: the call, and the creation as its child. There is -//! no second EVM and no state to merge. +//! 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: //! @@ -81,8 +81,8 @@ mod tx; pub use error::*; pub use tx::*; -pub(crate) use dispatch::{rewrite, KeylessCall, Rewrite}; -pub(crate) use settle::{give_back_history, settle}; +pub(crate) use dispatch::{is_dispatched, ready, run, runs, KeylessFrame}; +pub(crate) use settle::{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 d36385614..c5430dcf8 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -1,178 +1,184 @@ //! 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. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, vec::Vec}; - use alloy_evm::Database; use alloy_primitives::{Address, Bytes}; use alloy_sol_types::SolCall; use revm::{ context::{ - result::{FromStringError, HaltReason, OutOfGasError}, - ContextTr, JournalTr, + result::{HaltReason, OutOfGasError}, + ContextError, ContextTr, FrameStack, JournalTr, }, - context_interface::journaled_state::account::JournaledAccountTr, - handler::FrameResult, + context_interface::{cfg::gas::GasTracker, journaled_state::account::JournaledAccountTr}, + handler::{handle_reservoir_remaining_gas, EthFrame, FrameResult}, interpreter::{ - CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, SuccessOrHalt, + interpreter::EthInterpreter, Gas, InstructionResult, InterpreterAction, SuccessOrHalt, }, primitives::KECCAK_EMPTY, }; use crate::{ - settle_frame_result, - system::keyless::{ - encode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, - }, + system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, ExternalEnvTypes, MegaContext, MegaHaltReason, }; -use super::dispatch::KeylessCall; +use super::dispatch::{KeylessFrame, Started}; -/// Keeps `refund`, the history gas the creation's lane gave back when the creation returned, for -/// the `keylessDeploy` call that paid it: the creation is the outermost frame revm runs, so no -/// frame of revm's receives it. -pub(crate) fn give_back_history( - ctx: &mut MegaContext, - refund: u64, -) { - if let Some(call) = &mut ctx.keyless_call { - call.returned_history = call.returned_history.saturating_add(refund); - } +/// What a `keylessDeploy` call answers from, once its creation returned into it. +#[derive(Debug)] +pub(crate) struct Returned { + started: Started, + creation: Creation, } -/// Settles the result of a keyless deployment's creation into the `keylessDeploy` call that -/// started it, and replaces `result` with the call's own; returns the call's inputs, which an -/// inspector is told the call ended from. Nothing to do for a transaction that started no keyless -/// deployment. -/// -/// The call's gas takes the creation's back exactly as a `CREATE`'s frame does -/// ([`settle_frame_result`]): 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. The history of the records the creation did not keep comes -/// back too. The creation's lane was popped when it returned, or is popped here when it never -/// ran. +/// 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. /// -/// A deployment from nonce 0 keeps the creation's nonce bump. 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 is read here, before revm merges it into the call, which keeps nothing of it but its gas and +/// whether it succeeded. The call is the frame at depth 0: the creation's result lands in it when +/// the frame on top of the stack is the creation, finished, or the call itself, which a creation +/// answered without a frame of its own returns into directly. +pub(crate) fn returning( + ctx: &MegaContext, + stack: &mut FrameStack>, + result: &FrameResult, +) -> Option { + if !matches!(ctx.keyless_frame, Some(KeylessFrame::Deploying(_))) { + return None; + } + let top = stack.index()?; + if top != usize::from(stack.get().is_finished()) { + 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, + }, + }) +} + +/// 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`]). /// -/// Then the call answers, as a frame that resumes after its child returned would: +/// 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. /// -/// - with the stop a limit left it, when there is one: the latched one, or its own budget's, which -/// the nonce record a failed creation leaves a signer at nonce 0 on the call's lane can cross. -/// The call reverts with it, and its journal checkpoint goes with the revert, the signer's nonce -/// included; -/// - otherwise with `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. +/// 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`. /// -/// `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. -pub(crate) fn settle( +/// It runs before the call resumes, because the record it takes back may be what put the call +/// over its budget: 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, - result: &mut FrameResult, -) -> Result>, ERROR> -where - DB: Database, - ExtEnvs: ExternalEnvTypes, - ERROR: From + FromStringError, -{ - let Some(mut call) = ctx.keyless_call.take() else { return Ok(None) }; - // The call's lane and the creation's: the creation returned through the frame lifecycle when - // it ran, and never reached it when it was answered at its start. - if ctx.additional_limit.frame_depth() > 1 { - let refund = ctx.additional_limit.on_frame_return(result); - call.returned_history = call.returned_history.saturating_add(refund); - } - settle_frame_result::<_, ERROR>(ctx, call.gas.tracker_mut(), result)?; - call.gas.refill_history(call.returned_history); + 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, call.signer); - if nonce == call.signer_nonce { - call.gas.refill_reservoir(call.signer_account_charge); + 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 call.signer_nonce > 0 && nonce == call.signer_nonce + 1 { - take_back_bump(ctx, &mut call, result)?; + if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { + take_back_bump(ctx, gas, &started, creation.result)?; } - - let (status, output) = match ctx.additional_limit.stop_before_run() { - Some(stop) => (InstructionResult::Revert, stop.revert_data()), - None => answer(ctx, &call, result), - }; - if status.is_ok() { - ctx.journal_mut().checkpoint_commit(); - } else { - ctx.journal_mut().checkpoint_revert(call.checkpoint); - } - *result = FrameResult::Call(CallOutcome { - result: InterpreterResult::new(status, output, call.gas), - memory_offset: call.inputs.return_memory_offset.clone(), - was_precompile_called: false, - precompile_call_logs: Vec::new(), - charged_new_account_state_gas: call.inputs.charged_new_account_state_gas, - charged_state_gas_address: KEYLESS_DEPLOY_ADDRESS, - }); - Ok(Some(call.inputs)) + ctx.keyless_frame = Some(KeylessFrame::Returned(Returned { started, creation })); + Ok(()) } -/// The `keylessDeploy` answer of a call whose creation settled into `result`. +/// 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. -fn answer( +pub(crate) fn answer( ctx: &MegaContext, - call: &KeylessCall, - result: &FrameResult, + 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 gas_used = creation_gas_used(result.gas()); - let instruction_result = result.instruction_result(); - if instruction_result.is_revert() { - let output = result.interpreter_result().output.clone(); + let Returned { started, creation } = returned; + let gas_used = creation.gas_used; + if creation.result.is_revert() { + let output = creation.output.clone(); return failed(KeylessDeployError::ExecutionReverted { gas_used, output }, gas_used); } - if !instruction_result.is_ok() { - let reason = halt_reason(instruction_result); + if !creation.result.is_ok() { + let reason = halt_reason(creation.result); return failed(KeylessDeployError::ExecutionHalted { gas_used, reason }, gas_used); } - let created = match result { - FrameResult::Create(outcome) => outcome.address, - FrameResult::Call(_) => None, - }; - if created != Some(call.deploy_address) { - let error = if created.is_some() { + 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, call.deploy_address) { + if !holds_code(ctx, started.deploy_address) { return failed(KeylessDeployError::EmptyCodeDeployed { gas_used }, gas_used); } - returned(gas_used, call.deploy_address, Bytes::new()) + 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 @@ -194,20 +200,16 @@ fn holds_code( /// 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( +fn take_back_bump( ctx: &mut MegaContext, - call: &mut KeylessCall, - result: &FrameResult, -) -> Result<(), ERROR> -where - DB: Database, - ExtEnvs: ExternalEnvTypes, - ERROR: From, -{ - ctx.journal_mut().load_account_mut(call.signer)?.data.set_nonce(call.signer_nonce); - let moved_value = call.moves_value && result.instruction_result().is_ok(); + 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() { - call.gas.refill_history(call.signer_record_charge); + gas.refill_history(started.signer_record_charge); } Ok(()) } @@ -222,11 +224,11 @@ fn account_nonce( /// `keylessDeploy`'s return for a deployment that failed with `error`. fn failed(error: KeylessDeployError, gas_used: u64) -> (InstructionResult, Bytes) { - returned(gas_used, Address::ZERO, encode_error_result(error)) + returned_value(gas_used, Address::ZERO, encode_error_result(error)) } /// `keylessDeploy`'s return: a success, whatever the deployment did. -fn returned( +fn returned_value( gas_used: u64, deployed_address: Address, error_data: Bytes, diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 99508b9c2..974dba37b 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -482,9 +482,9 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { } } -/// 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; @@ -494,11 +494,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); From 2e1e8ca1481d92ddc69c06532e7fd8c3bd633c11 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:13:27 -0700 Subject: [PATCH 252/458] perf(limit): check a returning frame's caller only when the return hands it what no check held --- crates/mega-evm/src/limit/frame_limit.rs | 77 ++++++++++++++++ crates/mega-evm/src/limit/limit.rs | 106 ++++++++++++++++++++--- crates/mega-evm/tests/satin/stops.rs | 44 ++++++++++ 3 files changed, 215 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index dd604620c..91af59e2f 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -113,6 +113,21 @@ impl Lane { } } + /// 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 only an + /// inspector's rewrite of the frame's stop into a success returns. + /// + /// 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 { + self.net().crossing(self.budget).is_some() + } else { + self.creator_record + } + } + /// What the frame keeps if it succeeds. pub(crate) const fn net(&self) -> LimitUsage { self.used.saturating_sub(self.refund) @@ -342,6 +357,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 { @@ -546,6 +571,58 @@ mod tests { 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 = LimitUsage { data_size: 200, write_records: 10 }; + // 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, UNLIMITED, 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.crossing(budget).is_some(); + 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 budget = LimitUsage { data_size: 200, write_records: 10 }; + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, budget, 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, UNLIMITED, 0)); + assert!(t.hands_unchecked(&lane, true), "a caller is"); + assert!(!t.hands_unchecked(&lane, false), "which a failure hands nothing"); + } + /// A creation that fails before bumping the nonce takes the creator record back. #[test] fn test_drop_caller_record_rearms_the_caller() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index fee1d4b1a..71cfe91e9 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -208,6 +208,19 @@ impl AdditionalLimit { LimitCheck::WithinLimit } + /// Whether [`check`](Self::check) would find nothing to stop the running frame for, asked + /// without latching anything: the transaction keeps no more than its limits, and the running + /// frame no more than its budget. An exempt transaction is stopped by nothing, and a latched + /// one by nothing but the latch, which [`stop_before_run`](Self::stop_before_run) takes + /// first. + fn check_finds_nothing(&self) -> bool { + if self.is_exempt() || self.latched().is_some() { + return true; + } + self.tracker.net().crossing(self.limits.tx_usage_limit()).is_none() && + self.tracker.current().is_none_or(|lane| lane.net().crossing(lane.budget).is_none()) + } + /// The stop the running frame returns instead of running another instruction: the latched /// one, or the one [`on_frame_return`](Self::on_frame_return) left for a caller its child put /// over its budget. Taking it clears the latter, which stops one frame. @@ -800,15 +813,22 @@ impl AdditionalLimit { /// whatever produced it (an interceptor, an inspector's rewrite), so neither a success nor a /// halt passes it. /// - /// Then the caller is held to its limits with what it now holds, and a crossing is the stop - /// it returns before it runs on ([`stop_before_run`](Self::stop_before_run)): its own - /// frame-local revert for its budget, the latch for the transaction's limit. One return adds - /// to a caller what no check has held it to: the nonce record a failed creation leaves its - /// creator. 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. Any other return leaves the caller - /// within its limits: a failure hands it nothing, and a success hands it no more than the - /// share it gave. + /// Two returns 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)): its own frame-local revert for its budget, + /// the latch for 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 hands the caller more than the share it gave. Only + /// an inspector that rewrote the frame's stop into a success returns one. + /// + /// 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. /// /// 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. @@ -819,10 +839,20 @@ impl AdditionalLimit { // opcode, which failed after making it. self.pending_frame_charge = FrameCharge::NONE; let success = result.instruction_result().is_ok(); - let refund = self.tracker.pop(success).map_or(0, |lane| lane.history_refund(success)); + let lane = self.tracker.pop(success); + let refund = lane.as_ref().map_or(0, |lane| lane.history_refund(success)); self.state_gas.pop(); - let check = self.check(); - self.resume_stop = check.exceeded_limit().then_some(check); + 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_finds_nothing(), + "a frame's return put its caller over a limit no check held it to" + ); + None + }; refund } @@ -1138,6 +1168,58 @@ mod tests { ); } + /// 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.data_size, 98); + (limit, child) + } + + /// A success is checked on its return only when it kept more than its own budget, which an + /// inspector that rewrote the frame's stop into a success returns. 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 mut result = + crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&mut 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 = crate::limit::UNLIMITED; + limit.tracker.record(LimitUsage { data_size: 101, write_records: 0 }); + let mut result = + crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&mut result); + } + /// Limits every dimension holds at zero: anything a transaction counts crosses one. fn zero_limits() -> EvmTxRuntimeLimits { EvmTxRuntimeLimits::no_limits() diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index d913651ff..469a21233 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1356,6 +1356,50 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); } +/// A call its own frame budget stopped, revived into a success by an inspector, hands its caller +/// everything it counted: more than the share the caller gave it. The caller is held to its own +/// budget with it and returns its stop before it runs another instruction, as a creator a failed +/// creation's nonce record puts over its budget does. +/// +/// `A` has a frame cap of 1,000 bytes and gives `B` 98% of it. `B`'s log of 1,000 bytes counts +/// 1,032, which crosses `B`'s budget and, handed to `A`, `A`'s. +#[test] +fn test_a_call_revived_past_its_budget_stops_its_caller_before_it_runs_on() { + const FRAME_CAP: u64 = 1_000; + const LOGGED: u64 = 1_000; + assert!(LOG_BASE_SIZE + LOGGED > FRAME_CAP, "the log crosses A's budget too"); + let share = FRAME_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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(FRAME_CAP); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Rewriter::default()); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW)).unwrap(); + let rewriter = evm.inspector(); + + let stop = |limit| { + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used: 0, frame_local: true } + .revert_data() + }; + assert_eq!( + rewriter.ended, + vec![ + (B, InstructionResult::Revert, stop(share)), + (A, InstructionResult::Revert, stop(FRAME_CAP)) + ], + "B crossed its budget, and A its own with what B handed it" + ); + assert_eq!(rewriter.marker_writes, 0, "A ran no instruction after its call returned"); + assert!(outcome.result.is_success(), "the inspector rewrote A too: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); +} + /* ---------- a frame three calls down, answered without running ---------- */ /// An account with nothing at it, which a value call adds. From 1797785737757ba1e110eb2072e023549d16e89c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:13:36 -0700 Subject: [PATCH 253/458] docs: the live system address is read by the transaction, not the block executor --- AGENTS.md | 39 +++++++++++++++------------- crates/mega-evm/README.md | 13 ++++++---- crates/mega-evm/src/system/AGENTS.md | 17 +++++++----- 3 files changed, 39 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4aa76d914..df82f536e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,17 +100,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 (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and the live system address (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the live system address, and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read, its `applyPendingChanges()` pre-block call and the live system address read (`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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and whether the running transaction is the protocol's own (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | ### How Satin executes today @@ -186,7 +186,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. 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`. Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block and reads the live system address out of it (see the system calls below). + It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block (see the system calls below). + It does not read the live system address: a system-address transaction reads it itself (see below). - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. Three of the six system contracts answer calls through their interceptors (`system/`), and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless rewrite 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. @@ -215,10 +216,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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` stay in the ABI with no producer: 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. -- 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. - Which address that is, the `SequencerRegistry` says: block execution reads its `_currentSystemAddress` before each block's transactions, after applying a rotation due in the block, and sets it on the context (`MegaContext::system_address`), so a rotation governs its activation block; a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. - An EVM a node builds outside block execution — an RPC call, the replay of a block's transactions for a trace — starts no block, so the node reads the live address from the registry and sets it (`MegaContext::set_system_address`, or `with_system_address` on a context it builds); otherwise, once the address is rotated, that EVM runs the rotated address's transactions as ordinary ones. - A registry that is missing, holds other code or holds a zero address refuses the block (`system::resolve_system_address`). +- 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, 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. + Which address that is, the `SequencerRegistry` says, and the transaction reads it itself (`system::is_live_system_transaction`, called first thing in `MegaHandler::validate_env`): only a transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — reads `_currentSystemAddress` from the journal, cold and without the registry's code, and compares it with its caller. + A transaction of any other shape reads nothing and is never a system-address transaction, whoever sent it: one from the system address is an ordinary transaction, validated and charged as a user's is, where the legacy engine refused it. + 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 deploys and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution the pre-block deploy guarantees the code. + It is a read of the transaction's own, so the slot is in the system-address 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`). @@ -336,7 +339,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. - The layer's state belongs to one transaction: every entry point of `MegaEvm` resets it before it runs the handler. + 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. `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result, and a column of stopped creations that inspector revives. - **A per-frame gas cap stays inside the frame's tracker.** @@ -479,7 +482,7 @@ When the agent is requested to implement a new feature or bug fix, it should con 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 EIP-2935 and EIP-4788 calls and the post-block balance increments, `system/sequencer_registry.rs` the registry's due-change read, its `applyPendingChanges()` call and the system-address read, and the block executor is what commits them. + `block/eips.rs` holds the EIP-2935 and EIP-4788 calls and the post-block balance increments, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, 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/crates/mega-evm/README.md b/crates/mega-evm/README.md index 918fed374..08f530014 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -57,8 +57,8 @@ The execution figure a block counts for a transaction is its regular ledger — A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. 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, deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call, and reads the live system address out of the registry. -It hands each pre-block state — the two EIP calls, the seven deploys, the registry's two reads and its call — to an optional observer before it commits; that sequence is the witness a stateless client needs. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, and applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call. +It hands each pre-block state — the two EIP calls, the seven deploys, the read of the registry's pending changes and its call — to an optional observer before it commits; that sequence is the witness a stateless client needs. 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. @@ -102,9 +102,12 @@ The creation's bump is taken back with its write record, which stays only when a 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 whitelist, 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, which block execution reads before each block's transactions, once a rotation due in the block has been applied (`MegaContext::system_address`); a context no block has been started on uses `MEGA_SYSTEM_ADDRESS` unless it is given one. -A node that builds an EVM outside block execution — an RPC call, the replay of a block's transactions for a trace — reads the live address from the registry itself and sets it (`MegaContext::set_system_address`, `MegaContext::with_system_address`). +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 the transaction reads it itself: a transaction of that shape reads the registry's `_currentSystemAddress` from the journal when it is validated, without warming it, and compares it with its caller. +Every other transaction reads nothing, and one of another shape from the system address is an ordinary transaction. +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 the system-address 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 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. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 01415889a..853b55f9c 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## OVERVIEW -The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory, and the `SequencerRegistry`'s pre-block steps: the due-change read, the `applyPendingChanges()` system call and the read of the live system address. +The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory, and the `SequencerRegistry`'s pre-block steps: the due-change read and the `applyPendingChanges()` system call. The live system address is read by a transaction of the system shape when it is validated, not before the block. ## STRUCTURE - `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. @@ -9,10 +9,10 @@ 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 overhead, the nine rules, the charges of the creation's start and the rewrite into a creation (`dispatch.rs`); the settlement of the creation into its call and the ABI answer (`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, the [`SequencerRegistryConfig`] that seeds it, and its three pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) and `resolve_system_address` (fail-closed read of `_currentSystemAddress`). No interceptor. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, the [`SequencerRegistryConfig`] that seeds it, 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 `inspect_system_address`, the journal read of `_currentSystemAddress` a system-shaped transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. - `deploy.rs`: the declarative spec, `transact_deploy`, the EIP-7997 factory, and the list of seven predeploys. - `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 (`is_live_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. @@ -29,8 +29,9 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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. -- 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. +- 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. The shape is tested first, on the transaction's own fields, and only a shaped transaction reads the registry: every other transaction pays two comparisons and reads nothing, and one of another shape from the system address is an ordinary transaction. +- The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The chain id, the nonce and EIP-3607 are checked there, each under the configuration switch a user transaction obeys. +- Accounts and slots read during validation are read without warming them, so the transaction pays what any other transaction would pay for its first touch: the registry's account and slot, and the system address's account. ## PRE-BLOCK STATE CHANGE CONTRACT @@ -57,7 +58,8 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 make a transaction that lacks the system shape read the registry: the shape test is what keeps every other transaction free of the read. - Do not call `db.commit(...)` inside a helper that participates in `apply_pre_execution_changes`. It hides the step from a witness generator. - Do not return nothing from a helper on a "no change needed" path. @@ -72,4 +74,5 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. - Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list, delivers each witness to the pre-block observer, and commits. -- Change when a role change is applied or how the live system address is read: `sequencer_registry.rs`, whose three helpers `block/executor.rs::apply_pre_execution_changes` calls after the deploys, in that order; the result lives on the context (`MegaContext::system_address`). +- 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 deploys, in that order. +- Change how the live system address is read or which transactions read it: `sequencer_registry.rs::inspect_system_address` and `tx.rs::is_live_system_transaction`, which `MegaHandler::validate_env` calls; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). From a33892f5ff3236d2a4fb5bf0c714ebe3d35c0b39 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:15:00 -0700 Subject: [PATCH 254/458] test(keyless): pin the keylessDeploy call as a frame on revm's stack --- crates/mega-evm/tests/system/keyless/frame.rs | 322 ++++++++++++++++++ crates/mega-evm/tests/system/keyless/mod.rs | 1 + 2 files changed, 323 insertions(+) create mode 100644 crates/mega-evm/tests/system/keyless/frame.rs 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..17089d145 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -0,0 +1,322 @@ +//! 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::{ + system::keyless::{KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::BytecodeBuilder, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, POP, STOP}, + context::{ContextTr, JournalTr}, + handler::{EvmTr, FrameResult, ItemOrResult}, + interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInput, CallInputs, + CallOutcome, CallScheme, CallValue, CreateScheme, FrameInput, InstructionResult, + Interpreter, SharedMemory, + }, + Database, 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}"); + } +} + +/// 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/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index e54aac7bb..ddbf775d2 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -11,6 +11,7 @@ mod deploy; mod detention; mod differential; mod dispatch; +mod frame; mod inspector; mod limits; mod precedence; From 4bef3cc2ea5a192dc58daa010d23e0f5e841057f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:17:01 -0700 Subject: [PATCH 255/458] docs(keyless): describe the keylessDeploy call as a real frame --- AGENTS.md | 48 +++++++++++-------- crates/mega-evm/README.md | 4 +- crates/mega-evm/benches/transact.rs | 2 +- crates/mega-evm/src/system/AGENTS.md | 11 +++-- crates/mega-evm/src/system/keyless/mod.rs | 12 +++++ crates/mega-evm/tests/satin/equivalence.rs | 2 +- .../mega-evm/tests/system/keyless/dispatch.rs | 4 +- .../tests/system/keyless/inspector.rs | 2 +- 8 files changed, 53 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4aa76d914..0d457d60f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,17 +100,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 (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless rewrite point and the keyless settlement, 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, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and the live system address (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the live system address, and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 overhead, the nine rules, the charges of the creation's start and the rewrite (`keyless/dispatch.rs`), the settlement 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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read, its `applyPendingChanges()` pre-block call and the live system address read (`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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and the live system address (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the live system address, and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read, its `applyPendingChanges()` pre-block call and the live system address read (`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 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`, `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`) | — | ### How Satin executes today @@ -188,7 +188,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block and reads the live system address out of it (see the system calls below). - The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. - Three of the six system contracts answer calls through their interceptors (`system/`), and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless rewrite before interception. + Three of the six system contracts answer calls through their interceptors (`system/`), 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` 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`). @@ -201,12 +201,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 the transaction 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 `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 rewrite (`keyless::rewrite`) runs in `frame_init` before interception, so the creation is an ordinary creation from there on. - An inspector sees the frames the deployment is made of: `inspect_frame_init` tells it the call starts, rewrites the call, then tells it the creation starts, as the call's child one journal depth below, and `MegaHandler::inspect_execution` tells it the call ended once the creation is settled into it. + 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. - The call is a frame no code runs in: its lane (the one any depth-0 call pushes, running as the signer), its journal checkpoint and its gas (`KeylessCall`, on the context) stay until `MegaHandler::last_frame_result` — or, inspected, `inspect_execution` just before it — settles the creation into it (`keyless::settle`) and answers in the ABI, before the call's lane is popped. + 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 the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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. `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. @@ -280,13 +285,14 @@ Detention caps how much a transaction may still compute once it read such data ( Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. So is one priced between the allowance and its forward whose input fails a check made after its gas check: it runs out of the allowance before that check, where without the read the check fails the call, which burns its forward and which its caller survives. - 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`, and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer, or on a refused `keylessDeploy` call, in `inspect_frame_init`); the one answer of the engine's own that spends regular gas is a refused `keylessDeploy` call's, built on the whole forward, 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`, 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 a running frame: its gas is held to what the limit leaves it before it charges anything (`keyless::rewrite`), 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 the answer's settlement 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 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 is kept as the frame at depth 0, suspended on it (`Detention::on_call_rewritten`), 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 transaction through the latch, and the settlement reverts the call with the stop and takes the deployment back. - A call a rule refuses is an answer, held by the rule above. + 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 transaction through the latch, and the call returns the stop on its resume, which takes the deployment back. + 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`). @@ -323,7 +329,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The KV count a node reports is the write-record count, and the KV 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. - A `keylessDeploy` call rewritten into its creation pushes a lane of its own, under the creation's: the creation is the outermost frame revm runs, so the history its lane gives back is kept for the call (`keyless::give_back_history`), and the keyless settlement pops the creation's lane when the creation 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 state-gas limit's entry of what is held outside each frame is pushed and popped with the lane. - **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. @@ -354,7 +360,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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 the keyless rewrite 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. + 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 charges nothing. - **One hook prices every state charge.** diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 918fed374..9a0049b74 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -89,7 +89,9 @@ The Oracle's storage is read through the node's oracle service: an `SLOAD` in th 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 becomes a native creation before any interceptor sees it; a tracer sees the call, and the creation as its child. +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. diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 4a2799488..42e9a1b61 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -49,7 +49,7 @@ //! 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 its settlement into the ABI answer. +//! 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 diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 01415889a..ebdb8fad5 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -6,7 +6,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch ## STRUCTURE - `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/`: native keyless deployment. The `KeylessDeploy` address, code and ABI and the semantics of a deployment (`mod.rs`); the dispatch, the overhead, the nine rules, the charges of the creation's start and the rewrite into a creation (`dispatch.rs`); the settlement of the creation into its call and the ABI answer (`settle.rs`); the pre-EIP-155 transaction format and the error ABI (`tx.rs`, `error.rs`). +- `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, the [`SequencerRegistryConfig`] that seeds it, and its three pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) and `resolve_system_address` (fail-closed read of `_currentSystemAddress`). No interceptor. @@ -16,14 +16,14 @@ 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. -- `keylessDeploy` is not intercepted: a call a transaction makes is taken by the keyless rewrite, which runs before interception in `frame_init`, and between the inspector's `frame_start` of the call and that of the creation in `inspect_frame_init`, and becomes a native `CREATE` of its signer. Its test costs one comparison on every frame: the depth, then the address and the selector. +- `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 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 charges nothing: the frame starts as it was built. -- A keyless deployment's call is a frame no code runs in. It has the lane a depth-0 call pushes, running as the signer, a journal checkpoint, and its own gas (`KeylessCall` on the context), which gas detention holds as a running frame's before the call charges anything; it pays what the `CREATE` opcode charges its frame and starts the creation as its child at depth 1, kept by detention as the frame suspended on it. The creation's result is settled into it in `MegaHandler::last_frame_result`, which every first-frame result reaches, before the call's lane is popped; the inspected path settles it in `inspect_execution` just before, and tells the inspector the call ended. +- 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 is not forwarded is not counted. - 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). @@ -52,7 +52,8 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 translate its result anywhere but the settlement: the call pays the start as a `CREATE`'s frame does, and only `last_frame_result` (and `inspect_execution` before it) sees every first-frame result, the creation answered at its start included. +- 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. @@ -67,7 +68,7 @@ The executor hands it to the pre-block observer, then commits: the sequence the ## 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 settlement and the answer; `evm/execution.rs` for where the two are called; `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`, `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` 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. - Add a predeploy: a spec in `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 8a78a5ee2..235dbb621 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -16,6 +16,18 @@ //! //! 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 holds it from the fork that +//! deploys it on. //! - `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 diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 9d42f7f45..78248e243 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -558,7 +558,7 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { } /// A `keylessDeploy` transaction is a deployment in Satin and a call to the contract's bytecode in -/// op-revm, which has no keyless rewrite: Satin deploys the canonical `CREATE2` factory at its +/// 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. /// diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index 85892d2cd..0d9b47f5e 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -1,8 +1,8 @@ //! 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 is either rewritten into -//! its deployment or answered. The tests here send transactions a rule refuses, so that what is +//! 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. diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index aa922c846..d9d232e3c 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -232,7 +232,7 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { } } -/// A transaction the latch stopped before its first frame is not rewritten on the inspected path +/// A transaction the latch stopped before its first frame is not dispatched on the inspected path /// either: the inspector sees the call and its stop, and no creation. #[test] fn test_a_latched_transaction_is_seen_as_the_call_it_is() { From 0100c1b995141d80fe6a8fbaa8463d3b99e3d301 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:19:45 -0700 Subject: [PATCH 256/458] style(keyless): drop a redundant clone and needless borrows --- crates/mega-evm/src/system/keyless/dispatch.rs | 2 +- crates/mega-evm/tests/system/keyless/differential.rs | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index df0f1daee..5e3aabf97 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -112,7 +112,7 @@ pub(crate) fn ready( 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.clone())); + (KEYLESS_DEPLOY_CODE_HASH, Bytecode::new_raw(KEYLESS_DEPLOY_CODE)); } return Ok(None); } diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index 8416acf59..e540e95f5 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -700,7 +700,7 @@ fn scenarios() -> Vec { gas_limit, )); let relaying = BytecodeBuilder::default() - .mstore(0, &small.call_data(LARGE_OVERRIDE)) + .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()) @@ -720,7 +720,7 @@ fn scenarios() -> Vec { .to(relayer), ); let static_relaying = BytecodeBuilder::default() - .mstore(0, &small.call_data(LARGE_OVERRIDE)) + .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()) @@ -1026,8 +1026,10 @@ fn render_state(state: &EvmState) -> String { let mut out = String::new(); for (address, account) in accounts { let info = &account.info; - let code = - info.code.as_ref().map_or("unloaded".to_string(), |code| format!("{}", code.len())); + 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}", From 6946eb38eb2e084b478142b1082ecfb7bb35c49f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:36:17 -0700 Subject: [PATCH 257/458] perf(evm): ask a frame's caller whether it refuses the start once --- crates/mega-evm/src/evm/execution.rs | 46 ++++- crates/mega-evm/src/evm/instructions.rs | 10 +- crates/mega-evm/src/limit/limit.rs | 35 ++++ crates/mega-evm/tests/satin/transfer_logs.rs | 190 ++++++++++++++++++- 4 files changed, 271 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 72d6ffbe4..b6cdf4555 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -492,7 +492,7 @@ impl EvmTr for MegaEvm 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(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { return answered_by_inspector(ctx, inspector, &frame_init, output) @@ -1349,6 +1352,36 @@ pub(crate) fn caller_refuses_start( + 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. /// @@ -1440,7 +1473,8 @@ struct AppliedAuthorities { /// 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. +/// 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, @@ -1459,8 +1493,12 @@ fn charge_records_made_outside_a_frame( !ctx.additional_limit.target_is_authority() } }; - let top_level_record = - writes_a_record && !caller_refuses(ctx, tx.caller(), tx.value(), tx.kind().is_create()); + 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(top_level) = write_record_history_gas(u64::from(top_level_record)) else { return false; }; diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index a39575e29..591fa715b 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -297,7 +297,8 @@ fn selfdestruct( /// 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 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`]). @@ -320,7 +321,12 @@ fn charge_frame_start( // 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)) if !caller_refuses_start(host, input) => { + 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), diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 71cfe91e9..a63bf9d97 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -84,6 +84,11 @@ pub struct AdditionalLimit { /// 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. @@ -125,6 +130,7 @@ impl AdditionalLimit { self.intrinsic_history_bytes = 0; self.top_level_write_record_gas = 0; self.pending_frame_charge = FrameCharge::NONE; + self.pending_start_refused = None; self.history_gas_spent = 0; self.history_bytes = 0; self.state_gas.reset(); @@ -348,6 +354,31 @@ impl AdditionalLimit { 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; @@ -763,7 +794,11 @@ impl AdditionalLimit { /// 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; one staged for the call's own start is not the creation's. 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); diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 266953dec..6f464ea22 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -34,16 +34,20 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, }, test_utils::{is_transfer_log, op_transaction, transfer_log, BytecodeBuilder, MemoryDatabase}, - transaction_body_bytes, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, - MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + transaction_body_bytes, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, + MegaEvm, MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP}, + bytecode::opcode::{ + ADDRESS, CALL, DELEGATECALL, GAS, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP, + }, context::{ result::{ExecutionResult, Output}, TxEnv, }, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue}, + Database, Inspector, }; use crate::common::context; @@ -715,6 +719,184 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { assert!(funded.result.is_halt(), "{:?}", funded.result); } +/// 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( + 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(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 latches nothing"); + 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(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 From b26861573107784d5632ce95e0b8a0a7928af1a2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:40:36 -0700 Subject: [PATCH 258/458] style: satisfy clippy in the share assertion and the revived-call test --- crates/mega-evm/src/limit/limit.rs | 2 +- crates/mega-evm/tests/satin/stops.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index a63bf9d97..b2c8dbef5 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -937,7 +937,7 @@ impl AdditionalLimit { 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 % (D - N) == 0); + const _: () = assert!(N < D && D.is_multiple_of(D - N)); const K: u64 = D / (D - N); remaining - remaining.div_ceil(K) } diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 469a21233..3e9704f72 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1367,7 +1367,7 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { fn test_a_call_revived_past_its_budget_stops_its_caller_before_it_runs_on() { const FRAME_CAP: u64 = 1_000; const LOGGED: u64 = 1_000; - assert!(LOG_BASE_SIZE + LOGGED > FRAME_CAP, "the log crosses A's budget too"); + const { assert!(LOG_BASE_SIZE + LOGGED > FRAME_CAP, "the log crosses A's budget too") }; let share = FRAME_CAP * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; let a = call_all(BytecodeBuilder::default(), B) .append(POP) From 90d097bc515daada958425d8d96659c1988c78a6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 13:46:19 -0700 Subject: [PATCH 259/458] test(limit): pin that a staged start answer is taken once and dropped by reset --- crates/mega-evm/src/limit/limit.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index b2c8dbef5..7991f2585 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1255,6 +1255,29 @@ mod tests { let _ = limit.on_frame_return(&mut 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() From cb8d1501d77265bfd8431da317bce371d761b3ac Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 14:34:33 -0700 Subject: [PATCH 260/458] docs(system): name the keyless dispatch where interception defers to it --- crates/mega-evm/src/system/intercept.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index f1b997bd2..1dd165d30 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -20,7 +20,7 @@ //! - 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 keyless rewrite did not take — one a contract makes — reaches +//! 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. @@ -74,7 +74,7 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { /// /// The High-Precision Timestamp wrapper and the `SequencerRegistry` are not here: they have no /// interceptor and run their bytecode. `KeylessDeploy` is, but its `keylessDeploy` calls are taken -/// by the keyless rewrite before interception (see [`crate::system::keyless`]). +/// 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. @@ -113,7 +113,7 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option Date: Fri, 25 Sep 2026 15:33:30 -0700 Subject: [PATCH 261/458] docs(system): the Oracle accepts a non-legacy transaction from the system key as a user's --- AGENTS.md | 1 + crates/mega-evm/src/system/tx.rs | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 1ea0d64d0..0411a3fd3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -224,6 +224,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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, 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. Which address that is, the `SequencerRegistry` says, and the transaction reads it itself (`system::is_live_system_transaction`, called first thing in `MegaHandler::validate_env`): only a transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — reads `_currentSystemAddress` from the journal, cold and without the registry's code, and compares it with its caller. A transaction of any other shape reads nothing and is never a system-address transaction, whoever sent it: one from the system address is an ordinary transaction, validated and charged as a user's is, where the legacy engine refused it. + That is the engine's view, not the contracts': the Oracle's `onlySystemAddress` tests the sender alone, so a non-legacy transaction signed by the system key to the Oracle is accepted by the Oracle and its writes land, executed as a user's transaction — it pays fees, is held to every per-transaction limit, is detained, is priced by bucket, and pays history; both engines refused it at validation before. 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 deploys and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution the pre-block deploy guarantees the code. It is a read of the transaction's own, so the slot is in the system-address transaction's state and witness, not in the pre-block witness. diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index da6f1aa29..be3cecc34 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -14,6 +14,13 @@ //! shape reads nothing and is never a system-address transaction, whoever sent it: one from the //! system address is an ordinary transaction, validated and charged as a user's is. //! +//! "Ordinary" is the engine's view, not the contracts': the Oracle's `onlySystemAddress` tests +//! the sender alone. So a non-legacy transaction signed by the system key to the Oracle is +//! accepted by the Oracle, and its writes land, executed as a user's transaction: it pays fees, +//! is held to every per-transaction limit, is detained, is priced by bucket, and pays history. +//! Both the legacy engine and this one refused it at validation before the shape test came +//! first. +//! //! A deposit is unvalidated by construction, so the engine validates what still matters itself //! before promoting the transaction ([`validate_and_promote`]): //! From 63c8a30c1242eb95d9c896ea641fdf2abf50a866 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 15:33:50 -0700 Subject: [PATCH 262/458] docs(system): the registry code hash must be chosen per spec at the next upgrade --- crates/mega-evm/src/system/sequencer_registry.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 253b12c4d..c3f477f3a 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -230,6 +230,10 @@ where pub(crate) fn inspect_system_address( journal: &mut J, ) -> Result, J::DBError> { + // The expected hash is the registry code this engine deploys, 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. if journal.inspect_account_code_hash(SEQUENCER_REGISTRY_ADDRESS)? != SEQUENCER_REGISTRY_CODE_HASH { From a6dc2b0a0b06ddb99f21962491567f9e9bb27166 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 15:34:08 -0700 Subject: [PATCH 263/458] docs(limit): the creator's clear of the staged start answer is defensive --- crates/mega-evm/src/limit/limit.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 1d67186bd..439de6359 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -796,7 +796,10 @@ impl AdditionalLimit { /// 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; one staged for the call's own start is not the creation'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; From ba16c3b21e428879adefa45af623238a15c7caca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 15:35:05 -0700 Subject: [PATCH 264/458] refactor(keyless): name the frame-stack test for a result landing in the call --- crates/mega-evm/src/system/keyless/settle.rs | 21 +++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index c5430dcf8..3637f9de9 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -46,9 +46,8 @@ pub(crate) struct Creation { /// 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 call is the frame at depth 0: the creation's result lands in it when -/// the frame on top of the stack is the creation, finished, or the call itself, which a creation -/// answered without a frame of its own returns into directly. +/// 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>, @@ -57,8 +56,7 @@ pub(crate) fn returning( if !matches!(ctx.keyless_frame, Some(KeylessFrame::Deploying(_))) { return None; } - let top = stack.index()?; - if top != usize::from(stack.get().is_finished()) { + if !returns_into_the_call(stack) { return None; } let result_code = result.instruction_result(); @@ -77,6 +75,19 @@ pub(crate) fn returning( }) } +/// 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()) +} + /// 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`]). /// From 8b28cb3f06783d58e0d0a8ef790542912f984084 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 25 Sep 2026 15:37:38 -0700 Subject: [PATCH 265/458] test(keyless): a call where the state holds no contract code commits nothing for it --- crates/mega-evm/tests/system/keyless/frame.rs | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 17089d145..780cdbfc2 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -4,19 +4,25 @@ //! 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, }, - Database, Inspector, + primitives::KECCAK_EMPTY, + Database, DatabaseCommit, Inspector, }; use super::*; @@ -278,6 +284,64 @@ fn test_a_call_is_dispatched_where_the_state_holds_no_contract_code() { } } +/// 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, From a0cd8ff593a1407078cdbe891859f9ebb01cff2d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 10:54:21 -0700 Subject: [PATCH 266/458] chore(deps): pin the revm fork at v40.0.3-mega.4 Moves the twelve revm crates from v40.0.3-mega.3 to v40.0.3-mega.4; op-revm stays at v20.0.0-mega.2. The release renames the withheld crossing's API and changes what its record holds: the regular gas left before the failed charge, spendable and withheld parts together, in place of the withheld part alone. Detention's settlement keeps its billing: it takes the spendable part the frame had at the crossing back out of the record, which for a frame that ran is what the limit left the transaction then, and for an answer the allowance. The records the engine makes itself hold the regular gas the frame had before the charge, as the fork's rule says. --- Cargo.lock | 26 +++++++-------- Cargo.toml | 24 +++++++------- crates/mega-evm/src/access/detention.rs | 42 ++++++++++++++++--------- 3 files changed, 53 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bc87411fc..99a1afbf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3819,7 +3819,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "revm-bytecode", "revm-context", @@ -3838,7 +3838,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "bitvec", "phf 0.13.1", @@ -3849,7 +3849,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "bitvec", "cfg-if", @@ -3865,7 +3865,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3880,7 +3880,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-eips", "derive_more", @@ -3894,7 +3894,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "either", @@ -3907,7 +3907,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "derive-where", @@ -3925,7 +3925,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "either", @@ -3960,7 +3960,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3972,7 +3972,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3996,7 +3996,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-primitives", "once_cell", @@ -4006,7 +4006,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-eip7928", "bitflags 2.11.1", @@ -4019,7 +4019,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.3#5ac45ab8bf5db2c77f990d0c9044086bf017692b" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-eip7928", "k256", diff --git a/Cargo.toml b/Cargo.toml index 20389ab59..55902f9b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -234,18 +234,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.3" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.3" } +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 diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 361867fc9..7d9aefb80 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -370,8 +370,12 @@ impl Detention { } debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); self.frames.pop(); - if let Some(limit) = self.stop(gas) { - return Some(limit); + if let Some(crossing) = gas.withheld_crossing() { + // The record holds the regular gas left before the failed charge; the spendable part of + // it was what the limit left the transaction then. + gas.set_remaining(crossing.remaining()); + let spendable = self.limit.map_or(0, |limit| limit.saturating_sub(self.compute(gas))); + return self.stop(gas, spendable); } if result.is_halt() { // The settlement rolls the spill back into regular gas and burns it all. @@ -436,15 +440,19 @@ impl Detention { // part first, and the revert that settles the stop credits the spill back, so the // crossing withholds what is left once the spill is taken out, as the tracker's own // record of a running frame does. The spill is below `gas_limit - allowance`, since - // the regular gas the answer spent past it exceeds the allowance. - let withheld = NonZeroU64::new( - (gas_limit - allowance).saturating_sub(result.gas.state_gas_spilled()), - )?; + // the regular gas the answer spent past it exceeds the allowance. The record holds the + // regular gas the frame had before the charge: the gas limit, less the spill. + let spilled = result.gas.state_gas_spilled(); + if gas_limit - allowance <= spilled { + return None; + } + let remaining = NonZeroU64::new(gas_limit - spilled)?; result.result = InstructionResult::OutOfGas; result.gas.tracker_mut().set_limit(gas_limit); - result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); + result.gas.set_withheld_crossing(Some(WithheldCrossing::with_remaining(remaining))); } - self.stop(&mut result.gas) + let spendable = self.allowance(depth, gas_limit).unwrap_or(0); + self.stop(&mut result.gas, spendable) } /// Gives a precompile's answer, which ran on `withheld` less than its caller forwarded — the @@ -459,10 +467,11 @@ impl Detention { /// within its forward, past the allowance, whose input fails a check made after its gas check, /// which without the read fails the call instead. pub(crate) fn restore_forward(result: &mut InterpreterResult, withheld: NonZeroU64) { - let forward = result.gas.limit().saturating_add(withheld.get()); - result.gas.tracker_mut().set_limit(forward); + let forward = withheld.saturating_add(result.gas.limit()); + result.gas.tracker_mut().set_limit(forward.get()); if result.result == InstructionResult::PrecompileOOG { - result.gas.set_withheld_crossing(Some(WithheldCrossing::new(withheld))); + // 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()); } @@ -470,15 +479,16 @@ impl Detention { /// 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. + /// `spendable` is the spendable part the frame had at the crossing. /// /// The frame's gas becomes the withheld part at the crossing: the spendable part the frame had /// counts as spent, which brings the transaction's compute to the limit, and the withheld part /// goes back to its caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not /// (`MemoryOOG`), 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 { + fn stop(&self, gas: &mut Gas, spendable: u64) -> Option { let crossing = gas.withheld_crossing()?; - gas.set_remaining(crossing.withheld()); + gas.set_remaining(crossing.remaining().saturating_sub(spendable)); gas.clear_withheld_crossing(); self.limit } @@ -850,7 +860,11 @@ mod tests { detention.burned = 0; let mut out_of_gas = answer(InstructionResult::PrecompileOOG, 0); - assert_eq!(out_of_gas.gas.withheld_crossing(), Some(WithheldCrossing::new(withheld))); + 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(BLOCK_ENV_ACCESS_COMPUTE_GAS) From 1a0d428ad7db3ab3bdffa820b007ba613208111b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 10:59:56 -0700 Subject: [PATCH 267/458] feat(limit): hold deployed code at the fork's code-deposit admission `MegaContext` implements `ContextTr::admit_code_deposit`, which `return_create` asks once it has made every charge for a deposit and before it commits the creation. The hook holds the code's state gas to the state-gas limit, then counts its bytes as data size and history bytes on the creation's lane; a crossing refuses the deposit with the stop's revert data, and `return_create` reverts the creation on the gas it had before the deposit. This deletes the retrace of `return_create` the frame run made on every creation's return (`meter_deployed_code`, `deposit_state_gas`, `hold_deposit_state_gas`) and the rewrite of the creation's result in `on_create_return`, now `on_code_deposit`. The retrace stopped one charge short of `return_create`: it did not see the code's history charge. A creation below the execution cap that could pay its code's state gas but not its history was stopped by a limit its deposit crossed; it now runs out of gas on the history, whatever the limit, as a creation that cannot pay any other part of its deposit does. The deposit tests find their boundary at the deposit itself and pin that case. --- crates/mega-evm/src/evm/context.rs | 13 +- crates/mega-evm/src/evm/execution.rs | 120 +----------------- crates/mega-evm/src/limit/limit.rs | 63 +++++---- crates/mega-evm/src/limit/mod.rs | 11 +- crates/mega-evm/tests/satin/deposit_charge.rs | 82 ++++++------ 5 files changed, 90 insertions(+), 199 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 5504756da..6dd747e05 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -7,8 +7,8 @@ use revm::{ BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, Transaction, }, - context_interface::cfg::GasId, - primitives::{Address, StorageKey}, + context_interface::{cfg::GasId, context::CodeDeposit}, + primitives::{Address, Bytes, StorageKey}, Database, Journal, }; @@ -519,6 +519,15 @@ impl ContextTr for MegaContext &mut Result<(), ContextError>; } } + + /// Holds the code a creation deposits to the state-gas and data-size limits, 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. + #[inline] + fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + self.additional_limit.on_code_deposit(deposit) + } } impl ContextSetters for MegaContext { diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index a40a988ec..ce4418630 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -20,7 +20,7 @@ use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, transaction::TransactionType, - Cfg, ContextError, ContextTr, FrameStack, JournalTr, Transaction, + ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, @@ -545,8 +545,6 @@ impl EvmTr for MegaEvm( - ctx: &mut MegaContext, - frame: &EthFrame, - mut action: InterpreterAction, -) -> InterpreterAction { - if frame.data.is_create() { - if let InterpreterAction::Return(result) = &mut action { - let address = frame.interpreter.input.target_address; - if let Some(state_gas) = deposit_state_gas(ctx, address, result) { - hold_deposit_state_gas(ctx, result, state_gas); - ctx.additional_limit.on_create_return(result); - } - } - } - action -} - -/// Holds the `state_gas` `return_create` is about to charge for the code a creation deposits to -/// the state-gas limit, with what the creation already holds, and turns the return into the stop -/// when it crosses it. -/// -/// A crossing after `return_create` would leave the code deployed: the charge is made inside it, -/// after which it commits the creation's checkpoint. So the limit binds here, just before the -/// charge, and only once [`deposit_state_gas`] found that `return_create` will make it: a charge -/// the creation cannot pay is an out-of-gas whatever the limit, as it is at every other site. -fn hold_deposit_state_gas( - ctx: &mut MegaContext, - result: &mut InterpreterResult, - state_gas: u64, -) { - if state_gas == 0 { - return; - } - let running = result.gas.state_gas_spent().saturating_add_unsigned(state_gas); - let check = ctx.additional_limit.check_state_gas(running); - if check.exceeded_limit() { - result.result = InstructionResult::Revert; - result.output = check.revert_data(); - } -} - -/// The state gas `return_create` charges for the code a creation at `address` returns, when it -/// reaches that charge and the creation can pay it — zero when it charges none; `None` when it -/// fails the creation at that charge or before it. -/// -/// It retraces revm's `return_create` (`crates/handler/src/frame.rs`), step by step and on a copy -/// of the frame's gas, up to and including the state charge: -/// -/// 1. a return that is not a success deposits nothing: `if !interpreter_result.result.is_ok()`; -/// 2. code over the code-size limit fails the creation: `interpreter_result.output.len() > -/// max_code_size`; -/// 3. so does code starting with `0xEF`, unless EIP-3541 is off: `!is_eip3541_disabled && -/// interpreter_result.output.first() == Some(&0xEF)`; -/// 4. the regular deposit cost, `gas_params.code_deposit_cost(len)`, is charged, and a frame that -/// cannot pay it runs out of gas; -/// 5. under EIP-8037, so is the regular cost of hashing the code, `gas_params.keccak256_cost(len)`; -/// 6. under EIP-8037, when the schedule prices deposited code (`code_deposit_state_gas(len) > 0`), -/// the state gas is priced through the hook — a lookup that fails fails the creation — and -/// recorded as `record_state_cost` records it, the reservoir first and then regular gas, and a -/// frame that cannot pay it runs out of gas. -/// -/// Only a creation that passes all six is held, so every out-of-gas `return_create` would report -/// is still reported, and the hook is asked for a price only where `return_create` asks it: a -/// lookup that fails here fails there the same way. What `return_create` charges after the state -/// gas — the deposited code's history — is a charge like the history after any other state -/// charge, which the limit holds before. -/// -/// `return_create` also gates steps 2, 3 and 4's out-of-gas on EIP-170, London and Homestead, -/// which Satin's base spec, Osaka, enables. -fn deposit_state_gas( - ctx: &mut MegaContext, - address: Address, - result: &InterpreterResult, -) -> Option { - let code = &result.output; - let len = code.len(); - let cfg = ctx.cfg(); - if !result.result.is_ok() || - len > cfg.max_code_size() || - (!cfg.is_eip3541_disabled() && code.first() == Some(&0xEF)) - { - return None; - } - let mut gas = result.gas; - let gas_params = cfg.gas_params(); - if !gas.record_regular_cost(gas_params.code_deposit_cost(len)) { - return None; - } - if !cfg.is_amsterdam_eip8037_enabled() { - return Some(0); - } - if !gas.record_regular_cost(gas_params.keccak256_cost(len)) { - return None; - } - if gas_params.code_deposit_state_gas(len) == 0 { - return Some(0); - } - let charge = StateGasCharge::units( - GasId::code_deposit_state_gas(), - StateGasSite::account(address), - len as u64, - ); - let cost = ctx.state_gas_charge(charge)?; - gas.record_state_cost(cost).then_some(cost) -} - /// 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 439de6359..cffa07df2 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,9 +1,10 @@ //! 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::{CallInputs, CallScheme, FrameInput, InstructionResult, InterpreterResult}, + interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; use super::{ @@ -595,42 +596,48 @@ impl AdditionalLimit { self.check() } - /// Counts the code a creation is about to deposit, on the creation's own lane, and turns the - /// return into the stop when that crosses a limit. + /// Holds the code a creation deposits to the limits, and names the stop when it crosses one: + /// first the state gas `return_create` charged for the bytes, then the bytes themselves, + /// counted on the creation's own lane. /// - /// Called from the frame run, on a return `return_create` would deposit — a success whose code - /// it accepts, from a frame that can pay what it charges for the deposit — before it makes - /// those charges and commits the creation's journal checkpoint. A rewrite after that commit - /// would leave the code deployed: the checkpoint is already gone, and flipping the frame - /// result does not reopen it. A stop here makes `return_create` revert the checkpoint instead, - /// so the code is not written. 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. + /// 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 return that is already a revert or a halt deposits nothing, and its output is the - /// revert data, not code. Empty code deposits nothing either, and neither does code - /// `return_create` refuses or a creation that cannot pay for its deposit: those fail the - /// creation there, and are never counted. + /// 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_create_return(&mut self, result: &mut InterpreterResult) { - if !result.result.is_ok() { - return; - } - let bytes = result.output.len() as u64; + /// The state gas is held with what the creation already holds, and before the bytes, as it is + /// wherever both cross at one site. 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; + return Ok(()); + } + if deposit.state_gas() > 0 { + let check = self.check_state_gas(deposit.gas_after.state_gas_spent()); + if check.exceeded_limit() { + return Err(check.revert_data()); + } } 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; + if check.exceeded_limit() { + return Err(check.revert_data()); } - result.result = InstructionResult::Revert; - result.output = check.revert_data(); + Ok(()) } /// The budget of the frame about to start, in data-size bytes and in write records. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index c0d9311f2..28c1038ba 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -100,10 +100,13 @@ //! a value call its caller cannot fund, one past the call-stack limit — gives that charge back and //! is never held for it; a frame revm builds, or answers with a success, returns the stop. //! -//! Deployed code is held just before `return_create` charges it, as its bytes are, so a crossing -//! leaves no code behind — and only once `return_create` is sure to make the charge: a creation -//! that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas -//! there whatever the limit. +//! Deployed code is held once `return_create` has charged every part of its deposit and before it +//! commits the creation, as its bytes are ([`ContextTr::admit_code_deposit`]), so a crossing +//! leaves no code behind: the creation reverts with the stop, on the gas it had before the +//! deposit. A creation that cannot pay a part of its deposit — the regular costs, the state gas, +//! the history — runs out of gas there whatever the limit. +//! +//! [`ContextTr::admit_code_deposit`]: revm::context::ContextTr::admit_code_deposit //! //! Wherever the state gas and a record cross together at one site, the state gas is the stop //! reported. At a frame start the records are held before revm builds the frame, and a frame they diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 689dfef86..955e57f83 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -1,26 +1,25 @@ -//! Deployed code is held to the limits only where `return_create` charges its state gas. +//! Deployed code is held to the limits only once `return_create` charged every part of its +//! deposit. //! //! `return_create` charges a creation's deposit in this order: the regular deposit cost, the //! regular cost of hashing the code under EIP-8037, then the code's state gas — the reservoir -//! first, then regular gas — and last the code's history. A creation that cannot pay one of them -//! runs out of gas there, alone, and the chain keeps none of its code. The state-gas limit and the -//! data-size limit both hold the deposit before `return_create` commits it, and only once the -//! state gas is paid: a creation that cannot pay a charge up to it runs out of gas whatever the -//! limit, and its caller goes on. The history after it is held like a record's history after the -//! state gas of its slot: the limit comes first. +//! first, then regular gas — and last the code's history, the same way. A creation that cannot +//! pay one of them runs out of gas there, alone, and the chain keeps none of its code. The +//! state-gas limit and the data-size limit both hold the deposit after the last of those charges +//! and before `return_create` commits it: a creation that cannot pay a charge runs out of gas +//! whatever the limit, and its caller goes on. //! //! Each case finds its boundary on the engine: the least gas `A` can call the creator `B` with for -//! `return_create` to charge the code's state gas — or, without EIP-8037, to deposit the code — -//! when no limit is set. The creation then has no regular gas left after it, so it is exactly -//! enough. With that gas a limit the deposit crosses stops the creation; one gas short the -//! creation runs out of gas, under the limit exactly as without it. +//! the creation to deposit its code when no limit is set. The creation then has no regular gas left +//! after the deposit, so it is exactly enough. With that gas a limit the deposit crosses stops the +//! creation; one gas short the creation runs out of gas, under the limit exactly as without it. //! //! Which charge the creation runs out of gas on follows from where the gas comes from. Above the //! execution cap the reservoir pays the code's state gas and history, so the last regular charge -//! is the hash. Below it there is no reservoir, and the state gas is paid out of regular gas after -//! the hash. 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. +//! 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. 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. use alloy_primitives::{address, Address, U256}; use mega_evm::{ @@ -169,14 +168,6 @@ struct CreationEnd { remaining: u64, } -impl CreationEnd { - /// Whether `return_create` got as far as the charge the limits hold the deposit before: the - /// code's state gas, or, without EIP-8037, the deposit itself. - const fn reached(&self) -> bool { - self.deposited || self.charged_state_gas - } -} - impl Inspector, EthInterpreter> for CreationEnd { fn create_end( &mut self, @@ -201,20 +192,20 @@ fn creation_end(setup: Setup, gas: u64) -> CreationEnd { *evm.inspector() } -/// The least gas `A` can call `B` with for `return_create` to reach the charge the limits hold the -/// deposit before, with no limit set; and the unlimited outcome one gas short of it. +/// The least gas `A` can call `B` with for the creation to deposit its code, with no limit set; +/// and the unlimited outcome one gas short of it. /// -/// At the boundary the creation has no regular gas left after that charge, so it is exactly -/// enough; one gas short the creation runs out of gas and deploys nothing. +/// At the boundary the creation has no regular gas left after the deposit's last charge, so it is +/// exactly enough; one gas short the creation runs out of gas and deploys nothing. fn boundary(setup: Setup) -> (u64, MegaTransactionOutcome) { let (mut short, mut enough) = (0, 5_000_000); assert!( - !creation_end(setup, short).reached() && creation_end(setup, enough).reached(), + !creation_end(setup, short).deposited && creation_end(setup, enough).deposited, "{setup:?}: the search brackets the boundary" ); while enough - short > 1 { let middle = short + (enough - short) / 2; - if creation_end(setup, middle).reached() { + if creation_end(setup, middle).deposited { enough = middle; } else { short = middle; @@ -294,37 +285,36 @@ fn assert_data_size_limit_stands_aside(setup: Setup) { assert_eq!(ran_out.usage, short.usage, "{setup:?}: and it keeps what it keeps without it"); } -/// Above the execution cap the reservoir pays the code's state gas: a creation that cannot pay -/// the hash of its code runs out of gas on it, whatever the state-gas limit. +/// Above the execution cap the reservoir pays the code's state gas and history: a creation that +/// cannot pay the hash of its code runs out of gas on it, whatever the state-gas limit. #[test] fn test_a_creation_that_cannot_pay_the_hash_runs_out_of_gas_under_the_state_gas_limit() { let setup = Setup::Satin(ABOVE_CAP); let (enough, _) = boundary(setup); - assert!( - deployed(&run(setup, enough, EvmTxRuntimeLimits::no_limits())), - "the hash is the last charge the frame's own gas pays" - ); + let end = creation_end(setup, enough - 1); + assert!(!end.charged_state_gas, "one gas short, the hash is what it cannot pay: {end:?}"); assert_state_gas_limit_stands_aside(setup); } -/// Below the execution cap the code's state gas is paid out of regular gas: a creation that can -/// pay the hash of its code but not its state gas runs out of gas on the state gas, whatever the -/// state-gas limit. -/// -/// With exactly enough for the state gas the check fires, although without a limit the creation -/// would then run out of gas on the code's history: that is charged after the state gas, as a -/// record's history is after its slot's, and the limit holds what was charged before it. +/// Below the execution cap the code's state gas and then its history are paid out of regular gas: +/// a creation that can pay its state gas but not its history runs out of gas on the history, +/// whatever the state-gas limit. The limit holds the deposit once all of it is paid, not at the +/// state gas: a creation that could pay the state gas alone would otherwise be stopped by a limit +/// it never reaches. #[test] -fn test_a_creation_that_cannot_pay_its_state_gas_runs_out_of_gas_under_the_state_gas_limit() { +fn test_a_creation_that_cannot_pay_its_history_runs_out_of_gas_under_the_state_gas_limit() { let setup = Setup::Satin(BELOW_CAP); let (enough, _) = boundary(setup); - let end = creation_end(setup, enough); - assert!(end.charged_state_gas && !end.deposited, "the history is what it cannot pay: {end:?}"); + let end = creation_end(setup, enough - 1); + assert!( + end.charged_state_gas && !end.deposited, + "one gas short, the history is what it cannot pay: {end:?}" + ); assert_state_gas_limit_stands_aside(setup); } /// The data-size limit counts deployed code behind the same check: a creation that cannot pay the -/// hash of its code, or its state gas, runs out of gas whatever the limit. +/// hash of its code, or its history, runs out of gas whatever the limit. #[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(Setup::Satin(ABOVE_CAP)); From df178bea3776e593bf618908be41d941d96f316f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:01:39 -0700 Subject: [PATCH 268/458] refactor(limit): hold a deposit's state gas whether or not it charged any A deposit the schedule charges no state gas for adds none, so holding what the creation already held finds nothing its own charges did not: the guard only skipped a check that cannot fire. --- crates/mega-evm/src/limit/limit.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index cffa07df2..61f1be1b4 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -615,20 +615,19 @@ impl AdditionalLimit { /// runs out of gas whatever the limit. Empty code deposits nothing and is held to nothing. /// /// The state gas is held with what the creation already holds, and before the bytes, as it is - /// wherever both cross at one site. 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. + /// wherever both cross at one site. A deposit the schedule charges no state gas for adds none, + /// and holding what the creation already held finds nothing its own charges did not. 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(()); } - if deposit.state_gas() > 0 { - let check = self.check_state_gas(deposit.gas_after.state_gas_spent()); - if check.exceeded_limit() { - return Err(check.revert_data()); - } + let check = self.check_state_gas(deposit.gas_after.state_gas_spent()); + if check.exceeded_limit() { + return Err(check.revert_data()); } debug_assert!(self.tracker.current().is_some(), "a creation returns on its own lane"); self.tracker.record(LimitUsage { data_size: bytes, write_records: 0 }); From ed3e8a9a63baa7110b551f288aeb39fbf48f16ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:15:30 -0700 Subject: [PATCH 269/458] feat(access): decide a held precompile call from its price Gas detention decides a precompile call it holds to an allowance below its forward from the call's price, read before the call runs (the fork's `Precompile::required_gas`): priced within the allowance, the call runs on its whole forward, as without the limit; priced 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, which settles as the stop; priced past its whole forward, it runs on the forward and runs out of gas, a failed call its caller survives, where it used to be the stop. An input priced between the allowance and the forward that would fail a check made after the gas check is still the stop: the price cannot tell. The price comes from the engine's own Satin table, and only for an address whose dispatched entry is still the table's: an address a node replaced through `with_dyn_precompiles` is recorded and not priced, whatever id its precompile carries, nor is an entry whose id changed, nor anything once the neutral configuration installed the fixture fork's set. Those, a node's own precompiles and op-revm's size-limited wrappers, which carry no price, keep running on the allowance. The KZG entry carries its flat price. --- crates/mega-evm/src/access/detention.rs | 35 ++-- crates/mega-evm/src/access/mod.rs | 34 ++- crates/mega-evm/src/evm/execution.rs | 217 +++++++++++++++++--- crates/mega-evm/src/evm/mod.rs | 26 ++- crates/mega-evm/src/evm/precompiles.rs | 202 +++++++++++++++++- crates/mega-evm/src/test_utils/neutral.rs | 4 +- crates/mega-evm/tests/satin/detention.rs | 6 + crates/mega-evm/tests/satin/withheld_gas.rs | 166 +++++++++++++-- 8 files changed, 622 insertions(+), 68 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 7d9aefb80..8ee57c493 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -397,8 +397,10 @@ impl Detention { /// `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 that ran out of the allowance it was held to - /// ([`restore_forward`](Self::restore_forward)) — crossed the limit. Otherwise, an answer that + /// 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 @@ -455,17 +457,15 @@ impl Detention { self.stop(&mut result.gas, spendable) } - /// Gives a precompile's answer, 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 of the withheld part, - /// and [`on_answer`](Self::on_answer) settles it as the stop. + /// 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. /// - /// The precompile's price is not known without running it, so a precompile priced above its - /// whole forward runs out of the allowance as well, and is the stop too. So is one priced - /// within its forward, past the allowance, whose input fails a check made after its gas check, - /// which without the read fails the call instead. + /// 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()); @@ -477,6 +477,17 @@ impl Detention { } } + /// 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. /// `spendable` is the spendable part the frame had at the crossing. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 16a825539..ec6f40ac9 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -98,16 +98,30 @@ //! //! 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 run on that -//! allowance, and its answer gets the rest of the forward back. Priced within the allowance, it -//! answers as it would without the read. Priced past it, it answers out of gas without computing; -//! the answer is marked as a crossing, and the same rule stops the transaction. The price is not -//! known without running the precompile, so one priced past its whole forward runs out of the -//! allowance too, and is the stop, where without the read it would be a failed call that burns its -//! forward and that its caller survives. So is one priced between the allowance and its forward -//! whose input fails a check made after its gas check: it runs out of the allowance before that -//! check, where without the read the check fails the call, which burns its forward and which its -//! caller survives. A precompile run on the allowance also sees the allowance as its gas limit. +//! 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 +//! stops the transaction; +//! - 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, where without the read the check fails the call, +//! which burns its forward and which its caller survives. Running it to find out would compute +//! past the limit. +//! +//! A precompile the engine cannot price — a node's own, a Satin address a node replaced, one of +//! op-revm's size-limited wrappers, which carry no price — 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 its caller survives. +//! 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 diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ce4418630..7abbd1686 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -51,7 +51,7 @@ use crate::{ history_gas, synthetic_frame_result, system::keyless, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, - MegaContext, MegaEvm, MegaInstructions, VolatileDataAccess, + MegaContext, MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, }; /// The Satin handler. @@ -427,8 +427,10 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), - ItemOrResult::Result(result) => Err(result), + let (withheld, crossing) = match hold_precompile( + ctx, + &self.inner.precompiles, + &self.priced_precompiles, + &mut frame_init, + refused, + ) { + Ok(withheld) => (withheld, None), + Err(answer) => (None, Some(answer)), + }; + let outcome = match crossing { + Some(answer) => Err(answer), + None => 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)] @@ -787,9 +801,9 @@ fn after_frame_run( /// 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 that ran out of the -/// allowance it was run on ([`hold_precompile`]). An answer that halts otherwise burns what it was -/// given. +/// 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, @@ -803,24 +817,63 @@ fn settle_answer( } /// Holds a precompile the frame `frame_init` is about to call to what gas detention's limit leaves -/// it, and returns what it took off the forward: 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. +/// 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 (`Ok(None)`). 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, out of gas and marked as a crossing ([`Detention::cross_at_price`]), +/// which the answer's settlement turns into the stop (`Err`); +/// - 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 precompile runs on the allowance and sees it as its gas limit; its answer gets the rest -/// back ([`Detention::restore_forward`]) before it is settled. A call to anything else, and a -/// forward within the allowance, run as they are. +/// 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; +/// its answer gets the rest back ([`Detention::restore_forward`]) before it is settled +/// (`Ok(Some)`, what was taken off the forward). One priced past the allowance runs out of gas on +/// it and is the stop, whether its price is within the forward or not. fn hold_precompile( ctx: &MegaContext, precompiles: &PrecompilesMap, + priced: &PricedPrecompiles, frame_init: &mut FrameInit, -) -> Option { - let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return None }; - let allowance = ctx.detention.allowance(frame_init.depth, inputs.gas_limit)?; - let withheld = NonZeroU64::new(inputs.gas_limit.saturating_sub(allowance))?; - precompiles.get(&inputs.bytecode_address)?; - inputs.gas_limit = allowance; - Some(withheld) + refused: bool, +) -> Result, FrameResult> { + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return Ok(None) }; + let Some(allowance) = ctx.detention.allowance(frame_init.depth, inputs.gas_limit) else { + return Ok(None); + }; + let Some(withheld) = NonZeroU64::new(inputs.gas_limit.saturating_sub(allowance)) else { + return Ok(None); + }; + if precompiles.get(&inputs.bytecode_address).is_none() { + return Ok(None); + } + let price = priced.price(precompiles, &inputs.bytecode_address, &inputs.input.as_bytes(ctx)); + let Some(price) = price else { + inputs.gas_limit = allowance; + return Ok(Some(withheld)); + }; + if price <= allowance || price > inputs.gas_limit || refused { + return Ok(None); + } + let mut answer = synthetic_frame_result( + &frame_init.frame_input, + InstructionResult::PrecompileOOG, + Bytes::new(), + ); + Detention::cross_at_price(answer.interpreter_result_mut()); + Err(answer) } /// The gas limit of the frame `input` starts. @@ -1353,6 +1406,7 @@ mod tests { }; use alloy_primitives::{address, U256}; use alloy_sol_types::SolError; + use revm::interpreter::gas::WithheldCrossing; const CALLER: Address = address!("00000000000000000000000000000000000e0001"); const TARGET: Address = address!("00000000000000000000000000000000000e0002"); @@ -1402,6 +1456,123 @@ mod tests { ctx } + /// 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` with `input`, 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, + ) -> (Result, FrameResult>, u64) { + let ctx = detained(cap); + let mut frame_init = static_call(to, &[0; 32], 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!(matches!(held, Ok(None)), "{held:?}"); + assert_eq!(ran_on, 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 Err(FrameResult::Call(answer)) = held else { panic!("{held:?}") }; + 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); + assert_eq!(ran_on, forward, "the input is left 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!(matches!(held, Ok(None)), "{held:?}"); + assert_eq!(ran_on, 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!(matches!(held, Ok(None)), "{held:?}"); + assert_eq!(ran_on, 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!(matches!(held, Ok(None)) && ran_on == 3 * PRICE, "{held:?}"); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE, false); + assert!(matches!(held, Ok(None)) && ran_on == 3 * PRICE, "{held:?}"); + } + + /// 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 op-revm's wrapper of the BN254 pairing, a + /// Satin address a node replaced, and every precompile of a set that is not the Satin one. + #[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 map = crate::satin_precompiles_map(); + let mut replaced = PricedPrecompiles::default(); + replaced.record_replaced(KZG); + let mut foreign = PricedPrecompiles::default(); + foreign.record_foreign(); + for (priced, to) in [ + (&PricedPrecompiles::default(), pairing), + (&replaced, KZG), + (&foreign, KZG), + (&foreign, pairing), + ] { + let (held, ran_on) = hold(1_000, priced, &map, to, 300_000, false); + assert_eq!(held.ok(), Some(NonZeroU64::new(299_000)), "{to}"); + assert_eq!(ran_on, 1_000, "{to}: run on the allowance"); + } + } + /// A frame revm refuses — past the call-stack limit, which no transaction reaches under the /// execution cap — gives its caller's upfront charge back, so the charge is not held, for a /// call and a creation alike; the answer stays what it was. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index ed3cdfa06..b9f14ea35 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -94,6 +94,8 @@ pub struct MegaEvm MegaEvm { @@ -107,7 +109,12 @@ impl MegaEvm MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, trusted_inspector: false, + priced_precompiles: self.priced_precompiles, } } @@ -137,6 +145,7 @@ impl MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, trusted_inspector: true, + priced_precompiles: self.priced_precompiles, } } @@ -172,17 +181,30 @@ 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 diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index d515d53dc..80dd15b9a 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -8,13 +8,37 @@ //! 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. 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; +//! - a call to an entry of the table built without a price function: op-revm's size-limited +//! wrappers of the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and pairing, until the op-revm +//! fork prices them; +//! - 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 through the map's mutable accessors that keeps the id +//! of the entry it replaces. #[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,6 +65,59 @@ 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 by one that is not the Satin set: the neutral + /// configuration's, the fixture fork's own. + 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. An + /// entry of the table built without a price function answers `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 @@ -81,9 +158,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`]. @@ -130,7 +216,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, }; @@ -309,6 +395,116 @@ mod tests { assert_eq!(over.result, InstructionResult::PrecompileError); } + /// Every entry of the Satin set carries a price, but op-revm's size-limited wrappers, which + /// the op-revm fork builds without one: the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and + /// pairing. Gas detention runs a call to one of those on the allowance. + #[test] + fn test_every_satin_entry_is_priced_but_op_revms_wrappers() { + let mut unpriced: std::vec::Vec<_> = satin_precompiles() + .inner() + .values() + .filter(|precompile| precompile.required_gas(&[]).is_none()) + .map(|precompile| precompile.id().clone()) + .collect(); + unpriced.sort_by_key(|id| id.name().to_owned()); + let mut wrappers = std::vec![ + PrecompileId::Bn254Pairing, + PrecompileId::Bls12G1Msm, + PrecompileId::Bls12G2Msm, + PrecompileId::Bls12Pairing, + ]; + wrappers.sort_by_key(|id| id.name().to_owned()); + assert_eq!(unpriced, wrappers); + assert!(satin_precompiles().len() > wrappers.len(), "the rest are priced"); + } + + /// 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, and one of op-revm's wrappers, are never priced. + #[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. + let pairing = *op_revm::precompiles::bn254_pair::KARST.address(); + assert!(untouched.get(&pairing).is_some()); + assert_eq!(none.price(&untouched, &pairing, &[0; 192]), None); + } + /// 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]; diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 39e98aad8..2fa41ea08 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -107,8 +107,8 @@ pub fn neutralize_evm( fork: EthSpecId, ) -> Option<()> { let (precompiles, gas_table) = (neutral_precompiles(fork)?, neutral_gas_table(fork)?); - let (_, instructions, evm_precompiles, _) = evm.all_mut(); - *evm_precompiles = precompiles; + evm.replace_precompile_set(precompiles); + let (_, instructions, _, _) = evm.all_mut(); *instructions.gas_table_mut() = gas_table; Some(()) } diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index f8122f625..bbad4bb6e 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1035,6 +1035,10 @@ pub(crate) struct CallRecord { 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 { @@ -1056,6 +1060,8 @@ impl Inspector, EthInterpreter> for Calls { result: outcome.result.result, output: outcome.result.output.clone(), spent: gas.limit() - gas.remaining(), + forward: inputs.gas_limit, + precompile_ran: outcome.was_precompile_called, }); } } diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index ebfc84cf1..cff433d7b 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -898,9 +898,9 @@ fn run_precompile( } /// revm runs a precompile inside the frame's start, against the gas limit of the frame, so after -/// a read the precompile 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. +/// 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 crosses the limit. Priced a unit past it, it answers @@ -941,16 +941,16 @@ fn test_a_precompile_runs_on_the_allowance() { } } -/// Modexp on a costly input, after a read, against the same call without it: +/// 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 the transaction stops at the limit — 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 the -/// transaction stops at the limit. Without the read the call fails and its caller goes on: the -/// precompile's price is not known without running it, so it cannot be told from one priced -/// within the forward. +/// transaction stops at the limit. Without the read the call fails and its caller goes on: 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. @@ -1010,14 +1010,25 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { } /// A modexp priced far above the cap, 58,687,488 and 125,796,352 gas, called after a read with all -/// the gas, is run on the allowance, computes nothing, and the transaction is billed the limit, in -/// the built-in precompile set the chain runs as in the recording one. A transaction the -/// beneficiary sends straight to the precompile is detained from the start, so the precompile runs -/// on the cap itself. The same transaction from another sender computes. +/// 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; 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. 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( @@ -1032,19 +1043,43 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { let intrinsic = plain.run.outcome.gas.regular - price; for gas_limit in TIERS { - let code = calls_precompile(TIMESTAMP, MODEXP, None); - let db = MemoryDatabase::default().account_code(CONTRACT, code); + let db = |first| { + MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, None)) + }; let called = - run_precompile(db.clone(), MODEXP, recording_modexp, tx_with(&input, gas_limit)); + run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); assert_stopped(&called.run, intrinsic_with(&input, gas_limit)); - let built_in = execute(db, tx_with(&input, gas_limit)); - assert_stopped(&built_in, intrinsic_with(&input, gas_limit)); assert!( matches!(called.ran_on[..], [(gas, false)] if gas < CAP), "{:?}", called.ran_on ); + 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_stopped(&detained, intrinsic_with(&input, gas_limit)); + 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"); @@ -1053,6 +1088,105 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { assert_stopped(&sent.run, intrinsic); } } + assert_eq!(cases, (3, 1), "the stop above the cap for both, and below it for the cheaper"); +} + +/// The built-in modexp priced within the allowance runs as without the read: revm runs it, on the +/// whole forward, and it charges its price, the same result and the same bill. +#[test] +fn test_a_priced_precompile_within_the_allowance_runs_as_without_the_read() { + let input = costly_modexp_input(32, 32); + let price = mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&input).unwrap(); + assert!(price < CAP / 2, "{price}"); + for gas_limit in TIERS { + let run = |first| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, None)); + let mut evm = MegaEvm::new(context(db)).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(); + assert!(call.precompile_ran, "revm runs it"); + assert_eq!(call.spent, price, "it charges its price"); + run + }; + let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); + assert_as_without_read(&detained, &plain, "a price the allowance pays"); + assert_eq!(slot(&detained, 0), Some(U256::from(1))); + } +} + +/// A Satin address a node replaced is not priced from the built-in set, even when its precompile +/// carries the built-in's id: forwarded less than its price and more than the allowance, the +/// replaced modexp runs on the allowance and is the stop, where the built-in one, which the engine +/// prices, runs out of gas as without the read, and its caller goes on. +#[test] +fn test_a_replaced_precompile_is_not_priced_from_the_built_in_set() { + let input = costly_modexp_input(64, 0); + let price = mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&input).unwrap(); + assert!(price > CAP, "{price}"); + let short = u32::try_from(price - 1).unwrap(); + for gas_limit in TIERS { + let db = |first| { + MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, Some(short))) + }; + let replaced = + run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); + assert_stopped(&replaced.run, intrinsic_with(&input, gas_limit)); + assert!( + matches!(replaced.ran_on[..], [(gas, false)] if gas < CAP), + "run on the allowance: {:?}", + replaced.ran_on + ); + + let (built_in, plain) = ( + execute(db(TIMESTAMP), tx_with(&input, gas_limit)), + execute(db(PUSH0), tx_with(&input, gas_limit)), + ); + assert_as_without_read(&built_in, &plain, "a price past the forward"); + assert_eq!(slot(&built_in, 0), Some(U256::ZERO), "the call fails and its caller goes on"); + } +} + +/// op-revm's wrapper of the BN254 pairing carries no price, so it keeps the clamp: forwarded less +/// than its price and more than the allowance — three pairs, 147,000 gas, forwarded 120,000 under a +/// cap of 100,000 — it runs on the allowance and is the stop. The KZG entry, which carries its +/// price, forwarded less than it and more than the allowance — 100,000, forwarded 80,000 under a +/// cap of 50,000 — runs out of gas as without the read. +#[test] +fn test_an_unpriced_wrapper_keeps_the_clamp() { + let pairing = vec![0_u8; 3 * 192]; + let kzg = vec![0_u8; 192]; + let kzg_address = mega_evm::kzg_point_evaluation::ADDRESS; + assert_eq!( + mega_evm::satin_precompiles().get(&EC_PAIRING).unwrap().required_gas(&pairing), + None + ); + for gas_limit in TIERS { + let run = |first, to, forward, cap, input: &[u8]| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, to, Some(forward))); + 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(); + assert_eq!(call.forward, u64::from(forward)); + assert!(call.precompile_ran, "{to}: revm runs it"); + run + }; + + let detained = run(TIMESTAMP, EC_PAIRING, 120_000, 100_000, &pairing); + let plain = run(PUSH0, EC_PAIRING, 120_000, 100_000, &pairing); + assert_stopped(&detained, intrinsic_with(&pairing, gas_limit)); + assert!(plain.outcome.result.is_success()); + assert_eq!(slot(&plain, 0), Some(U256::ZERO), "without the read the call fails"); + + let detained = run(TIMESTAMP, kzg_address, 80_000, 50_000, &kzg); + let plain = run(PUSH0, kzg_address, 80_000, 50_000, &kzg); + 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 From ea7c2b59270253249772099ef0d234e19101eac5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:43:15 -0700 Subject: [PATCH 270/458] feat(access): give a stopped frame the gas it had before the crossing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A frame stopped at a detention crossing now gets back exactly the regular gas it had before the charge that crossed, read off the fork's crossing record: the charge is not made, and the spendable part the frame had is no longer forfeited. A stopped transaction is billed its compute at the crossing, less than one charge short of the limit, where it used to be billed the limit. An answer that crosses — an interceptor's that spends past the allowance, a precompile priced past it, one run on the allowance that runs out of gas — spent nothing before its crossing, so its frame gets its whole gas back. The stop's revert data is unchanged. What `limit_exceeded` reports as used is now the transaction's compute at the crossing, the figure the regular ledger bills, computed the same way at every crossing site, in place of the limit. This removes the adapter the fork pin added, which took the spendable part back out of the record to keep the old billing. The tests that pinned the old billing derive where each stop lands from the regular charges their programs make after the read (`Charges` in the detention tests), and assert the bill and the reported compute from it. --- crates/mega-evm/src/access/detention.rs | 155 +++++++---- crates/mega-evm/src/access/mod.rs | 18 +- crates/mega-evm/src/evm/execution.rs | 24 +- crates/mega-evm/src/limit/mod.rs | 12 +- .../tests/satin/detained_transfers.rs | 123 ++++++--- crates/mega-evm/tests/satin/detention.rs | 261 +++++++++++++++--- crates/mega-evm/tests/satin/stops.rs | 152 ++++++---- .../mega-evm/tests/satin/volatile_access.rs | 33 ++- crates/mega-evm/tests/satin/withheld_gas.rs | 216 ++++++++++----- .../tests/system/keyless/detention.rs | 115 ++++++-- .../mega-evm/tests/system/keyless/limits.rs | 26 +- 11 files changed, 824 insertions(+), 311 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 8ee57c493..ff134bbe0 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -11,6 +11,17 @@ use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, Interpret use super::VolatileDataAccess; use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; +/// A transaction gas detention stops: the compute limit it 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 { @@ -351,16 +362,17 @@ impl Detention { /// 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 limit when the frame ran out of gas on a charge the withheld part of its gas + /// 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 stop the - /// transaction rather than halt. + /// transaction 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 { + ) -> Option { let left_at_halt = self.left_at_halt.take(); if self.disabled_from.is_some_and(|from| from >= depth) { self.disabled_from = None; @@ -370,12 +382,8 @@ impl Detention { } debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); self.frames.pop(); - if let Some(crossing) = gas.withheld_crossing() { - // The record holds the regular gas left before the failed charge; the spendable part of - // it was what the limit left the transaction then. - gas.set_remaining(crossing.remaining()); - let spendable = self.limit.map_or(0, |limit| limit.saturating_sub(self.compute(gas))); - return self.stop(gas, spendable); + 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. @@ -400,20 +408,21 @@ impl Detention { /// 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 of what the frame would have had withheld. A crossing is - /// settled by the same rule as a frame that ran ([`stop`](Self::stop)). Returns the limit - /// when it crossed. + /// 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. pub(crate) fn on_answer( &mut self, result: &mut InterpreterResult, depth: usize, gas_limit: u64, - ) -> Option { + ) -> Option { if !self.detains { return None; } @@ -438,23 +447,19 @@ impl Detention { // an inspector's answer built on another limit is settled on what the frame was // forwarded. // - // State and history gas that spilled onto regular gas would have drawn the withheld - // part first, and the revert that settles the stop credits the spill back, so the - // crossing withholds what is left once the spill is taken out, as the tracker's own - // record of a running frame does. The spill is below `gas_limit - allowance`, since - // the regular gas the answer spent past it exceeds the allowance. The record holds the - // regular gas the frame had before the charge: the gas limit, less the spill. - let spilled = result.gas.state_gas_spilled(); - if gas_limit - allowance <= spilled { - return None; - } - let remaining = NonZeroU64::new(gas_limit - spilled)?; + // 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 spendable = self.allowance(depth, gas_limit).unwrap_or(0); - self.stop(&mut result.gas, spendable) + let limit = self.stop(&mut result.gas)?; + let used = + self.compute_at_start(depth, gas_limit).saturating_add(regular_spent(&result.gas)); + Some(ComputeStop { limit, used }) } /// Gives the answer of a precompile the engine cannot price, which ran on `withheld` less than @@ -490,16 +495,18 @@ impl Detention { /// 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. - /// `spendable` is the spendable part the frame had at the crossing. /// - /// The frame's gas becomes the withheld part at the crossing: the spendable part the frame had - /// counts as spent, which brings the transaction's compute to the limit, and the withheld part - /// goes back to its caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not - /// (`MemoryOOG`), 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, spendable: u64) -> Option { + /// 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().saturating_sub(spendable)); + gas.set_remaining(crossing.remaining()); gas.clear_withheld_crossing(); self.limit } @@ -689,10 +696,11 @@ mod tests { 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 becomes the - /// withheld part, and the spendable part it had counts as spent. + /// 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_withheld_part_left() { + fn test_a_crossing_stops_with_the_gas_it_had_before_the_charge() { for (result, zeroed) in [(InstructionResult::OutOfGas, true), (InstructionResult::MemoryOOG, false)] { @@ -706,13 +714,38 @@ mod tests { frame.spend_all(); } let stop = detention.on_frame_end(result, &mut frame, 0); - assert_eq!(stop, Some(BLOCK_ENV_ACCESS_COMPUTE_GAS), "{result:?}"); - assert_eq!(frame.remaining(), 100_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); + 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), BLOCK_ENV_ACCESS_COMPUTE_GAS, "compute at the limit"); + 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); + 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() { @@ -793,8 +826,8 @@ mod tests { } /// 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 what the frame would have had - /// withheld. State gas that spilled onto the answer's regular gas is not compute. + /// 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(); @@ -824,18 +857,26 @@ mod tests { assert_eq!(detention.burned, 90_000_000); detention.burned = 0; - let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, InstructionResult::Return); - assert_eq!( - detention.on_answer(&mut beyond, 1, 90_000_000), - Some(BLOCK_ENV_ACCESS_COMPUTE_GAS) - ); - assert_eq!(beyond.result, InstructionResult::OutOfGas); - assert_eq!(beyond.gas.remaining(), 90_000_000 - BLOCK_ENV_ACCESS_COMPUTE_GAS); + // 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 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 rest left. + /// 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(); @@ -878,9 +919,9 @@ mod tests { ); assert_eq!( detention.on_answer(&mut out_of_gas, 1, 90_000_000), - Some(BLOCK_ENV_ACCESS_COMPUTE_GAS) + Some(ComputeStop { limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, used: 0 }) ); - assert_eq!(out_of_gas.gas.remaining(), withheld.get(), "the allowance counts as spent"); + 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"); } diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index ec6f40ac9..f9310c202 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -80,7 +80,7 @@ //! //! 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 withheld part it could not draw. +//! and the fork records the crossing, with the regular gas the frame had before the charge. //! //! # The stop //! @@ -88,10 +88,12 @@ //! the withheld part would have paid the charge. The frame stops the transaction the way every //! transaction-level limit does — it reverts with `MegaLimitExceeded` (kind: compute), the //! transaction is latched, no caller resumes, and the transaction settles like an EIP-8037 revert -//! (see [`AdditionalLimit`](crate::AdditionalLimit)). The stopped frame's gas is the withheld part -//! at the crossing: the spendable part it had counts as spent, which brings the transaction's -//! compute to the limit exactly, and the withheld part goes back to the sender. The stop reports -//! the limit as what was used; the size of the charge that crossed is not kept. +//! (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, the spendable +//! part the frame had and the withheld part go back to the sender, and the transaction is billed +//! its compute at the crossing, less than one charge short of the limit. The stop reports that +//! compute 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. //! //! 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. @@ -144,8 +146,9 @@ //! 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 withheld part back with -//! its revert; and a halt burns the frame's gas, withheld part included, as it would undetained. +//! 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. //! @@ -166,6 +169,7 @@ mod detention; mod volatile; +pub(crate) use detention::ComputeStop; pub use detention::{ decode_volatile_data_access_disabled, volatile_data_access_disabled_revert_data, Detention, }; diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7abbd1686..5a9a4e488 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -47,6 +47,7 @@ use revm::{ }; use crate::{ + access::ComputeStop, evm::{history::transaction_body_bytes, inspector::frame_end_checked}, history_gas, synthetic_frame_result, system::keyless, @@ -785,10 +786,10 @@ fn after_frame_run( } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); - if let Some(limit) = + 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(), limit); + stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); } } Err(_) => {} @@ -811,8 +812,8 @@ fn settle_answer( answer: &mut FrameResult, ) { let answer = answer.interpreter_result_mut(); - if let Some(limit) = ctx.detention.on_answer(answer, depth, gas_limit) { - stop_at_the_compute_limit(ctx, answer, limit); + if let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) { + stop_at_the_compute_limit(ctx, answer, stop); } } @@ -885,20 +886,19 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { } } -/// Turns a frame that crossed gas detention's compute `limit` into the transaction-level stop: a +/// Turns a frame that crossed gas detention's compute limit into the transaction-level stop: a /// revert carrying `MegaLimitExceeded` (kind: compute), with the transaction latched, so no caller -/// resumes. The frame's gas is what detention left it — the withheld part at the crossing — which -/// goes back with the revert, to the caller and in the end to the sender. +/// resumes. The frame's gas is what it had before the charge that crossed, which goes back with +/// the revert, to the caller and in the end to the sender. /// -/// The crossing charge's size is not kept, so the stop reports the limit as what was used -/// ([`LimitCheck::ExceedsLimit`]): the transaction's compute reached it exactly, the spendable gas -/// the frame had counting as spent. +/// 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, - limit: u64, + stop: ComputeStop, ) { - let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, limit, limit); + let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, stop.limit, stop.used); result.result = InstructionResult::Revert; result.output = stop.revert_data(); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 28c1038ba..0c4fe748e 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -9,7 +9,7 @@ //! [`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 a transaction //! through the same latch ([`AdditionalLimit::latch`]), with the compute the transaction may reach -//! as the limit, and the limit as what was used ([`LimitCheck::ExceedsLimit`]). +//! as the limit, and its compute at the crossing as what was used ([`LimitCheck::ExceedsLimit`]). //! //! 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 @@ -513,10 +513,12 @@ pub enum LimitCheck { limit: u64, /// The usage that crossed it. /// - /// For [`LimitKind::ComputeGas`] it is the limit itself. Gas detention stops a frame on a - /// regular charge its spendable gas could not pay, and the charge's size is not kept; the - /// spendable gas the frame had counts as spent, which brings the transaction's compute to - /// the limit exactly. + /// 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, diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 998d367c3..62c6de164 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -27,8 +27,8 @@ use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult}; use crate::{ detention::{ - assert_stopped, context, intrinsic, op, run_on, spin, Calls, Run, BENEFICIARY, CALLER, CAP, - CHILD, CONTRACT, TIERS, + assert_stopped, context, intrinsic, memory_cost, op, run_on, spin, Calls, Charges, Run, + BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, }, withheld_gas::{costly_modexp_input, intrinsic_with}, }; @@ -65,6 +65,40 @@ fn calls_with_value(first: u8, to: Address, gas: Option) -> Bytes { 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. +const CALL_TO_A_CONTRACT: u64 = 2_600 + 9_000; + +/// A value call's own charges to a precompile whose account is empty: the warm access, the +/// transfer, and the account the transfer adds, whose regular price Satin keeps beside its state +/// gas. +const CALL_TO_AN_EMPTY_PRECOMPILE: u64 = 100 + 9_000 + 25_000; + /// The accounts every case runs against: [`CONTRACT`] running `code` and holding `held`, a /// [`RECEIVER`] and a [`DESTRUCTOR`]. fn accounts(code: Bytes, held: u64) -> MemoryDatabase { @@ -159,13 +193,13 @@ fn balance(run: &Run, address: Address) -> U256 { /// /// - 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 runs out of the allowance without -/// computing, the frame's checkpoint takes the move and the log back, and the transaction stops -/// at the limit, billed its intrinsic gas and the limit and keeping its body alone. Without the -/// read the call succeeds, and its log is kept. +/// - Priced past the allowance but within the forward, modexp is answered without running: nothing +/// moves and no log is journaled, and the transaction stops at the limit, billed its intrinsic +/// gas and its compute at the call, and keeping its body alone. 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 and runs on the cap: priced past it, the same stop, and the value the -/// transaction carries does not move. +/// 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)); @@ -188,11 +222,13 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { let ((detained, calls), body) = exec(TIMESTAMP, &above); let ((plain, _), _) = exec(PUSH0, &above); - assert_stopped(&detained, intrinsic_with(&above, gas_limit)); - // The answer is the stop, having spent the allowance it ran on. - let (result, allowance) = ended(&calls, MODEXP); - assert_eq!(result, InstructionResult::Revert); - assert!(allowance < detained.limit.unwrap(), "{allowance}"); + // 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()]); + assert_stopped(&detained, intrinsic_with(&above, gas_limit), charges.left(CAP)); + // 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"); @@ -215,8 +251,11 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { 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, CAP)); - assert_stopped(&detained, plain.outcome.gas.regular - price); + 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"); } @@ -308,7 +347,8 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { assert_eq!(detained.outcome.usage.write_records, 1, "the beneficiary's record"); for cap in [DESTRUCT_AFTER_READ - 1, DESTRUCT_AFTER_READ - 2_600 - 1] { let stopped = run_own(TIMESTAMP, cap); - assert_stopped(&stopped, intrinsic(gas_limit)); + let left = Charges::default().then(&[2, 3, 5_000, 2_600]).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"); @@ -332,7 +372,13 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { false, ) .0; - assert_stopped(&stopped, intrinsic(gas_limit)); + // 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, 2_600, 3, 5_000, 2_600, 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"); } @@ -350,8 +396,9 @@ struct Start { input: fn() -> Vec, /// What [`CONTRACT`] holds. held: u64, - /// Whether the cap stops the transaction. - stops: bool, + /// When the cap stops the transaction: the regular charges it makes after the read, 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 @@ -373,63 +420,70 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { code: |first| calls_with_value(first, RECEIVER, None), input: none, held: VALUE, - stops: false, + 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, - stops: true, + // 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: false, + 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: false, + 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: false, + 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, - stops: true, + // 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: false, + 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: false, + 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: false, + stops: None, }, Start { name: "a CREATE with an endowment", @@ -442,7 +496,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { }, input: none, held: VALUE, - stops: false, + stops: None, }, Start { name: "a CREATE2 with an endowment", @@ -455,7 +509,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { }, input: none, held: VALUE, - stops: false, + stops: None, }, Start { name: "a CREATE its creator cannot fund", @@ -468,7 +522,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { }, input: none, held: VALUE - 1, - stops: false, + stops: None, }, Start { name: "a call to a contract that destructs", @@ -479,7 +533,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { }, input: none, held: VALUE, - stops: false, + stops: None, }, ]; for gas_limit in TIERS { @@ -496,8 +550,9 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { }; let detained = exec(TIMESTAMP); assert_counts_its_transfer_logs(&detained, body, &case); - if start.stops { - assert_stopped(&detained, intrinsic_with(&input, gas_limit)); + if let Some(charges) = start.stops { + let left = charges(input.len() as u64).left(CAP); + assert_stopped(&detained, intrinsic_with(&input, gas_limit), left); 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 bbad4bb6e..7b65d27c3 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -3,9 +3,11 @@ //! 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 exactly its limit -//! and its intrinsic gas on the regular ledger: the allowance it had left when the charge failed -//! is spent, and the gas detention withheld is not. +//! 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. @@ -155,44 +157,167 @@ 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 spent exactly its limit. -pub(crate) fn assert_stopped(run: &Run, intrinsic: u64) -> u64 { +/// 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: limit, + used, frame_local: false }) ); assert_eq!( run.outcome.gas.regular, - intrinsic + limit, - "the transaction computed up to its limit and not one unit past it" + 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 } +/* ---------- 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, mut allowance: u64) -> u64 { + 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 allowance; + } + allowance -= charge; + } + unreachable!("a round the allowance cannot pay whole has a charge it cannot pay"); + } + panic!("the program ends within the allowance") + } + + /// 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, 100, 22_000], 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, and the kind it -/// records. +/// 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 { @@ -215,72 +340,84 @@ fn reads() -> Vec { 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", @@ -292,36 +429,43 @@ fn reads() -> Vec { }, 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", @@ -336,6 +480,7 @@ fn reads() -> Vec { ) }, access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], }, Read { name: "SLOAD of the Oracle's storage", @@ -347,6 +492,8 @@ fn reads() -> Vec { ) }, access: VolatileDataAccess::ORACLE, + // The Oracle's `POP`, then its caller's. + after: &[2, 2], }, ] } @@ -368,8 +515,8 @@ pub(crate) fn with_delegation( } /// Every read caps the transaction from where it read, not from its start: the transaction first -/// spends more compute than the cap, then reads, then computes forever, and it stops having spent -/// exactly its compute at the read plus the cap. +/// spends more 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. #[test] fn test_every_volatile_read_caps_the_transaction_from_where_it_read() { for gas_limit in TIERS { @@ -378,7 +525,9 @@ fn test_every_volatile_read_caps_the_transaction_from_where_it_read() { 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)); - let limit = assert_stopped(&run, intrinsic); + // 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 && @@ -402,7 +551,8 @@ fn test_the_cap_counts_from_a_spend_larger_than_itself() { MemoryDatabase::default().account_code(CONTRACT, code), tx(CALLER, CONTRACT, gas_limit), ); - let limit = assert_stopped(&run, intrinsic(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); @@ -452,17 +602,19 @@ fn test_a_transaction_touching_the_beneficiary_is_detained_from_the_start() { for gas_limit in TIERS { let intrinsic = intrinsic(gas_limit); let spinner = spin(BytecodeBuilder::default()); + // Detained before its first instruction: the whole program runs after the read. + let left = Charges::default().spin(0).left(CAP); // The sender. let db = MemoryDatabase::default().account_code(CONTRACT, spinner.clone()); let run_sender = execute(db, tx(BENEFICIARY, CONTRACT, gas_limit)); // A sender's intrinsic gas is the same whoever it is. - assert_eq!(assert_stopped(&run_sender, intrinsic), CAP, "the sender"); + assert_eq!(assert_stopped(&run_sender, intrinsic, left), CAP, "the sender"); // The recipient. let db = MemoryDatabase::default().account_code(BENEFICIARY, spinner.clone()); let run_recipient = execute(db, tx(CALLER, BENEFICIARY, gas_limit)); - assert_eq!(assert_stopped(&run_recipient, intrinsic), CAP, "the recipient"); + assert_eq!(assert_stopped(&run_recipient, intrinsic, left), CAP, "the recipient"); // An applied authority. let authorization = Either::Right(RecoveredAuthorization::new_unchecked( @@ -604,7 +756,21 @@ fn test_the_most_restrictive_limit_binds_whatever_the_order() { .account_code(CONTRACT, code) .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); - let limit = assert_stopped(&run, intrinsic); + // 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, 2_600, 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); } @@ -630,15 +796,19 @@ fn test_a_callers_limits_set_the_caps() { run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)) }; - // `TIMESTAMP` is the first instruction: 2 of compute at the read. + // `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))); - assert_eq!(assert_stopped(&run, intrinsic), 2 + 1_000_000); + 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)), ); - let limit = assert_stopped(&run, intrinsic); + // 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); @@ -710,22 +880,21 @@ fn test_spending_exactly_the_cap_completes() { assert_eq!(run.outcome.gas.regular, intrinsic(gas_limit) + spent); // One more round crosses it. - let code = - burn(op(BytecodeBuilder::default(), TIMESTAMP), u32::try_from(rounds).unwrap() + 1) - .stop() - .build(); + 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), ); - assert_stopped(&run, intrinsic(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 exactly the limit, and so does a transaction carrying value, whose own frame -/// is given what the transaction has left and no stipend. +/// regular ledger at its compute before the charge that crossed, 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)); @@ -741,7 +910,9 @@ fn test_a_stipend_is_not_compute() { .account_balance(CONTRACT, U256::from(1)) .account_code(CHILD, child.clone()); let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); - assert_stopped(&run, intrinsic(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_stopped(&run, intrinsic(gas_limit), left); let db = MemoryDatabase::default() .account_code(CONTRACT, spin(op(BytecodeBuilder::default(), TIMESTAMP))) @@ -749,7 +920,7 @@ fn test_a_stipend_is_not_compute() { 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)); + let limit = assert_stopped(&run, intrinsic_of_a_value_call(gas_limit), left); assert_eq!(limit, CAP + 2, "TIMESTAMP was the first opcode"); } } @@ -804,7 +975,9 @@ fn test_a_childs_read_caps_its_caller() { .account_code(CONTRACT, parent) .account_code(CHILD, child.clone()); let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); - let limit = assert_stopped(&run, intrinsic); + // 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}"); } } @@ -826,7 +999,8 @@ fn test_no_caller_resumes_after_the_stop() { .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 limit = assert_stopped(&run, intrinsic); + let left = Charges::default().then(&[2]).spin(0).left(CAP); + let limit = assert_stopped(&run, intrinsic, left); assert!(run.outcome.state[&CONTRACT].storage.values().all(|slot| !slot.is_changed())); let calls = &evm.inspector().calls; assert_eq!( @@ -858,7 +1032,8 @@ fn test_the_stop_bills_the_same_above_and_below_the_execution_cap() { .account_code(CONTRACT, parent.clone()) .account_code(CHILD, child.clone()); let run = execute(db, tx(CALLER, CONTRACT, *gas_limit)); - assert_stopped(&run, intrinsic(*gas_limit)); + let left = Charges::default().then(&[2]).spin(0).left(CAP); + assert_stopped(&run, intrinsic(*gas_limit), left); 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"); @@ -912,8 +1087,9 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { /// 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, a thousand fresh slots — 22,100,000 of compute — -/// cross it and stop the transaction. Without that room the writes drain the withheld gas first -/// and the frame runs out of its own gas where it would have undetained: it halts. +/// cross it and stop the transaction, at the first write's charge past it. Without that room 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 mut code = op(BytecodeBuilder::default(), TIMESTAMP); @@ -926,7 +1102,8 @@ fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { MemoryDatabase::default().account_code(CONTRACT, code.clone()), tx(CALLER, CONTRACT, ABOVE), ); - assert_stopped(&run, intrinsic(ABOVE)); + let left = Charges::default().then(&[2]).fresh_writes(1_000).left(CAP); + assert_stopped(&run, intrinsic(ABOVE), left); let run = execute( MemoryDatabase::default().account_code(CONTRACT, code), @@ -1267,7 +1444,11 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { MemoryDatabase::default().account_code(CONTRACT, code), tx(CALLER, CONTRACT, gas_limit), ); - assert_stopped(&run, intrinsic); + // The 2,631 spent up to the call's cold access; 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(&[2_631, 2, 3, 3, 3, 100, 22_000]).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. @@ -1370,7 +1551,8 @@ fn test_gas_spilled_before_the_read_is_not_compute() { MemoryDatabase::default().account_code(CONTRACT, code.clone()), tx(CALLER, CONTRACT, gas_limit), ); - let limit = assert_stopped(&run, intrinsic(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 22,100 of regular gas, a hundred times, then TIMESTAMP. assert_eq!(limit - CAP, 100 * (3 + 3 + 22_100) + 2, "{gas_limit}"); } @@ -1387,5 +1569,8 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { MemoryDatabase::default().account_code(CONTRACT, code), tx(CALLER, CONTRACT, BELOW), ); - assert_stopped(&run, intrinsic(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); } diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 3e9704f72..38a505891 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -53,7 +53,7 @@ use revm::{ use crate::{ common::{call, call_with_data, create}, - detention::{context, work, BENEFICIARY}, + detention::{context, work, Charges, BENEFICIARY}, withheld_gas::{priced, Runs, PRICED}, }; @@ -271,16 +271,20 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { // The limit crossed, and the usage that crossed it: one more byte, record or unit of state gas // than the limit. The compute limit is set by the read, at the compute it ran to plus the cap, - // and the stop reports it as what was used. + // 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, slot); let (value, used) = match value { Some(value) => (value, value + 1), - None => (before_crossing + CAP, before_crossing + CAP), + 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 the cap past the read. - let ran = if limit == Limit::Compute { value } else { before_crossing }; + // What ran: up to the crossing, and for the compute limit up to the charge that crosses it. + let ran = if limit == Limit::Compute { used } else { before_crossing }; let plain = execute(chain(limit, crossing, false), configured, gas_limit); let mut evm = @@ -630,10 +634,10 @@ fn detained_callee_at(depth: usize) -> MemoryDatabase { } /// A callee that reads the block's timestamp and then computes past the cap does not make its -/// callers burn their gas: the stop bills the transaction its intrinsic gas plus the limit the read -/// set — its compute at the read plus the cap — and nothing of what the callers held, whatever the -/// gas limit, one call down or three, below the execution cap and above it. No caller resumes: the -/// callee runs the last step. +/// callers burn their gas: the stop bills the transaction its intrinsic gas plus its compute up to +/// the charge that crosses the limit the read set — its compute at the read plus the cap — and +/// nothing of what the callers held, whatever the gas limit, one call down or three, below the +/// execution cap and above it. No caller resumes: the callee runs the last step. #[test] fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_gas() { for depth in [1, 3] { @@ -657,10 +661,12 @@ fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_g (&outcome.result, outcome.gas), "{case}: the recorder changes nothing" ); + // The read's `POP`, then the callee's work. + let used = limit - Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); let stop = LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, limit, - used: limit, + used, frame_local: false, }; assert!( @@ -673,8 +679,8 @@ fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_g // The read came after the callers' calls and the callee's log: its compute then is // theirs alone, a sliver of the cap. assert!(limit - CAP < 50_000, "{case}: compute at the read {}", limit - CAP); - assert_eq!(outcome.gas.regular, intrinsic.gas.regular + limit, "{case}"); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + limit, "{case}"); + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + used, "{case}"); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + used, "{case}"); assert_eq!( outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, "{case}: the reservoir comes back" @@ -985,12 +991,14 @@ fn with_oracle_read(db: MemoryDatabase) -> MemoryDatabase { /// Runs `db`'s `A` under `limits` with [`ROOMY`] gas and asserts the detention stop: a revert /// carrying `MegaLimitExceeded(2, limit)` for the limit the reads set, billed the intrinsic gas -/// plus that limit and nothing of the gas the transaction had left. The frame `crossing` crossed -/// it, and ran the last step: no caller resumed. Returns the limit and what the transaction read. +/// plus the compute up to the charge that crosses that limit, `left` short of it, and nothing of +/// the gas the transaction had left. The frame `crossing` crossed it, and ran the last step: no +/// caller resumed. Returns the limit and what the transaction read. fn assert_detention_stop( db: MemoryDatabase, limits: EvmTxRuntimeLimits, crossing: Address, + left: u64, ) -> (u64, mega_evm::VolatileDataAccess) { let intrinsic = intrinsic(ROOMY); let (recorded, last) = @@ -1005,12 +1013,9 @@ fn assert_detention_stop( ); let detention = evm.ctx().detention(); let limit = detention.compute_limit().expect("a read set a limit"); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used: limit, - frame_local: false, - }; + 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()), @@ -1018,21 +1023,34 @@ fn assert_detention_stop( outcome.result ); assert_eq!(outcome.limit_exceeded, Some(stop)); - assert_eq!(outcome.gas.regular, intrinsic.gas.regular + limit); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + limit); + 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 thousand fresh slots, of which the reservoir +/// pays the state and history gas. +fn pop_then_writes() -> Charges { + Charges::default().then(&[2]).fresh_writes(1_000) +} + +/// After the Oracle's read: its `POP`, its caller's, then the thousand fresh slots. +fn oracle_pops_then_writes() -> Charges { + Charges::default().then(&[2, 2]).fresh_writes(1_000) +} + /// A frame that reads the block's timestamp and then writes a thousand fresh slots stops at the -/// limit the read set, and bills that limit: the transaction's own frame, a child whose caller -/// never runs on, and a caller whose child did its work after the read. +/// 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 never runs on, 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 = thousand_writes(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); let db = MemoryDatabase::default().account_code(A, code.stop().build()); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); + let left = pop_then_writes().left(CAP); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A, left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); } @@ -1046,7 +1064,8 @@ fn test_nested_call_block_env_access_child_oog() { let db = MemoryDatabase::default() .account_code(A, parent.stop().build()) .account_code(B, child.stop().build()); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), B); + let left = pop_then_writes().left(CAP); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), B, left); assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); } @@ -1060,27 +1079,36 @@ fn test_parent_block_env_access_oog_after_nested_call() { let db = MemoryDatabase::default() .account_code(A, thousand_writes(parent).stop().build()) .account_code(B, child.stop().build()); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); + // 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, 2_600, 3, 3, 3, 2, 2]) + .fresh_writes(1_000) + .left(CAP); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A, left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); } /// A call to the Oracle that reads its storage, then a thousand fresh slots: the transaction stops -/// at the compute at the read plus the Oracle's cap, the spec's 20,000,000, and bills it. +/// 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 = thousand_writes(call_oracle(BytecodeBuilder::default(), None)); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A, 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 limit, not the gas limit. +/// 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 = thousand_writes(call_oracle(BytecodeBuilder::default(), Some(0xffff))); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); - assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + assert_detention_stop(db, EvmTxRuntimeLimits::default(), A, left); } /// A contract that calls one that reads the Oracle's storage and then writes a thousand fresh @@ -1093,20 +1121,23 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { let db = MemoryDatabase::default() .account_code(A, outer.stop().build()) .account_code(B, middle.stop().build()); + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); let (_, accessed) = - assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), B); + assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), B, 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 it. +/// 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, thousand_writes(code).stop().build()); let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); - let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, A); + let left = oracle_pops_then_writes().left(ORACLE_CAP); + let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, A, left); assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); assert_eq!( accessed, @@ -1114,13 +1145,14 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { ); } -/// A read of the block's timestamp, then compute past the cap: the stop comes at the compute at the -/// read plus the cap. +/// 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 (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A); + let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), A, left); assert!(limit - CAP < 1_000, "{}", limit - CAP); } @@ -1470,16 +1502,32 @@ fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { .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 + 2_600; + 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 it reports. The compute -/// limit is set by `A`'s read, at the read's own two gas plus the cap; the state-gas limit is one -/// gas short of the schedule's new account, which the test database prices at the minimum bucket. +/// 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. The +/// state-gas limit is one gas short of the schedule's new account, which the test database prices +/// at the minimum bucket. 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 + CAP)) - } + Answered::PastTheAllowance | Answered::Precompile => ( + EvmTxRuntimeLimits::default(), + stop(LimitKind::ComputeGas, 2 + CAP, 2 + to_the_answer(answered)), + ), Answered::NewAccount => { let account = satin_gas_params().get(GasId::new_account_state_gas()); ( @@ -1575,18 +1623,18 @@ fn run_answered( /// One answered cell, both columns: `answered`'s chain at `gas_limit`, without the rewrite and /// with it. /// -/// A compute stop bills exactly its limit past the intrinsic gas. Any other stop bills what ran, -/// read off the twin: the same frames without limits, each reverting once its call returned, which -/// bills what the stopped frames ran plus the two pushes of each revert. The twin runs on the same -/// engine, so that 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 compute stop bills its compute up to the answer past the intrinsic gas. Any other stop bills +/// what ran, read off the twin: the same frames without limits, each reverting once its call +/// returned, which bills what the stopped frames ran plus the two pushes of each revert. The twin +/// runs on the same engine, so that 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, limit, .. } = stop else { unreachable!() }; + let LimitCheck::ExceedsLimit { kind, used, .. } = stop else { unreachable!() }; let ran = if kind == LimitKind::ComputeGas { - limit + used } else { let twin = execute(answered_chain(answered, true), EvmTxRuntimeLimits::no_limits(), gas_limit); @@ -1630,10 +1678,8 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { "{cell}: no value moved" ); if answered == Answered::Precompile { - let [(allowance, false)] = run.ran_on[..] else { - panic!("{cell}: the precompile ran on {:?}", run.ran_on) - }; - assert!(allowance < CAP, "{cell}: run on the allowance, {allowance}"); + 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}"); diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index f25b0676f..f30aad0c1 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -22,8 +22,8 @@ use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult, use crate::detention::{ assert_stopped, burn, call, context, execute, intrinsic, on_beneficiary, op, run_on, spin, - stop_data, tx, with_delegation, work, Calls, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, - DELEGATOR, TIERS, + stop_data, tx, with_delegation, work, Calls, Charges, BELOW, BENEFICIARY, CALLER, CAP, CHILD, + CONTRACT, DELEGATOR, TIERS, }; /// A second contract, never the beneficiary. @@ -176,7 +176,10 @@ fn test_a_read_two_frames_down_caps_every_caller() { db(spin(call(BytecodeBuilder::default(), CALL, CHILD))), tx(CALLER, CONTRACT, gas_limit), ); - let limit = assert_stopped(&run, intrinsic(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); @@ -219,7 +222,10 @@ fn test_a_read_in_a_frame_that_reverts_still_caps() { .account_code(CHILD, child.clone()) .account_code(BENEFICIARY, beneficiary.clone()); let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); - let limit = assert_stopped(&run, intrinsic(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}"); } } @@ -287,9 +293,11 @@ fn test_the_oracle_reading_its_own_storage_is_held_to_the_cap() { .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), + assert_stopped(&run, intrinsic, left), CAP + 2 + 2_100, "the direct call: PUSH0 and a cold SLOAD" ); @@ -299,7 +307,7 @@ fn test_the_oracle_reading_its_own_storage_is_held_to_the_cap() { 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_stopped(&run, intrinsic); + assert_stopped(&run, intrinsic, left); assert_eq!(run.accessed, VolatileDataAccess::ORACLE, "{scheme:#04x}"); } } @@ -394,7 +402,9 @@ fn test_the_beneficiarys_own_frame_is_detained() { MemoryDatabase::default().account_code(BENEFICIARY, code), tx(CALLER, BENEFICIARY, gas_limit), ); - assert_eq!(assert_stopped(&run, intrinsic(gas_limit)), CAP); + // 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() @@ -717,19 +727,22 @@ fn test_a_cap_below_the_intrinsic_gas_stops_nothing_before_the_first_frame() { 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 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: tiny, + used, frame_local: false }) ); assert_eq!(past.outcome.result.output(), Some(&stop_data(tiny))); - assert_eq!(past.outcome.gas.regular, intrinsic + 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 index cff433d7b..552cf3dc5 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -49,8 +49,8 @@ use revm::{ }; use crate::detention::{ - assert_stopped, burn, context, execute, intrinsic, op, run_on, spin, stop_data, tx, work, - Calls, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, + assert_stopped, burn, context, execute, intrinsic, memory_cost, op, run_on, spin, stop_data, + tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, }; /// A contract between the transaction's frame and `CHILD`. @@ -448,10 +448,10 @@ fn test_an_exp_that_cannot_pay_its_exponent_burns_what_its_frame_had() { /// 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 regular -/// ledger holds 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. +/// 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. #[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(); @@ -467,17 +467,40 @@ fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { 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 { 2_600 } 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: limit, + used, frame_local: false }) ); - let overshoot = detained.outcome.gas.regular - intrinsic(gas_limit) - limit; - assert!(overshoot < 5_000, "{overshoot}"); + assert_eq!(detained.outcome.gas.regular, intrinsic(gas_limit) + 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"); @@ -514,24 +537,31 @@ fn test_a_callee_computing_past_the_cap_stops_the_transaction() { }); assert!(plain.outcome.result.is_success()); assert_eq!(slot(&plain, 0), Some(U256::from(1)), "the callee completes without the read"); - assert_stopped(&detained, intrinsic(gas_limit)); + // 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, 2_600]).work(10_000, 0).left(CAP); + assert_stopped(&detained, intrinsic(gas_limit), left); assert_eq!(slot(&detained, 0), None, "the caller never resumed"); } } -/// The stop reports the limit 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 limit and what the callee burned, and nothing past either. +/// 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_the_limit_whatever_a_callee_burned() { - let cases: [(&str, Bytes); 3] = [ - ("out of gas", huge_hash(BytecodeBuilder::default()).stop().build()), - ("out of memory gas", huge_memory(BytecodeBuilder::default()).stop().build()), - ("an invalid opcode", BytecodeBuilder::default().append(INVALID).build()), +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) in &cases { + for (name, child, computed) in &cases { let parent = call_keeping_status( op(BytecodeBuilder::default(), TIMESTAMP), CHILD, @@ -542,17 +572,24 @@ fn test_the_stop_reports_the_limit_whatever_a_callee_burned() { .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, 2_600, *computed, 2]) + .spin(0) + .left(CAP); + let used = limit - left; assert_eq!( run.outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, limit, - used: limit, + used, frame_local: false }), "{name}" ); - let burned = run.outcome.gas.regular - intrinsic - limit; + let burned = run.outcome.gas.regular - intrinsic - used; assert!( (4_990_000..=5_000_000).contains(&burned), "{name}: the callee burned {burned}" @@ -564,7 +601,7 @@ fn test_the_stop_reports_the_limit_whatever_a_callee_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 the limit, to the gas, so the work between the hash and the halt is compute. +/// 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]); @@ -582,7 +619,14 @@ fn test_a_halt_burns_what_its_frame_had_when_it_halted() { assert!(call.spent > 260_000, "{}", call.spent); let limit = run.limit.unwrap(); assert_eq!(run.outcome.result.output(), Some(&stop_data(limit))); - let burned = run.outcome.gas.regular - intrinsic(gas_limit) - 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, 2_600, 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"); } } @@ -849,6 +893,31 @@ fn calls_precompile(first: u8, to: Address, gas: Option) -> Bytes { 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 { @@ -903,9 +972,9 @@ fn run_precompile( /// 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 crosses the limit. Priced a unit past it, it answers -/// out of gas without computing, and the transaction stops, billed exactly the allowance the -/// precompile ran on. +/// 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 the transaction stops, +/// billed nothing of the allowance the precompile ran on. #[test] fn test_a_precompile_runs_on_the_allowance() { for gas_limit in TIERS { @@ -915,17 +984,20 @@ fn test_a_precompile_runs_on_the_allowance() { 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>(); - assert_stopped(&run.run, intrinsic_with(&input, gas_limit)); + let left = to_the_call.clone().then(&[price, 3]).left(CAP); + assert_stopped(&run.run, intrinsic_with(&input, gas_limit), left); }; - // Priced past every allowance: the stop, whose bill says what the allowance was. + // Priced past every allowance: the stop. let past = run(TIMESTAMP, CAP + 1); stopped(&past, CAP + 1); - let allowance = past.spent; - assert!(allowance < CAP, "{allowance}"); 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)); @@ -966,8 +1038,8 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { }; let (detained, plain) = (run(TIMESTAMP, None, &above), run(PUSH0, None, &above)); - assert_stopped(&detained.run, intrinsic_with(&above, gas_limit)); - let allowance = detained.spent; + let allowance = CAP - charges_to_the_precompile(above.len(), None).total(); + assert_stopped(&detained.run, intrinsic_with(&above, gas_limit), allowance); 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}"); @@ -997,12 +1069,9 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { let short = u32::try_from(above_price).unwrap() - 1; let (detained, plain) = (run(TIMESTAMP, Some(short), &above), run(PUSH0, Some(short), &above)); - assert_stopped(&detained.run, intrinsic_with(&above, gas_limit)); - assert!( - matches!(detained.ran_on[..], [(gas, false)] if gas < CAP), - "{:?}", - detained.ran_on - ); + let allowance = CAP - charges_to_the_precompile(above.len(), Some(short)).total(); + assert_stopped(&detained.run, intrinsic_with(&above, gas_limit), allowance); + 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"); @@ -1049,12 +1118,9 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { }; let called = run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); - assert_stopped(&called.run, intrinsic_with(&input, gas_limit)); - assert!( - matches!(called.ran_on[..], [(gas, false)] if gas < CAP), - "{:?}", - called.ran_on - ); + let allowance = CAP - charges_to_the_precompile(input.len(), None).total(); + assert_stopped(&called.run, intrinsic_with(&input, gas_limit), allowance); + 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()); @@ -1068,7 +1134,7 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { assert_eq!(forward, plain_forward, "the read leaves the forward as it is"); assert!(forward > CAP, "{forward}"); if price <= forward { - assert_stopped(&detained, intrinsic_with(&input, gas_limit)); + assert_stopped(&detained, intrinsic_with(&input, gas_limit), allowance); 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"); @@ -1084,8 +1150,8 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { 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, CAP); - assert_stopped(&sent.run, intrinsic); + 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"); @@ -1132,12 +1198,9 @@ fn test_a_replaced_precompile_is_not_priced_from_the_built_in_set() { }; let replaced = run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); - assert_stopped(&replaced.run, intrinsic_with(&input, gas_limit)); - assert!( - matches!(replaced.ran_on[..], [(gas, false)] if gas < CAP), - "run on the allowance: {:?}", - replaced.ran_on - ); + let allowance = CAP - charges_to_the_precompile(input.len(), Some(short)).total(); + assert_stopped(&replaced.run, intrinsic_with(&input, gas_limit), allowance); + assert_eq!(replaced.ran_on, [(allowance, false)], "run on the allowance"); let (built_in, plain) = ( execute(db(TIMESTAMP), tx_with(&input, gas_limit)), @@ -1178,7 +1241,8 @@ fn test_an_unpriced_wrapper_keeps_the_clamp() { let detained = run(TIMESTAMP, EC_PAIRING, 120_000, 100_000, &pairing); let plain = run(PUSH0, EC_PAIRING, 120_000, 100_000, &pairing); - assert_stopped(&detained, intrinsic_with(&pairing, gas_limit)); + let allowance = 100_000 - charges_to_the_precompile(pairing.len(), Some(120_000)).total(); + assert_stopped(&detained, intrinsic_with(&pairing, gas_limit), allowance); assert!(plain.outcome.result.is_success()); assert_eq!(slot(&plain, 0), Some(U256::ZERO), "without the read the call fails"); @@ -1207,7 +1271,8 @@ fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowan run_on(&mut evm, tx_with(&input, gas_limit)) }; let (detained, plain) = (run(TIMESTAMP, 100_000), run(PUSH0, 100_000)); - assert_stopped(&detained, intrinsic_with(&input, gas_limit)); + let allowance = 100_000 - charges_to_the_precompile(input.len(), None).total(); + assert_stopped(&detained, intrinsic_with(&input, gas_limit), allowance); 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)); @@ -1280,18 +1345,22 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { assert_eq!(answer.deployedAddress, CREATE2_FACTORY_CONTRACT, "it deploys"); 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); - assert_stopped(&both(BENEFICIARY, 0, &deploys, cap), deploy_intrinsic); + assert_stopped(&detained, refused_intrinsic, cap); + assert_stopped(&both(BENEFICIARY, 0, &deploys, cap), deploy_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); - assert_stopped(&stopped, deploy_intrinsic); + 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"); // The creation's own compute: the regular gas the deployment spent past the call's. @@ -1299,7 +1368,13 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { deployed.outcome.gas.regular - deploy_intrinsic - KEYLESS_DEPLOY_OVERHEAD_GAS - create; let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + create + creation - 1; let stopped = both(BENEFICIARY, 0, &deploys, cap); - assert_stopped(&stopped, deploy_intrinsic); + let code = deployed.outcome.state[&CREATE2_FACTORY_CONTRACT].info.code.clone().unwrap(); + let hash = 6 * (code.len() as u64).div_ceil(32); + let left = Charges::default() + .then(&[KEYLESS_DEPLOY_OVERHEAD_GAS, create, creation - hash, hash]) + .left(cap); + assert_eq!(left, hash - 1, "the hash of the deposited code crosses"); + assert_stopped(&stopped, deploy_intrinsic, left); assert!( stopped.outcome.state.get(&CREATE2_FACTORY_CONTRACT).is_none_or(|a| a.info.is_empty()), "the stop takes the deployment back" @@ -1408,12 +1483,13 @@ impl Inspector, EthInterpreter> for AnswersPastThe } } -/// An answer past the allowance is the stop, billed the intrinsic gas and the limit, whatever state -/// or history gas the answer charged: below the execution cap that gas spills onto regular gas and -/// the stop's revert gives it back, so the stop withholds none of it a second time. Above the cap -/// the reservoir pays it and nothing spills. +/// 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_the_limit() { +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])); @@ -1428,7 +1504,17 @@ fn test_an_answer_past_the_allowance_with_a_spill_is_billed_the_limit() { 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.gas.regular, intrinsic + CAP, "{gas_limit}, history {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/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index 0585cba89..73435d997 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -125,9 +125,10 @@ fn run_as_creation(init_code: Bytes, gas_limit: u64, limits: EvmTxRuntimeLimits) run_tx(context_in(system_db(), BENEFICIARY, limits), tx, false) } -/// Asserts `run` of `deployment` at `gas_limit` was stopped by gas detention, having computed -/// exactly its limit past its intrinsic gas, and kept nothing of the deployment. -fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: u64) { +/// 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); @@ -136,20 +137,21 @@ fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: u64) { 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: limit, - frame_local: false, + used, + frame_local: false }), ); let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); assert_eq!( run.outcome.gas.regular, - reference.gas.regular + limit, - "the transaction computed up to its limit and not one unit past it, at {gas_limit}", + 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"); @@ -202,7 +204,8 @@ fn refused_read(outcome: &MegaTransactionOutcome) -> VolatileDataAccess { /// 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. +/// 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() { @@ -226,7 +229,7 @@ fn test_a_signer_that_is_the_beneficiary_detains_its_deployment() { 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); + assert_stopped(&stopped, &deployment, gas_limit, cap); } } @@ -237,8 +240,9 @@ fn test_a_signer_that_is_the_beneficiary_detains_its_deployment() { /// 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 limit: the call reverts with the stop, and the deployment -/// is taken back whole. Plain and inspected, below and above the execution cap. +/// Past it, the constructor stops at the first charge of its loop past the limit: the call reverts +/// with the stop, and the deployment is taken back whole. 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); @@ -257,7 +261,10 @@ fn test_a_constructor_that_reads_volatile_data_is_held_to_the_cap() { let stopped = run_both(&reads, gas_limit, capped(1_000)); assert_eq!(stopped.limit, Some(charges + 2 + 1_000)); - assert_stopped(&stopped, &reads, gas_limit); + // 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_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); } @@ -265,7 +272,8 @@ fn test_a_constructor_that_reads_volatile_data_is_held_to_the_cap() { /// 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 constructor's last charge crosses. +/// 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. #[test] fn test_a_sender_that_is_the_beneficiary_holds_the_whole_deployment_to_the_cap() { let init_code = reads_then_burns(PUSH0, 100); @@ -285,15 +293,15 @@ fn test_a_sender_that_is_the_beneficiary_holds_the_whole_deployment_to_the_cap() 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_stopped(&short, &deployment, gas_limit); + assert_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 at the cap having computed exactly the cap. 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. +/// 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))); @@ -304,7 +312,7 @@ fn test_a_sender_that_is_the_beneficiary_is_held_before_the_overhead() { 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); + assert_stopped(&run, &deployment, gas_limit, cap); } } } @@ -460,8 +468,10 @@ fn reads_the_oracle(rounds: u16) -> Bytes { /// 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 the cap, the constructor stops at the limit, and the -/// deployment is taken back whole. +/// 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 deployment is taken back whole. #[test] fn test_a_constructor_reads_the_oracle_as_any_frame_does() { let deployment = Deployment::new(reads_the_oracle(1_000)); @@ -497,12 +507,75 @@ fn test_a_constructor_reads_the_oracle_as_any_frame_does() { 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_stopped(&stopped, &deployment, gas_limit); + assert_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 diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 2a23c4eac..69fbc2a5e 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -30,7 +30,10 @@ use revm::{ Database, Inspector, }; -use super::{detention::reads_then_burns, *}; +use super::{ + detention::{crossing_left, reads_then_burns}, + *, +}; use crate::common::context; /// Init code that logs `len` bytes of data and deploys a one-byte runtime. @@ -524,12 +527,16 @@ impl Crossing { (limits.with_tx_state_gas_limit(limit), stop) } Self::Compute => { - // Read at the call's charges and the read's own two gas; the stop brings the - // compute to the limit exactly. + // 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)) + (limits, Crossed::new(LimitKind::ComputeGas, limit, limit - left)) } } } @@ -617,16 +624,17 @@ fn plain_and_rewritten( /// constructor's, not the creation's start or the call's charges. Every run keeps nothing of the /// deployment: the signer's nonce is where it was, neither spent from 0 nor left at 2 from 1; no /// code, no record, and no state or history gas beyond the transaction's body; above the cap the -/// reservoir comes back. A compute stop bills exactly its limit past the body: the call's -/// charges, the read and the cap. The inspector sees the creation end with the stop, then the -/// call, and changes nothing the transaction reports. +/// reservoir comes back. 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. The +/// inspector sees the creation end with the stop, then the call, and changes nothing the +/// transaction reports. #[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, signer_nonce); - let Crossed { kind, limit, .. } = expected; + let Crossed { kind, limit, used } = expected; let db = match signer_nonce { 0 => system_db(), nonce => system_db().account_nonce(deployment.signer, nonce), @@ -651,7 +659,7 @@ fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { if kind == LimitKind::ComputeGas { let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); let [_, regular, ..] = beyond(outcome, &reference); - assert_eq!(regular, limit, "{cell}: computed up to the limit exactly"); + assert_eq!(regular, used, "{cell}: computed up to the charge that crossed"); } } assert_eq!( From 7724961623fb5dcd73f22b24ae95a5be716e6954 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:45:20 -0700 Subject: [PATCH 271/458] docs: describe the code-deposit admission, the precompile price and the stop's settlement AGENTS.md and the crate README describe deployed code held at the fork's code-deposit admission, a held precompile call decided from its price with the Satin table's entry as its source, and a detention stop that gives the frame the gas it had before the charge that crossed and reports the transaction's compute at the crossing as used. --- AGENTS.md | 50 +++++++++++++++++--------------- crates/mega-evm/README.md | 9 +++--- crates/mega-evm/src/evm/frame.rs | 6 ++-- 3 files changed, 35 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0411a3fd3..7a5592b41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,7 +83,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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. -- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), which upstream revm does not have. +- 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 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 @@ -100,17 +101,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 (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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 (`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); the EIP-7708 switch and the system-call reservoir split the spec fixes on, and whether the running transaction is the protocol's own (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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` and the creation-revival refusal (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | ### How Satin executes today @@ -155,7 +156,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A creation revm answers without bumping its creator's nonce keeps nothing its start counted, whatever the answer. 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 revm would deposit before the creation is committed (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 before it is forwarded. + 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. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default 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 like the block's execution gas (see the block executor below). @@ -168,7 +169,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame revm refuses — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, just before `return_create` makes its charge, priced through the same hook, as the data-size limit counts the same bytes there, so a crossing leaves no code behind; both hold the deposit only once `return_create` is sure to make that charge, so a creation that cannot pay the regular costs it charges first, or the state gas itself, runs out of gas whatever the limit. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame revm refuses — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. @@ -275,21 +276,24 @@ Detention caps how much a transaction may still compute once it read such data ( 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 withheld part. + 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 latch's revert, `MegaLimitExceeded(2, limit)`, with its gas the record's withheld part: the spendable part it had counts as spent, which brings the compute to the limit exactly, and the withheld part goes back to the sender. - The settlement is the same whether the halt zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`). - The stop reports the limit as what was used (`LimitCheck::ExceedsLimit`): the size of the charge that crossed is not kept. + The frame becomes the latch'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 the sender, and the transaction is billed its compute at the crossing, less than one charge short of 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 run on the allowance (`hold_precompile` in `MegaEvm::frame_init`), and its answer gets the rest of the forward back (`Detention::restore_forward`). - Priced within the allowance, it answers as it would without the read; priced past it, it answers out of gas without computing, is marked with `set_withheld_crossing`, and is stopped by the same classification. - The price is not known without running the precompile, so one priced past its whole forward is the stop too, where without the read it would be a failed call that burns its forward and that its caller survives; and a precompile run on the allowance sees the allowance as its gas limit. - So is one priced between the allowance and its forward whose input fails a check made after its gas check: it runs out of the allowance before that check, where without the read the check fails the call, which burns its forward and which its caller survives. - 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`, 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. + 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 and op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing carry no price either. + alloy-evm's `PrecompilesMap` erases what it holds once a node changes it, so a change made through its mutable accessors that keeps the replaced entry's id is not seen; 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 50fd3aca5..f99abc594 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -145,10 +145,11 @@ The one exception is what a frame has left when an opcode's static gas fails, wh 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: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute up to the limit, and the sender gets back everything withheld. -A precompile is run on what the limit leaves its frame, not on all its caller forwarded: one priced past that computes nothing and is the same crossing, as is an interceptor's answer that spent more than it. -A precompile forwarded more than what the limit leaves its frame, and priced past its whole forward, is the crossing too, where without the read it would be a failed call its caller survives. -So is one priced between what the limit leaves its frame and its forward whose input fails a check made after its gas check: without the read, that check fails the call, which its caller survives. +That charge crossed the cap, and it is not made: the transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute before that charge, less than one charge short of the limit, and the sender gets back everything the frame had, the part withheld included. +The stop reports that compute as what the transaction used. +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. +A precompile the engine cannot price — a node's own, an address a node replaced, op-revm's size-limited wrappers — 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. diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index d981219e2..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, the -//! system contract interceptors, a `keylessDeploy` call carrying value, and, when it lands, -//! precompile normalisation. 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: +//! 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; From a774f945106c84937ec591fdd1b103083f19417d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:52:52 -0700 Subject: [PATCH 272/458] perf(access): keep a frame start that holds no precompile call as cheap as before `hold_precompile` returns a small decision (`PrecompileHold`) in place of a result that carried a whole frame result on every frame start, checks for a compute limit before anything else, and leaves the detained path out of line; the crossing answer is built in a cold function. The decision is unchanged. Measured with callgrind against the code-deposit commit (the parent of the price-first decision): `system_address_misses` +2,825 Ir instead of +16,094, `deep_calls` +793 instead of +5,161, `intercepted_calls` +1,425 instead of +494; most of what remains is in revm's own `EthFrame::init_with_context`, which this change does not touch. --- crates/mega-evm/src/evm/execution.rs | 145 +++++++++++++++++---------- 1 file changed, 93 insertions(+), 52 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 5a9a4e488..49bef9c02 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -491,22 +491,20 @@ impl EvmTr for MegaEvm (withheld, None), - Err(answer) => (None, Some(answer)), - }; - let outcome = match crossing { - Some(answer) => Err(answer), - None => match self.inner.frame_init(frame_init)? { + ); + 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), - }, + } }; let ctx = &mut self.inner.ctx; #[cfg(debug_assertions)] @@ -527,7 +525,7 @@ impl EvmTr for MegaEvm( } } +/// 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 (`Ok(None)`). A -/// precompile the engine can price ([`PricedPrecompiles::price`]) is decided from its price -/// before it runs: +/// 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, out of gas and marked as a crossing ([`Detention::cross_at_price`]), -/// which the answer's settlement turns into the stop (`Err`); +/// 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. /// @@ -839,42 +848,65 @@ fn settle_answer( /// 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; -/// its answer gets the rest back ([`Detention::restore_forward`]) before it is settled -/// (`Ok(Some)`, what was taken off the forward). One priced past the allowance runs out of gas on -/// it and is the stop, whether its price is within the forward or not. +/// 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, -) -> Result, FrameResult> { - let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return Ok(None) }; +) -> 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 Ok(None); + return PrecompileHold::Unheld; }; let Some(withheld) = NonZeroU64::new(inputs.gas_limit.saturating_sub(allowance)) else { - return Ok(None); + return PrecompileHold::Unheld; }; if precompiles.get(&inputs.bytecode_address).is_none() { - return Ok(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 Ok(Some(withheld)); + return PrecompileHold::Clamped(withheld); }; if price <= allowance || price > inputs.gas_limit || refused { - return Ok(None); + return PrecompileHold::Unheld; } - let mut answer = synthetic_frame_result( - &frame_init.frame_input, - InstructionResult::PrecompileOOG, - Bytes::new(), - ); + 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()); - Err(answer) + answer } /// The gas limit of the frame `input` starts. @@ -1487,8 +1519,8 @@ mod tests { } } - /// What `hold_precompile` decides for a call to `to` with `input`, forwarded `forward`, under - /// an allowance of `cap`, with `priced`; and the gas limit the call is left to run on. + /// 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, @@ -1496,7 +1528,7 @@ mod tests { to: Address, forward: u64, refused: bool, - ) -> (Result, FrameResult>, u64) { + ) -> (PrecompileHold, u64) { let ctx = detained(cap); let mut frame_init = static_call(to, &[0; 32], forward); let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init, refused); @@ -1516,37 +1548,45 @@ mod tests { // Within the allowance: runs on the forward. let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE, false); - assert!(matches!(held, Ok(None)), "{held:?}"); - assert_eq!(ran_on, 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 Err(FrameResult::Call(answer)) = held else { panic!("{held:?}") }; - 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); - assert_eq!(ran_on, forward, "the input is left as it was"); + 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!(matches!(held, Ok(None)), "{held:?}"); - assert_eq!(ran_on, 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!(matches!(held, Ok(None)), "{held:?}"); - assert_eq!(ran_on, 3 * PRICE); + 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!(matches!(held, Ok(None)) && ran_on == 3 * PRICE, "{held:?}"); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE, false); - assert!(matches!(held, Ok(None)) && ran_on == 3 * PRICE, "{held:?}"); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + } + + /// 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 @@ -1568,7 +1608,8 @@ mod tests { (&foreign, pairing), ] { let (held, ran_on) = hold(1_000, priced, &map, to, 300_000, false); - assert_eq!(held.ok(), Some(NonZeroU64::new(299_000)), "{to}"); + 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"); } } From e4b8bde5b1c248477a03457e4d14c176c9d851f9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 11:58:21 -0700 Subject: [PATCH 273/458] test(precompile): the neutral set replaces the Satin one and is not priced from it Replacing the whole precompile set installs the fixture fork's set on the EVM, and gas detention prices nothing from the Satin table after it. --- crates/mega-evm/src/evm/mod.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index b9f14ea35..9ec4fd6e2 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -551,6 +551,26 @@ 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 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 { From 5d16c64e886670b475d12404742eec713945b360 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 12:43:43 -0700 Subject: [PATCH 274/458] test(limit): hold the deposit's state-gas stop to the creation that made it --- crates/mega-evm/tests/satin/deposit_charge.rs | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 955e57f83..a2feac3bd 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -21,7 +21,7 @@ //! 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. -use alloy_primitives::{address, Address, U256}; +use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{neutral_cfg, neutralize_evm, BytecodeBuilder, MemoryDatabase}, @@ -157,7 +157,7 @@ fn creation_answer(outcome: &MegaTransactionOutcome) -> U256 { } /// The creation's frame once `return_create` is done with it. -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Debug, Default)] struct CreationEnd { /// Whether the creation deposited its code. deposited: bool, @@ -166,6 +166,8 @@ struct CreationEnd { 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 Inspector, EthInterpreter> for CreationEnd { @@ -180,16 +182,21 @@ impl Inspector, EthInterpreter> for CreationEnd { deposited: outcome.result.is_ok(), charged_state_gas: gas.state_gas_spent() > 0, remaining: gas.remaining(), + reverted_with: outcome.result.is_revert().then(|| outcome.result.output.clone()), }; } } /// How the creation ends when `A` calls `B` with `gas` and no limit is set. fn creation_end(setup: Setup, gas: u64) -> CreationEnd { - let mut evm = - evm(setup, gas, EvmTxRuntimeLimits::no_limits()).with_inspector(CreationEnd::default()); + creation_end_under(setup, gas, EvmTxRuntimeLimits::no_limits()) +} + +/// How the creation ends when `A` calls `B` with `gas`, under `limits`. +fn creation_end_under(setup: Setup, gas: u64, limits: EvmTxRuntimeLimits) -> CreationEnd { + let mut evm = evm(setup, gas, limits).with_inspector(CreationEnd::default()); evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit(setup))).unwrap(); - *evm.inspector() + evm.inspector().clone() } /// The least gas `A` can call `B` with for the creation to deposit its code, with no limit set; @@ -231,6 +238,12 @@ fn creation_state_gas() -> u64 { /// Under a state-gas limit one gas short of what the creation holds with its code, the creation /// that reaches the charge is stopped, and the one that cannot runs out of gas as it does without /// the limit: the transaction succeeds with no code deployed and the same gas. +/// +/// The stop latches the transaction, so the whole transaction reverts whichever frame crossed; a +/// limit held anywhere after the deposit — at `A`'s next `SSTORE`, which holds the state gas the +/// transaction has by then — would report the same stop and deploy nothing as well. The creation's +/// own end tells them apart: the deposit is held where it is made when the creation itself reverts +/// with the stop. fn assert_state_gas_limit_stands_aside(setup: Setup) { let (enough, short) = boundary(setup); let creation = creation_state_gas(); @@ -246,6 +259,13 @@ fn assert_state_gas_limit_stands_aside(setup: Setup) { }; assert_eq!(stopped.limit_exceeded, Some(stop), "{setup:?}: exactly enough, the check fires"); assert!(!deployed(&stopped), "{setup:?}"); + let end = creation_end_under(setup, enough, limits); + assert!(!end.deposited, "{setup:?}: the deposit is refused: {end:?}"); + assert_eq!( + end.reverted_with, + Some(stop.revert_data()), + "{setup:?}: the creation that made the deposit is the one the stop ends", + ); let ran_out = run(setup, enough - 1, limits); assert!(ran_out.result.is_success(), "{setup:?}: {:?}", ran_out.result); From 4d9a7f89a5bed1fdd592b3a1933a1f42056657fb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 12:45:40 -0700 Subject: [PATCH 275/458] refactor(access): drop the answer stop's regular-spent term, always zero once put back --- crates/mega-evm/src/access/detention.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index ff134bbe0..fbd61051b 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -457,9 +457,12 @@ impl Detention { result.gas.set_withheld_crossing(Some(WithheldCrossing::with_remaining(remaining))); } let limit = self.stop(&mut result.gas)?; - let used = - self.compute_at_start(depth, gas_limit).saturating_add(regular_spent(&result.gas)); - Some(ComputeStop { limit, used }) + // 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 From 9e8172cf0fb3476083d354a63ae081550083a587 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 12:47:39 -0700 Subject: [PATCH 276/458] docs(precompile): a set replaced through a mutable reference to the map is not seen --- AGENTS.md | 3 ++- crates/mega-evm/src/evm/mod.rs | 24 ++++++++++++++++++++++++ crates/mega-evm/src/evm/precompiles.rs | 18 ++++++++++++++---- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7a5592b41..a05187646 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,7 +291,8 @@ Detention caps how much a transaction may still compute once it read such data ( 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 and op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing carry no price either. - alloy-evm's `PrecompilesMap` erases what it holds once a node changes it, so a change made through its mutable accessors that keeps the replaced entry's id is not seen; a node changes the set through `with_dyn_precompiles` or the factory's builder. + 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. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 9ec4fd6e2..4214a9eb7 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -571,6 +571,30 @@ mod tests { 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. fn tx(value: U256) -> MegaTransaction { diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 80dd15b9a..02adf7151 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -30,8 +30,17 @@ //! 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 through the map's mutable accessors that keeps the id -//! of the entry it replaces. +//! 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; @@ -72,8 +81,9 @@ 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 by one that is not the Satin set: the neutral - /// configuration's, the fixture fork's own. + /// 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, } From 66d063b4ec83c8400a4ce69cdabe8a52291e6332 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 13:10:27 -0700 Subject: [PATCH 277/458] perf(access): keep detention's frame figures only from the first read that sets a limit --- AGENTS.md | 1 + crates/mega-evm/src/access/detention.rs | 262 +++++++++++++++++++++++- crates/mega-evm/src/evm/execution.rs | 18 +- 3 files changed, 270 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a05187646..1b856e568 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -270,6 +270,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 `BlockLimits::default()` detain. - **The enforcement point: the withheld part.** diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index fbd61051b..a6ac5f49f 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -32,6 +32,79 @@ struct DetainedFrame { 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 as detention kept them from a transaction's first frame on, before they +/// were kept only from the first read that sets a limit: debug builds keep them alongside and hold +/// the figures detention keeps to them. +#[cfg(debug_assertions)] +#[derive(Clone, Debug, Default)] +struct EagerFrames { + /// 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, +} + +#[cfg(debug_assertions)] +impl EagerFrames { + fn clear(&mut self) { + self.frames.clear(); + self.suspended = 0; + } + + fn on_frame_run(&mut self, gas_limit: u64, depth: usize) { + if self.frames.len() == depth { + let caller = depth.checked_sub(1); + let contribution = caller + .and_then(|i| self.frames.get(i)) + .map_or(0, |caller| caller.at_suspension.saturating_sub(gas_limit)); + if let Some(caller) = caller.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; + } + } + + 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); + } + } + + 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(); + } + + /// Asserts that the figures detention keeps, `frames` and `suspended`, are the eager ones: the + /// same entries, but for the running frame's regular gas spent at its last suspension, which + /// the eager form keeps stale until the frame suspends again and nothing reads before. + fn assert_kept(&self, frames: &[DetainedFrame], suspended: u64) { + assert_eq!(suspended, self.suspended, "the compute of the suspended frames"); + assert_eq!(frames.len(), self.frames.len(), "one entry per frame that runs"); + if let Some(((last, below), (eager_last, eager_below))) = + 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. /// @@ -85,6 +158,17 @@ struct DetainedFrame { /// 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: @@ -116,14 +200,26 @@ pub struct Detention { accessed: VolatileDataAccess, /// The most compute the transaction may reach, once it read volatile data. limit: Option, - /// The compute of the frames suspended on a child that runs. + /// The compute of the frames suspended on a child that runs, once a read set a limit. suspended: u64, /// 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, - /// One entry per frame that runs or is suspended, the running one last. + /// Once a read set a limit: one entry per frame that runs or is suspended, the running one + /// last. frames: Vec, + /// The depth of the frame that runs. + depth: usize, + /// While no read has set a limit: at each depth, the record of the frame there when revm last + /// built a child of it ([`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; the others are + /// stale, and are never read. Kept across transactions, for its allocation. + callers: Vec, + /// The frames' figures kept eagerly 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: EagerFrames, } impl Detention { @@ -153,6 +249,9 @@ impl Detention { self.burned = 0; self.left_at_halt = None; self.frames.clear(); + self.depth = 0; + #[cfg(debug_assertions)] + self.eager.clear(); } /// Starts every transaction with volatile-data access switched off from `depth` down, as if @@ -252,7 +351,8 @@ impl Detention { /// Commits the reads `observed` of the opcode the running frame completed, whose gas is `gas`: /// 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. + /// 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. @@ -267,6 +367,9 @@ impl Detention { if cap == u64::MAX { return; } + if self.limit.is_none() { + self.track(gas); + } let compute = self.compute(gas).saturating_sub(forwarded); let limit = self.lower_limit(compute.saturating_add(cap)); gas.limit_spendable(limit.saturating_sub(compute)); @@ -311,16 +414,22 @@ impl Detention { /// The frame at `depth`, whose gas is `gas`, is about to run: for the first time, or again /// after a child returned into it. /// - /// 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, and the switch is read for 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); + self.depth = depth; if !self.detains { return; } + #[cfg(debug_assertions)] + self.eager.on_frame_run(gas.limit(), depth); + if self.limit.is_none() { + return; + } 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)) { @@ -333,6 +442,8 @@ impl Detention { frame.contribution = 0; } debug_assert_eq!(self.frames.len(), depth + 1, "one entry per frame that runs"); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.frames, self.suspended); self.hold(gas); } @@ -340,7 +451,11 @@ impl Detention { /// still until the child returns. #[inline] pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) { - if !self.detains { + #[cfg(debug_assertions)] + if self.detains { + self.eager.on_frame_suspend(gas, depth); + } + if self.limit.is_none() { return; } if let Some(frame) = self.frames.get_mut(depth) { @@ -348,6 +463,63 @@ impl Detention { } } + /// 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, 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) { + let depth = self.depth; + debug_assert!(self.callers.len() >= depth, "every frame below the reading one recorded"); + self.frames.clear(); + self.suspended = 0; + for index in 0..depth { + let record = |index: usize| self.callers.get(index).copied().unwrap_or_default(); + let at_suspension = record(index).spent; + let child_limit = if index + 1 < depth { record(index + 1).limit } else { gas.limit() }; + let contribution = at_suspension.saturating_sub(child_limit); + self.suspended = self.suspended.saturating_add(contribution); + self.frames.push(DetainedFrame { at_suspension, contribution }); + } + self.frames.push(DetainedFrame::default()); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.frames, self.suspended); + } + /// 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 @@ -380,8 +552,14 @@ impl Detention { if !self.detains { return None; } - debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); - self.frames.pop(); + #[cfg(debug_assertions)] + self.eager.on_frame_end(depth); + if self.limit.is_some() { + debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); + self.frames.pop(); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.frames, self.suspended); + } if let Some(limit) = self.stop(gas) { return Some(ComputeStop { limit, used: self.compute(gas) }); } @@ -778,6 +956,7 @@ mod tests { #[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)); @@ -797,6 +976,68 @@ mod tests { assert_eq!(detention.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.frames.is_empty(), "nothing kept before a read"); + assert_eq!(detention.burned, 9_000); + + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 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.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.suspended, caller_adds); + assert_eq!(detention.compute(&child), compute + 600); + assert_eq!(child.spendable(), CAP - 600); + } + /// 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. @@ -956,6 +1197,7 @@ mod tests { 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); assert_eq!(detention.compute_limit(), Some(100_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 49bef9c02..7e64c46d4 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -415,7 +415,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm( } } +/// 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. /// From b317e584388ebd6266636d36f7ea4e77ccc49c54 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 13:11:34 -0700 Subject: [PATCH 278/458] perf(access): settle an answer inline while no read has set a limit --- crates/mega-evm/src/access/detention.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index a6ac5f49f..ba9878ec7 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -595,6 +595,10 @@ impl Detention { /// ([`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. + #[inline] pub(crate) fn on_answer( &mut self, result: &mut InterpreterResult, @@ -604,6 +608,24 @@ impl Detention { 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); From ac08f28a969f66afc70a57963906eec1ec45fc9a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 13:14:11 -0700 Subject: [PATCH 279/458] perf(access): read only the limit when a frame runs untracked --- crates/mega-evm/src/access/detention.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index ba9878ec7..2777140c5 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -422,14 +422,15 @@ impl Detention { pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) { self.refusing = self.disabled_from.is_some_and(|from| depth >= from); self.depth = depth; - if !self.detains { - return; - } #[cfg(debug_assertions)] - self.eager.on_frame_run(gas.limit(), depth); + 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"); 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)) { From 70a57fe038d0070bc14f0d6f9f685d29d3e8d7da Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 13:20:56 -0700 Subject: [PATCH 280/458] test(access): pin when callers are recorded, the reset and the eager check --- crates/mega-evm/src/access/detention.rs | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 2777140c5..588af4407 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -1061,6 +1061,67 @@ mod tests { 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); + 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); + 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.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, 0); + assert_eq!(detention.suspended, 3_000); + assert_eq!(detention.frames.len(), 2); + assert_eq!(detention.compute_limit(), Some(3_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); + } + + /// 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 = EagerFrames::default(); + eager.on_frame_run(1_000_000, 0); + eager.assert_kept(&[DetainedFrame::default()], 0); + eager.assert_kept(&[DetainedFrame::default()], 1); + } + /// 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. From 2ba369a0b3d711b09eb18285f1616f37d17bb1d8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:01:45 -0700 Subject: [PATCH 281/458] refactor(access): forget the callers a transaction recorded when the next one starts --- crates/mega-evm/src/access/detention.rs | 34 +++++++++++++++++-------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 588af4407..3ccad10b9 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -212,9 +212,8 @@ pub struct Detention { /// The depth of the frame that runs. depth: usize, /// While no read has set a limit: at each depth, the record of the frame there when revm last - /// built a child of it ([`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; the others are - /// stale, and are never read. Kept across transactions, for its allocation. + /// 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 eagerly 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. @@ -250,6 +249,7 @@ impl Detention { self.left_at_halt = None; self.frames.clear(); self.depth = 0; + self.callers.clear(); #[cfg(debug_assertions)] self.eager.clear(); } @@ -504,17 +504,16 @@ impl Detention { #[cold] #[inline(never)] fn track(&mut self, gas: &Gas) { - let depth = self.depth; - debug_assert!(self.callers.len() >= depth, "every frame below the reading one recorded"); + // 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[..self.depth]; self.frames.clear(); self.suspended = 0; - for index in 0..depth { - let record = |index: usize| self.callers.get(index).copied().unwrap_or_default(); - let at_suspension = record(index).spent; - let child_limit = if index + 1 < depth { record(index + 1).limit } else { gas.limit() }; - let contribution = at_suspension.saturating_sub(child_limit); + for (index, record) in records.iter().enumerate() { + let child_limit = records.get(index + 1).map_or(gas.limit(), |child| child.limit); + let contribution = record.spent.saturating_sub(child_limit); self.suspended = self.suspended.saturating_add(contribution); - self.frames.push(DetainedFrame { at_suspension, contribution }); + self.frames.push(DetainedFrame { at_suspension: record.spent, contribution }); } self.frames.push(DetainedFrame::default()); #[cfg(debug_assertions)] @@ -1111,6 +1110,19 @@ mod tests { 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] From 6f245221d40cda11307137979f335cfeda3b20c9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:04:36 -0700 Subject: [PATCH 282/458] refactor(access): keep detention's frame figures and their debug copy by one update body --- crates/mega-evm/src/access/detention.rs | 142 +++++++++++------------- 1 file changed, 65 insertions(+), 77 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 3ccad10b9..7ad15f45a 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -43,32 +43,31 @@ struct CallerRecord { limit: u64, } -/// The frames' figures as detention kept them from a transaction's first frame on, before they -/// were kept only from the first read that sets a limit: debug builds keep them alongside and hold -/// the figures detention keeps to them. -#[cfg(debug_assertions)] +/// 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 EagerFrames { +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, } -#[cfg(debug_assertions)] -impl EagerFrames { +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 caller = depth.checked_sub(1); - let contribution = caller - .and_then(|i| self.frames.get(i)) - .map_or(0, |caller| caller.at_suspension.saturating_sub(gas_limit)); - if let Some(caller) = caller.and_then(|i| self.frames.get_mut(i)) { + 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); @@ -77,27 +76,41 @@ impl EagerFrames { 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(); } - /// Asserts that the figures detention keeps, `frames` and `suspended`, are the eager ones: the - /// same entries, but for the running frame's regular gas spent at its last suspension, which - /// the eager form keeps stale until the frame suspends again and nothing reads before. - fn assert_kept(&self, frames: &[DetainedFrame], suspended: u64) { - assert_eq!(suspended, self.suspended, "the compute of the suspended frames"); - assert_eq!(frames.len(), self.frames.len(), "one entry per frame that runs"); + /// 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))) = - frames.split_last().zip(self.frames.split_last()) + 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"); @@ -200,25 +213,22 @@ pub struct Detention { accessed: VolatileDataAccess, /// The most compute the transaction may reach, once it read volatile data. limit: Option, - /// The compute of the frames suspended on a child that runs, once a read set a limit. - suspended: u64, /// 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, - /// Once a read set a limit: one entry per frame that runs or is suspended, the running one - /// last. - frames: Vec, + /// The frames' figures, once a read set a limit. + figures: FrameFigures, /// The depth of the frame that runs. depth: usize, /// 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 eagerly 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. + /// 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: EagerFrames, + eager: FrameFigures, } impl Detention { @@ -244,10 +254,9 @@ impl Detention { } self.accessed = VolatileDataAccess::empty(); self.limit = None; - self.suspended = 0; self.burned = 0; self.left_at_halt = None; - self.frames.clear(); + self.figures.clear(); self.depth = 0; self.callers.clear(); #[cfg(debug_assertions)] @@ -431,20 +440,9 @@ impl Detention { return; } debug_assert!(self.detains, "a limit on a transaction detention does not hold"); - 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"); + self.figures.on_frame_run(gas.limit(), depth); #[cfg(debug_assertions)] - self.eager.assert_kept(&self.frames, self.suspended); + self.eager.assert_kept(&self.figures); self.hold(gas); } @@ -459,9 +457,7 @@ impl Detention { if self.limit.is_none() { return; } - if let Some(frame) = self.frames.get_mut(depth) { - frame.at_suspension = regular_spent(gas); - } + self.figures.on_frame_suspend(gas, depth); } /// Whether revm building a frame's child is to be recorded ([`on_child_build`]): the @@ -507,17 +503,17 @@ impl Detention { // 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[..self.depth]; - self.frames.clear(); - self.suspended = 0; + let figures = &mut self.figures; + figures.clear(); for (index, record) in records.iter().enumerate() { let child_limit = records.get(index + 1).map_or(gas.limit(), |child| child.limit); let contribution = record.spent.saturating_sub(child_limit); - self.suspended = self.suspended.saturating_add(contribution); - self.frames.push(DetainedFrame { at_suspension: record.spent, contribution }); + figures.suspended = figures.suspended.saturating_add(contribution); + figures.frames.push(DetainedFrame { at_suspension: record.spent, contribution }); } - self.frames.push(DetainedFrame::default()); + figures.frames.push(DetainedFrame::default()); #[cfg(debug_assertions)] - self.eager.assert_kept(&self.frames, self.suspended); + self.eager.assert_kept(&self.figures); } /// Records a read of `access` the running frame, whose gas is `gas`, makes itself rather than @@ -555,10 +551,9 @@ impl Detention { #[cfg(debug_assertions)] self.eager.on_frame_end(depth); if self.limit.is_some() { - debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); - self.frames.pop(); + self.figures.on_frame_end(depth); #[cfg(debug_assertions)] - self.eager.assert_kept(&self.frames, self.suspended); + self.eager.assert_kept(&self.figures); } if let Some(limit) = self.stop(gas) { return Some(ComputeStop { limit, used: self.compute(gas) }); @@ -745,27 +740,18 @@ impl Detention { /// The transaction's compute while the running frame has `gas`. fn compute(&self, gas: &Gas) -> u64 { - self.suspended.saturating_add(regular_spent(gas)).saturating_sub(self.burned) + 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.suspended - .saturating_add(self.caller_contribution(depth, gas_limit)) + self.figures + .suspended + .saturating_add(self.figures.caller_contribution(depth, gas_limit)) .saturating_sub(self.burned) } - /// 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)) - } - /// 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)); @@ -995,7 +981,7 @@ mod tests { 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.suspended, 0); + 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 @@ -1038,13 +1024,13 @@ mod tests { let mut grandchild = gas(30_000, 0); detention.on_frame_run(&mut grandchild, 2); assert!(grandchild.record_regular_cost(500)); - assert!(detention.frames.is_empty(), "nothing kept before a read"); + assert!(detention.figures.frames.is_empty(), "nothing kept before a read"); assert_eq!(detention.burned, 9_000); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 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.suspended, caller_adds + child_adds); + 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)); @@ -1055,7 +1041,7 @@ mod tests { 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.suspended, caller_adds); + assert_eq!(detention.figures.suspended, caller_adds); assert_eq!(detention.compute(&child), compute + 600); assert_eq!(child.spendable(), CAP - 600); } @@ -1093,7 +1079,7 @@ mod tests { detention.on_frame_suspend(&caller, 0); let mut child = gas(500_000, 0); detention.on_frame_run(&mut child, 1); - assert_eq!(detention.suspended, 7_000); + 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); @@ -1105,8 +1091,8 @@ mod tests { let mut child = gas(500_000, 0); detention.on_frame_run(&mut child, 1); detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 0); - assert_eq!(detention.suspended, 3_000); - assert_eq!(detention.frames.len(), 2); + 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)); } @@ -1128,10 +1114,12 @@ mod tests { #[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 = EagerFrames::default(); + let mut eager = FrameFigures::default(); eager.on_frame_run(1_000_000, 0); - eager.assert_kept(&[DetainedFrame::default()], 0); - eager.assert_kept(&[DetainedFrame::default()], 1); + 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 From 86d049bc2200407452be88cff1b16392aca38860 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:07:15 -0700 Subject: [PATCH 283/458] refactor(access): take a read's depth from the frame that makes it rather than a field --- crates/mega-evm/src/access/detention.rs | 73 ++++++++++--------- crates/mega-evm/src/evm/instructions.rs | 2 +- .../mega-evm/src/system/keyless/dispatch.rs | 5 +- 3 files changed, 42 insertions(+), 38 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 7ad15f45a..4a4778f3d 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -219,8 +219,6 @@ pub struct Detention { left_at_halt: Option, /// The frames' figures, once a read set a limit. figures: FrameFigures, - /// The depth of the frame that runs. - depth: usize, /// 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. @@ -257,7 +255,6 @@ impl Detention { self.burned = 0; self.left_at_halt = None; self.figures.clear(); - self.depth = 0; self.callers.clear(); #[cfg(debug_assertions)] self.eager.clear(); @@ -358,10 +355,11 @@ impl Detention { self.observed.replace(VolatileDataAccess::empty()) } - /// Commits the reads `observed` of the opcode the running frame completed, whose gas is `gas`: - /// 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)). + /// 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. @@ -369,6 +367,7 @@ impl Detention { &mut self, observed: VolatileDataAccess, gas: &mut Gas, + depth: usize, forwarded: u64, ) { self.accessed |= observed; @@ -377,7 +376,7 @@ impl Detention { return; } if self.limit.is_none() { - self.track(gas); + self.track(gas, depth); } let compute = self.compute(gas).saturating_sub(forwarded); let limit = self.lower_limit(compute.saturating_add(cap)); @@ -430,7 +429,6 @@ impl Detention { #[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); - self.depth = depth; #[cfg(debug_assertions)] if self.detains { self.eager.on_frame_run(gas.limit(), depth); @@ -490,7 +488,7 @@ impl Detention { } /// Starts keeping the frames' figures at the first read that sets a limit, made by the frame - /// that runs, whose gas is `gas`. + /// 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 @@ -499,10 +497,10 @@ impl Detention { /// have been when each child first ran. #[cold] #[inline(never)] - fn track(&mut self, gas: &Gas) { + 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[..self.depth]; + let records = &self.callers[..depth]; let figures = &mut self.figures; figures.clear(); for (index, record) in records.iter().enumerate() { @@ -516,14 +514,19 @@ impl Detention { self.eager.assert_kept(&self.figures); } - /// 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 + /// 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) { + pub(crate) fn read_by_frame( + &mut self, + access: VolatileDataAccess, + gas: &mut Gas, + depth: usize, + ) { if self.detains { - self.commit_reads(access, gas, 0); + self.commit_reads(access, gas, depth, 0); } } @@ -848,7 +851,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); + 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); @@ -864,9 +867,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); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); assert!(frame.record_regular_cost(5_000)); - detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0); + 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); } @@ -878,7 +881,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); + 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); @@ -896,7 +899,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); + 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 { @@ -918,7 +921,7 @@ 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); + 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); @@ -941,7 +944,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); + 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(); @@ -952,7 +955,7 @@ 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); + 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(); @@ -1027,7 +1030,7 @@ mod tests { assert!(detention.figures.frames.is_empty(), "nothing kept before a read"); assert_eq!(detention.burned, 9_000); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 0); + 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); @@ -1058,7 +1061,7 @@ mod tests { 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); + 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); @@ -1073,7 +1076,7 @@ mod tests { 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); + 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); @@ -1090,7 +1093,7 @@ mod tests { 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, 0); + 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)); @@ -1161,7 +1164,7 @@ 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); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); assert!(caller.record_withheld_first_cost(90_000_000)); detention.on_frame_suspend(&caller, 0); @@ -1210,7 +1213,7 @@ 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); + 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(); @@ -1283,14 +1286,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); + 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); + free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0); assert_eq!((free.compute_limit(), free.accessed()), (None, VolatileDataAccess::empty())); } @@ -1424,11 +1427,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); + 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); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); assert_eq!(detention.compute_limit(), Some(5)); } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 591fa715b..70ef77887 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -495,7 +495,7 @@ fn settle_reads( } _ => 0, }; - host.detention.commit_reads(observed, &mut interpreter.gas, forwarded); + host.detention.commit_reads(observed, &mut interpreter.gas, interpreter.input.depth, forwarded); result } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 5e3aabf97..11d262d59 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -368,9 +368,10 @@ fn prepare( let signer_info = ctx.journal_mut().inspect_account(signer, checks_code)?.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. + // 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); + ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas, 0); } if signer_info.nonce > 1 { refuse!(KeylessDeployError::SignerNonceTooHigh { signer_nonce: signer_info.nonce }); From 4413e6439bf941ada25352adbf136905b5ee0c28 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:09:17 -0700 Subject: [PATCH 284/458] style(access): read the reading frame's gas limit once in the rebuild --- crates/mega-evm/src/access/detention.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 4a4778f3d..236aea862 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -501,10 +501,11 @@ impl Detention { // 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(gas.limit(), |child| child.limit); + 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 }); From c1231f66b72004fbcfc45bf8f1e23e42f596e930 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:42:34 -0700 Subject: [PATCH 285/458] chore(deps): pin op-revm at v20.0.0-mega.3, whose size-limited precompiles are priced The release prices op-revm's size-limited precompile wrappers through `Precompile::required_gas`: the wrapped run's price within the input size limit, and 0 above it, where the wrapper refuses the input before any gas check. It pins the revm fork at the tag the engine already uses, so `Cargo.lock` moves only op-revm's source. The Satin set dispatches four of the nine: the Karst BN254 pairing and the Jovian BLS12-381 G1 MSM, G2 MSM and pairing. Gas detention now decides a call to one of them from its price rather than running it on the allowance, so the tests that pinned an unpriced wrapper move to the priced behaviour: every Satin entry is priced, and a node's own precompile is what keeps the clamp. The pairing of three pairs and a stray byte is still the stop past the allowance, now answered without running. --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/mega-evm/src/evm/execution.rs | 18 ++++-- crates/mega-evm/src/evm/precompiles.rs | 34 ++++------- crates/mega-evm/tests/satin/withheld_gas.rs | 67 +++++++++++++-------- 5 files changed, 68 insertions(+), 55 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 99a1afbf3..d3b935006 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3186,7 +3186,7 @@ dependencies = [ [[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", diff --git a/Cargo.toml b/Cargo.toml index 55902f9b2..8f55f2d01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -250,4 +250,4 @@ revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3- [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/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7e64c46d4..bd25b13e3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1606,19 +1606,29 @@ mod tests { } /// 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 op-revm's wrapper of the BN254 pairing, a - /// Satin address a node replaced, and every precompile of a set that is not the Satin one. + /// 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 map = crate::satin_precompiles_map(); + 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(), pairing), + (&PricedPrecompiles::default(), own), (&replaced, KZG), (&foreign, KZG), (&foreign, pairing), diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 02adf7151..ef0322999 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -405,27 +405,14 @@ mod tests { assert_eq!(over.result, InstructionResult::PrecompileError); } - /// Every entry of the Satin set carries a price, but op-revm's size-limited wrappers, which - /// the op-revm fork builds without one: the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and - /// pairing. Gas detention runs a call to one of those on the allowance. + /// 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. #[test] - fn test_every_satin_entry_is_priced_but_op_revms_wrappers() { - let mut unpriced: std::vec::Vec<_> = satin_precompiles() - .inner() - .values() - .filter(|precompile| precompile.required_gas(&[]).is_none()) - .map(|precompile| precompile.id().clone()) - .collect(); - unpriced.sort_by_key(|id| id.name().to_owned()); - let mut wrappers = std::vec![ - PrecompileId::Bn254Pairing, - PrecompileId::Bls12G1Msm, - PrecompileId::Bls12G2Msm, - PrecompileId::Bls12Pairing, - ]; - wrappers.sort_by_key(|id| id.name().to_owned()); - assert_eq!(unpriced, wrappers); - assert!(satin_precompiles().len() > wrappers.len(), "the rest are priced"); + fn test_every_satin_entry_is_priced() { + for precompile in satin_precompiles().inner().values() { + assert!(precompile.required_gas(&[]).is_some(), "{:?} is priced", precompile.id()); + } } /// The KZG entry's price is its run's: below [`GAS_COST`](kzg_point_evaluation::GAS_COST) the @@ -462,7 +449,8 @@ mod tests { /// 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, and one of op-revm's wrappers, are never priced. + /// 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(); @@ -509,10 +497,10 @@ mod tests { 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. + // 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]), None); + 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/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 552cf3dc5..dec8175e3 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1211,54 +1211,65 @@ fn test_a_replaced_precompile_is_not_priced_from_the_built_in_set() { } } -/// op-revm's wrapper of the BN254 pairing carries no price, so it keeps the clamp: forwarded less -/// than its price and more than the allowance — three pairs, 147,000 gas, forwarded 120,000 under a -/// cap of 100,000 — it runs on the allowance and is the stop. The KZG entry, which carries its -/// price, forwarded less than it and more than the allowance — 100,000, forwarded 80,000 under a -/// cap of 50,000 — runs out of gas as without the read. +/// op-revm's wrapper of the BN254 pairing is priced, so a call forwarded less than its price and +/// more than the allowance — three pairs, 147,000 gas, forwarded 120,000 under a cap of 100,000 — +/// runs on its forward and runs out of gas as without the read, and its caller goes on, as the KZG +/// entry does — 100,000, forwarded 80,000 under a cap of 50,000. A node's own precompile, which the +/// engine cannot price, keeps the clamp: at the pairing's price and forward, it runs on the +/// allowance and is the stop. #[test] -fn test_an_unpriced_wrapper_keeps_the_clamp() { +fn test_a_nodes_own_precompile_keeps_the_clamp_a_priced_wrapper_does_not() { let pairing = vec![0_u8; 3 * 192]; + // EIP-1108: 45,000, and 34,000 a pair. + let price = 45_000 + 3 * 34_000; + let entry = mega_evm::satin_precompiles().get(&EC_PAIRING).unwrap(); + assert_eq!(entry.required_gas(&pairing), Some(price)); let kzg = vec![0_u8; 192]; let kzg_address = mega_evm::kzg_point_evaluation::ADDRESS; - assert_eq!( - mega_evm::satin_precompiles().get(&EC_PAIRING).unwrap().required_gas(&pairing), - None - ); + let own_input = U256::from(price).to_be_bytes::<32>(); + let limits = |cap| EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); for gas_limit in TIERS { let run = |first, to, forward, cap, input: &[u8]| { - let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); let db = MemoryDatabase::default() .account_code(CONTRACT, calls_precompile(first, to, Some(forward))); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits(cap))) .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(); assert_eq!(call.forward, u64::from(forward)); - assert!(call.precompile_ran, "{to}: revm runs it"); + assert!(call.precompile_ran, "{to}: revm runs it, on its forward"); run }; let detained = run(TIMESTAMP, EC_PAIRING, 120_000, 100_000, &pairing); let plain = run(PUSH0, EC_PAIRING, 120_000, 100_000, &pairing); - let allowance = 100_000 - charges_to_the_precompile(pairing.len(), Some(120_000)).total(); - assert_stopped(&detained, intrinsic_with(&pairing, gas_limit), allowance); - assert!(plain.outcome.result.is_success()); - assert_eq!(slot(&plain, 0), Some(U256::ZERO), "without the read the call fails"); + 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"); let detained = run(TIMESTAMP, kzg_address, 80_000, 50_000, &kzg); let plain = run(PUSH0, kzg_address, 80_000, 50_000, &kzg); 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"); + + let runs = Runs::default(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(TIMESTAMP, PRICED, Some(120_000))); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits(100_000))) + .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])); + let own = run_on(&mut evm, tx_with(&own_input, gas_limit)); + let allowance = 100_000 - charges_to_the_precompile(32, Some(120_000)).total(); + assert_stopped(&own, intrinsic_with(&own_input, gas_limit), allowance); + assert_eq!(*runs.lock().unwrap(), [(allowance, false)], "run on the allowance"); } } /// 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, which checks -/// the input's length after its gas. Under a cap of 100,000 it runs out of the allowance before the -/// length check, and the transaction stops; 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. +/// 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, and the transaction stops; 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]; @@ -1267,15 +1278,19 @@ fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowan 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)); - run_on(&mut evm, tx_with(&input, gas_limit)) + 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, plain) = (run(TIMESTAMP, 100_000), run(PUSH0, 100_000)); + 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(); assert_stopped(&detained, intrinsic_with(&input, gas_limit), allowance); + 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)); + 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"); } From c49eae6a02d02c4c15d2d589520d57ee3f9a564c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:45:07 -0700 Subject: [PATCH 286/458] test(access): hold each size-limited precompile of the Satin set from its price The Satin set dispatches four of op-revm's size-limited precompiles: the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and pairing. Their prices are pinned against the formulas of EIP-1108 and EIP-2537 up to each size limit, and at nothing past it, where the wrapper refuses the input before any gas check. Gas detention's decision is pinned for each of the four, at the unit level and through a transaction: within the allowance the call runs on its forward, as without the read; past the allowance and within the forward it is answered without running and stops the transaction; past the forward it runs on the forward and is a failed call its caller survives. An input past the size limit runs on its forward under any allowance. --- crates/mega-evm/src/evm/execution.rs | 72 ++++++++++++++- crates/mega-evm/src/evm/precompiles.rs | 63 +++++++++++++ crates/mega-evm/tests/satin/withheld_gas.rs | 99 +++++++++++++++++++++ 3 files changed, 233 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index bd25b13e3..329d60ac9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1544,9 +1544,22 @@ mod tests { 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, &[0; 32], forward); + 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)) } @@ -1587,6 +1600,63 @@ mod tests { 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] diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index ef0322999..f0f60234b 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -415,6 +415,69 @@ mod tests { } } + /// 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. diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index dec8175e3..e242b1152 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -71,6 +71,15 @@ 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) { @@ -1296,6 +1305,96 @@ fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowan } } +/// 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, and the transaction stops, 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}"); + assert_stopped(&detained, intrinsic_with(input, gas_limit), allowance); + 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 From b7d58ef6164dabfd475aa82daeeb41f67496c1b2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 14:46:32 -0700 Subject: [PATCH 287/458] docs: op-revm's size-limited precompiles are priced Every entry of the Satin set now carries a price, op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing included, so gas detention decides a call to one of them from its price. The precompile module, the detention module, AGENTS.md and the crate README no longer list the wrappers among the precompiles the engine cannot price, which are a node's own and an address a node replaced, and name the op-revm fork's prices among what detention builds on. --- AGENTS.md | 4 +++- crates/mega-evm/README.md | 5 +++-- crates/mega-evm/src/access/mod.rs | 15 ++++++++------- crates/mega-evm/src/evm/precompiles.rs | 19 +++++++++++-------- 4 files changed, 25 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1b856e568..2fc35d080 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,6 +84,7 @@ 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 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 @@ -291,7 +292,8 @@ Detention caps how much a transaction may still compute once it read such data ( 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 and op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing carry no price either. + 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index f99abc594..2ad60c6c9 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -8,7 +8,7 @@ The legacy engine (specs `Equivalence` through `Rex7`) 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`. @@ -149,7 +149,8 @@ That charge crossed the cap, and it is not made: the transaction is stopped with The stop reports that compute as what the transaction used. 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. -A precompile the engine cannot price — a node's own, an address a node replaced, op-revm's size-limited wrappers — is run on what the limit leaves its frame, and one it does not pay is the crossing, whatever its price. +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. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index f9310c202..8efc48b54 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -117,13 +117,14 @@ //! which burns its forward and which its caller survives. Running it to find out would compute //! past the limit. //! -//! A precompile the engine cannot price — a node's own, a Satin address a node replaced, one of -//! op-revm's size-limited wrappers, which carry no price — 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 its caller survives. -//! It also sees the allowance as its gas 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 its caller survives. 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 diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index f0f60234b..cc263a133 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -15,17 +15,19 @@ //! 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. 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: +//! 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; -//! - a call to an entry of the table built without a price function: op-revm's size-limited -//! wrappers of the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and pairing, until the op-revm -//! fork prices them; //! - 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. //! @@ -109,8 +111,9 @@ impl PricedPrecompiles { /// 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. An - /// entry of the table built without a price function answers `None`. + /// 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, From 55906ab4918e48097995ef3fa6ed90660812265b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 21:50:16 -0700 Subject: [PATCH 288/458] ci(mutants): raise the test-timeout floor for mutants tested in parallel on one runner --- .cargo/mutants.toml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 From 94cd9d7cfb571b8bcab0822a4c154623ad946476 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:10:15 -0700 Subject: [PATCH 289/458] test: derive nine cases from the byte prices instead of the spec's ordering Each assumed that a state byte costs about 1,530: a deposit dominating its creator's record history, a hundred fresh slots outweighing the detention cap, a canonical keyless transaction too short for its code. They now derive their bounds from the schedule, and hold at MEGA_SATIN_CPSB=312.5. --- crates/mega-evm/tests/satin/deposit_charge.rs | 20 +++- crates/mega-evm/tests/satin/detention.rs | 58 +++++++---- crates/mega-evm/tests/satin/withheld_gas.rs | 38 +++++--- crates/mega-evm/tests/system/keyless/rules.rs | 96 +++++++++++++++---- 4 files changed, 159 insertions(+), 53 deletions(-) diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index a2feac3bd..7ac2c2eef 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -46,14 +46,23 @@ const A: Address = address!("0000000000000000000000000000000000a00001"); const B: Address = address!("0000000000000000000000000000000000a00002"); /// The bytes the creation deploys. -const CODE_LEN: u16 = 1_024; +/// +/// Enough that the deposit, and not `B`, binds at any byte price. `B` keeps a sixty-fourth of what +/// it forwards, and below the execution cap it pays the history of the creation's two write +/// records, 80 bytes, out of it after the forward; the creation pays the history of every byte of +/// its code at the same price, and their state gas on top. More than 63 × 80 bytes of code outweigh +/// the records whatever the prices, where a kilobyte does only while a state byte is dear. +const CODE_LEN: u16 = 6 * 1_024; /// Below the execution cap: there is no reservoir, and every state charge is paid out of regular /// gas. -const BELOW_CAP: u64 = 10_000_000; +const BELOW_CAP: u64 = 100_000_000; /// Above the execution cap: the reservoir pays every state and history charge. const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; +/// The neutral configuration's gas limit: Osaka holds a transaction to 2^24 gas (EIP-7825). +const NEUTRAL_GAS_LIMIT: u64 = 10_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; @@ -135,7 +144,7 @@ fn evm( const fn gas_limit(setup: Setup) -> u64 { match setup { Setup::Satin(gas_limit) => gas_limit, - Setup::NeutralOsaka => BELOW_CAP, + Setup::NeutralOsaka => NEUTRAL_GAS_LIMIT, } } @@ -203,9 +212,10 @@ fn creation_end_under(setup: Setup, gas: u64, limits: EvmTxRuntimeLimits) -> Cre /// and the unlimited outcome one gas short of it. /// /// At the boundary the creation has no regular gas left after the deposit's last charge, so it is -/// exactly enough; one gas short the creation runs out of gas and deploys nothing. +/// exactly enough; one gas short the creation runs out of gas and deploys nothing. The search +/// starts from half the transaction's gas, which leaves `A` the other half for its own writes. fn boundary(setup: Setup) -> (u64, MegaTransactionOutcome) { - let (mut short, mut enough) = (0, 5_000_000); + let (mut short, mut enough) = (0, gas_limit(setup) / 2); assert!( !creation_end(setup, short).deposited && creation_end(setup, enough).deposited, "{setup:?}: the search brackets the boundary" diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 7b65d27c3..4c368ba76 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -18,14 +18,14 @@ use mega_evm::{ constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, 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, BlockLimits, EvmTxRuntimeLimits, LimitCheck, - LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, - MegaTransactionOutcome, VolatileDataAccess, + volatile_data_access_disabled_revert_data, write_record_history_gas, BlockLimits, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, VolatileDataAccess, }; use revm::{ bytecode::opcode::*, context::{result::ExecutionResult, BlockEnv, TxEnv}, - context_interface::block::BlobExcessGasAndPrice, + context_interface::{block::BlobExcessGasAndPrice, cfg::GasId}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult, Interpreter, }, @@ -46,6 +46,17 @@ pub(crate) const BELOW: u64 = 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 22,100. +pub(crate) const FRESH_WRITE: u64 = 3 + 3 + 22_100; + +/// 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; @@ -1086,10 +1097,11 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { } /// 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, a thousand fresh slots — 22,100,000 of compute — -/// cross it and stop the transaction, at the first write's charge past it. Without that room the -/// writes drain the withheld gas first and the frame runs out of its own gas where it would have -/// undetained: it halts. +/// reservoir for their state and history gas, a thousand fresh slots — 22,106,000 of compute — +/// cross it and stop 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 mut code = op(BytecodeBuilder::default(), TIMESTAMP); @@ -1098,20 +1110,26 @@ fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { } let code = code.stop().build(); + // A reservoir that pays every write's state gas and history. + let gas_limit = TX_GAS_LIMIT_CAP + 1_000 * fresh_write_spill(); let run = execute( MemoryDatabase::default().account_code(CONTRACT, code.clone()), - tx(CALLER, CONTRACT, ABOVE), + tx(CALLER, CONTRACT, gas_limit), ); let left = Charges::default().then(&[2]).fresh_writes(1_000).left(CAP); - assert_stopped(&run, intrinsic(ABOVE), left); + 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, BELOW), + 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(), BELOW, "a halt burns the gas"); + assert_eq!(run.outcome.result.gas().tx_gas_used(), gas_limit, "a halt burns the gas"); } /* ---------- what is not marked ---------- */ @@ -1515,12 +1533,17 @@ fn test_a_frames_return_hands_back_what_was_withheld() { } /// State and history gas are not compute, whether they come out of the reservoir or spill onto -/// regular gas: after the read, a frame writes more state gas than the cap and still completes. +/// 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() { - // 300 fresh slots: 29,376,000 of state gas and 1,056,000 of history, 6,630,000 of 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(); + 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..=300_u64 { + for slot in 1..=slots { code = code.sstore(U256::from(slot), U256::from(1)); } let code = code.stop().build(); @@ -1530,8 +1553,9 @@ fn test_state_and_history_gas_are_not_compute() { tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); - assert!(run.outcome.gas.state > CAP, "{}", run.outcome.gas.state); - assert!(run.outcome.gas.regular < CAP); + let gas = run.outcome.gas; + assert!(gas.state + gas.history >= slots * spill, "{gas:?}"); + assert!(gas.regular < CAP, "{gas:?}"); } } diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index e242b1152..52b8c9e7f 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -17,8 +17,8 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, - satin_gas_params, + constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + history_gas, satin_gas_params, system::{ keyless::{ decode_keyless_tx, @@ -39,6 +39,7 @@ use revm::{ transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, + context_interface::cfg::GasId, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, @@ -49,8 +50,9 @@ use revm::{ }; use crate::detention::{ - assert_stopped, burn, context, execute, intrinsic, memory_cost, op, run_on, spin, stop_data, - tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, + assert_stopped, burn, context, execute, fresh_write_spill, intrinsic, memory_cost, op, run_on, + spin, stop_data, tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, + CONTRACT, FRESH_WRITE, TIERS, }; /// A contract between the transaction's frame and `CHILD`. @@ -195,9 +197,10 @@ fn test_gas_answers_the_whole_regular_gas_after_a_read() { } /// 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. Below the -/// execution cap the callee runs out of gas on its third fresh slot, above it the reservoir pays -/// all three — each as without the read. +/// 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; 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() @@ -206,16 +209,17 @@ fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { .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"); for (gas_limit, status) in [(BELOW, 0), (ABOVE, 1)] { let (detained, plain) = with_and_without_read(|first| { let parent = - call_keeping_status(op(BytecodeBuilder::default(), first), CHILD, Some(150_000)); + 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 callee bounded to 150,000"); + assert_as_without_read(&detained, &plain, "a bounded callee"); assert_eq!(slot(&detained, 0), Some(U256::from(status)), "{gas_limit}"); } } @@ -271,20 +275,28 @@ fn test_an_out_of_gas_nothing_could_pay_halts_as_without_the_read() { } } -/// A creation whose code costs more state gas than the transaction has halts as without the read: -/// a failed state charge is never the cap. +/// 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); + assert!(gas_limit > 2 * CAP, "the transaction holds more than the cap: {gas_limit}"); let run = |first| { let initcode = op(BytecodeBuilder::default(), first) - .push_number(70_000_u32) + .push_number(len) .append_many([PUSH0, RETURN]) .build(); let create = OpTx(op_transaction(TxEnv { caller: CALLER, kind: TxKind::Create, data: initcode, - gas_limit: BELOW, + gas_limit, ..Default::default() })); run_on(&mut MegaEvm::new(context(MemoryDatabase::default())), create) diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 62f8e2d69..11520a871 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -13,6 +13,7 @@ use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ + active_satin_prices, alloy_consensus::TxEip1559, constants::{MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, system::keyless::{ @@ -100,21 +101,76 @@ fn test_keyless_deploy_gas_limit_too_low() { } /// An override equal to the signed gas limit passes rule 2, and the creation runs with exactly -/// that much. The canonical `CREATE2` factory was signed for a chain that charges no state gas -/// for deployed code: without a reservoir its 100,000 gas does not cover the code it deposits, -/// and the creation runs out of gas; above the execution cap the reservoir pays that state gas, -/// and the same gas limit deploys it. +/// 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 narrow = submit(system_db(), CREATE2_FACTORY_TX, 100_000, 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, 100_000, "the creation ran on the signed gas limit, and spent it"); - assert_eq!(nonce(&narrow, CREATE2_FACTORY_DEPLOYER), 1, "the nonce is spent all the same"); - - let wide = submit(system_db(), CREATE2_FACTORY_TX, 100_000, GAS_LIMITS[1]); - assert_eq!(returned(&wide).deployedAddress, CREATE2_FACTORY_CONTRACT); + 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 @@ -395,7 +451,8 @@ fn test_a_signer_at_nonce_one_stays_there_however_often_it_fails() { /// 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: without a reservoir, the signed gas limit does not cover the code either deposits. +/// 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), @@ -406,9 +463,10 @@ const CANONICAL: [(&[u8], u64, Address, Address); 2] = [ /// 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 CANONICAL { - fail_then_deploy(tx, signed, signer, address, GAS_LIMITS[0], deploying_at); + 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 @@ -478,9 +536,11 @@ fn fail_then_deploy( /// 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 CANONICAL { - let db = fail_then_deploy(tx, signed, signer, address, GAS_LIMITS[0], deploying_at); + 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)), From eb3497b120455a25f80d1a860e27c53969a33106 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:16:23 -0700 Subject: [PATCH 290/458] fix(inspector): settle a frame that kept nothing as one, whatever an inspector made of its result --- crates/mega-evm/src/evm/execution.rs | 18 +- crates/mega-evm/src/evm/inspector.rs | 106 ++++- crates/mega-evm/src/limit/frame_limit.rs | 63 ++- crates/mega-evm/src/limit/limit.rs | 29 +- .../tests/satin/inspector_settlement.rs | 365 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/stops.rs | 44 ++- 7 files changed, 580 insertions(+), 46 deletions(-) create mode 100644 crates/mega-evm/tests/satin/inspector_settlement.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 329d60ac9..db43be7ed 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -654,7 +654,7 @@ 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, and its - /// answer is held to the state-gas limit as revm's own is ([`hold_upfront_state_gas`]). + /// answer settles as a frame that never started ([`answered_without_running`]). /// /// A frame nothing may start — a latched transaction's, one past the call-stack limit — is /// answered by [`EvmTr::frame_init`], after the inspector's `frame_start`, as every frame @@ -676,7 +676,7 @@ where return answered_by_inspector(ctx, inspector, &frame_init, output) .map(ItemOrResult::Result); } - let frame_input = frame_init.frame_input.clone(); + let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); let logs_i = ctx.journal().logs().len(); if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { let (ctx, inspector) = self.ctx_inspector(); @@ -693,7 +693,7 @@ where } } } - frame_end_checked(ctx, inspector, &frame_input, &mut output); + frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, false); return Ok(ItemOrResult::Result(output)); } let (ctx, inspector, frame) = self.ctx_inspector_frame(); @@ -728,7 +728,7 @@ where 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); + frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, false); frame.set_finished(true); } next @@ -1063,8 +1063,11 @@ where /// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as /// [`EvmTr::frame_init`] settles an answer: an empty lane stands in for the frame, and the answer -/// is held to the compute limit ([`settle_answer`]) and to the state-gas limit -/// ([`hold_upfront_state_gas`]). Then the inspector is told the frame ended. +/// 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`]). That charge never stands, so it is not held to the +/// state-gas limit. fn answered_without_running( ctx: &mut MegaContext, inspector: &mut INSP, @@ -1077,8 +1080,7 @@ where 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); - hold_upfront_state_gas(ctx, Some(&mut output)); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output, frame_init.depth, true); output } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index b8e58f489..83484999a 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -31,17 +31,18 @@ use std::{format, string::String}; use revm::{ context::{ContextError, ContextTr, JournalTr}, + context_interface::{cfg::StateGasCharge, Host}, handler::FrameResult, inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, Interpreter, InterpreterTypes, }, - primitives::{Address, Log, U256}, + primitives::{Address, Bytes, Log, U256}, Database, Inspector, }; -use crate::{ExternalEnvTypes, MegaContext}; +use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; /// The message of the `EVMError::Custom` a refused creation revival fails the transaction with. /// @@ -328,16 +329,21 @@ 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`] — unless the transaction is latched, where the creation is put back -/// and reports the stop, which the latch writes over every result. +/// Hands a frame's end to the inspector, then settles what its rewrite does not change. /// -/// 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. The latch is read after the hooks that can -/// set it — the frame's run, detention's classification of its end, the hold on a start's upfront -/// state gas, and the answer before building — have run, so a creation the latch stopped is never +/// - **The refusal.** A creation that failed, rewritten into a success, is put back and fails the +/// transaction with [`FORBIDDEN_CREATE_REVIVAL`] — unless the transaction is latched, where the +/// creation is put back and reports the stop, which the latch writes over every result. +/// - **A frame that kept nothing.** A frame the inspector answered in place of running +/// (`answered`), 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`]). +/// +/// 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. A frame the inspector answered with a +/// success itself is no revival: nothing failed. The latch is read after the hooks that can set +/// it — the frame's run, detention's classification of its end, the hold on a start's upfront state +/// gas, and the answer before building — have run, so a creation the latch stopped is never /// refused. #[inline] pub(crate) fn frame_end_checked( @@ -345,6 +351,8 @@ pub(crate) fn frame_end_checked( inspector: &mut INSP, frame_input: &FrameInput, frame_result: &mut FrameResult, + depth: usize, + answered: bool, ) where DB: Database, ExtEnvs: ExternalEnvTypes, @@ -354,6 +362,82 @@ pub(crate) fn frame_end_checked( let before = frame_result.instruction_result(); frame_end(context, inspector, frame_input, frame_result); refuse_create_revival(context, before, frame_result); + if answered || !before.is_ok() { + settle_kept_nothing(context, frame_input, frame_result, depth); + } +} + +/// 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 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. +/// +/// A latched transaction is left to the latch, which writes the stop over every result, and the +/// stop settles as a revert. +fn settle_kept_nothing( + context: &mut MegaContext, + input: &FrameInput, + result: &mut FrameResult, + depth: usize, +) { + carry_upfront_flags(input, result); + if !result.instruction_result().is_ok() || context.additional_limit.latched().is_some() { + 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.rollback_state_gas(); + gas.set_refunded(0); + gas.refill_reservoir(upfront.unwrap_or_default()); + gas.refill_history(history); + context.additional_limit.discard_returning_lane(); +} + +/// 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 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() } /// Puts a revived creation back to `before` and, unless the transaction is latched, records the diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 91af59e2f..00e9c83b6 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -115,8 +115,10 @@ impl Lane { /// 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 only an - /// inspector's rewrite of the frame's stop into a success returns. + /// ([`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. @@ -302,6 +304,18 @@ impl FrameLimitTracker { lane.records_made = false; } + /// 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. + pub(crate) fn discard_running_lane(&mut self) { + let Some(lane) = self.pop(false) else { return }; + self.lanes.push(Lane::empty(lane.history_refund(false))); + } + /// 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. @@ -623,6 +637,51 @@ mod tests { 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, UNLIMITED, 0)); + t.record(bytes(10)); + t.push(Lane::new(None, false, bytes(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, UNLIMITED); + 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, UNLIMITED, 0)); + t.record_caller(true, 4); + t.discard_running_lane(); + assert_eq!(t.net(), bytes(10).saturating_add(WRITE_RECORD)); + assert_eq!(t.pop(true).unwrap().history_refund(true), 0); + + // With no lane to discard, nothing happens. + let mut empty = FrameLimitTracker::default(); + empty.discard_running_lane(); + assert_eq!(empty.depth(), 0); + } + /// A creation that fails before bumping the nonce takes the creator record back. #[test] fn test_drop_caller_record_rearms_the_caller() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 61f1be1b4..d5adb1310 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -834,6 +834,17 @@ impl AdditionalLimit { 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. /// @@ -851,17 +862,19 @@ impl AdditionalLimit { /// whatever produced it (an interceptor, an inspector's rewrite), so neither a success nor a /// halt passes it. /// - /// Two returns 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)): its own frame-local revert for its budget, + /// 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)): its own frame-local revert for its budget, /// the latch for 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 hands the caller more than the share it gave. Only - /// an inspector that rewrote the frame's stop into a success returns one. + /// - 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 @@ -1219,9 +1232,9 @@ mod tests { (limit, child) } - /// A success is checked on its return only when it kept more than its own budget, which an - /// inspector that rewrote the frame's stop into a success returns. Within its budget it hands - /// the caller no more than the caller's share, and the caller runs on unchecked; past it, the + /// 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() { 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..3e0c5ccb0 --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -0,0 +1,365 @@ +//! What a frame that kept nothing settles into its caller, whatever an inspector made of its +//! result. +//! +//! 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. 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, STOP}, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + InstructionResult, InterpreterResult, InterpreterTypes, + }, + Inspector, +}; + +use crate::salt::{ + create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, + SaltEnvs, 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: the frame never starts. An answered creation reports `address`. +struct Answers { + target: Address, + result: InstructionResult, + address: Option

, +} + +impl Answers { + const fn call(target: Address, result: InstructionResult) -> Self { + Self { target, result, address: None } + } + + const fn creation(result: InstructionResult, address: Option
) -> 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(|| { + CallOutcome::new( + InterpreterResult::new(self.result, Bytes::new(), untouched_call_gas(inputs)), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + (self.target == Address::ZERO).then(|| { + CreateOutcome::new( + InterpreterResult::new(self.result, Bytes::new(), untouched_create_gas(inputs)), + 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") +} + +/// 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. +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.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!(kept.gas.state > 0, "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 = + inspected(db(caller()), envs(), tx.clone(), 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 = + 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"); + } + } +} + +/// 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 = + inspected(db(caller()), envs(), tx.clone(), 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"); + } +} + +/// 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, so it never stands against the state-gas +/// limit. The caller then fills a slot, and a limit one gas short of the slot and the account +/// together stops the caller whose call ran, and not the one whose call was answered. +#[test] +fn test_an_answered_call_holds_nothing_against_the_state_gas_limit() { + 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 limit = slot + entry(GasId::new_account_state_gas()) - 1; + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit); + let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); + let context = || salt_context(db(caller()), minimal_envs()).with_tx_runtime_limits(limits); + + let ran = MegaEvm::new(context()).execute_transaction(tx.clone()).unwrap(); + assert!(ran.limit_exceeded.is_some(), "the account and the slot cross: {:?}", ran.result); + + let answered = MegaEvm::new(context()) + .with_inspector(Answers::call(EMPTY, InstructionResult::Stop)) + .execute_transaction(tx) + .unwrap(); + assert_eq!(answered.limit_exceeded, None, "{:?}", answered.result); + assert!(answered.result.is_success(), "{:?}", answered.result); + assert_eq!(answered.gas.state, slot, "the slot alone"); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 275be6067..3f7af0348 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,7 @@ mod history_exemption; mod history_gas; mod history_reservoir; mod inspector; +mod inspector_settlement; mod intrinsic; mod kv_limit; mod limit_exemption; diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 38a505891..d0c3cfb99 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1389,17 +1389,17 @@ fn test_data_size_top_level_exceed_is_frame_local_revert() { } /// A call its own frame budget stopped, revived into a success by an inspector, hands its caller -/// everything it counted: more than the share the caller gave it. The caller is held to its own -/// budget with it and returns its stop before it runs another instruction, as a creator a failed -/// creation's nonce record puts over its budget does. +/// 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 its own budget, +/// and the transaction is the one no inspector runs: the rewrite changed only the flag `A` drops. /// /// `A` has a frame cap of 1,000 bytes and gives `B` 98% of it. `B`'s log of 1,000 bytes counts -/// 1,032, which crosses `B`'s budget and, handed to `A`, `A`'s. +/// 1,032, which crosses `B`'s budget, and would cross `A`'s were it handed on. #[test] -fn test_a_call_revived_past_its_budget_stops_its_caller_before_it_runs_on() { +fn test_a_call_revived_past_its_budget_hands_its_caller_nothing() { const FRAME_CAP: u64 = 1_000; const LOGGED: u64 = 1_000; - const { assert!(LOG_BASE_SIZE + LOGGED > FRAME_CAP, "the log crosses A's budget too") }; + const { assert!(LOG_BASE_SIZE + LOGGED > FRAME_CAP, "the log would cross A's budget too") }; let share = FRAME_CAP * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; let a = call_all(BytecodeBuilder::default(), B) .append(POP) @@ -1410,26 +1410,36 @@ fn test_a_call_revived_past_its_budget_stops_its_caller_before_it_runs_on() { BytecodeBuilder::default().push_number(LOGGED).append_many([PUSH0, LOG0]).stop().build(); let db = MemoryDatabase::default().account_code(A, a).account_code(B, b); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(FRAME_CAP); + let plain = execute(db.clone(), limits, BELOW); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) .with_inspector(Rewriter::default()); let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW)).unwrap(); let rewriter = evm.inspector(); - let stop = |limit| { - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used: 0, frame_local: true } - .revert_data() - }; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: share, + used: 0, + frame_local: true, + } + .revert_data(); assert_eq!( rewriter.ended, - vec![ - (B, InstructionResult::Revert, stop(share)), - (A, InstructionResult::Revert, stop(FRAME_CAP)) - ], - "B crossed its budget, and A its own with what B handed it" + vec![(B, InstructionResult::Revert, stop), (A, InstructionResult::Stop, Bytes::new())], + "B crossed its budget; A did not" ); - assert_eq!(rewriter.marker_writes, 0, "A ran no instruction after its call returned"); - assert!(outcome.result.is_success(), "the inspector rewrote A too: {:?}", outcome.result); + assert_eq!(rewriter.marker_writes, 1, "A ran on after its call returned"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + "the body and A's marker: none of B's log" + ); + assert!(outcome.result.logs().is_empty(), "B's log was reverted with B"); + assert!(plain.result.is_success(), "{:?}", plain.result); + assert_eq!((&outcome.result, &outcome.state), (&plain.result, &plain.state)); + assert_eq!((outcome.gas, outcome.usage), (plain.gas, plain.usage)); } /* ---------- a frame three calls down, answered without running ---------- */ From 0eebe0abcf48a2eb4a756959d1e5021dfc56ac53 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:33 -0700 Subject: [PATCH 291/458] docs: draft the Satin upgrade page --- docs/spec/upgrades/satin.md | 795 ++++++++++++++++++++++++++++++++++++ 1 file changed, 795 insertions(+) create mode 100644 docs/spec/upgrades/satin.md diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md new file mode 100644 index 000000000..997562e60 --- /dev/null +++ b/docs/spec/upgrades/satin.md @@ -0,0 +1,795 @@ +--- +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, per-transaction limits that stop a transaction 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, and block limits as packing budgets. +--- + +# Satin Network Upgrade + +This page is an informative summary of the Satin specification. +For the full normative definition, see the Satin spec in the mega-evm repository. + +{% 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 KV updates, measure state growth in state gas, and drop the separate compute-gas limit: compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md). +Every transaction-level limit — data size, KV updates, state gas, and detention's compute limit — now stops a transaction with a revert carrying `MegaLimitExceeded(kind, limit)` instead of a halt, and the sender 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 every block-level execution limit a packing budget that never refuses a deposit. + +Satin follows Rex7 on the spec ladder. +Rex7 changes no behavior of [Rex6](rex6.md), 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 and EIP-2780 intrinsic cost, with the EIP-8038 repricing left at Osaka's values. +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 and KV updates over a byte table and write records, state growth as a state-gas limit, and no compute-gas limit. +11. **The revert-class stop.** Every transaction-level limit stops the transaction with a revert. +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.** + +## 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 and the node's per-transaction gas-limit policy. +- 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 as the node supplies it, and zero for a block that carries none. +- The Karst block rules apply to MegaETH blocks: + - A block in which Satin activates, or in which an Optimism fork from Jovian onward activates, MUST contain only deposit transactions; a non-deposit transaction in it makes the block invalid. + - 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. + +### 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. +KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 gas fails with `OutOfGas`, and a successful call is charged exactly 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 check their operands, the static context and the initcode size in the inherited order: Satin charges nothing ahead of those checks. + +### 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, a limit that 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. +- **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 towards its execution-gas limit 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 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`). + +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-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 three changes: + +- the seventeen regular-gas entries below, which Amsterdam repriced for [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) (four of them because EIP-8037 moved the cost of creating state onto the state dimension), MUST keep their Osaka values; +- 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, including 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. + +Regular-gas entries that keep their Osaka value: + +| Entry | Satin | +| ---------------------------------------------- | ------ | +| Warm storage read | 100 | +| Cold account access, additional | 2,500 | +| Cold storage access, additional | 2,000 | +| Cold `SLOAD` | 2,100 | +| Value transfer of a call | 9,000 | +| New account of a call | 25,000 | +| New account of `SELFDESTRUCT` | 25,000 | +| `SSTORE` static cost | 100 | +| `SSTORE` of a fresh slot, before the load cost | 19,900 | +| `SSTORE` reset, before the cold load | 2,800 | +| `SSTORE` refund of a restored fresh slot | 19,900 | +| `SSTORE` refund of a restored reset | 2,800 | +| `SSTORE` refund of a cleared slot | 4,800 | +| `CREATE` and `CREATE2` | 32,000 | +| Creation transaction (unused under EIP-2780) | 32,000 | +| Access-list address | 2,400 | +| Access-list storage key | 1,900 | + +Entries that differ from Osaka: + +| Entry | Osaka | Satin | +| --------------------------------------------- | ------ | ------- | +| 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 | + +Under EIP-2780 the floor's base is the transaction's own decomposed intrinsic base (below), not the 12,000 entry. + +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 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. + +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, access-list addresses and the block beneficiary — as warm, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) has it: Rex6's cold charge on the first `CALL`-family touch of such an address does not apply. + +### 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, MUST fail the transaction; it MUST NOT be priced at any multiplier. +- 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)). + +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 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. +- 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 it does not count against the execution cap. + 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. +- 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 `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. +- 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. +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 is zero too. + +The EIP-7623 floor is still computed and validated. +At these prices it never raises a receipt's gas used, because the history gas of the same bytes is higher; it does bind the figure a block counts towards its execution-gas limit, `max(regular, floor)` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +### 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 counted at runtime. +- A transaction crossing a limit halts; a frame crossing its budget reverts alone. + +#### New behavior + +Three dimensions are limited per transaction; compute is not one of them (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +| Dimension | Counted in | Transaction limit | Frame budget | +| ---------- | ---------------------------------------- | ---------------------------------------------------------- | ------------ | +| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 unless the chain sets another | Yes | +| KV updates | Write records | Unlimited unless the chain sets one | Yes | +| State gas | EIP-8037 state gas the transaction holds | Unlimited unless the chain sets one | No | + +- **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. + A deposit's data size is counted like any transaction's. +- **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 own account and the four fee accounts are part of the body and MUST NOT be counted as records; a frame running as the sender records nothing for the sender's account. + Records MUST be deduplicated per frame: a frame records an account once. + 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. +- **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_SHARE_NUMERATOR / FRAME_SHARE_DENOMINATOR` = 98/100 of what its parent has left, rounded down, in each of data size and write records, under an optional per-frame cap. + A frame that crosses its budget MUST revert with `MegaLimitExceeded(kind, budget)` and its caller continues. +- **State gas** is the net EIP-8037 state gas the transaction holds: what it was charged before the first frame, plus what every frame on the call stack holds, net of refills and of failed frames. + It MUST be checked wherever state gas is charged, after the charge: a charge the frame cannot pay is an out-of-gas whatever the limit. + The sites are the applied authorities and the account a deposit-like transaction creates for its caller, before the first frame (the authorities are taken back on a crossing), the first frame's recipient or created account, a fresh slot, a `SELFDESTRUCT`'s new beneficiary, a new account a `CALL`, `CREATE` or `CREATE2` adds (held once the frame is decided: a frame refused on its caller's account gives the charge back and is not held for it), and deployed code (at the deposit, before the creation commits). + Because it is a limit on gas, a slot or an account in a bucket `m` times the minimum reaches it `m` times sooner. +- **Order at one site.** + Where the state gas and a count cross at the same site, the state gas is the dimension reported; between the counts, data size is checked before write records, and a transaction limit before a frame budget. + A frame start is the exception: its records and transfer log are held before the frame is built, and the state gas its opcode charged upfront for the account it adds only once the frame is decided; a start the records stop adds no account, so its upfront state gas is given back rather than held, and the data-size or KV stop is the one reported. +- **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 per-transaction limits and the per-frame caps are execution parameters the node supplies with each block, and every node executing a chain MUST use the same values; the values above apply when none is set. + The 98/100 share is not a parameter. + At the default data-size limit a transaction keeps fewer than 327,680 write records (13,107,200 / 40), so a KV limit binds only below that. + +### 11. The Revert-Class Stop + +#### Previous behavior + +- A transaction crossing a runtime transaction-level limit halts: it produces a failed receipt, its remaining gas is preserved and refunded to the sender, and it is included in the block. +- A frame crossing its budget reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` and its parent continues. + +#### New behavior + +Every transaction-level limit — data size, KV updates, state gas, and gas detention's compute limit — MUST stop the transaction with a revert, never a halt: + +1. The frame that crosses the limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. +2. From then on no frame runs another instruction: a caller receiving that result MUST return the same revert instead of resuming, a frame about to start MUST be answered with it, and every result returned upward MUST be rewritten to it, whatever produced the result. +3. The transaction MUST settle like an EIP-8037 revert: it keeps none of its writes or logs; the sender pays the intrinsic gas, the body's history gas and what ran; the unspent regular gas and the reservoir return to the sender. +4. The transaction is included with a failed receipt, and its usage counts towards the block's counters. + +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. + The one exception is the state gas the calling opcode charges upfront for the account the frame adds: it is held once the frame is decided, so a frame built by then returns the stop before its first instruction, a frame answered without running is rewritten to the stop, and what the start moved is reverted with the frames the stop reverts. +- A body over the data-size limit MUST stop the transaction before it runs: no authorization is applied, no record made outside a frame is charged, the first frame's start is charged nothing, and the first frame is answered with the stop. +- EIP-7702 authorities whose state gas or records would cross a limit MUST be taken back before the first frame. + +A frame budget MUST revert its frame alone, with the same revert data, and its caller continues. +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 | +| 1 | KV updates | The limit or frame budget crossed, in write records | +| 2 | Compute (gas detention) | The compute the transaction may reach: its compute at the binding read plus the cap, in gas | +| 3 | State growth | The transaction's state-gas limit, in gas | + +The discriminants are Rex6's, so a decoder of the Rex6 revert data decodes Satin's. +Kind 3 changes unit: Rex6 reported it in new accounts and slots, Satin in state gas. +A contract can revert with the same bytes, so the revert data alone does not identify a stop. + +### 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. +- **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 execution parameters the node supplies with each block, 20,000,000 each when none is set. +- **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`), 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 refund at the end of the transaction. + 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 transaction MUST be stopped with `MegaLimitExceeded(2, limit)` (see [The Revert-Class Stop](#11-the-revert-class-stop)). + The transaction is billed what it spent before that charge, less than one charge short of the limit, and the sender gets back everything the frames had, the withheld part included. + 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. + A precompile the node adds or replaces has no price: it MUST run on the allowance, and running out of it is the crossing. +- **Interceptor answers.** + A system contract's intercepted answer that spent more regular gas than the frame's allowance MUST be the crossing. +- **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)). + +### 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. +- 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. +- 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. +- 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). + +### 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. +- A `SELFDESTRUCT` to itself of an account created in the same transaction burns the balance without a log. +- 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. + +### 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 nothing; 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. +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 | `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: 32,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 the legacy engine's order, so a call several rules refuse reports the Rex6 error. +- The deploy-address read of step 12 MUST NOT warm the deploy address and MUST NOT load its code. +- A signer that is the block beneficiary MUST be detained as a read of the beneficiary's account. +- 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 succeeded 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 also for a constructor that destroyed its own account. + `gasUsed` MUST be what the creation spent from both pools, before refunds, with no intrinsic gas. +- **Limits.** + A frame budget the creation crosses reverts the creation, and the call answers `ExecutionReverted` with the stop's revert data. + A transaction-level limit stops the transaction: the call 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 its own frame budget, the call reverts with that stop and the deployment, the nonce included, is taken back without stopping the transaction. +- Of the contract's errors, `ParentBudgetExceeded(uint8,uint64,uint64)`, `InvalidTransaction()`, `InsufficientComputeGas(uint64,uint64)` and `InternalError()` MUST NOT be produced: a failed database read or SALT lookup fails the transaction with its cause. + `AddressMismatch()` and `NoContractCreated()` remain as answers to a creation reported at another address or at none, which no deployment reaches. +- The `KeylessDeploy` contract, its interface and its errors are unchanged. + +### 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. +- 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 `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. +- 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 hint that would cross the transaction's data-size limit is not forwarded, and the limit stops the transaction. + +### 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. + +#### New behavior + +- A transaction MUST be tested for the system shape on its own fields first: type `0x0`, a call (not a creation) to an address on `MEGA_SYSTEM_TX_WHITELIST` (the Oracle). +- Only a transaction with that shape MUST read the registry: when the registry holds the code this spec deploys, the node reads `_currentSystemAddress` from the transaction's own state, cold, without the registry's code, and compares it with the caller. + The registry account (without code) and that slot are part of the transaction's state and witness, not the pre-block witness. +- A registry that is absent, holds other code, or names the zero address MUST make no transaction a Mega System Transaction. +- A transaction of any other shape reads nothing and is never a Mega System Transaction, whoever sent it. + A transaction from the system address without the shape is an ordinary transaction, validated and charged as a user's. + The Oracle authorizes writes on the sender alone, so such a transaction to the Oracle succeeds as a user transaction: it pays fees, is held to every per-transaction limit, is detained, is priced by bucket, and pays history gas. +- A Mega System Transaction is validated (chain id, nonce, EIP-3607) and promoted to a deposit exactly as in Rex6. +- Because a role change can only be scheduled for a later block 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. + +### 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. + +#### 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. +- **The pre-block sequence.** + Before its transactions, a block MUST, in order: + 1. make the EIP-2935 call; + 2. make the EIP-4788 call (neither call runs in the genesis block, and a block without a parent beacon block root is invalid, as EIP-2935 and EIP-4788 define); + 3. deploy 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` with nonce 1; + 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`. +- **Deploys.** + Each deploy is idempotent: an address already holding the expected code is only read (its nonce kept). + An absent account, or one with empty code and nonce 0, MUST get the code, nonce 1 and the registry's seed slots; it keeps any balance it has, and any storage it had is cleared. + There is one version of each contract (the Oracle and the SequencerRegistry at version 2.0.0): an address holding other code, an address with empty code and a non-zero nonce, and a factory with the expected code and nonce 0 MUST make the block invalid. +- **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 a deploy or in the due-change read is always an internal error. + +### 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 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, but a user's deposit is not system-originated: it is held to every per-transaction limit, detained, and priced by bucket. + +### 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. +Four of those counts can be limited: + +| Block limit | Counted | Checked | Default | +| ------------- | ------------------------------------- | -------------------------------- | ---------------- | +| Execution gas | `max(regular, floor)` per transaction | Before the next transaction runs | Unlimited | +| State gas | State gas per transaction | After the next transaction runs | Unlimited | +| Data size | Data-size bytes per transaction | Before the next transaction runs | 13,107,200 bytes | +| KV updates | Write records per transaction | Before the next transaction runs | Unlimited | + +- These are packing budgets: the transaction that reaches a limit MUST be included, and later transactions MUST be skipped — for state gas, only a later transaction that adds state gas. +- A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by any of the four, and MUST count towards all four. + A Mega System Transaction is a legacy transaction in the block, so at block level it is held to these budgets and to the data-availability limits like any non-deposit transaction. +- History gas has no block limit; the block's history bytes are reported, not limited. +- The pre-execution limits are unchanged in kind: the block gas limit (a transaction's declared gas limit must fit in what the block has left), the per-transaction gas limit, the encoded size, and the data-availability size, from which deposits are exempt. +- The limits are execution parameters the node supplies with each block; every node executing a chain MUST use the same values. + +### 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. + +#### New behavior + +A transaction MUST be rejected before inclusion when: + +- 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 a Mega System Transaction that fails the chain-id, nonce or EIP-3607 check; +- it fails any inherited validation. + +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; +- it does not fit the block's encoded-size or data-availability budget; +- its data-availability footprint does not fit in what the block's gas limit has left for footprints; +- the block has reached its execution-gas, data-size or KV budget; +- the block has reached its state-gas budget and the transaction adds state gas; +- it is not a deposit and the block activates Satin or an Optimism fork from Jovian onward. + +A block that contains a transaction it should have skipped is invalid. + +A transaction exceeding a per-transaction encoded-size, data-availability or gas-limit policy MUST be rejected permanently. + +A transaction MUST be included with a failed receipt when it reverts, halts, or is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). +A failed bucket-capacity read or database read MUST fail the transaction with its cause rather than settle it at any price. + +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)); +- a system-contract address holds foreign code or has empty code and a used nonce, or the factory's address holds the factory's code at nonce 0; +- it contains a transaction the rules above skip. + +## 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` 165,826 (97,920 of it state gas), a `LOG1` with 32 bytes of data 51,746, and a value `CALL` that creates its recipient 267,241 (183,600 of it state gas). +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 transaction stopped by a resource limit or by gas detention now reverts rather than halting, with `MegaLimitExceeded(kind, limit)` as its output, and its sender pays only for what ran. +Kind 3 now reports the state-gas limit in gas. +A transaction that reads volatile data is still stopped at its compute at the read plus 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. +`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 failed attempts by anyone cannot make its address undeployable; only a delegated signer whose own code spends a nonce during the creation moves past it. + +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. + +## 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; the Satin deploy step refuses, rather than upgrades, any other code at their addresses. +A system-address transaction without the system shape is now executed as a user transaction instead of being refused; only the holder of the system key can send one. + +The per-transaction and block limits and the detention caps are execution parameters the node supplies with each block: unless set, the KV-update and state-gas limits and the block's execution-gas limit are unlimited, the data-size limits are 13,107,200 bytes, and the detention caps are 20,000,000 each. +Every node executing a chain must use the same values. + +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-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. From 23d565e4efc1c46ff37a85d3c09d3279049d7e07 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:45 -0700 Subject: [PATCH 292/458] docs: state Rex6's fee-reward accounting correctly on the Satin page --- docs/spec/upgrades/satin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 997562e60..f37c4404e 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -358,7 +358,7 @@ At these prices it never raises a receipt's gas used, because the history gas of - 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 counted at runtime. +- 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 transaction crossing a limit halts; a frame crossing its budget reverts alone. #### New behavior From 182248324bde53576c3ee6ae22bc4a235f3e5e70 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:45 -0700 Subject: [PATCH 293/458] docs: add the Satin terms and rung to the glossary --- docs/spec/glossary.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 226a02b9b..c1735cd01 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. @@ -163,7 +198,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 → REX7 → SATIN`. +`REX7` and `SATIN` are unstable. `MINI_REX_1` and `MINI_REX_2` are [alias rungs](#alias-spec) executing `EQUIVALENCE` and `MINI_REX` behavior respectively. ## Alias Spec From 5643c054c957ed71a5a511f81bbb52eb59dcb3b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:46 -0700 Subject: [PATCH 294/458] docs: list Satin on the spec ladder --- docs/spec/SUMMARY.md | 1 + docs/spec/hardfork-spec.md | 27 +++++++++++++++++++++++---- docs/spec/overview.md | 12 +++++++++++- docs/spec/upgrades/overview.md | 16 +++++++++++++++- 4 files changed, 50 insertions(+), 6 deletions(-) diff --git a/docs/spec/SUMMARY.md b/docs/spec/SUMMARY.md index 69e615e9d..9cf174441 100644 --- a/docs/spec/SUMMARY.md +++ b/docs/spec/SUMMARY.md @@ -40,6 +40,7 @@ - [Rex5](upgrades/rex5.md) - [Rex6](upgrades/rex6.md) - [Rex7](upgrades/rex7.md) +- [Satin](upgrades/satin.md) ## Reference diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index 1fbd9623e..df9f8b808 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 → REX7 → SATIN ``` Each newer behavior-introducing spec includes all previous behaviors. 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 REX7 builds on Optimism Isthmus (Ethereum Prague) as the base layer; SATIN builds on Optimism Karst (Ethereum Osaka). +All specs through REX6 are frozen; REX7 and SATIN are **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. +REX7 and SATIN are unstable and have no activation timestamp on either mainnet or testnet. ### Backward Compatibility @@ -190,3 +190,22 @@ 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. _See [Rex7 Network Upgrade](upgrades/rex7.md) for the current state._ + +### SATIN + +SATIN is an **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 REX7's: + +- **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, KV updates and state gas per transaction, with no separate compute-gas limit; every transaction-level limit stops a transaction with a revert carrying `MegaLimitExceeded`. +- **[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; the pre-block calls, the system-contract deploys and the EIP-7997 factory run before every block. +- **Live system address** — a system-shaped transaction reads the [SequencerRegistry](system-contracts/sequencer-registry.md) itself. +- **Block limits** — execution gas, state gas, data size and KV updates are packing budgets that never refuse a deposit. + +_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..0a5623aab 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 pays history gas, so no transaction 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 → REX7 → 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. @@ -75,6 +84,7 @@ Contracts deployed under a given spec will continue to behave identically, regar - **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** — An **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/upgrades/overview.md b/docs/spec/upgrades/overview.md index b79328b9e..3b8c74627 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 @@ -155,6 +155,20 @@ Not yet scheduled Unstable; under active development. No behavioral change over Rex6 yet. +### [Satin](satin.md) + +{% tabs %} +{% tab title="Testnet" %} +Not yet scheduled +{% endtab %} +{% tab title="Mainnet" %} +Not yet scheduled +{% endtab %} +{% 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, per-transaction limits that stop a transaction 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, block limits as packing budgets, and the EIP-7997 factory. + ## How to Read These Pages Each upgrade page follows a consistent structure: From 491b71bb7412545aa1f38ce444dfe8c59b6226e1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:51 -0700 Subject: [PATCH 295/458] test: make the costly modexp and the spinning frame cheap to run The modexp input keeps its 1,024-byte base, so its price is unchanged, and takes a one-byte modulus, which sizes the work: it computes in a moment instead of a second in an unoptimized build. The frame that runs out of its own gas spends it on 32 KiB copies instead of 11-gas rounds. The suite's serial test time drops from 43.9 s to 28.8 s. --- crates/mega-evm/tests/satin/stops.rs | 9 +++++---- crates/mega-evm/tests/satin/withheld_gas.rs | 17 +++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 38a505891..5e0d62f00 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -38,8 +38,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADD, BALANCE, CALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, - RETURNDATASIZE, REVERT, SLOAD, SSTORE, TIMESTAMP, + ADD, BALANCE, CALL, GAS, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, + SLOAD, SSTORE, TIMESTAMP, }, context::result::ExecutionResult, context_interface::cfg::GasId, @@ -838,9 +838,10 @@ fn armed() -> EvmTxRuntimeLimits { .with_tx_state_gas_limit(TX_GAS_LIMIT_CAP) } -/// A loop that never ends. +/// 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 { - BytecodeBuilder::default().append(JUMPDEST).append_many([PUSH0, JUMP]).build() + crate::detention::spin(BytecodeBuilder::default()) } /// The ECRECOVER precompile, whose price is 3,000 whatever its input. diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 52b8c9e7f..1e62b5cd1 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -882,20 +882,21 @@ fn recording_modexp(runs: &Runs) -> DynPrecompile { }) } -/// The calldata of a modexp that is costly to compute: a 1,024-byte base with no zero byte, an -/// exponent of `exponent_len` bytes, all ones, and an odd 1,024-byte modulus, then `padding` -/// zero bytes the precompile ignores. Its price grows with the exponent, and so does the work. +/// 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_024] { + 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)); - let mut modulus: Vec = (0..1_024_u32).map(|i| (i % 241) as u8).collect(); - modulus[0] = 0xff; - modulus[1_023] |= 1; - input.extend(modulus); + input.push(0xfb); input.extend(core::iter::repeat_n(0_u8, padding)); input } From bf84a0bed95a16039bdeadd7a4a7d44c06c1cd8b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:22:57 -0700 Subject: [PATCH 296/458] build: optimize c-kzg and blst in dev builds Every KZG test loads the trusted setup, and under nextest each test is its own process: at opt-level 3 the load's C code takes about 11% less, 1.45 s to 1.29 s per test. --- Cargo.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 8f55f2d01..26954bd6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -200,6 +200,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 From 84f4b35c790fb56ce0121a9e8913acd42b946ed3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:24:11 -0700 Subject: [PATCH 297/458] fix(inspector): keep a charge an inspector cannot pay from classifying the frame --- crates/mega-evm/src/evm/execution.rs | 10 +- crates/mega-evm/src/evm/inspector.rs | 116 ++++++-- .../mega-evm/tests/satin/inspector_limits.rs | 277 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 4 files changed, 383 insertions(+), 21 deletions(-) create mode 100644 crates/mega-evm/tests/satin/inspector_limits.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index db43be7ed..619b78b99 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -48,7 +48,10 @@ use revm::{ use crate::{ access::ComputeStop, - evm::{history::transaction_body_bytes, inspector::frame_end_checked}, + evm::{ + history::transaction_body_bytes, + inspector::{frame_end_checked, StepGuard}, + }, history_gas, synthetic_frame_result, system::keyless, write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, @@ -709,6 +712,9 @@ where /// 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, @@ -720,7 +726,7 @@ where None => inspect_instructions( ctx, &mut frame.interpreter, - &mut *inspector, + StepGuard(&mut *inspector), instructions.instruction_table(), instructions.gas_table(), ), diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 83484999a..91f121dbb 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -1,29 +1,61 @@ -//! 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: +//! # 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. +//! +//! # What a rewrite does not change //! -//! - **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. A transaction a limit stopped is the exception: once it is latched, every -//! frame's result is the stop whatever produced it, so a revived creation is put back and reports -//! the stop, and the transaction does not fail. A creation stopped by its own frame budget -//! latches nothing, and its revival is refused. Every other rewrite is the tool's business. +//! push an address for code that does not exist. A transaction a limit stopped is the exception: +//! once it is latched, every frame's result is the stop whatever produced it, so a revived +//! creation is put back and reports the stop, and the transaction does not fail. A creation +//! stopped by its own frame budget latches nothing, and its revival is refused. +//! - **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. +//! - **The latch.** Once a limit stopped the transaction, every frame's result is the stop, +//! whatever produced it: an inspector turns it into neither a success nor a halt. +//! +//! 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`]). +//! - **An answer carries the gas its caller merges.** The caller adopts an answer's `Gas` as the +//! frame's, reservoir included. An answer built on `Gas::new(limit)` carries no reservoir, and a +//! caller above the execution cap adopts that; one built on +//! [`untouched_call_gas`](crate::untouched_call_gas) or +//! [`untouched_create_gas`](crate::untouched_create_gas) hands the reservoir back. #[cfg(not(feature = "std"))] use alloc as std; @@ -232,6 +264,52 @@ 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, which makes the four callbacks +/// forwarded here and no other; frame starts and ends reach the inspector itself. +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)>; 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..be894fdce --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -0,0 +1,277 @@ +//! 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 the gas its caller merges, reservoir included: an answer built on `Gas::new` +//! carries no reservoir, and a caller above the execution cap adopts that. + +use alloy_primitives::{address, Address, Bytes, Log, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + untouched_call_gas, 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"); + } +} + +/// Answers every call to `B` with a success, on the call's untouched gas or on `Gas::new`. +#[derive(Clone)] +struct AnswersB { + untouched: bool, +} + +impl Inspector, EthInterpreter> for AnswersB { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + (inputs.target_address == B).then(|| { + let gas = if self.untouched { + untouched_call_gas(inputs) + } else { + Gas::new(inputs.gas_limit) + }; + CallOutcome::new( + InterpreterResult::new(InstructionResult::Stop, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// The gas an answer carries is what its caller merges, the reservoir included. Above the +/// execution cap, an answer built on the frame's untouched gas hands the caller back the reservoir +/// it forwarded, and the transaction keeps its reservoir as it does when `B` runs; an answer built +/// on `Gas::new` carries none, the caller adopts that, and the sender pays for the reservoir. +#[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"); + + let (untouched, _) = run(a_calls_b(), limits, gas_limit, Some(AnswersB { untouched: true })); + assert_eq!(untouched.gas.reservoir_remaining, plain.gas.reservoir_remaining); + + let (fresh, _) = run(a_calls_b(), limits, gas_limit, Some(AnswersB { untouched: false })); + assert_eq!(fresh.gas.reservoir_remaining, 0, "the caller adopted an empty reservoir"); + assert_eq!( + fresh.gas.gas_used, + untouched.gas.gas_used + plain.gas.reservoir_remaining, + "and the sender paid for it" + ); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 3f7af0348..6d18f4cfa 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,7 @@ mod history_exemption; mod history_gas; mod history_reservoir; mod inspector; +mod inspector_limits; mod inspector_settlement; mod intrinsic; mod kv_limit; From 45bc97cac4e7fe3ed6f5f13fae015dcd636308b4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:26:14 -0700 Subject: [PATCH 298/458] docs(inspector): say what an inspector sees and may rewrite in each phase of a block --- crates/mega-evm/src/evm/inspector.rs | 33 ++++- crates/mega-evm/tests/block/inspector.rs | 155 ++++++++++++++++++++++- crates/mega-evm/tests/satin/inspector.rs | 59 +++++++++ 3 files changed, 241 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 91f121dbb..ae62d985f 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -8,15 +8,42 @@ //! 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 latch +//! writes the stop over its results. +//! - **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 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. +//! 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 at every entry point, before anything changes: the pre-block +//! changes, the execution of a transaction — a system transaction as a user one — the commit of an +//! outcome, and the end of the block. 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 //! diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index bf94da4ce..2a85549e9 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,11 +1,32 @@ -//! 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, }; -use mega_evm::{test_utils::GasInspector, DeclaredObserver, MegaEvmFactory}; -use revm::inspector::NoOpInspector; +use alloy_primitives::{Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{BytecodeBuilder, GasInspector}, + BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaEvmFactory, MegaTxEnvelope, + PreBlockStateSource, +}; +use revm::{ + database::State, + handler::FrameResult, + inspector::NoOpInspector, + interpreter::{FrameInput, Interpreter, InterpreterTypes}, + state::EvmState, + Inspector, +}; +use std::sync::{Arc, Mutex}; use crate::common::{self, user_tx}; @@ -137,3 +158,131 @@ 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 system-address transaction: a legacy call from the system address the registry names to the +/// Oracle's `getSlot(0)`. +fn system_tx() -> Recovered { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + Recovered::new_unchecked( + common::tx(0, ORACLE_CONTRACT_ADDRESS, input.into(), 1_000_000), + MEGA_SYSTEM_ADDRESS, + ) +} + +/// 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 factory = common::factory(); + let mut executor = factory.create_executor_with_trusted_inspector( + &mut state, + common::evm_env(), + recording_ctx(), + DeclaredObserver::new(Seen::default()), + ); + let pre_block = Arc::new(Mutex::new(Vec::new())); + let log = Arc::clone(&pre_block); + executor.set_pre_block_observer(Some(Box::new( + move |source: PreBlockStateSource, state: &EvmState| { + let wrote = + state.values().any(|account| account.storage.values().any(|s| s.is_changed())); + log.lock().unwrap().push((source, wrote)); + }, + ))); + + executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + let calls: Vec<_> = pre_block + .lock() + .unwrap() + .iter() + .filter(|(source, _)| { + matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) + }) + .copied() + .collect(); + assert_eq!( + calls, + [(PreBlockStateSource::Eip2935, true), (PreBlockStateSource::Eip4788, true)], + "both pre-block calls ran and 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"); +} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index c12d2a997..6690f29cb 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -600,3 +600,62 @@ 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().latched().is_none(), "no limit holds a system call"); +} From da4f0081ffc8bfc6613ae1db5d2386d3ec73ab1e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:30:28 -0700 Subject: [PATCH 299/458] test(inspector): drive four Foundry cheatcodes through the engine as Foundry's inspector does --- .../tests/satin/inspector_cheatcodes.rs | 378 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 2 files changed, 379 insertions(+) create mode 100644 crates/mega-evm/tests/satin/inspector_cheatcodes.rs 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..775b647dd --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -0,0 +1,378 @@ +//! 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, and a failed call `expectRevert` turns into a success settles +//! as the failure on every ledger. `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: Foundry answers a cheatcode on `Gas::new`, which carries no reservoir. +const GAS_LIMIT: u64 = 10_000_000; + +/// 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) { + 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.state > 0 && metered.gas.gas_used > 0, "unpaused, the region pays"); +} + +/// `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"); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6d18f4cfa..8cbe4ffa4 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,7 @@ mod history_exemption; mod history_gas; mod history_reservoir; mod inspector; +mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; From 484f59d63001c41596850cefe1ee5f29b44d697b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:31:10 -0700 Subject: [PATCH 300/458] ci(mutants): read a mutation run fail-closed, and refuse an old bash The gate passed when a run left no results, or empty lists: a driver that crashed under bash 3.2, a failed baseline or an interrupted run all read as nothing to test. It now scores outcomes.json only when the baseline succeeded and every mutant has an outcome, and passes a run that tested nothing only on the producer's word: cargo-mutants' empty mutants.json, or the line it prints when --in-diff leaves no mutant, which the driver records. umutate.py writes the same record. The driver refuses a bash older than 5, clears its results before anything can fail, and hands an empty diff to cargo-mutants. The gate's tests run in a new self-test job. --- .github/workflows/mutation.yml | 25 ++- mutants/README.md | 13 +- scripts/mutation_gate.py | 287 +++++++++++++++++++++++++-------- scripts/mutation_test.sh | 82 ++++++---- scripts/test_mutation_gate.py | 275 +++++++++++++++++++++++++++++++ scripts/umutate.py | 24 ++- 6 files changed, 607 insertions(+), 99 deletions(-) create mode 100644 scripts/test_mutation_gate.py diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index a74acc03f..5324602c4 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -1,13 +1,14 @@ name: Mutation Testing -# All mutation-testing CI lives here. Four concerns, one file: +# All mutation-testing CI lives here. Five 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 four share the scorer scripts/mutation_gate.py. See mutants/README.md. +# * gate self-test — the scorer's and the driver's own tests +# All four gates share the scorer scripts/mutation_gate.py. See mutants/README.md. on: workflow_dispatch: @@ -95,7 +96,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}`; @@ -124,6 +125,7 @@ jobs: path: | target/mutants/mutants.out target/mutants.diff + target/mutants.log mutation-report.md if-no-files-found: ignore @@ -182,7 +184,9 @@ jobs: uses: actions/upload-artifact@v4 with: name: mutation-results-infra - path: target/mutants-infra/mutants.out + path: | + target/mutants-infra/mutants.out + target/mutants-infra.log if-no-files-found: ignore # ── spec-gate: diff-scoped blocking gate on PRs ──────────────────────────── @@ -318,6 +322,19 @@ jobs: path: target/umutate/${{ matrix.subsystem }} if-no-files-found: ignore + # ── 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: 10 + steps: + - uses: actions/checkout@v4 + - 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 # (suppressions, operators, or src edits) and the infrastructure job to PRs diff --git a/mutants/README.md b/mutants/README.md index 776d89b47..a99eb4ff9 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -43,7 +43,8 @@ python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.o 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 with Python 3.9 it fails before mutating anything. +The gate's own tests run with `python3 -m unittest discover -s scripts -p 'test_*.py'`, on the same Python. When to shard is in `REVIEW.md` (Test gates, Mutation testing). ## The gate @@ -53,6 +54,10 @@ 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 whose baseline succeeded and whose every mutant has an outcome. +Missing results, a missing or failed baseline, or an interrupted run 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`. + ## 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 +86,12 @@ 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. ``` 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 diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index f93dfc871..8feb16704 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -1,18 +1,41 @@ #!/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. + 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 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. + 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). + 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. + +The results a run leaves are read fail-closed. A run is scored from its +`outcomes.json`, cargo-mutants' own record (scripts/umutate.py writes the same +shape): `total_mutants`, and `outcomes`, each with a `scenario`, `"Baseline"` or +`{"Mutant": {"name": ...}}`, and a `summary`. It is scored only if its baseline +succeeded and every mutant has an outcome. 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 baseline that failed +or is missing, a mutant without an outcome, an outcome of a kind this script +does not know. 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 +44,34 @@ from __future__ import annotations import argparse +import json import re import sys import tomllib +from dataclasses import dataclass, field from pathlib import Path # 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. +NOTHING_TO_MUTATE = ("No mutants to filter", "Diff file is empty") + +# The file `note-empty` records such a line in. +NO_MUTANTS_NOTE = "no-mutants.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 +109,181 @@ 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 empty_list_evidence(results: Path) -> str | None: + """The producer's own word that it had nothing to test, if it gave it.""" + listed = results / "mutants.json" + if listed.exists(): + try: + mutants = json.loads(listed.read_text()) + except json.JSONDecodeError as err: + raise ResultsError(f"{listed} is not JSON: {err}") from err + if mutants == []: + return "the mutant list under the run's filters was empty" + raise ResultsError( + f"{listed} lists {len(mutants)} mutants but {results} has no outcomes.json: " + f"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" + ) + 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"] + total = data["total_mutants"] + except (json.JSONDecodeError, KeyError, TypeError) as err: + raise ResultsError(f"{outcomes_path} is not a mutation run's outcomes: {err!r}") from err + + 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) + if len(mutants) != total: + raise ResultsError( + f"{len(mutants)} of {total} mutants have an outcome in {outcomes_path}: " + f"the run was interrupted" + ) + if total == 0: + 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 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. + """ + _, line_supp = load_suppressions(Path(path)) if path else ([], []) + return {e["mutant"].strip() for e in line_supp if "mutant" in e} + + +def is_suppressed(name: str, supp: set[str]) -> bool: + return name in supp or mutant_body(name) in supp + + +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) + 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 and not (run.timeout or run.caught or run.missed): + note = f"**Nothing to test**: {run.nothing_to_test}" + if run.unviable: + note += f" ({len(run.unviable)} unviable)" + 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") + caught, missed, timeout = run.caught, run.missed, 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} + supp = suppressed_names(args.suppressions) 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 +301,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 +319,9 @@ 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)}", ] + md.append("") def section(title: str, blurb: str, items: list[str], artifact: str) -> list[str]: out = [f"### {title}", "", blurb, ""] @@ -191,14 +354,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 @@ -261,6 +417,11 @@ 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) + pr = sub.add_parser("report") pr.add_argument("--results", required=True) pr.add_argument("--suppressions", default=None) diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 2be52d012..0c0dfa246 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -13,11 +13,25 @@ # 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. 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. + +# 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)" @@ -35,6 +49,10 @@ INFRA_FILES=( 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" + 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 +73,46 @@ 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 \ - "${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, - # 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 + 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" } cmd="${1:-}" @@ -93,12 +123,10 @@ case "$cmd" in 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. + # (and a wasted run) when a PR touches only tests/, Cargo.toml, etc. 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 -- '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 run_mutants --in-diff "$diff_file" ;; full) diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py new file mode 100644 index 000000000..563d96052 --- /dev/null +++ b/scripts/test_mutation_gate.py @@ -0,0 +1,275 @@ +#!/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 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 shutil +import subprocess +import sys +import tempfile +import unittest +from argparse import Namespace +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parent + + +def load_gate(): + spec = importlib.util.spec_from_file_location("mutation_gate", SCRIPTS / "mutation_gate.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 = load_gate() + +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()" + + +def mutant(name: str, summary: str) -> dict: + return {"scenario": {"Mutant": {"name": name}}, "summary": summary} + + +def outcomes_json(*mutants: dict, baseline: str | None = "Success", total: int | None = None) -> dict: + outcomes = [] if baseline is None else [{"scenario": "Baseline", "summary": baseline}] + outcomes += list(mutants) + return {"total_mutants": len(mutants) if total is None else total, "outcomes": outcomes} + + +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) -> Path: + path = self.tmp / name + path.mkdir(parents=True) + if outcomes is not None: + (path / "outcomes.json").write_text(json.dumps(outcomes)) + for file, text in (files or {}).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, suppressions: Path | None = None) -> tuple[int, str]: + comment = self.tmp / "comment.md" + args = Namespace( + results=str(results), + 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_an_interrupted_run(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"), total=3)) + self.assert_unscorable(results, "1 of 3 mutants have an outcome") + + 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_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") + + + +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_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_timeout_fails(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"))) + code, text = self.report(results) + self.assertEqual(code, 1, text) + self.assertIn("Timed-out mutants", 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) + + +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_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 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" + + def assert_refused(self, shell: str) -> None: + run = subprocess.run([shell, str(self.DRIVER), "full"], capture_output=True, text=True, + timeout=60) + 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 Linux, bash 3.2 in POSIX mode on macOS. + self.assert_refused("/bin/sh") + + def test_an_old_bash_is_refused(self) -> None: + bash = shutil.which("bash", path="/bin") + if bash is None: + self.skipTest("no /bin/bash") + version = subprocess.run([bash, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True, + text=True).stdout.strip() + if int(version) >= 5: + self.skipTest(f"/bin/bash is bash {version}") + self.assert_refused(bash) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/umutate.py b/scripts/umutate.py index 8215b8b9f..8911ac54a 100755 --- a/scripts/umutate.py +++ b/scripts/umutate.py @@ -24,7 +24,10 @@ 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 `, with the + record the gate scores: outcomes.json in cargo-mutants' shape when a + mutant was tested, and mutants.json holding [] when none was generated. + A failing baseline exits before anything is written. 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. @@ -35,6 +38,7 @@ import difflib import fnmatch import glob +import json import os import re import shutil @@ -322,6 +326,10 @@ def cmd_run(args) -> int: require_tools() 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 @@ -370,6 +378,20 @@ 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: say so as cargo-mutants does. + if baselined: + 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({ + "total_mutants": len(caught) + len(missed) + len(timeouts), + "caught": len(caught), "missed": len(missed), "timeout": len(timeouts), + "unviable": 0, "outcomes": outcomes, + }, indent=2) + "\n") + else: + (out / "mutants.json").write_text("[]\n") 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 a91565951f749dce3f09066904e713452ddd41c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:31:28 -0700 Subject: [PATCH 301/458] ci(mutants): re-run a timed-out mutant alone before the gate scores it A mutant is tested beside the others the run tests at once, each running the whole suite on the same cores: on CI one that a test catches in seconds alone timed out. The driver re-runs every unsuppressed timeout once with --jobs 1, into recheck/mutants.out, and the gate takes that outcome for it: caught alone is caught, surviving alone is a survivor, and timing out again stays inconclusive. --- .github/workflows/mutation.yml | 8 +++ REVIEW.md | 2 +- mutants/README.md | 7 ++- scripts/mutation_gate.py | 71 +++++++++++++++++++++++--- scripts/mutation_test.sh | 39 ++++++++++++++- scripts/test_mutation_gate.py | 91 ++++++++++++++++++++++++++++++++-- 6 files changed, 202 insertions(+), 16 deletions(-) diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 5324602c4..7255c0e54 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -68,6 +68,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 }}" @@ -79,6 +81,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" @@ -124,8 +127,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 @@ -176,6 +181,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" @@ -186,7 +192,9 @@ jobs: name: mutation-results-infra path: | 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: diff-scoped blocking gate on PRs ──────────────────────────── diff --git a/REVIEW.md b/REVIEW.md index 7795de057..180e0798d 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -118,7 +118,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. diff --git a/mutants/README.md b/mutants/README.md index a99eb4ff9..74642834e 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -29,7 +29,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,7 +37,7 @@ 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 @@ -58,6 +58,9 @@ The gate reads a run **fail-closed**: it scores `outcomes.json`, and only a run Missing results, a missing or failed baseline, or an interrupted run 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. + ## 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. diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 8feb16704..6822ef1ad 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -15,12 +15,18 @@ that line to /no-mutants.txt. Does nothing when exists, and fails when it does not and the output says no such thing. - 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 or timeout remains (the "no new survivors" gate). - Exits 2, with a report saying why, when the results cannot be scored. + 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. @@ -248,6 +254,22 @@ 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) @@ -261,6 +283,9 @@ 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" @@ -276,7 +301,23 @@ def cmd_report(args: argparse.Namespace) -> int: write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) return 0 - caught, missed, timeout = run.caught, run.missed, run.timeout + 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) supp = suppressed_names(args.suppressions) @@ -321,6 +362,15 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: f"- suppressed (equivalent/dead-code): {len(suppressed) + len(supp_timeouts)}", 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]: @@ -422,8 +472,15 @@ def main() -> int: 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 0c0dfa246..7bf86a033 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -15,7 +15,9 @@ # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # 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. Run scripts/mutation_gate.py afterwards to score + gate the run. +# instead. A mutant that timed out is re-run once, alone, into +# $OUT_DIR/recheck/mutants.out/. 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 @@ -113,6 +115,39 @@ run_mutants() { 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 1 \ + --output "$OUT_DIR/recheck" \ + --no-shuffle \ + -vV \ + "${re_args[@]}" 2>&1 | tee "$OUT_DIR/recheck.log" || rc=$? + # A re-check that fails as a run leaves the timeouts standing, and the gate + # reports its results as it finds them rather than the job ending here. + if ! run_outcome "$rc"; then + echo "the re-check of the timed-out mutants failed (exit $rc); see $OUT_DIR/recheck.log" >&2 + fi } cmd="${1:-}" @@ -150,4 +185,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/test_mutation_gate.py b/scripts/test_mutation_gate.py index 563d96052..558593442 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -16,6 +16,7 @@ import importlib.util import io import json +import re import shutil import subprocess import sys @@ -75,10 +76,12 @@ def suppressions(self, *mutants: str) -> Path: path.write_text("\n".join(entries)) return path - def report(self, results: Path, suppressions: Path | None = None) -> tuple[int, str]: + 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, @@ -140,6 +143,12 @@ 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) class NothingToTest(GateCase): @@ -198,12 +207,12 @@ def test_a_suppressed_survivor_passes(self) -> None: code, text = self.report(results, suppressions=self.suppressions(suppressed)) self.assertEqual(code, 0, text) - def test_a_timeout_fails(self) -> None: + 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) + code, text = self.report(results, self.tmp / "no-recheck") self.assertEqual(code, 1, text) - self.assertIn("Timed-out mutants", 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( @@ -211,6 +220,48 @@ def test_a_suppressed_timeout_passes(self) -> None: 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 NoteEmpty(GateCase): """`note-empty` records cargo-mutants saying it had nothing to mutate, and nothing else.""" @@ -244,6 +295,38 @@ def test_it_leaves_results_cargo_mutants_wrote_alone(self) -> None: 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 DriverGuard(unittest.TestCase): """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" From d0ae7827c2ff77ddb27b1e3c97727f903399ad27 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:32:56 -0700 Subject: [PATCH 302/458] chore(spec): end the legacy ladder at Rex6 --- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/block/hardfork.rs | 4 ++-- crates/mega-evm/src/evm/spec.rs | 16 +++++++--------- crates/mega-evm/src/lib.rs | 2 +- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 2ad60c6c9..8f9474db4 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -3,7 +3,7 @@ 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 diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index b38a39b15..bd0e05bfb 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -22,7 +22,7 @@ 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 { @@ -447,7 +447,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"); } } 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/lib.rs b/crates/mega-evm/src/lib.rs index 903994b16..f2c63c0e7 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -2,7 +2,7 @@ //! //! 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 From 69e0e32400564e62fa85d1d4655af2c2c973f9fd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:33:19 -0700 Subject: [PATCH 303/458] test(inspector): port the parked inspector rows --- crates/mega-evm/tests/_pending/README.md | 15 +- .../_pending/block_executor/inspector.rs | 424 ------------------ .../_pending/rex4/intrinsic_limit_bypass.rs | 179 -------- crates/mega-evm/tests/block/inspector.rs | 223 ++++++++- crates/mega-evm/tests/satin/inspector.rs | 68 +++ 5 files changed, 294 insertions(+), 615 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/block_executor/inspector.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e4676ee45..1d7ca9ea5 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,9 +28,8 @@ 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 | -| 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** | **32** | **32** | **0** | **22** | **3** | **7** | +| **Total** | **28** | **28** | **0** | **21** | **0** | **7** | ## Tests ported in place @@ -357,6 +356,16 @@ These 17 rows run in a real test target now, adapted to the Satin API: a transac | `rex5/oracle_hint_metering.rs` | revert-class aborts (1) | 1 | `tests/system/oracle.rs` | | **Total** | | **17** | | +## Tests ported by inspector support + +These 4 rows run in a real test target now, adapted to the Satin API: block execution admits an inspector only when it is declared an observer, so an inspector that answers a frame has no route to a block and is exercised on the EVM, where a frame it answers, or a failed frame it rewrites into a success, settles as a frame that kept nothing; and a body over the data-size limit is stopped before any inspector's answer to its first frame. The counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `block_executor/inspector.rs` | inspector support (3) | 3 | `tests/block/inspector.rs` | +| `rex4/intrinsic_limit_bypass.rs` | inspector support (1) | 1 | `tests/satin/inspector.rs` | +| **Total** | | **4** | | + ## Tests retired after the inventory These 21 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. @@ -391,11 +400,9 @@ Each cell lists `disposition count (mechanism · decision)`. | File | Tests | Owners | |---|---:|---| -| `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | | `mini_rex/gas.rs` | 2 | undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `rex4/intrinsic_limit_bypass.rs` | 1 | rewrite 1 (inspector support · D41) | | `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) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | 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/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs deleted file mode 100644 index 2a071f929..000000000 --- a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs +++ /dev/null @@ -1,179 +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 2: Intrinsic + execution overflow (KVUpdate) -// ============================================================================ - -// ============================================================================ -// TEST 4: Intrinsic-only overflow (KVUpdate) -// ============================================================================ - -// ============================================================================ -// TEST 8: Intrinsic-only KVUpdate overflow + intercepted system contract -// ============================================================================ - -// ============================================================================ -// 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}" - ); -} diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 2a85549e9..c862412f3 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,32 +1,41 @@ //! 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_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, BlockExecutorFactory}, - Evm, EvmFactory, + Evm, EvmFactory, FromRecoveredTx, }; -use alloy_primitives::{Bytes, B256, U256}; +use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - test_utils::{BytecodeBuilder, GasInspector}, - BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaEvmFactory, MegaTxEnvelope, + test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, + transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, + MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, MegaTxEnvelope, PreBlockStateSource, }; use revm::{ + bytecode::opcode::{ADD, POP, PUSH0, SLOAD, SSTORE}, + context::{ContextTr, JournalTr}, database::State, handler::FrameResult, inspector::NoOpInspector, - interpreter::{FrameInput, Interpreter, InterpreterTypes}, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, + Interpreter, InterpreterResult, InterpreterTypes, + }, state::EvmState, Inspector, }; -use std::sync::{Arc, Mutex}; +use std::{ + cell::Cell, + sync::{Arc, Mutex}, +}; use crate::common::{self, user_tx}; @@ -179,7 +188,7 @@ impl Inspector for Seen { /// 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 { +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()); @@ -286,3 +295,201 @@ fn test_a_rewriting_inspector_is_refused_at_a_system_transaction() { 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); + } +} + +/// Answers every creation itself with a success and no address, and counts those answers and every +/// creation's end. +#[derive(Default)] +struct SkipCreateInspector { + creates_intercepted: Cell, + create_ends: Cell, +} + +impl Inspector for SkipCreateInspector { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + self.creates_intercepted.set(self.creates_intercepted.get() + 1); + Some(CreateOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit()), + ), + None, + )) + } + + fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, _: &mut CreateOutcome) { + self.create_ends.set(self.create_ends.get() + 1); + } +} + +/// A legacy creation from [`common::CALLER`] running `init_code`. +fn creation_tx(nonce: u64, gas_limit: u64, init_code: Bytes) -> Recovered { + let tx = TxLegacy { + chain_id: Some(common::CHAIN_ID), + nonce, + gas_price: 1_000_000, + gas_limit, + to: TxKind::Create, + value: U256::ZERO, + input: init_code, + }; + common::recovered(MegaTxEnvelope::Legacy(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(0xc0), + ))) +} + +/// 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); +} + +/// An inspector that answers a creation rewrites what execution produces, so block execution +/// refuses it before the transaction runs. On the EVM, the transaction's own creation answered +/// with a success and no address settles as a creation that never started: no account, so the +/// state gas EIP-2780 charged for it and the history of its write record come back, and the +/// transaction keeps only its body. +#[test] +fn test_inspector_early_return_create_with_additional_limits() { + let tx = creation_tx(0, 10_000_000, Bytes::from_static(&[0x00])); + + let mut state = common::state(); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(SkipCreateInspector::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().creates_intercepted.get(), 0, "nothing ran"); + + let mut state = common::state(); + let mut inspector = SkipCreateInspector::default(); + let (tx, outcome) = run_as_a_tool(&mut state, &tx, &mut inspector); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(inspector.creates_intercepted.get(), 1, "the creation was answered"); + assert_eq!(inspector.create_ends.get(), 1, "and ended"); + let body = transaction_body_bytes(&tx); + assert_eq!(outcome.gas.state, 0, "no account, so no state gas"); + assert_eq!(outcome.gas.history_bytes, body, "and no record: the body alone"); + assert_eq!(outcome.gas.history, mega_evm::history_gas(body).unwrap()); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + let created = common::CALLER.create(0); + assert!(outcome.state.get(&created).is_none_or(|account| account.info.is_empty())); +} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index 6690f29cb..98fea9e49 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -659,3 +659,71 @@ fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { assert_eq!(*evm.inspector(), Seen { frames: 1, steps: 3 }, "PUSH0, POP, STOP"); assert!(evm.ctx().additional_limit().latched().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 latches the transaction before it runs, and its first frame is +/// answered with the stop — in place of the answer an inspector that answers every call gives it. +/// The transaction is the one no inspector runs: the stop, which settles like a revert, so the +/// sender gets back what the frame did not spend. +#[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()) + .unwrap(); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(SkipAllCallsInspector::default()); + let answered = evm.execute_transaction(tx).unwrap(); + + assert_eq!(evm.inspector().answered, 1, "the inspector answered the first frame"); + let stop = answered.limit_exceeded.expect("the transaction is stopped"); + assert!( + matches!( + stop, + mega_evm::LimitCheck::ExceedsLimit { + kind: mega_evm::LimitKind::DataSize, + limit: LIMIT, + .. + } + ), + "{stop:?}" + ); + assert!( + matches!(&answered.result, revm::context::result::ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "the stop, not the answer: {:?}", + answered.result + ); + assert_eq!(answered.result, plain.result); + assert_eq!(answered.gas, plain.gas); + assert_eq!(answered.usage, plain.usage); + assert!(answered.gas.gas_used < TX_GAS_LIMIT / 100, "the unspent gas comes back"); +} From 192ad3387ed0d43912e2e37a40fc27888a5b89cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:33:45 -0700 Subject: [PATCH 304/458] chore(mega-evme): default to Rex6 and stop listing Rex7 --- bin/mega-evme/README.md | 2 +- bin/mega-evme/src/common/env.rs | 6 +++--- bin/mega-t8n/src/cmd.rs | 4 ++-- docs/mega-evme/commands/replay.md | 2 +- docs/mega-evme/commands/run.md | 6 +++--- docs/mega-evme/commands/tx.md | 2 +- docs/mega-evme/configuration/chain-and-spec.md | 3 +-- 7 files changed, 12 insertions(+), 13 deletions(-) diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index 63ef5a55d..4b91bcd5c 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -265,7 +265,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: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`MiniRex1`/`MiniRex2` are aliases executing `Equivalence`/`MiniRex` behavior) | | `--chain-id ` | 6342 | Chain ID | ### Block Environment diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 1f6b7379a..170dd425f 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -26,9 +26,9 @@ use super::{EvmeError, Result}; #[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")] + /// `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`MiniRex1`/`MiniRex2` are alias + /// specs executing `Equivalence`/`MiniRex` behavior) + #[arg(long = "spec", default_value = "Rex6")] pub spec: String, /// `ChainID` to use diff --git a/bin/mega-t8n/src/cmd.rs b/bin/mega-t8n/src/cmd.rs index 7117b59fa..c2db5c431 100644 --- a/bin/mega-t8n/src/cmd.rs +++ b/bin/mega-t8n/src/cmd.rs @@ -89,8 +89,8 @@ pub(crate) struct Cmd { 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) + /// `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`MiniRex1`/`MiniRex2` + /// are alias specs executing `Equivalence`/`MiniRex` behavior) #[arg(long = "state.fork", default_value = "MiniRex")] pub fork: String, diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index b21c9a96d..fa27f7b3c 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -150,7 +150,7 @@ 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`. +For any other chain, `replay` enables every hardfork up to a pinned spec at genesis — currently `Rex6`. 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. diff --git a/docs/mega-evme/commands/run.md b/docs/mega-evme/commands/run.md index 8fd2f1a1b..f54d392a0 100644 --- a/docs/mega-evme/commands/run.md +++ b/docs/mega-evme/commands/run.md @@ -62,7 +62,7 @@ Each group is documented on its own page. | Option | Default | | ------------ | -------------------------------------------- | -| `--spec` | `Rex7` | +| `--spec` | `Rex6` | | `--gas` | `10000000` | | `--sender` | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` | | `--receiver` | `0x0000000000000000000000000000000000000000` | @@ -327,9 +327,9 @@ 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, possible values: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`MiniRex1`/`MiniRex2` are alias specs executing `Equivalence`/`MiniRex` behavior) - [default: Rex7] + [default: Rex6] --chain-id Chain ID [default: 6342] [aliases: --chainid] diff --git a/docs/mega-evme/commands/tx.md b/docs/mega-evme/commands/tx.md index ce45e33b9..5ef142c85 100644 --- a/docs/mega-evme/commands/tx.md +++ b/docs/mega-evme/commands/tx.md @@ -213,7 +213,7 @@ RPC Options: --rpc.rate-limit Retry-layer compute-units-per-second budget [default: 660] Chain Options: - --spec Spec [default: Rex7] + --spec Spec [default: Rex6] --chain-id Chain ID [default: 6342] [aliases: --chainid] Block Options: diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index b38561260..e254b8b6d 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -12,7 +12,7 @@ The `replay` command auto-detects the spec from the chain ID and block timestamp | Flag | Default | Aliases | Description | | ----------------- | ------- | ----------- | ------------------- | -| `--spec ` | `Rex7` | — | MegaETH spec to use | +| `--spec ` | `Rex6` | — | MegaETH spec to use | | `--chain-id ` | `6342` | `--chainid` | Chain ID | ## Available Specs @@ -32,7 +32,6 @@ 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**) | ## Examples From f40a91d355255a8c2c899059770789aebd89e3b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:33:53 -0700 Subject: [PATCH 305/458] ci(bench): drop rex7 from the baseline-gap rows --- .github/scripts/bench_compare.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/bench_compare.py b/.github/scripts/bench_compare.py index ba3a225e5..393a2fa27 100644 --- a/.github/scripts/bench_compare.py +++ b/.github/scripts/bench_compare.py @@ -279,7 +279,7 @@ def compare(data, iters: int): ROW_ORDER = [ "revm_pinned", "revm_latest", "op_revm_pinned", "op_revm_latest", "equivalence", "mini_rex", "rex", "rex1", "rex2", "rex3", "rex4", "rex5", - "rex6", "rex7", + "rex6", ] SPECS = set(ROW_ORDER) From 81cb800d0338fc65111eceb3a9b752c64a10ea63 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:34:27 -0700 Subject: [PATCH 306/458] docs: describe the inspector contract in the agent guide and the crate README --- AGENTS.md | 31 ++++++++++++++++++++----------- crates/mega-evm/README.md | 9 ++++++++- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2fc35d080..080ca16b1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,17 +102,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 (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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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` and the creation-revival refusal (`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`) | 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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, the settlement of a frame that kept nothing 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`) | — | +| `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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | ### How Satin executes today @@ -366,9 +366,18 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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. The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`), unless the transaction is latched: the creation is put back, and the latch reports the stop. A creation stopped by its own frame budget latches nothing, and its revival is refused. 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, 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 is not held: a success an inspector rewrites into a failure settles as a failure, and the writes its journal kept are on no ledger. +- **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, so an answer built on `Gas::new(limit)` hands its caller an empty reservoir. + 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. - **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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 2ad60c6c9..43598c31f 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -38,7 +38,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 abort protocol that stops a transaction crossing a limit with a revert, and the inspector admission gate. +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 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. @@ -209,6 +209,13 @@ 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. +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. + ## Documentation - [Specification](https://megaeth-labs.github.io/mega-evm/) (describes the legacy engine until the Satin pages land) From 08e97026004393e7aecf67cdbf03e76ac73a19c7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:34:55 -0700 Subject: [PATCH 307/458] ci(mutants): end the spec-gate ladder at REX6 --- mutants/operators/spec-gate/generate.py | 22 +++++++++++++-------- mutants/operators/spec-gate/spec-gate.rules | 1 - 2 files changed, 14 insertions(+), 9 deletions(-) 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 From bc99a2d1c76cc56a213a28a79802f703a2c7e9cf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:35:35 -0700 Subject: [PATCH 308/458] docs(spec): remove Rex7; Satin follows Rex6 as the one unstable spec --- docs/spec/SUMMARY.md | 1 - docs/spec/glossary.md | 4 +-- docs/spec/hardfork-spec.md | 19 +++++--------- docs/spec/overview.md | 5 ++-- docs/spec/upgrades/overview.md | 14 ---------- docs/spec/upgrades/rex7.md | 47 ---------------------------------- docs/spec/upgrades/satin.md | 3 +-- 7 files changed, 11 insertions(+), 82 deletions(-) delete mode 100644 docs/spec/upgrades/rex7.md diff --git a/docs/spec/SUMMARY.md b/docs/spec/SUMMARY.md index 9cf174441..8cc78497c 100644 --- a/docs/spec/SUMMARY.md +++ b/docs/spec/SUMMARY.md @@ -39,7 +39,6 @@ - [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 c1735cd01..c1bb69faf 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -198,8 +198,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 → SATIN`. -`REX7` and `SATIN` are unstable. +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 df9f8b808..b53ba9e67 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 → SATIN +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. 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)). -Every spec through REX7 builds on Optimism Isthmus (Ethereum Prague) as the base layer; SATIN builds on Optimism Karst (Ethereum Osaka). -All specs through REX6 are frozen; REX7 and SATIN are **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 and SATIN are unstable and have no activation timestamp on either mainnet or testnet. +SATIN is unstable and has no activation timestamp on either mainnet or testnet. ### Backward Compatibility @@ -184,18 +184,11 @@ REX6 is frozen and scheduled on both networks; see the [upgrade overview](upgrad _See [Rex6 Network Upgrade](upgrades/rex6.md) for full details._ -### REX7 - -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. - -_See [Rex7 Network Upgrade](upgrades/rex7.md) for the current state._ - ### SATIN -SATIN is an **unstable** spec under active development, scheduled by the `Satin` hardfork. +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 REX7's: +It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather than adding to REX6's: - **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. diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 0a5623aab..b6de2b08e 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -62,7 +62,7 @@ MegaETH uses a spec system to version its verifiable behavior at each stage of t 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 → SATIN +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. @@ -83,8 +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** — An **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, 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/upgrades/overview.md b/docs/spec/upgrades/overview.md index 3b8c74627..2f2e568b8 100644 --- a/docs/spec/upgrades/overview.md +++ b/docs/spec/upgrades/overview.md @@ -141,20 +141,6 @@ 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) - -{% tabs %} -{% tab title="Testnet" %} -Not yet scheduled -{% endtab %} -{% tab title="Mainnet" %} -Not yet scheduled -{% endtab %} -{% endtabs %} - -Unstable; under active development. -No behavioral change over Rex6 yet. - ### [Satin](satin.md) {% tabs %} 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 index f37c4404e..f65aefa1e 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -25,8 +25,7 @@ Detention holds each frame's spendable regular gas inside the frame's own gas, s 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 every block-level execution limit a packing budget that never refuses a deposit. -Satin follows Rex7 on the spec ladder. -Rex7 changes no behavior of [Rex6](rex6.md), so every **Previous behavior** below is Rex6's. +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: From 5554ed20d169c2070621136ce19b6bb553ef3eed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:36:08 -0700 Subject: [PATCH 309/458] docs: end the legacy engine at Rex6 and name Satin the unstable spec --- AGENTS.md | 5 +++-- ARCH.md | 3 ++- README.md | 16 ++++++++-------- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2fc35d080..767c60a2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,8 @@ MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on ** 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. +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. @@ -96,7 +97,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `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. +- The legacy spec names (`Equivalence` … `Rex6`) 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. 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/README.md b/README.md index 90e6d12e2..79226176b 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,14 @@ 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 | -| [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 | +| 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-t8n](bin/mega-t8n) | Standalone state transition (t8n) tool | +| [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 From 2d79fb012896e5f92c0a3420963ad95a169a2ea2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:36:20 -0700 Subject: [PATCH 310/458] docs: label a PR that changes Satin spec:unstable --- .github/pull_request_template.md | 2 ++ AGENTS.md | 3 +++ 2 files changed, 5 insertions(+) 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/AGENTS.md b/AGENTS.md index 767c60a2e..eef2915db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -451,6 +451,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 From bb68e3fd2b08187407fc9a7ab9910d7daeeb24cf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:36:56 -0700 Subject: [PATCH 311/458] docs(spec): state that Rex6 is scheduled on both networks --- docs/spec/upgrades/rex6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 1af056d3fddc0f3a5778fd393a202d7a983cb8b9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:38:35 -0700 Subject: [PATCH 312/458] bench(block): measure a block in the chain's steady state Every measured block started from a state without the seven predeploys, so it paid their first deployment, which a chain pays once, and ran without any limit. The block benches now start each block from a fresh State over the state the previous block's pre-block changes left, predeploys included, under BlockLimits::default(), and hand the state back so its drop is not measured. The first block after activation keeps its own arm, activation_pre_block. --- REVIEW.md | 3 +- crates/mega-evm/benches/block.rs | 229 ++++++++++++++++++++----------- 2 files changed, 153 insertions(+), 79 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 180e0798d..f1e2e07f9 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -106,7 +106,8 @@ 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` (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 that already holds the predeploys, under `BlockLimits::default()`; the one-off deployment of the first block after activation is its own arm, `block/activation_pre_block`. - `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/benches/block.rs b/crates/mega-evm/benches/block.rs index e249fdf25..080fd0ece 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -1,8 +1,16 @@ //! 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 already holds the seven predeploys, which a chain deploys once, in its first +//! block after activation: the state the previous block's pre-block changes left; +//! - under the limits a block runs under when its caller configures nothing else, +//! `BlockLimits::default()`: the production data-size limits and gas detention's caps; +//! - 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,11 +19,14 @@ //! 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. A third arm, `steady_pre_block`, measures `apply_pre_execution_changes` alone on a -//! block whose seven predeploys are already in state: the per-block cost of the idempotent -//! check. +//! 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. Two more +//! arms measure `apply_pre_execution_changes` alone: +//! +//! - `steady_pre_block`: on the steady state, the per-block cost of the idempotent check of the +//! predeploys and of the pre-block system calls; +//! - `activation_pre_block`: on a state without the predeploys, the first block after activation, +//! which deploys all seven. A chain pays it once; it is the one arm that runs the deploys. #![allow(missing_docs)] use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; @@ -34,6 +45,7 @@ use revm::{ context::{BlockEnv, CfgEnv}, database::State, state::EvmState, + DatabaseCommit, }; use std::{ hint::black_box, @@ -56,6 +68,10 @@ const SENDER: Address = address!("0x2000000000000000000000000000000000000002"); const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); const WRITER: Address = address!("0x1000000000000000000000000000000000000001"); +/// What the pre-block changes of a block handed their observer, in the order the executor +/// commits them. +type PreBlockStates = Arc>>; + /// 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 { @@ -74,7 +90,7 @@ 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, and nothing the chain deploys. fn database() -> MemoryDatabase { let mut db = MemoryDatabase::default(); db.set_account_code(WRITER, writer_code()); @@ -83,23 +99,29 @@ fn database() -> MemoryDatabase { 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 under the limits a block runs under when its caller configures nothing else. fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits()) + MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::default()) } /// `N` transactions to `to`, one per nonce, each carrying the input `input` builds for it. @@ -133,21 +155,70 @@ fn chain_spec() -> MegaHardforkConfig { .with_params(SequencerRegistryConfig::placeholder()) } -/// A database on which the seven predeploys have already been installed. -fn deployed_state() -> State { +/// Runs the pre-block changes of block `number` on `db` and returns what they handed their +/// observer, without committing anything to `db`. +fn pre_block_states(db: MemoryDatabase, number: u64) -> Vec<(PreBlockStateSource, EvmState)> { let spec = chain_spec(); - 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 first block deploys"); + let mut state = State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env_at(number)); + let mut executor = + MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); + let log = PreBlockStates::default(); + let captured = Arc::clone(&log); + executor.set_pre_block_observer(Some(Box::new( + move |source: PreBlockStateSource, state: &EvmState| { + captured.lock().expect("pre-block observer").push((source, state.clone())); + }, + ))); + executor.apply_pre_execution_changes().expect("the pre-block changes apply"); + drop(executor); + let states = std::mem::take(&mut *log.lock().expect("pre-block observer")); + 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, the seven predeploys among them, committed in +/// the order the executor commits them. +fn steady_database() -> MemoryDatabase { + let mut db = database(); + let states = pre_block_states(db.clone(), BLOCK_NUMBER - 1); + let deployed = states + .iter() + .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) + .filter(|(_, state)| state.values().any(|account| account.is_created())) + .count(); + assert_eq!(deployed, SYSTEM_CONTRACT_DEPLOY_COUNT, "the previous block deploys all seven"); + for (_, state) in states { + db.commit(state); } - state + db +} + +/// Asserts that the pre-block changes of the bench's block on `db` find every predeploy in place: +/// each is a read-only witness entry, neither created nor touched. +fn assert_predeploys_in_place(db: &MemoryDatabase) { + let states = pre_block_states(db.clone(), BLOCK_NUMBER); + let deploys: Vec<_> = states + .iter() + .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) + .collect(); + assert_eq!(deploys.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); + for (source, state) in &deploys { + assert_eq!(state.len(), 1, "{source:?} is one witness account"); + let account = state.values().next().expect("the account is present"); + assert!(!account.is_touched(), "{source:?} is not touched"); + assert!(!account.is_created(), "{source:?} is not created"); + } + assert_eq!(states[0].0, PreBlockStateSource::Eip2935); + assert_eq!(states[1].0, PreBlockStateSource::Eip4788); } fn bench_block(c: &mut Criterion) { let spec = chain_spec(); + let steady = steady_database(); + // Checked once before measurement, so a block that would deploy is not measured as steady. + assert_predeploys_in_place(&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. @@ -160,7 +231,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()); @@ -169,6 +240,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" @@ -183,8 +255,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, @@ -193,63 +291,38 @@ 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, - ); - }); - } - group.finish(); - - // The idempotent pre-block path: everything is already deployed, so each of the seven - // specs is a read-only witness entry. Checked once against the executor's own observer - // before measurement so a broken deploy does not get timed. - { - let mut state = deployed_state(); - let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); - let mut executor = - MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); - let log = Arc::new(Mutex::new(Vec::new())); - let captured = Arc::clone(&log); - executor.set_pre_block_observer(Some(Box::new( - move |source: PreBlockStateSource, state: &EvmState| { - captured.lock().expect("pre-block observer").push((source, state.clone())); + executor.limiter().block_gas_used + }; + (state, black_box(used)) }, - ))); - executor.apply_pre_execution_changes().expect("the idempotent check"); - let outcomes = log.lock().expect("pre-block observer"); - let deploys: Vec<_> = outcomes - .iter() - .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) - .collect(); - assert_eq!(deploys.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); - for (source, state) in &deploys { - assert_eq!(state.len(), 1, "{source:?} is one witness account"); - let account = state.values().next().expect("the account is present"); - assert!(!account.is_touched(), "{source:?} is not touched"); - assert!(!account.is_created(), "{source:?} is not created"); - } - assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); - assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); - } + BatchSize::SmallInput, + ); + }); - let mut group = c.benchmark_group("block"); - group.bench_function("steady_pre_block", |b| { + // The first block after activation deploys all seven, checked once before measurement. + let deployed = pre_block_states(database(), BLOCK_NUMBER) + .iter() + .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) + .filter(|(_, state)| state.values().any(|account| account.is_created())) + .count(); + assert_eq!(deployed, SYSTEM_CONTRACT_DEPLOY_COUNT, "the first block deploys all seven"); + + group.bench_function("activation_pre_block", |b| { b.iter_batched( - deployed_state, + || 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(); - black_box(executor.limiter().block_gas_used) + let used = { + 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(); + executor.limiter().block_gas_used + }; + (state, black_box(used)) }, BatchSize::SmallInput, ); From 16e6900435efcefd57cdfade6724ed72fb477f4f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:43:00 -0700 Subject: [PATCH 313/458] test(mutants): keep the driver-guard test from starting a run Where /bin/sh is bash 5 the guard lets it through, and the test ran the driver's full subcommand. It now skips a shell that is bash 5 or newer, and calls the driver with a subcommand it does not have, a scratch output directory and a minimal PATH. --- scripts/test_mutation_gate.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 558593442..5bb7d69a9 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -332,26 +332,35 @@ class DriverGuard(unittest.TestCase): 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: - run = subprocess.run([shell, str(self.DRIVER), "full"], capture_output=True, text=True, - timeout=60) + 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 Linux, bash 3.2 in POSIX mode on macOS. + # 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: - bash = shutil.which("bash", path="/bin") - if bash is None: + if not Path("/bin/bash").exists(): self.skipTest("no /bin/bash") - version = subprocess.run([bash, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True, - text=True).stdout.strip() - if int(version) >= 5: - self.skipTest(f"/bin/bash is bash {version}") - self.assert_refused(bash) + self.assert_refused("/bin/bash") if __name__ == "__main__": From cff1de3b48c92750381dd5cf1ea0ec1e82aee3af Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:43:22 -0700 Subject: [PATCH 314/458] ci(mutants): fail a run whose outcomes are not objects, and drop a dead note An outcomes list of anything but objects crashed the gate with a traceback; it is now results that cannot be scored, with the reason. The nothing-to-test report no longer counts unviable mutants a run without outcomes cannot have. --- scripts/mutation_gate.py | 6 +++--- scripts/test_mutation_gate.py | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 6822ef1ad..5670b3bb7 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -179,6 +179,8 @@ def load_run(results: Path) -> Run: data = json.loads(outcomes_path.read_text()) outcomes = data["outcomes"] total = data["total_mutants"] + 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 @@ -294,10 +296,8 @@ def cmd_report(args: argparse.Namespace) -> int: ) return 2 - if run.nothing_to_test is not None and not (run.timeout or run.caught or run.missed): + if run.nothing_to_test is not None: note = f"**Nothing to test**: {run.nothing_to_test}" - if run.unviable: - note += f" ({len(run.unviable)} unviable)" write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) return 0 diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 5bb7d69a9..fe3959650 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -135,6 +135,11 @@ 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") From 7d32937e31f5b448e1c17de97b1e5d37b20a1feb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 22:43:48 -0700 Subject: [PATCH 315/458] ci(mutants): clear the driver's results before it looks for nproc Stock macOS has no nproc, and the driver computed its job count before it cleared the previous run's results, so a run that stopped there left them for the gate to read. --- scripts/mutation_test.sh | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 7bf86a033..1b3a7a183 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -38,6 +38,13 @@ 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)}" PKG_ARGS=(--package mega-evm) @@ -49,12 +56,6 @@ INFRA_FILES=( crates/mega-evm/src/test_utils/scenario.rs ) -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" - if ! cargo mutants --version >/dev/null 2>&1; then echo "cargo-mutants is required. Install with 'cargo install cargo-mutants --locked'." >&2 exit 1 From d3b3cb5dd220904623e4713379524efc2211fc32 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:29:44 -0700 Subject: [PATCH 316/458] fix(inspector): hand an answered frame's caller back the reservoir it forwarded A frame an inspector answers never runs, so it draws nothing from the reservoir. Its answer now carries only the regular gas the inspector chose: the answer's state and history charges are rolled back, its refund dropped, and its reservoir set to the one the frame inherited, whatever Gas it was built on. Foundry answers every cheatcode on Gas::new(limit) and runs tests at 2^30 gas, above the execution cap, so a forge test no longer loses its reservoir at its first cheatcode call. --- AGENTS.md | 3 +- crates/mega-evm/README.md | 1 + crates/mega-evm/src/evm/inspector.rs | 45 ++++++-- .../tests/satin/inspector_cheatcodes.rs | 43 +++++++- .../mega-evm/tests/satin/inspector_limits.rs | 76 +++++++++---- .../tests/satin/inspector_settlement.rs | 104 +++++++++++++++--- 6 files changed, 218 insertions(+), 54 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eaa3b8e0d..0495e1fc1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -377,7 +377,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer So Foundry's `expectRevert` on a call that wrote and reverted bills the transaction as the revert does. The reverse is not held: a success an inspector rewrites into a failure settles as a failure, and the writes its journal kept are on no ledger. - **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, so an answer built on `Gas::new(limit)` hands its caller an empty reservoir. + 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. - **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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 920ab5cbd..5bb20d222 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -213,6 +213,7 @@ A declared observer sees a block's transactions, user and system alike, and noth 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. 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. diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index ae62d985f..63e126751 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -78,11 +78,12 @@ //! 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`]). -//! - **An answer carries the gas its caller merges.** The caller adopts an answer's `Gas` as the -//! frame's, reservoir included. An answer built on `Gas::new(limit)` carries no reservoir, and a -//! caller above the execution cap adopts that; one built on -//! [`untouched_call_gas`](crate::untouched_call_gas) or -//! [`untouched_create_gas`](crate::untouched_create_gas) hands the reservoir back. +//! - **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. #[cfg(not(feature = "std"))] use alloc as std; @@ -468,7 +469,7 @@ pub(crate) fn frame_end_checked( frame_end(context, inspector, frame_input, frame_result); refuse_create_revival(context, before, frame_result); if answered || !before.is_ok() { - settle_kept_nothing(context, frame_input, frame_result, depth); + settle_kept_nothing(context, frame_input, frame_result, depth, answered); } } @@ -482,6 +483,14 @@ pub(crate) fn frame_end_checked( /// 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: @@ -502,9 +511,20 @@ fn settle_kept_nothing( input: &FrameInput, result: &mut FrameResult, depth: usize, + answered: bool, ) { carry_upfront_flags(input, result); - if !result.instruction_result().is_ok() || context.additional_limit.latched().is_some() { + let success = + result.instruction_result().is_ok() && context.additional_limit.latched().is_none(); + 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 @@ -515,8 +535,6 @@ fn settle_kept_nothing( let history = if depth == 0 { context.additional_limit.top_level_write_record_gas() } else { 0 }; let gas = result.gas_mut(); - gas.rollback_state_gas(); - gas.set_refunded(0); gas.refill_reservoir(upfront.unwrap_or_default()); gas.refill_history(history); context.additional_limit.discard_returning_lane(); @@ -538,6 +556,15 @@ fn carry_upfront_flags(input: &FrameInput, result: &mut FrameResult) { } } +/// 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 { diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 775b647dd..640a4ade9 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -61,8 +61,11 @@ const TEST: Address = address!("0000000000000000000000000000000000f00001"); 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: Foundry answers a cheatcode on `Gas::new`, which carries no reservoir. +/// 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"; @@ -196,7 +199,16 @@ fn call_and_note(code: BytecodeBuilder, target: Address, input: &[u8]) -> Byteco /// 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) { - let tx = call(CALLER, TEST, U256::ZERO, GAS_LIMIT); + 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); } @@ -376,3 +388,30 @@ fn test_expect_revert_is_honored_on_a_result_no_frame_ran_to_produce() { 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 index be894fdce..86c7d8fef 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -6,14 +6,15 @@ //! - 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 the gas its caller merges, reservoir included: an answer built on `Gas::new` -//! carries no reservoir, and a caller above the execution cap adopts that. +//! - 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, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaTransactionOutcome, + untouched_call_gas, with_pools_of, EvmTxRuntimeLimits, MegaContext, MegaEvm, + MegaTransactionOutcome, }; use revm::{ bytecode::opcode::{LOG0, POP, PUSH0, TIMESTAMP}, @@ -231,32 +232,54 @@ fn test_an_inspector_cannot_overdraw_a_frame() { } } -/// Answers every call to `B` with a success, on the call's untouched gas or on `Gas::new`. +/// 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 { - untouched: bool, + 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 = if self.untouched { - untouched_call_gas(inputs) - } else { - Gas::new(inputs.gas_limit) + 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(InstructionResult::Stop, Bytes::new(), gas), + InterpreterResult::new(self.result, Bytes::new(), gas), inputs.return_memory_offset.clone(), ) }) } } -/// The gas an answer carries is what its caller merges, the reservoir included. Above the -/// execution cap, an answer built on the frame's untouched gas hands the caller back the reservoir -/// it forwarded, and the transaction keeps its reservoir as it does when `B` runs; an answer built -/// on `Gas::new` carries none, the caller adopts that, and the sender pays for the reservoir. +/// 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; @@ -264,14 +287,19 @@ fn test_an_answer_carries_the_reservoir_its_caller_merges() { let (plain, _) = run::(a_calls_b(), limits, gas_limit, None); assert!(plain.gas.reservoir_remaining > 0, "the reservoir comes back"); - let (untouched, _) = run(a_calls_b(), limits, gas_limit, Some(AnswersB { untouched: true })); - assert_eq!(untouched.gas.reservoir_remaining, plain.gas.reservoir_remaining); - - let (fresh, _) = run(a_calls_b(), limits, gas_limit, Some(AnswersB { untouched: false })); - assert_eq!(fresh.gas.reservoir_remaining, 0, "the caller adopted an empty reservoir"); - assert_eq!( - fresh.gas.gas_used, - untouched.gas.gas_used + plain.gas.reservoir_remaining, - "and the sender paid for it" - ); + 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 index 3e0c5ccb0..d110f017d 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -11,7 +11,10 @@ //! //! 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. Where a new +//! 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. @@ -25,9 +28,9 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{CALL, POP, PUSH0, STOP}, - context_interface::cfg::GasId, + context_interface::{cfg::GasId, Transaction}, interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, InstructionResult, InterpreterResult, InterpreterTypes, }, Inspector, @@ -35,7 +38,7 @@ use revm::{ use crate::salt::{ create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, - SaltEnvs, CONTRACT, EMPTY, + SaltEnvs, CALLER, CONTRACT, EMPTY, }; /// A contract `CONTRACT` calls. @@ -64,28 +67,39 @@ impl Inspector for Revives { } /// Answers every call to `target`, and every creation, itself with `result`, on the gas the frame -/// was forwarded, untouched: the frame never starts. An answered creation reports `address`. +/// 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 } + Self { target, result, address: None, fresh: false } } const fn creation(result: InstructionResult, address: Option
) -> Self { - Self { target: Address::ZERO, result, address } + 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(), untouched_call_gas(inputs)), + InterpreterResult::new(self.result, Bytes::new(), gas), inputs.return_memory_offset.clone(), ) }) @@ -93,10 +107,12 @@ impl Inspector for Answers { fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { (self.target == Address::ZERO).then(|| { - CreateOutcome::new( - InterpreterResult::new(self.result, Bytes::new(), untouched_create_gas(inputs)), - self.address, - ) + 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) }) } } @@ -122,17 +138,43 @@ 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) } /// 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. +/// 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}"); } @@ -271,7 +313,7 @@ fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas].map( |result| { let answered = - inspected(db(caller()), envs(), tx.clone(), Answers::call(EMPTY, result)); + 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); @@ -296,8 +338,7 @@ 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 = - inspected(db(Bytes::new()), envs(), tx.clone(), Answers::call(EMPTY, result)); + 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"); @@ -325,8 +366,7 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { (InstructionResult::Revert, None), ] .map(|(result, address)| { - let answered = - inspected(db(caller()), envs(), tx.clone(), Answers::creation(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); @@ -338,6 +378,34 @@ 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. +#[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, so it never stands against the state-gas /// limit. The caller then fills a slot, and a limit one gas short of the slot and the account From a64ccfb5c570218377b83be86dd819133572b49e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:31:36 -0700 Subject: [PATCH 317/458] ci(mutants): pass a diff that changes no Rust source, and scope the driver's diff to Rust sources cargo-mutants 27.1.0 has a third line for a diff that leaves it nothing to mutate, 'Diff changes no Rust source files', which the gate did not know. The driver's diff reached it: scoped to src/**, it carried the module guides under src/, so a PR editing only one failed the gate. The gate now knows the line, and the driver scopes its diff to the crate's Rust sources with :(glob), under which **/ also matches the files at the top of src/; a test holds the pathspec to every tracked .rs file under src/ and nothing else. --- scripts/mutation_gate.py | 12 ++++++++--- scripts/mutation_test.sh | 15 ++++++++----- scripts/test_mutation_gate.py | 40 +++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 5670b3bb7..b974be412 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -11,7 +11,8 @@ 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 or touches no mutant, and says so only in its output; this writes + 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. @@ -62,8 +63,13 @@ MAX_SURVIVORS_SHOWN = 20 # What cargo-mutants 27 prints, and writes no results for, when `--in-diff` -# leaves it nothing to mutate. -NOTHING_TO_MUTATE = ("No mutants to filter", "Diff file is empty") +# 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" diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 1b3a7a183..5a0328177 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -46,6 +46,10 @@ cd "$ROOT_DIR" rm -rf "$OUT_DIR" SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" +# 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' JOBS="${JOBS:-$(nproc)}" PKG_ARGS=(--package mega-evm) CONFIG_ARGS=() @@ -158,11 +162,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. 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 -- 'crates/mega-evm/src/**' > "$diff_file" + # 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) diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index fe3959650..cc52e2ee1 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -180,6 +180,10 @@ 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) @@ -287,6 +291,17 @@ def test_it_records_what_cargo_mutants_printed(self) -> None: 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) @@ -332,6 +347,31 @@ def test_results_without_outcomes_select_nothing(self) -> None: 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) + + class DriverGuard(unittest.TestCase): """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" From 7e3ead17b367a7935a68b624c809b5922b214166 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:33:04 -0700 Subject: [PATCH 318/458] docs(inspector): name the checked commit the admission gate guards The gate is checked where an outcome is produced or chosen: the pre-block changes, a transaction's execution, the end of the block and commit_transaction_outcome. 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. A test pins that sequence: the unchecked commit commits, the next execution is refused. --- AGENTS.md | 3 ++- crates/mega-evm/src/evm/inspector.rs | 15 ++++++++---- crates/mega-evm/tests/block/inspector.rs | 30 ++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0495e1fc1..5c558c883 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -365,7 +365,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. + 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. The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`), unless the transaction is latched: the creation is put back, and the latch reports the stop. diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 63e126751..5a70d596b 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -39,11 +39,16 @@ //! 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 at every entry point, before anything changes: the pre-block -//! changes, the execution of a transaction — a system transaction as a user one — the commit of an -//! outcome, and the end of the block. 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. +//! 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 //! diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index c862412f3..c6fb4415c 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -114,8 +114,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(); @@ -141,6 +141,32 @@ fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { 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, 100_000)) + .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, 100_000))), "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] From 8764f8b1ea21254568e024c646757607838fa1d3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:45:18 -0700 Subject: [PATCH 319/458] fix(inspector): take a frame's journal back when an inspector rewrites its success into a failure A success an inspector turned into a failure settled as the failure on every ledger while the journal kept its writes, so the state held an account, a slot or code nothing billed. The journal now follows the result: it is taken back to the frame's checkpoint, which survives the commit, or, for a start revm answered without building a frame, to where the start began, with the journal's depth left as it was. A creation keeps its creator's nonce bump, which revm makes before the checkpoint, as a failed creation does. The plain path is unchanged. --- AGENTS.md | 25 +- crates/mega-evm/README.md | 1 + crates/mega-evm/src/evm/execution.rs | 17 +- crates/mega-evm/src/evm/inspector.rs | 76 ++++- .../tests/satin/inspector_cheatcodes.rs | 7 +- .../tests/satin/inspector_settlement.rs | 290 +++++++++++++++++- 6 files changed, 384 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5c558c883..c2a2c5ddf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,17 +103,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 (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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, the settlement of a frame that kept nothing 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`) | — | -| `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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | -| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | +| Module | Holds now | Filled by | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, 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`) | — | +| `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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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`, `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`) | — | ### How Satin executes today @@ -376,7 +376,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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, 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 is not held: a success an inspector rewrites into a failure settles as a failure, and the writes its journal kept are on no ledger. + 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 5bb20d222..446c3f3e0 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -214,6 +214,7 @@ Outside block execution an inspector may rewrite what execution produces — Fou 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. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 619b78b99..ae91db13c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -50,7 +50,7 @@ use crate::{ access::ComputeStop, evm::{ history::transaction_body_bytes, - inspector::{frame_end_checked, StepGuard}, + inspector::{frame_end_checked, journal_position, ResultSource, StepGuard}, }, history_gas, synthetic_frame_result, system::keyless, @@ -680,7 +680,11 @@ where .map(ItemOrResult::Result); } let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); - let logs_i = ctx.journal().logs().len(); + // 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 @@ -696,7 +700,8 @@ where } } } - frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, false); + let source = ResultSource::Engine(start); + frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source); return Ok(ItemOrResult::Result(output)); } let (ctx, inspector, frame) = self.ctx_inspector_frame(); @@ -734,7 +739,8 @@ where 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, frame.depth, false); + let source = ResultSource::Engine(frame.checkpoint); + frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source); frame.set_finished(true); } next @@ -1086,7 +1092,8 @@ where 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); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output, frame_init.depth, true); + let (input, depth) = (&frame_init.frame_input, frame_init.depth); + frame_end_checked(ctx, inspector, input, &mut output, depth, ResultSource::Inspector); output } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 5a70d596b..ef093fe9d 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -66,6 +66,17 @@ //! 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. +//! - **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. //! - **The latch.** Once a limit stopped the transaction, every frame's result is the stop, //! whatever produced it: an inspector turns it into neither a success nor a halt. //! @@ -96,7 +107,7 @@ use std::{format, string::String}; use revm::{ context::{ContextError, ContextTr, JournalTr}, - context_interface::{cfg::StateGasCharge, Host}, + context_interface::{cfg::StateGasCharge, journaled_state::JournalCheckpoint, Host}, handler::FrameResult, inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ @@ -440,18 +451,34 @@ fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callbac } } +/// 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. /// /// - **The refusal.** A creation that failed, rewritten into a success, is put back and fails the /// transaction with [`FORBIDDEN_CREATE_REVIVAL`] — unless the transaction is latched, where the /// creation is put back and reports the stop, which the latch writes over every result. -/// - **A frame that kept nothing.** A frame the inspector answered in place of running -/// (`answered`), 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 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. A frame the inspector answered with a +/// Every place a frame result reaches the inspector goes through here, so all three cover 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. The latch is read after the hooks that can set /// it — the frame's run, detention's classification of its end, the hold on a start's upfront state /// gas, and the answer before building — have run, so a creation the latch stopped is never @@ -463,7 +490,7 @@ pub(crate) fn frame_end_checked( frame_input: &FrameInput, frame_result: &mut FrameResult, depth: usize, - answered: bool, + source: ResultSource, ) where DB: Database, ExtEnvs: ExternalEnvTypes, @@ -473,6 +500,15 @@ pub(crate) fn frame_end_checked( let before = frame_result.instruction_result(); frame_end(context, inspector, frame_input, frame_result); refuse_create_revival(context, before, 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); } @@ -545,6 +581,30 @@ fn settle_kept_nothing( 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. +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) { diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 640a4ade9..89f2ee517 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -13,9 +13,10 @@ //! //! 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, and a failed call `expectRevert` turns into a success settles -//! as the failure on every ledger. `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, 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}; diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index d110f017d..ead43d3db 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -1,5 +1,6 @@ //! What a frame that kept nothing settles into its caller, whatever an inspector made of its -//! result. +//! 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 @@ -27,12 +28,14 @@ use mega_evm::{ MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, POP, PUSH0, STOP}, - context_interface::{cfg::GasId, Transaction}, + bytecode::opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, + context::{ContextTr, JournalTr}, + context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr, Transaction}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, InterpreterResult, InterpreterTypes, + InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, }, + state::{AccountStatus, EvmStorageSlot}, Inspector, }; @@ -431,3 +434,282 @@ fn test_an_answered_call_holds_nothing_against_the_state_gas_limit() { assert!(answered.result.is_success(), "{:?}", answered.result); assert_eq!(answered.gas.state, slot, "the slot alone"); } + +/* ---------- 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"); +} From 4f77903e432052d3cbc6d6a244cf1453c6984c9b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:47:50 -0700 Subject: [PATCH 320/458] docs: say a Mega System Transaction is a legacy transaction to the block The block decides on the envelope before the engine promotes the transaction to a deposit, so a Mega System Transaction is held to the data-availability limits and the packing budgets like any non-deposit transaction, as in the legacy engine, and an activation block refuses it. The guide said a block cap never refuses one; it now says what the code does, and two block tests pin the activation-block refusal and the data-availability footprint it costs. --- AGENTS.md | 6 ++-- crates/mega-evm/tests/block/common.rs | 13 ++++++- crates/mega-evm/tests/block/inspector.rs | 14 +------- crates/mega-evm/tests/block/rules.rs | 43 +++++++++++++++++++++++- 4 files changed, 59 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c2a2c5ddf..923c80a24 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,7 +177,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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 them, a system transaction being promoted to a deposit. + 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. @@ -187,6 +188,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. The KV limit refuses like the data-size one. None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. + A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which the block decides on before the engine promotes it to a deposit, so it is held to the four budgets and to the data-availability limits like any non-deposit transaction, as in the legacy engine, and an activation block refuses it. 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`. Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block (see the system calls below). @@ -224,7 +226,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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` stay in the ABI with no producer: 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. -- 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, 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 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, 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::is_live_system_transaction`, called first thing in `MegaHandler::validate_env`): only a transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — reads `_currentSystemAddress` from the journal, cold and without the registry's code, and compares it with its caller. A transaction of any other shape reads nothing and is never a system-address transaction, whoever sent it: one from the system address is an ordinary transaction, validated and charged as a user's is, where the legacy engine refused it. That is the engine's view, not the contracts': the Oracle's `onlySystemAddress` tests the sender alone, so a non-legacy transaction signed by the system key to the Oracle is accepted by the Oracle and its writes land, executed as a user's transaction — it pays fees, is held to every per-transaction limit, is detained, is priced by bucket, and pays history; both engines refused it at validation before. diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index cd02342ed..b834d97c5 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -8,8 +8,9 @@ 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 alloy_sol_types::SolCall; use mega_evm::{ - system::{SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS}, + system::{IOracle, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, @@ -214,6 +215,16 @@ pub(crate) fn user_tx(nonce: u64, gas_limit: u64) -> Recovered { recovered(tx(nonce, CONTRACT, Bytes::new(), gas_limit)) } +/// A Mega System Transaction: a legacy call from the system address the registry names to the +/// Oracle's `getSlot(0)`. +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), + 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/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index c6fb4415c..afb182163 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -11,9 +11,7 @@ use alloy_evm::{ Evm, EvmFactory, FromRecoveredTx, }; use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; use mega_evm::{ - system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, MegaTxEnvelope, @@ -37,7 +35,7 @@ use std::{ sync::{Arc, Mutex}, }; -use crate::common::{self, user_tx}; +use crate::common::{self, 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. @@ -235,16 +233,6 @@ fn recording_ctx() -> MegaBlockExecutionCtx { ) } -/// A system-address transaction: a legacy call from the system address the registry names to the -/// Oracle's `getSlot(0)`. -fn system_tx() -> Recovered { - let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - Recovered::new_unchecked( - common::tx(0, ORACLE_CONTRACT_ADDRESS, input.into(), 1_000_000), - MEGA_SYSTEM_ADDRESS, - ) -} - /// 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 diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index b0567977c..7ad139019 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -18,7 +18,8 @@ use revm::{ }; use crate::common::{ - self, deposit_tx, executor, unlimited_ctx, user_tx, TestExecutor, BLOCK_GAS_LIMIT, BLOCK_NUMBER, + self, deposit_tx, 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 @@ -95,6 +96,23 @@ fn test_activation_block_rejects_a_user_transaction() { assert!(executor.receipts().is_empty(), "nothing was packed"); } +/// 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_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(&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() { @@ -147,6 +165,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] From cfd14f730bab51fc0e7ddbc41c35da4fe00f9088 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:48:44 -0700 Subject: [PATCH 321/458] docs(spec): give the two program-dependent Developer Impact figures as approximate A LOG1's and a creating value CALL's gas depend by a few gas on the code that sets them up, so the Satin page gives them as about 51,750 and about 267,240 and says so; the other three figures are exact. --- docs/spec/upgrades/satin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index f65aefa1e..7fd1cee49 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -748,7 +748,7 @@ A block MUST be invalid when: ## 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` 165,826 (97,920 of it state gas), a `LOG1` with 32 bytes of data 51,746, and a value `CALL` that creates its recipient 267,241 (183,600 of it state gas). +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` 165,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 267,240 (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. From 344c49987784956e716a113ef06cc62e5c08d853 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:48:44 -0700 Subject: [PATCH 322/458] docs(spec): state the node-added precompile rule as an implementation note A precompile a node adds or replaces is outside the Satin set, so how gas detention treats one is not protocol. The Satin page drops the MUST from its detention rules and says in an info hint what the reference implementation does. --- docs/spec/upgrades/satin.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 7fd1cee49..83c65a968 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -472,7 +472,6 @@ A contract can revert with the same bytes, so the revert data alone does not ide 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. - A precompile the node adds or replaces has no price: it MUST run on the allowance, and running out of it is the crossing. - **Interceptor answers.** A system contract's intercepted answer that spent more regular gas than the frame's allowance MUST be the crossing. - **Refused reads.** @@ -480,6 +479,11 @@ A contract can revert with the same bytes, so the revert data alone does not ide - **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 From f6e6246d02f7ef187d04fba730c91712a62f3f6c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:50:37 -0700 Subject: [PATCH 323/458] ci(mutants): say so, rather than print a traceback, under a Python older than 3.11 The gate, umutate.py and the gate's tests read TOML with tomllib, new in Python 3.11; on macOS's Python 3.9 each failed with a traceback on the import. The scripts now exit with a sentence naming the version they need and the one they run on, and the tests run one test in place of the rest that fails with that sentence: a failure rather than a skip, so a job on an old Python cannot pass on nothing tested. --- mutants/README.md | 4 ++-- scripts/mutation_gate.py | 12 +++++++++--- scripts/test_mutation_gate.py | 21 ++++++++++++++++++++- scripts/umutate.py | 10 ++++++++-- 4 files changed, 39 insertions(+), 8 deletions(-) diff --git a/mutants/README.md b/mutants/README.md index 74642834e..58606dc8f 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -43,8 +43,8 @@ python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.o MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main ``` -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 with Python 3.9 it fails before mutating anything. -The gate's own tests run with `python3 -m unittest discover -s scripts -p 'test_*.py'`, on the same Python. +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 diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index b974be412..d29d5c576 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -54,9 +54,15 @@ import json import re import sys -import tomllib -from dataclasses import dataclass, field -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/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. diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index cc52e2ee1..74df3052d 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -27,6 +27,25 @@ 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_gate(): spec = importlib.util.spec_from_file_location("mutation_gate", SCRIPTS / "mutation_gate.py") @@ -37,7 +56,7 @@ def load_gate(): return module -gate = load_gate() +gate = None if TOO_OLD else load_gate() 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" diff --git a/scripts/umutate.py b/scripts/umutate.py index 8911ac54a..b45845b46 100755 --- a/scripts/umutate.py +++ b/scripts/umutate.py @@ -46,8 +46,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" From cf1e64ed334840972dee012d546024a825c6bc3f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:51:11 -0700 Subject: [PATCH 324/458] docs(inspector): say why the step guard forwards four callbacks and what a fork upgrade checks StepGuard forwards only the callbacks revm's instruction loop makes; a forward the loop never reaches would be code nothing tests. A callback the loop gains in a later fork revision would reach no inspector until it is forwarded, so the comment says a fork upgrade checks the loop's callbacks against the guard's list. --- crates/mega-evm/src/evm/inspector.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index ef093fe9d..127e75c9c 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -318,8 +318,12 @@ where /// 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, which makes the four callbacks -/// forwarded here and no other; frame starts and ends reach the inspector 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> From 60931d98137dd3a3dbffef720b545b416aa8c646 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:51:35 -0700 Subject: [PATCH 325/458] docs(inspector): say that gas an inspector puts back carries its withheld split The withheld part is in the frame's Gas, and gas detention sets it only at a read, a frame's start or resume, and after an SSTORE. An inspector that overwrites the interpreter's gas, as Foundry's pauseGasMetering does before every instruction, overwrites the split with it until the next of those; the step guard keeps only the crossing record. --- AGENTS.md | 1 + crates/mega-evm/src/evm/inspector.rs | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 923c80a24..cf535f090 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -384,6 +384,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 127e75c9c..716afb04f 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -94,6 +94,12 @@ //! 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 From 425b11f04054ad8cfaede56ce444c43e13c8dbb1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 26 Sep 2026 23:52:03 -0700 Subject: [PATCH 326/458] test: say where the bounded callee runs out of gas at the spec's prices The comment's claim, that the callee runs out before its third write completes, holds at every price; at the spec's prices it already runs out on its second write's state gas, which the comment now says. --- crates/mega-evm/tests/satin/withheld_gas.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 1e62b5cd1..f4cc338cd 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -200,7 +200,8 @@ fn test_gas_answers_the_whole_regular_gas_after_a_read() { /// 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; above it the reservoir pays all three — each as without the read. +/// 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() From 51fb9ca551f34751892a72b4166bb631f812a6d3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 27 Sep 2026 00:30:36 -0700 Subject: [PATCH 327/458] fix(mutants): hold a run's outcomes to its selection and its end_time cargo-mutants rewrites outcomes.json after every outcome, and its total_mutants counts the outcomes recorded so far, so comparing the two passed a run that stopped part way. The gate now requires the end_time the producer sets only when the run finishes, and outcomes naming exactly the mutants mutants.json selects. umutate.py writes its selection before it tests anything and its outcomes, with an end_time, once all are tested. --- mutants/README.md | 9 ++- scripts/mutation_gate.py | 91 +++++++++++++++++------- scripts/test_mutation_gate.py | 126 +++++++++++++++++++++++++++++++--- scripts/umutate.py | 84 ++++++++++++++++------- 4 files changed, 248 insertions(+), 62 deletions(-) diff --git a/mutants/README.md b/mutants/README.md index 58606dc8f..0d27cc601 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -54,8 +54,12 @@ 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 whose baseline succeeded and whose every mutant has an outcome. -Missing results, a missing or failed baseline, or an interrupted run fail the gate with the reason, instead of reading as nothing to test. +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. @@ -90,6 +94,7 @@ 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 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)─┐ diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index d29d5c576..3a3f96f76 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -32,17 +32,24 @@ orphans --suppressions --universe Flag suppressions that match no live mutant. -The results a run leaves are read fail-closed. A run is scored from its -`outcomes.json`, cargo-mutants' own record (scripts/umutate.py writes the same -shape): `total_mutants`, and `outcomes`, each with a `scenario`, `"Baseline"` or -`{"Mutant": {"name": ...}}`, and a `summary`. It is scored only if its baseline -succeeded and every mutant has an outcome. 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 baseline that failed -or is missing, a mutant without an outcome, an outcome of a kind this script -does not know. +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. 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 @@ -54,6 +61,7 @@ import json import re import sys +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): @@ -148,19 +156,30 @@ def nothing_to_mutate(line: str) -> bool: 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.""" - listed = results / "mutants.json" - if listed.exists(): - try: - mutants = json.loads(listed.read_text()) - except json.JSONDecodeError as err: - raise ResultsError(f"{listed} is not JSON: {err}") from err - if mutants == []: + 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"{listed} lists {len(mutants)} mutants but {results} has no outcomes.json: " - f"the run stopped before it recorded an outcome" + 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(): @@ -190,12 +209,18 @@ def load_run(results: Path) -> Run: try: data = json.loads(outcomes_path.read_text()) outcomes = data["outcomes"] - total = data["total_mutants"] 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( @@ -223,12 +248,28 @@ def load_run(results: Path) -> Run: f"({', '.join(MUTANT_SUMMARIES)})" ) getattr(run, kind).append(name) - if len(mutants) != total: + + 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"{len(mutants)} of {total} mutants have an outcome in {outcomes_path}: " - f"the run was interrupted" + 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 total == 0: + if not selected: run.nothing_to_test = "the run tested no mutant" return run diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 74df3052d..39bbfb110 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -7,7 +7,7 @@ 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 and scripts/umutate.py write them, and runs the gate's +shapes cargo-mutants 27.1.0 and scripts/umutate.py write them, and runs the gate's subcommands on it. """ from __future__ import annotations @@ -47,8 +47,8 @@ def load_tests(loader: unittest.TestLoader, tests: unittest.TestSuite, return loader.loadTestsFromTestCase(PythonVersion) if TOO_OLD else tests -def load_gate(): - spec = importlib.util.spec_from_file_location("mutation_gate", SCRIPTS / "mutation_gate.py") +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 @@ -56,7 +56,8 @@ def load_gate(): return module -gate = None if TOO_OLD else load_gate() +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" @@ -64,14 +65,39 @@ def load_gate(): 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", total: int | None = None) -> dict: +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) - return {"total_mutants": len(mutants) if total is None else total, "outcomes": outcomes} + 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): @@ -80,12 +106,20 @@ def setUp(self) -> None: self.addCleanup(shutil.rmtree, self.tmp) def results(self, name: str = "mutants.out", outcomes: dict | None = None, - files: dict[str, str] | None = None) -> Path: + 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)) - for file, text in (files or {}).items(): + 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 @@ -142,9 +176,51 @@ 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_an_interrupted_run(self) -> None: - results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"), total=3)) - self.assert_unscorable(results, "1 of 3 mutants have an 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"))) @@ -291,6 +367,34 @@ def test_a_recheck_only_speaks_for_the_timeouts(self) -> None: 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.""" diff --git a/scripts/umutate.py b/scripts/umutate.py index b45845b46..b1960d5aa 100755 --- a/scripts/umutate.py +++ b/scripts/umutate.py @@ -24,10 +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 `, with the - record the gate scores: outcomes.json in cargo-mutants' shape when a - mutant was tested, and mutants.json holding [] when none was generated. - A failing baseline exits before anything is written. + , 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. @@ -35,6 +39,7 @@ from __future__ import annotations import argparse +import datetime import difflib import fnmatch import glob @@ -271,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.""" @@ -330,6 +365,7 @@ 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. @@ -359,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 "")) @@ -385,19 +430,10 @@ def write(name, items): # 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: say so as cargo-mutants does. + # baseline run, no mutant was generated, and the selection written above, + # holding [], says so as cargo-mutants does. if baselined: - 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({ - "total_mutants": len(caught) + len(missed) + len(timeouts), - "caught": len(caught), "missed": len(missed), "timeout": len(timeouts), - "unviable": 0, "outcomes": outcomes, - }, indent=2) + "\n") - else: - (out / "mutants.json").write_text("[]\n") + 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 f836bf8c0f5a647a9305c76a1dec83362e73d183 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 27 Sep 2026 00:32:20 -0700 Subject: [PATCH 328/458] fix(mutants): refuse the results of a re-check that exited abnormally The driver let a re-check that failed as a run hand its files to the gate, which scored them as a finished run's. It now records the exit in the re-check's results, and the gate refuses results so marked, with the reason. A test drives the real driver with a stand-in cargo-mutants. --- mutants/README.md | 1 + scripts/mutation_gate.py | 14 +++++- scripts/mutation_test.sh | 13 +++-- scripts/test_mutation_gate.py | 92 +++++++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 5 deletions(-) diff --git a/mutants/README.md b/mutants/README.md index 0d27cc601..a53211a97 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -64,6 +64,7 @@ A run that tested nothing passes only on the producer's own word for it: cargo-m 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) diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 3a3f96f76..1aeb3b89c 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -49,7 +49,9 @@ 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. +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 @@ -88,6 +90,10 @@ # 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", @@ -197,6 +203,12 @@ def load_run(results: Path) -> Run: 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) diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 5a0328177..3324cc9ae 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -16,8 +16,9 @@ # 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/. Run scripts/mutation_gate.py afterwards to score -# + gate the run, passing both. +# $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 @@ -148,10 +149,14 @@ recheck_timeouts() { --no-shuffle \ -vV \ "${re_args[@]}" 2>&1 | tee "$OUT_DIR/recheck.log" || rc=$? - # A re-check that fails as a run leaves the timeouts standing, and the gate - # reports its results as it finds them rather than the job ending here. + # 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 } diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 39bbfb110..b3d8bf1c2 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -250,6 +250,16 @@ def test_a_broken_recheck_of_a_timeout(self) -> None: 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.""" @@ -495,6 +505,88 @@ def test_the_pathspec_selects_every_rust_source_and_nothing_else(self) -> None: 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.""" From 51fcfaff7bbf7cb5a4aaebfb25e6f7e924549511 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 27 Sep 2026 00:35:24 -0700 Subject: [PATCH 329/458] test(satin): pin what a stop keeps from before the first frame An admitted EIP-7702 authority keeps its nonce, delegation, state gas, write record and that record's history through a stop, while the first frame's value and record come back with the frame; a stopped deposit keeps the caller it created, with its mint and state gas. --- .../mega-evm/tests/satin/state_gas_limit.rs | 71 ++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index 24091100f..b410c7910 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -16,7 +16,7 @@ use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaTransaction, - MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, + MegaTransactionOutcome, AUTHORIZATION_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -542,6 +542,75 @@ fn test_charges_before_the_first_frame_and_in_it_add_up() { assert_eq!(stopped.gas.state, authority, "the authority's state gas stays with it"); } +/// 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. +#[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()) + }; + 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 held = state_gas_of(&writes, &tx); + let stopped = run_under(writes, tx.clone(), held - 1); + assert_state_stopped("the slot after the authority", &stopped, held - 1, held); + let applied = run_under(idle, tx, u64::MAX); + 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, 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. +#[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 held = state_gas_of(&writes, &tx); + let stopped = run_under(writes, tx, held - 1); + assert_state_stopped("the slot after the caller", &stopped, held - 1, held); + let (idle, tx) = deposit(BytecodeBuilder::default().stop().build()); + let created = run_under(idle, tx, u64::MAX); + 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, one_account()); +} + /* ---------- refills give their room back ---------- */ /// The limit holds what the transaction holds net: a slot written back gives its room back, and From 9f7e5a26f17216190e23c396523ad78561f40295 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 27 Sep 2026 00:37:21 -0700 Subject: [PATCH 330/458] docs(spec): scope a stop's rollback to what the frames did A transaction-level stop reverts the frames' writes and logs, not what pre-execution applied: admitted EIP-7702 authorizations keep their nonce and delegation writes, their state gas, their records and those records' history, and a deposit keeps its mint and created caller, beside the sender's nonce and fees. Authorities that would cross a limit are still taken back before the first frame. --- AGENTS.md | 1 + docs/spec/upgrades/satin.md | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cf535f090..a6f9556b8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -352,6 +352,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A stopped creation an inspector revived is one of them: the creation-revival refusal puts it back and leaves a latched transaction to the latch rather than failing it. 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 frame budget reverts its frame alone, without a latch. + The stop 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_gas_limit.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), and EIP-7702 authorities whose state gas or records would cross it are taken back before the first frame. The one exception is the state gas an opcode charges upfront for the account the frame it starts adds: revm gives it back for a frame it refuses, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts. 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. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 83c65a968..5eb36558c 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -306,6 +306,7 @@ 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 log, a storage write's record and the record of a `SELFDESTRUCT`'s beneficiary MUST be charged by the opcode, once it completed. - 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. @@ -409,15 +410,21 @@ Every transaction-level limit — data size, KV updates, state gas, and gas dete 1. The frame that crosses the limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. 2. From then on no frame runs another instruction: a caller receiving that result MUST return the same revert instead of resuming, a frame about to start MUST be answered with it, and every result returned upward MUST be rewritten to it, whatever produced the result. -3. The transaction MUST settle like an EIP-8037 revert: it keeps none of its writes or logs; the sender pays the intrinsic gas, the body's history gas and what ran; the unspent regular gas and the reservoir return to the sender. +3. 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. 4. 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 later stop 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. + 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. The one exception is the state gas the calling opcode charges upfront for the account the frame adds: it is held once the frame is decided, so a frame built by then returns the stop before its first instruction, a frame answered without running is rewritten to the stop, and what the start moved is reverted with the frames the stop reverts. - A body over the data-size limit MUST stop the transaction before it runs: no authorization is applied, no record made outside a frame is charged, the first frame's start is charged nothing, and the first frame is answered with the stop. -- EIP-7702 authorities whose state gas or records would cross a limit MUST be taken back before the first frame. +- EIP-7702 authorities whose state gas or records would cross a limit MUST be taken back before the first frame, with their writes and the state gas applying them charged; the first frame is then answered with the stop. + Authorities admitted there are kept through a later stop, as above. A frame budget MUST revert its frame alone, with the same revert data, and its caller continues. A real out-of-gas, a precompile given less than its price, and an invalid opcode still halt and consume the frame's gas. From a5c4c472d60a9654958df79d96fd3d35de22a7d8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:00:35 -0400 Subject: [PATCH 331/458] feat(hardfork): check a scheduled fork's params values at load require_params, and so validate_schedule, now runs the params type's own validate() on the value a scheduled fork carries and reports ScheduleError::InvalidParams, so a node whose schedule type attaches its parameters without MegaHardforkConfig::with_params still refuses a bad value at load. with_params_unchecked, under test-utils, attaches a value no chain may carry for tests. --- crates/mega-evm/src/block/hardfork.rs | 91 ++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index bd0e05bfb..7c7d169a1 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -137,17 +137,26 @@ 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`. + /// Refuses a schedule that activates `P::FORK` without attaching `P`, or with a `P` its + /// [`validate`](HardforkParams::validate) refuses. /// /// 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. + /// type a fork requires; it is public so a params type can be checked on its own. The value + /// is checked here as well as in [`MegaHardforkConfig::with_params`], because a node's own + /// implementation of this trait attaches its parameters without going through that method. + /// A fork the schedule does not activate requires nothing. 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 }); + if self.mega_fork_activation(P::FORK) == ForkCondition::Never { + return Ok(()); } - Ok(()) + let params = self + .fork_params::

() + .ok_or(ScheduleError::MissingParams { fork: P::FORK, params: P::NAME })?; + params.validate().map_err(|error| ScheduleError::InvalidParams { + fork: P::FORK, + params: P::NAME, + message: error.message, + }) } /// Checks that this schedule is one a chain can run, so a configuration mistake is caught @@ -158,8 +167,8 @@ 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 + /// - The parameters every scheduled fork requires are attached, and their values pass their + /// type's own checks ([`require_params`](Self::require_params)). Satin requires /// [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) so the registry can be /// seeded at the first block. /// @@ -196,6 +205,15 @@ pub enum ScheduleError { /// The required params type, as [`HardforkParams::NAME`] names it. params: &'static str, }, + /// A scheduled fork carries parameters whose own checks refuse them. + InvalidParams { + /// The scheduled fork. + fork: MegaHardfork, + /// The params type, as [`HardforkParams::NAME`] names it. + params: &'static str, + /// What [`HardforkParams::validate`] reported. + message: String, + }, } impl fmt::Display for ScheduleError { @@ -210,6 +228,9 @@ impl fmt::Display for ScheduleError { "hardfork {fork:?} is scheduled but its {params} params are not configured" ) } + Self::InvalidParams { fork, params, message } => { + write!(f, "hardfork {fork:?} is scheduled with invalid {params} params: {message}") + } } } } @@ -329,10 +350,30 @@ impl MegaHardforkConfig { /// /// 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 { + pub fn with_params(self, params: P) -> Self { if let Err(e) = params.validate() { panic!("Invalid params for fork {:?}: {}", P::FORK, e.message); } + self.attach(params) + } + + /// Attaches `params` to the fork they belong to without checking them. + /// + /// Test tooling, behind the `test-utils` feature: it lets a test run block execution under a + /// value no chain may carry, such as limits that leave gas detention off. A production build + /// has no such route: [`with_params`](Self::with_params) checks every value it attaches, and + /// [`validate_schedule`](MegaHardforks::validate_schedule) checks them again at load. + /// + /// # Panics + /// + /// If the fork is not registered in this schedule. + #[cfg(any(test, feature = "test-utils"))] + pub fn with_params_unchecked(self, params: P) -> Self { + self.attach(params) + } + + /// Attaches `params` to their fork's entry. + fn attach(mut self, params: P) -> Self { let entry = self .entries .iter_mut() @@ -614,6 +655,36 @@ mod tests { assert_eq!(with_registry.validate_schedule(), Ok(())); } + /// A scheduled fork's params are checked at load even when they were attached without + /// [`MegaHardforkConfig::with_params`], as a node's own schedule type attaches them; an + /// unscheduled fork's are not read at all. + #[test] + fn test_require_params_refuses_a_value_its_type_refuses() { + let invalid = TestParams { sequencer: alloy_primitives::Address::ZERO }; + + let scheduled = + MegaHardforkConfig::default().with_all_activated().with_params_unchecked(invalid); + let error = scheduled.require_params::().unwrap_err(); + assert_eq!( + error, + ScheduleError::InvalidParams { + fork: MegaHardfork::Satin, + params: "TestParams", + message: "sequencer must be set".into(), + } + ); + assert_eq!( + error.to_string(), + "hardfork Satin is scheduled with invalid TestParams params: sequencer must be set" + ); + + // The same value on a schedule that never activates the fork requires nothing. + let unscheduled = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Never) + .with_params_unchecked(TestParams { sequencer: alloy_primitives::Address::ZERO }); + assert_eq!(unscheduled.require_params::(), 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] From 9467cbea732829dd3c5087f027f06ff2fd005bdc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:05:13 -0400 Subject: [PATCH 332/458] fix(hardfork): keep one params value per type of a fork A schedule entry held one params value per fork, so attaching a second params type to a fork silently replaced the first. The entry now keeps one value per type, and fork_params_any looks a value up by fork and TypeId, so a fork can require several params types as validate_schedule already allows. --- crates/mega-evm/src/block/hardfork.rs | 90 +++++++++++++++++++++------ 1 file changed, 72 insertions(+), 18 deletions(-) diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 7c7d169a1..a09516f6a 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -8,7 +8,10 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::{any::Any, fmt}; +use core::{ + any::{Any, TypeId}, + fmt, +}; use std::{boxed::Box, string::String, sync::Arc, vec, vec::Vec}; use alloy_hardforks::{hardfork, EthereumHardfork, EthereumHardforks, ForkCondition, Hardfork}; @@ -60,7 +63,8 @@ impl core::error::Error for HardforkParamsError {} /// /// 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; +/// twice. A fork may require several params types; a schedule carries one value of each. +/// [`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). @@ -89,14 +93,22 @@ 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)> { + /// The parameters of the type `params` names that are attached to `fork`, type-erased; `None` + /// when the schedule carries no value of that type for the fork. + /// + /// A fork may carry several params types, so the value is looked up by fork and type: an + /// implementation answers each `(fork, TypeId::of::

())` it holds a `P` for with that `P`. + fn fork_params_any( + &self, + _fork: MegaHardfork, + _params: TypeId, + ) -> Option<&(dyn Any + Send + Sync)> { None } - /// The parameters of the fork `P` belongs to, or `None` when the schedule carries none. + /// The `P` attached to 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::

() + self.fork_params_any(P::FORK, TypeId::of::

())?.downcast_ref::

() } /// The latest `MegaETH` fork active at `timestamp`, or `None` before the first one. @@ -237,12 +249,13 @@ 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, when it activates, and the parameters it carries, one +/// value per params type. #[derive(Debug)] struct ForkEntry { fork: Box, condition: ForkCondition, - params: Option>, + params: Vec<(TypeId, Arc)>, } impl Clone for ForkEntry { @@ -278,7 +291,7 @@ where .map(|(fork, condition)| ForkEntry { fork: Box::new(fork) as Box, condition, - params: None, + params: Vec::new(), }) .collect(), } @@ -331,7 +344,7 @@ impl MegaHardforkConfig { Self { entries: forks .into_iter() - .map(|(fork, condition)| ForkEntry { fork, condition, params: None }) + .map(|(fork, condition)| ForkEntry { fork, condition, params: Vec::new() }) .collect(), } } @@ -372,7 +385,8 @@ impl MegaHardforkConfig { self.attach(params) } - /// Attaches `params` to their fork's entry. + /// Attaches `params` to their fork's entry, replacing a value of the same type and keeping + /// the values of every other type. fn attach(mut self, params: P) -> Self { let entry = self .entries @@ -386,7 +400,11 @@ impl MegaHardforkConfig { P::FORK, ) }); - entry.params = Some(Arc::new(params)); + let value: Arc = Arc::new(params); + match entry.params.iter_mut().find(|(type_id, _)| *type_id == TypeId::of::

()) { + Some((_, slot)) => *slot = value, + None => entry.params.push((TypeId::of::

(), value)), + } self } @@ -409,7 +427,11 @@ impl MegaHardforkConfig { 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, + params: Vec::new(), + }); } } @@ -439,11 +461,13 @@ impl MegaHardforks for MegaHardforkConfig { 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()) + fn fork_params_any( + &self, + fork: MegaHardfork, + params: TypeId, + ) -> Option<&(dyn Any + Send + Sync)> { + let entry = self.entries.iter().find(|entry| entry.fork.name() == fork.name())?; + entry.params.iter().find(|(type_id, _)| *type_id == params).map(|(_, value)| value.as_ref()) } } @@ -567,6 +591,36 @@ mod tests { assert_eq!(retrieved, ¶ms()); } + /// A fork carries one value per params type: attaching a second type keeps the first, and + /// attaching a type again replaces that type's value alone. + #[test] + fn test_a_fork_carries_one_value_per_params_type() { + #[derive(Clone, Debug, PartialEq, Eq)] + struct OtherParams(u64); + + impl HardforkParams for OtherParams { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "OtherParams"; + } + + let config = MegaHardforkConfig::default() + .with_all_activated() + .with_params(params()) + .with_params(OtherParams(1)); + assert_eq!(config.fork_params::(), Some(¶ms())); + assert_eq!(config.fork_params::(), Some(&OtherParams(1))); + + let replaced = config.with_params(OtherParams(2)); + assert_eq!(replaced.fork_params::(), Some(¶ms()), "untouched"); + assert_eq!(replaced.fork_params::(), Some(&OtherParams(2))); + + // The type-erased lookup answers by fork and type. + assert!(replaced + .fork_params_any(MegaHardfork::Satin, TypeId::of::()) + .is_some_and(|value| value.downcast_ref::() == Some(&OtherParams(2)))); + assert!(replaced.fork_params_any(MegaHardfork::Satin, TypeId::of::()).is_none()); + } + #[test] fn test_fork_params_none_when_not_configured() { let config = From bc43a52f52bfd255a470fcfff6bc642eae791de9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:06:00 -0400 Subject: [PATCH 333/458] feat(limit): carry the consensus limits as Satin's ProtocolLimits params ProtocolLimits holds the limits every node of a chain must share: the per-transaction runtime limits and the block's execution-gas, state-gas, data-size and KV budgets. It is a Satin HardforkParams type, serde-ready for a chain configuration, whose validate() refuses a zero limit, a transaction data-size limit below a body and an unlimited detention cap. Its default is today's values. validate_schedule requires it, MegaHardforks::protocol_limits resolves it at a timestamp, and the unknown-chain fallback carries the default. Block execution does not read it yet. --- crates/mega-evm/src/block/chain.rs | 17 +- crates/mega-evm/src/block/hardfork.rs | 77 ++++- crates/mega-evm/src/block/limit.rs | 367 +++++++++++++++++++++++- crates/mega-evm/src/limit/mod.rs | 3 +- crates/mega-evm/tests/block/schedule.rs | 20 +- 5 files changed, 469 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 7af6f1fcf..fba9a2570 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -8,7 +8,9 @@ use alloy_hardforks::ForkCondition; use alloy_primitives::BlockTimestamp; -use crate::{system::SequencerRegistryConfig, MegaHardfork, MegaHardforkConfig, MegaSpecId}; +use crate::{ + system::SequencerRegistryConfig, MegaHardfork, MegaHardforkConfig, MegaSpecId, ProtocolLimits, +}; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -83,6 +85,9 @@ pub fn testnet_hardforks() -> MegaHardforkConfig { /// `_minRotationDelay` is [`crate::system::PLACEHOLDER_MIN_ROTATION_DELAY`]. The placeholder /// only matters when bootstrapping a fresh registry: on a chain whose registry is already /// deployed, the live roles are read from storage. +/// +/// Satin also requires its [`ProtocolLimits`]; an unknown chain runs on +/// [`ProtocolLimits::DEFAULT`]. pub fn all_activated_hardforks() -> MegaHardforkConfig { let mut config = MegaHardforkConfig::new(); for fork in MegaHardfork::VARIANTS { @@ -93,7 +98,7 @@ pub fn all_activated_hardforks() -> MegaHardforkConfig { }; config.insert(*fork, condition); } - config.with_params(SequencerRegistryConfig::placeholder()) + config.with_params(SequencerRegistryConfig::placeholder()).with_params(ProtocolLimits::DEFAULT) } /// The hardfork schedule of `chain_id`: a known chain's table, or the unknown-chain fallback. @@ -144,7 +149,8 @@ mod tests { fn test_a_scheduled_activation_resolves_at_its_timestamp() { let hf = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) } .hardforks() - .with_params(SequencerRegistryConfig::placeholder()); + .with_params(SequencerRegistryConfig::placeholder()) + .with_params(ProtocolLimits::DEFAULT); assert_eq!(hf.spec_id(1_799_999_999), None); assert_eq!(hf.spec_id(1_800_000_000), Some(MegaSpecId::SATIN)); @@ -176,6 +182,11 @@ mod tests { assert_eq!(params.initial_from_block, 0); assert_eq!(params.min_rotation_delay, PLACEHOLDER_MIN_ROTATION_DELAY); assert_ne!(params.min_rotation_delay, 0); + assert_eq!( + hf.protocol_limits(0), + Some(ProtocolLimits::DEFAULT), + "an unknown chain runs on Satin's default limits" + ); } /// [`SequencerRegistryConfig::placeholder`] is attached only by the unknown-chain fallback. diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index a09516f6a..7313fcf88 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -19,7 +19,7 @@ use alloy_op_hardforks::{OpHardfork, OpHardforks}; use alloy_primitives::{BlockTimestamp, U256}; use auto_impl::auto_impl; -use crate::MegaSpecId; +use crate::{MegaSpecId, ProtocolLimits}; hardfork! { /// `MegaETH` network upgrades that schedule a Satin-engine spec. It is expected to mix with @@ -129,6 +129,17 @@ pub trait MegaHardforks: OpHardforks { self.hardfork(timestamp).map(|fork| fork.spec_id()) } + /// The limits the protocol holds a block at `timestamp` to: the [`ProtocolLimits`] the fork + /// active there carries, or `None` when no `MegaETH` fork is active there or the fork carries + /// none. + /// + /// This is where block execution reads them; a later fork that changes a limit answers here. + fn protocol_limits(&self, timestamp: BlockTimestamp) -> Option { + match self.hardfork(timestamp)? { + MegaHardfork::Satin => self.fork_params::().copied(), + } + } + /// 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) @@ -182,7 +193,8 @@ pub trait MegaHardforks: OpHardforks { /// - The parameters every scheduled fork requires are attached, and their values pass their /// type's own checks ([`require_params`](Self::require_params)). Satin requires /// [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) so the registry can be - /// seeded at the first block. + /// seeded at the first block, and [`ProtocolLimits`], the limits every node of the chain + /// holds its blocks and transactions to. /// /// 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. @@ -196,6 +208,7 @@ pub trait MegaHardforks: OpHardforks { // Required parameters, one `self.require_params::

()?` per params type. self.require_params::()?; + self.require_params::()?; Ok(()) } @@ -703,10 +716,68 @@ mod tests { }) ); + // Satin requires both of its params types: the registry's alone does not load. let with_registry = MegaHardforkConfig::default() .with_all_activated() .with_params(crate::system::SequencerRegistryConfig::placeholder()); - assert_eq!(with_registry.validate_schedule(), Ok(())); + assert_eq!( + with_registry.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Satin, + params: "ProtocolLimits", + }) + ); + assert_eq!( + with_registry.validate_schedule().unwrap_err().to_string(), + "hardfork Satin is scheduled but its ProtocolLimits params are not configured" + ); + let with_limits = MegaHardforkConfig::default() + .with_all_activated() + .with_params(ProtocolLimits::default()); + assert_eq!( + with_limits.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Satin, + params: "SequencerRegistryConfig", + }) + ); + let with_both = with_registry.with_params(ProtocolLimits::default()); + assert_eq!(with_both.validate_schedule(), Ok(())); + + // Limits no chain may carry are refused at load, however they were attached. + let unlimited = MegaHardforkConfig::default() + .with_all_activated() + .with_params(crate::system::SequencerRegistryConfig::placeholder()) + .with_params_unchecked(ProtocolLimits::no_limits()); + assert!( + matches!( + unlimited.validate_schedule(), + Err(ScheduleError::InvalidParams { + fork: MegaHardfork::Satin, + params: "ProtocolLimits", + .. + }) + ), + "{:?}", + unlimited.validate_schedule() + ); + } + + /// A block reads the limits of the fork active at its timestamp: Satin's from its activation + /// on, and none before it or on a schedule that carries none. + #[test] + fn test_protocol_limits_are_the_active_forks_params() { + let limits = ProtocolLimits::default().with_block_kv_update_limit(7); + let config = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(100)) + .with_params(limits); + + assert_eq!(config.protocol_limits(99), None, "no MegaETH fork is active yet"); + assert_eq!(config.protocol_limits(100), Some(limits)); + assert_eq!(config.protocol_limits(u64::MAX), Some(limits)); + + let without = MegaHardforkConfig::default().with_all_activated(); + assert_eq!(without.protocol_limits(0), None, "Satin carries no limits here"); } /// A scheduled fork's params are checked at load even when they were attached without diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 5418870ec..1f5efe9c8 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -54,15 +54,198 @@ use alloy_primitives::TxHash; #[cfg(not(feature = "std"))] use alloc as std; -use std::boxed::Box; +use std::{boxed::Box, format}; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ - BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, - MegaTxLimitExceededError, + BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, HardforkParamsError, LimitUsage, + MegaBlockLimitExceededError, MegaGasUsage, MegaHardfork, MegaTxLimitExceededError, + TX_BODY_SIZE, }; +/// The limits the protocol holds every block and every transaction to: the Satin fork's +/// parameters. +/// +/// Each of them changes what a validator computes when it re-executes a block, so every node of +/// a chain holds the same values, and they travel with the chain configuration, attached to the +/// fork ([`HardforkParams`]). Block execution reads them from the schedule at the block's +/// timestamp ([`MegaHardforks::protocol_limits`](crate::MegaHardforks::protocol_limits)); a node +/// does not pass them with a block. +/// +/// - [`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 four block budgets hold what a block's transactions spend and keep together. A validator +/// refuses a block that packs a transaction after the block reached one; a builder may pack +/// tighter ([`BlockLimits`]), never looser. +/// +/// [`Default`] is [`DEFAULT`](Self::DEFAULT): the values of [`crate::constants`], provisional +/// until the economics sign-off fixes them. +#[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, write records and state gas, per transaction and per frame, and gas + /// detention's two caps. + pub tx_runtime_limits: EvmTxRuntimeLimits, + /// The most execution gas a block's transactions may spend together. The transaction that + /// reaches it is packed; after it, only a deposit is. + pub block_execution_gas_limit: u64, + /// The most state gas a block's transactions may spend together. The transaction that reaches + /// it is packed; after it, only a transaction that adds no state gas is, or a deposit. + pub block_state_gas_limit: u64, + /// 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, + /// The most write records a block's transactions may keep together: the block's KV count. The + /// transaction that reaches it is packed; after it, only a deposit is. + pub block_kv_update_limit: u64, +} + +impl Default for ProtocolLimits { + fn default() -> Self { + Self::DEFAULT + } +} + +impl ProtocolLimits { + /// Satin's limits: each transaction holds [`TX_DATA_LIMIT`] bytes of data size and a block + /// [`BLOCK_DATA_LIMIT`], a read of volatile data caps the transaction's compute at + /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] or [`ORACLE_ACCESS_COMPUTE_GAS`], and every other limit is + /// unlimited. Provisional, as the constants are. + /// + /// [`TX_DATA_LIMIT`]: crate::constants::TX_DATA_LIMIT + /// [`BLOCK_DATA_LIMIT`]: crate::constants::BLOCK_DATA_LIMIT + /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS + /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS + pub const DEFAULT: Self = Self { + tx_runtime_limits: EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) + .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) + .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS), + block_execution_gas_limit: u64::MAX, + block_state_gas_limit: u64::MAX, + block_txs_data_limit: crate::constants::BLOCK_DATA_LIMIT, + block_kv_update_limit: u64::MAX, + }; + + /// No limit at all, gas detention's caps included, so no transaction is detained + /// ([`EvmTxRuntimeLimits::no_limits`]). + /// + /// For tests and equivalence runs: [`validate`](HardforkParams::validate) refuses it, so no + /// chain configuration carries it. + pub const fn no_limits() -> Self { + Self { + tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), + block_execution_gas_limit: u64::MAX, + block_state_gas_limit: u64::MAX, + block_txs_data_limit: u64::MAX, + block_kv_update_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 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 state-gas limit. + pub const fn with_block_state_gas_limit(mut self, limit: u64) -> Self { + self.block_state_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 block's KV limit: the most write records its transactions may keep together. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_limit = limit; + self + } +} + +impl HardforkParams for ProtocolLimits { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "ProtocolLimits"; + + /// Refuses a value no chain can run on: + /// + /// - a limit of zero, which is what a field left out of a configuration reads as, and which + /// stops or refuses every transaction that uses the dimension; + /// - a transaction data-size limit below [`TX_BODY_SIZE`], the bytes every transaction's body + /// counts, which stops every transaction before it runs; + /// - an unlimited gas-detention cap: `u64::MAX` caps nothing, and a read of volatile data must + /// be held to a finite one on a chain. + /// + /// `u64::MAX` is a valid value for every other limit: it leaves the dimension unlimited. + fn validate(&self) -> Result<(), HardforkParamsError> { + let EvmTxRuntimeLimits { + tx_data_size_limit, + frame_data_size_limit, + tx_kv_update_limit, + frame_kv_update_limit, + tx_state_gas_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, + } = self.tx_runtime_limits; + let detention_caps = [ + ( + "tx_runtime_limits.block_env_access_compute_gas_limit", + block_env_access_compute_gas_limit, + ), + ("tx_runtime_limits.oracle_access_compute_gas_limit", oracle_access_compute_gas_limit), + ]; + let limits = [ + ("tx_runtime_limits.tx_data_size_limit", tx_data_size_limit), + ("tx_runtime_limits.frame_data_size_limit", frame_data_size_limit), + ("tx_runtime_limits.tx_kv_update_limit", tx_kv_update_limit), + ("tx_runtime_limits.frame_kv_update_limit", frame_kv_update_limit), + ("tx_runtime_limits.tx_state_gas_limit", tx_state_gas_limit), + detention_caps[0], + detention_caps[1], + ("block_execution_gas_limit", self.block_execution_gas_limit), + ("block_state_gas_limit", self.block_state_gas_limit), + ("block_txs_data_limit", self.block_txs_data_limit), + ("block_kv_update_limit", self.block_kv_update_limit), + ]; + + let invalid = |message| Err(HardforkParamsError { message }); + for (name, limit) in limits { + if limit == 0 { + return invalid(format!("ProtocolLimits.{name} must not be zero")); + } + } + if tx_data_size_limit < TX_BODY_SIZE { + return invalid(format!( + "ProtocolLimits.tx_runtime_limits.tx_data_size_limit must be at least \ + {TX_BODY_SIZE}, the bytes every transaction's body counts" + )); + } + for (name, cap) in detention_caps { + if cap == u64::MAX { + return invalid(format!( + "ProtocolLimits.{name} must be finite: u64::MAX leaves a read of volatile \ + data undetained" + )); + } + } + Ok(()) + } +} + /// The limits one block holds its transactions to. /// /// [`Default`] carries the production data-size caps and leaves every other dimension unlimited. @@ -506,8 +689,186 @@ fn invalid_tx( #[cfg(test)] mod tests { use super::*; + use crate::{MegaHardforkConfig, MegaHardforks}; use alloy_primitives::B256; + /// The protocol's default limits, written out so a change to one is a visible diff: today's + /// provisional constants, and unlimited everywhere else. + #[test] + fn test_the_default_protocol_limits_are_the_provisional_constants() { + use crate::constants::{ + BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, + TX_DATA_LIMIT, + }; + assert_eq!(ProtocolLimits::default(), ProtocolLimits::DEFAULT); + assert_eq!( + ProtocolLimits::DEFAULT, + ProtocolLimits { + tx_runtime_limits: EvmTxRuntimeLimits { + tx_data_size_limit: TX_DATA_LIMIT, + frame_data_size_limit: u64::MAX, + tx_kv_update_limit: u64::MAX, + frame_kv_update_limit: u64::MAX, + tx_state_gas_limit: u64::MAX, + block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, + oracle_access_compute_gas_limit: ORACLE_ACCESS_COMPUTE_GAS, + }, + block_execution_gas_limit: u64::MAX, + block_state_gas_limit: u64::MAX, + block_txs_data_limit: BLOCK_DATA_LIMIT, + block_kv_update_limit: u64::MAX, + } + ); + assert_eq!( + ProtocolLimits::DEFAULT.tx_runtime_limits, + EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_DATA_LIMIT), + "a transaction's defaults are a bare context's, with the data-size limit" + ); + assert_eq!(ProtocolLimits::DEFAULT.validate(), Ok(())); + } + + /// The limits travel with a chain configuration: they survive a round trip through its JSON, + /// whose shape is written out here, and through a schedule, which hands back what was + /// attached. + #[test] + fn test_protocol_limits_round_trip() { + let limits = ProtocolLimits::DEFAULT + .with_tx_runtime_limits( + ProtocolLimits::DEFAULT + .tx_runtime_limits + .with_frame_data_size_limit(1) + .with_tx_kv_update_limit(2) + .with_frame_kv_update_limit(3) + .with_tx_state_gas_limit(4), + ) + .with_block_execution_gas_limit(5) + .with_block_state_gas_limit(6) + .with_block_txs_data_limit(7) + .with_block_kv_update_limit(8); + + let json = serde_json::to_string(&limits).expect("serializes"); + assert_eq!( + json, + r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"frameDataSizeLimit":1,"txKvUpdateLimit":2,"frameKvUpdateLimit":3,"txStateGasLimit":4,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockExecutionGasLimit":5,"blockStateGasLimit":6,"blockTxsDataLimit":7,"blockKvUpdateLimit":8}"# + ); + assert_eq!(serde_json::from_str::(&json).expect("deserializes"), limits); + + // A field left out is an error, not a zero; so is one the type does not have. + let missing = json.replace(r#","blockKvUpdateLimit":8"#, ""); + assert!(serde_json::from_str::(&missing).is_err(), "{missing}"); + let missing_tx = json.replace(r#""txStateGasLimit":4,"#, ""); + assert!(serde_json::from_str::(&missing_tx).is_err(), "{missing_tx}"); + let unknown = json.replace(r#""blockKvUpdateLimit":8"#, r#""blockKvUpdateLimit":8,"x":1"#); + assert!(serde_json::from_str::(&unknown).is_err(), "{unknown}"); + + let schedule = MegaHardforkConfig::default().with_all_activated().with_params(limits); + assert_eq!(schedule.fork_params::(), Some(&limits)); + assert_eq!(schedule.protocol_limits(0), Some(limits)); + } + + /// Every limit refuses zero, the value a field left out of a configuration reads as; the + /// transaction's data size refuses less than a body; the detention caps refuse `u64::MAX`, + /// and every other limit accepts it. + #[test] + fn test_validate_refuses_what_no_chain_can_run_on() { + let base = ProtocolLimits::DEFAULT; + let tx = |f: fn(EvmTxRuntimeLimits, u64) -> EvmTxRuntimeLimits, value| { + base.with_tx_runtime_limits(f(base.tx_runtime_limits, value)) + }; + type Set = fn(ProtocolLimits, u64) -> ProtocolLimits; + let fields: [(&str, Set); 11] = [ + ("tx_runtime_limits.tx_data_size_limit", |l, v| { + l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_data_size_limit(v)) + }), + ("tx_runtime_limits.frame_data_size_limit", |l, v| { + l.with_tx_runtime_limits(l.tx_runtime_limits.with_frame_data_size_limit(v)) + }), + ("tx_runtime_limits.tx_kv_update_limit", |l, v| { + l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_kv_update_limit(v)) + }), + ("tx_runtime_limits.frame_kv_update_limit", |l, v| { + l.with_tx_runtime_limits(l.tx_runtime_limits.with_frame_kv_update_limit(v)) + }), + ("tx_runtime_limits.tx_state_gas_limit", |l, v| { + l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_state_gas_limit(v)) + }), + ("tx_runtime_limits.block_env_access_compute_gas_limit", |l, v| { + l.with_tx_runtime_limits( + l.tx_runtime_limits.with_block_env_access_compute_gas_limit(v), + ) + }), + ("tx_runtime_limits.oracle_access_compute_gas_limit", |l, v| { + l.with_tx_runtime_limits( + l.tx_runtime_limits.with_oracle_access_compute_gas_limit(v), + ) + }), + ("block_execution_gas_limit", ProtocolLimits::with_block_execution_gas_limit), + ("block_state_gas_limit", ProtocolLimits::with_block_state_gas_limit), + ("block_txs_data_limit", ProtocolLimits::with_block_txs_data_limit), + ("block_kv_update_limit", ProtocolLimits::with_block_kv_update_limit), + ]; + + for (name, set) in fields { + assert_eq!( + set(base, 0).validate(), + Err(HardforkParamsError { + message: std::format!("ProtocolLimits.{name} must not be zero") + }), + "{name}" + ); + assert_eq!( + set(base, 1).validate().is_ok(), + name != "tx_runtime_limits.tx_data_size_limit", + "{name} at one" + ); + let unlimited = set(base, u64::MAX).validate(); + if name.ends_with("compute_gas_limit") { + assert_eq!( + unlimited, + Err(HardforkParamsError { + message: std::format!( + "ProtocolLimits.{name} must be finite: u64::MAX leaves a read of \ + volatile data undetained" + ) + }), + "{name}" + ); + assert_eq!(set(base, u64::MAX - 1).validate(), Ok(()), "{name} just below"); + } else { + assert_eq!(unlimited, Ok(()), "{name} may be unlimited"); + } + } + + // The transaction's data size holds at least a body, and exactly a body is enough. + assert_eq!( + tx(EvmTxRuntimeLimits::with_tx_data_size_limit, TX_BODY_SIZE - 1).validate(), + Err(HardforkParamsError { + message: std::format!( + "ProtocolLimits.tx_runtime_limits.tx_data_size_limit must be at least \ + {TX_BODY_SIZE}, the bytes every transaction's body counts" + ) + }) + ); + assert_eq!( + tx(EvmTxRuntimeLimits::with_tx_data_size_limit, TX_BODY_SIZE).validate(), + Ok(()) + ); + + // The unlimited set of tests and equivalence runs is refused. + assert!(ProtocolLimits::no_limits().validate().is_err()); + } + + /// A schedule refuses to carry the unlimited set, so no validated chain configuration does. + #[test] + #[should_panic(expected = "Invalid params for fork Satin: \ + ProtocolLimits.tx_runtime_limits.block_env_access_compute_gas_limit must be \ + finite")] + fn test_a_schedule_refuses_the_unlimited_protocol_limits() { + let _ = MegaHardforkConfig::default() + .with_all_activated() + .with_params(ProtocolLimits::no_limits()); + } + /// A block that configures nothing holds the production data-size caps and gas detention's /// caps, and nothing else. #[test] diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0c4fe748e..8851ee709 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -258,7 +258,8 @@ pub struct LimitUsage { /// /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[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. pub tx_data_size_limit: u64, diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index 856e0775b..f26c0c5a6 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -4,8 +4,8 @@ use alloy_evm::block::BlockExecutor; use alloy_hardforks::ForkCondition; use mega_evm::{ chain_activation, mainnet_hardforks, system::SequencerRegistryConfig, testnet_hardforks, - MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError, MAINNET_CHAIN_ID, - TESTNET_CHAIN_ID, + MegaHardfork, MegaHardforkConfig, MegaHardforks, ProtocolLimits, ScheduleError, + MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, }; use crate::common::{self, registry_config, user_tx}; @@ -64,11 +64,20 @@ fn test_a_schedule_missing_its_fork_params_is_refused_at_load() { }), ); - // With the parameters attached the schedule loads, and a block runs on it. - let loaded = missing.with_params(registry_config()); - assert_eq!(loaded.require_params::(), Ok(())); + // The registry's alone is not enough: Satin requires its limits too. + let registry_only = missing.with_params(registry_config()); + assert_eq!(registry_only.require_params::(), Ok(())); + assert_eq!( + registry_only.validate_schedule(), + Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "ProtocolLimits" }), + ); + + // With both attached the schedule loads, and a block runs on it. + let loaded = registry_only.with_params(ProtocolLimits::DEFAULT); + assert_eq!(loaded.require_params::(), Ok(())); assert_eq!(loaded.validate_schedule(), Ok(())); assert_eq!(loaded.fork_params::(), Some(®istry_config())); + assert_eq!(loaded.fork_params::(), Some(&ProtocolLimits::DEFAULT)); let mut state = common::state(); let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), loaded); @@ -82,5 +91,6 @@ fn test_an_unscheduled_fork_needs_no_params() { let unscheduled = MegaHardforkConfig::default(); assert_eq!(unscheduled.require_params::(), Ok(())); + assert_eq!(unscheduled.require_params::(), Ok(())); assert_eq!(unscheduled.validate_schedule(), Ok(())); } From 9a959e375a681ca5eb5ded3ec2b13d7f69e942fb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:15:12 -0400 Subject: [PATCH 334/458] feat(block): read the consensus limits from the schedule, not the block context MegaBlockExecutor now reads the ProtocolLimits of the fork active at the block's timestamp: it installs their per-transaction limits on the EVM at construction and again before every transaction, and holds the block to their four budgets. BlockLimits in the block context is the builder's policy only: the transaction gas, encoded-size and data-availability limits, and caps that can lower a block budget but never raise it (BlockLimits::within); its default restricts nothing. A block whose schedule carries no limits is refused before it starts (MissingProtocolLimits). The limiter is no longer a public field. Block tests run on a test chain whose limits are the unlimited set, attached through the test-only unchecked route, so each test runs under the limits it ran under before; a test that holds a block to a limit attaches its own. --- crates/mega-evm/benches/block.rs | 10 +- crates/mega-evm/src/access/mod.rs | 13 +- crates/mega-evm/src/block/executor.rs | 122 ++++++++- crates/mega-evm/src/block/factory.rs | 11 +- crates/mega-evm/src/block/limit.rs | 237 +++++++++++------- crates/mega-evm/src/constants.rs | 17 +- crates/mega-evm/src/evm/mod.rs | 6 +- crates/mega-evm/src/limit/mod.rs | 15 +- crates/mega-evm/tests/block/common.rs | 56 +++-- crates/mega-evm/tests/block/deploy.rs | 5 +- crates/mega-evm/tests/block/detention.rs | 15 +- crates/mega-evm/tests/block/eips.rs | 14 +- crates/mega-evm/tests/block/factory.rs | 110 ++++---- crates/mega-evm/tests/block/limits.rs | 9 +- .../tests/block/sequencer_registry.rs | 2 +- crates/mega-evm/tests/satin/detention.rs | 10 +- 16 files changed, 443 insertions(+), 209 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 080fd0ece..486788071 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -5,8 +5,8 @@ //! //! - on a state that already holds the seven predeploys, which a chain deploys once, in its first //! block after activation: the state the previous block's pre-block changes left; -//! - under the limits a block runs under when its caller configures nothing else, -//! `BlockLimits::default()`: the production data-size limits and gas detention's caps; +//! - under the chain's default limits, `ProtocolLimits::DEFAULT`: 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 @@ -38,7 +38,7 @@ use mega_evm::{ system::{SequencerRegistryConfig, SYSTEM_CONTRACT_DEPLOY_COUNT}, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, PreBlockStateSource, + MegaSpecId, MegaTxEnvelope, PreBlockStateSource, ProtocolLimits, }; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, @@ -119,7 +119,8 @@ fn evm_env() -> EvmEnv { evm_env_at(BLOCK_NUMBER) } -/// A block under the limits a block runs under when its caller configures nothing else. +/// 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::default()) } @@ -153,6 +154,7 @@ fn chain_spec() -> MegaHardforkConfig { MegaHardforkConfig::default() .with_all_activated() .with_params(SequencerRegistryConfig::placeholder()) + .with_params(ProtocolLimits::DEFAULT) } /// Runs the pre-block changes of block `number` on `db` and returns what they handed their diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 8efc48b54..d48f7ef11 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -17,12 +17,13 @@ //! //! The caps are runtime limits ([`EvmTxRuntimeLimits`](crate::EvmTxRuntimeLimits)): the spec's, //! [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) and -//! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default, and a -//! caller's limits may set either. 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. +//! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default. In block +//! execution they are the chain's ([`ProtocolLimits`](crate::ProtocolLimits)), which must be +//! finite; a standalone EVM's caller may set either. 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 diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index eaa158406..d0d7ed066 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -4,6 +4,16 @@ //! 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 limits every node must agree on are the chain's: the executor reads the +//! [`ProtocolLimits`] the fork active at the block's timestamp carries +//! ([`MegaHardforks::protocol_limits`]), installs their per-transaction half on the EVM before +//! every transaction, and holds the block to their four budgets. The node's context adds only the +//! builder's policy ([`BlockLimits`]), which can tighten a budget and never loosen one; a validator +//! leaves it at its default. A block whose schedule carries no limits at its timestamp is refused +//! before anything runs. +//! //! # The block rules of the Karst base //! //! - **An activation block admits only deposits.** The caller sets @@ -115,13 +125,15 @@ use crate::{ }, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, 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 activation-block flag and the builder's +/// packing policy. The limits the protocol holds the block to are not here: they are the chain's +/// ([`ProtocolLimits`]), read from the schedule. #[derive(Clone, Debug, Default)] pub struct MegaBlockExecutionCtx { /// The parent block's hash, which the EIP-2935 pre-block call records. @@ -136,7 +148,11 @@ 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. + /// The builder's packing policy: the limits only a builder applies, and caps on the block's + /// budgets 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, } @@ -191,6 +207,12 @@ pub enum MegaBlockExecutionError { }, /// Satin is scheduled but the schedule does not carry a [`SequencerRegistryConfig`]. MissingSequencerRegistryConfig, + /// The schedule carries no [`ProtocolLimits`] for the block's timestamp: no `MegaETH` fork is + /// active there, or the fork active there carries none. + MissingProtocolLimits { + /// The block's timestamp. + timestamp: u64, + }, /// The EIP-7997 factory holds the right runtime but nonce 0. ZeroFactoryNonce { /// The factory address. @@ -236,6 +258,10 @@ impl fmt::Display for MegaBlockExecutionError { Self::MissingSequencerRegistryConfig => { f.write_str("Satin is scheduled but SequencerRegistryConfig is not configured") } + Self::MissingProtocolLimits { timestamp } => write!( + f, + "the schedule carries no ProtocolLimits for the block at timestamp {timestamp}" + ), Self::ZeroFactoryNonce { address } => write!( f, "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" @@ -323,8 +349,12 @@ 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, + /// 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 schedule holds this block to, read at the block's timestamp; `None` when it + /// carries none there, which refuses the block. + protocol_limits: Option, /// 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. @@ -376,25 +406,39 @@ 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 come from `spec`, at the block environment's timestamp + /// ([`MegaHardforks::protocol_limits`]): 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 the chain's limits, + /// whatever the caller did or did not apply to the EVM. The block is held to the protocol's + /// budgets, each 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. + /// + /// A schedule with no limits at the block's timestamp builds an executor all the same; the + /// block is refused at its first entry point + /// ([`MegaBlockExecutionError::MissingProtocolLimits`]). 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); + let protocol_limits = spec.protocol_limits(timestamp); + let policy = match &protocol_limits { + Some(protocol) => { + evm.set_tx_runtime_limits(protocol.tx_runtime_limits); + ctx.block_limits.within(protocol) + } + None => ctx.block_limits, + }; + let limits = policy.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), @@ -404,9 +448,15 @@ where evm, receipts: Vec::new(), limiter: limits.to_block_limiter(), + protocol_limits, pre_block_observer: OptionalPreBlockObserver(None), } } + + /// The limits the schedule holds this block to, read at the block's timestamp. + pub const fn protocol_limits(&self) -> Option<&ProtocolLimits> { + self.protocol_limits.as_ref() + } } impl MegaBlockExecutor, R, Spec> @@ -484,6 +534,17 @@ where self.limiter.post_execution_check(output.tx_hash, &output.block_usage()) } + /// The limits the schedule holds this block to, or the refusal of a block whose schedule + /// carries none at its timestamp. + fn require_protocol_limits(&self) -> Result { + self.protocol_limits.ok_or_else(|| { + MegaBlockExecutionError::MissingProtocolLimits { + timestamp: self.evm.block().timestamp().saturating_to(), + } + .into() + }) + } + /// 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 @@ -567,6 +628,7 @@ where /// nothing inside the block can change it again. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; + self.require_protocol_limits()?; // The block starts with an empty block-hash record, so what it holds at the end is what // this block read. @@ -818,6 +880,7 @@ where BlockExecutionError, > { self.check_admission()?; + let limits = self.require_protocol_limits()?; let (tx_env, tx) = tx.into_parts(); let inner = tx.tx(); @@ -885,6 +948,9 @@ where None }; + // The transaction runs under the chain's limits, whatever was set on the EVM since the + // last one. + self.evm.set_tx_runtime_limits(limits.tx_runtime_limits); let outcome = self .evm .execute_transaction(tx_env) @@ -958,16 +1024,17 @@ mod tests { let mut executor = MegaBlockExecutor::new( MegaEvm::new(ctx), MegaBlockExecutionCtx::default(), - MegaHardforkConfig::default().with_all_activated(), + MegaHardforkConfig::default().with_all_activated().with_params(ProtocolLimits::DEFAULT), 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); + assert_eq!(executor.protocol_limits(), Some(&ProtocolLimits::DEFAULT)); assert_eq!( executor.evm().tx_runtime_limits().tx_data_size_limit, crate::constants::TX_DATA_LIMIT, - "a default block installs the production per-transaction data-size cap" + "a default chain installs the production per-transaction data-size cap" ); assert_eq!(executor.evm().tx_runtime_limits().frame_data_size_limit, u64::MAX); assert_eq!( @@ -978,6 +1045,37 @@ mod tests { assert!(executor.into_evm().is_inspecting()); } + /// A schedule that carries no limits at the block's timestamp refuses the block before any + /// pre-block step runs: the block is not executed under limits nobody chose. + #[test] + fn test_a_block_without_protocol_limits_is_refused_before_it_starts() { + let ctx = + MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN).with_block(BlockEnv { + timestamp: alloy_primitives::U256::from(7), + ..Default::default() + }); + let mut executor = MegaBlockExecutor::new( + MegaEvm::new(ctx), + MegaBlockExecutionCtx::default(), + MegaHardforkConfig::default() + .with_all_activated() + .with_params(crate::system::SequencerRegistryConfig::placeholder()), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ); + + assert_eq!(executor.protocol_limits(), None); + let error = executor.apply_pre_execution_changes().expect_err("no limits, no block"); + assert_eq!( + error.to_string(), + MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 }.to_string() + ); + assert_eq!( + error.to_string(), + "the schedule carries no ProtocolLimits for the block at timestamp 7" + ); + assert!(executor.receipts().is_empty()); + } + /// The executor prints whether a pre-block observer is installed. A trait object has no /// `Debug`, so the observer is reported as a flag rather than dropped: a reader of a node's /// log can tell a block whose pre-block states were witnessed from one whose were not. diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index 2862938d6..7b452d100 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -16,8 +16,9 @@ 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, with the limits the +/// protocol holds a block to, the EVM factory and the receipt builder — and each block adds its +/// own [`MegaBlockExecutionCtx`]. #[derive(Clone, Debug, Default)] pub struct MegaBlockExecutorFactory { receipt_builder: R, @@ -101,9 +102,9 @@ 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 chain's limits at the block's timestamp are installed by [`MegaBlockExecutor::new`], + /// from the factory's schedule, so an EVM the caller built without them, or 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/limit.rs b/crates/mega-evm/src/block/limit.rs index 1f5efe9c8..d37df486a 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -1,11 +1,21 @@ //! 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. Data size defaults to the -//! production caps — [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) for the block and -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) for each transaction — gas detention's caps -//! to the spec's, and every other limit to unlimited. [`BlockLimits::no_limits`] clears the -//! data-size and detention caps too. +//! The limits come from two places, by who must agree on them: +//! +//! - [`ProtocolLimits`] are the limits every node of a chain holds its blocks and transactions to, +//! because a different value is a different result: the per-transaction limits the EVM enforces +//! and the block's four budgets. They are the Satin fork's parameters, read from the schedule at +//! the block's timestamp, and their default is [`ProtocolLimits::DEFAULT`]: data size capped at +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) per transaction and +//! [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) per block, gas detention's caps at +//! the spec's, and every other limit unlimited. +//! - [`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 caps a builder may put on the block's budgets 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 //! @@ -45,10 +55,10 @@ //! Of the three gas ledgers the block counts ([`BlockGasCounters`]), execution and state have a //! block limit. History has none by design; the history bytes beside it are reported, not //! limited. The write-record count, which is the block's KV count, has one too: -//! [`BlockLimits::block_kv_update_limit`]. Every record weighs forty bytes of data size, so a +//! [`ProtocolLimits::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 whatever its KV limit; the KV limit binds only below that, and is unlimited unless a -//! node sets it. +//! records whatever its KV limit; the KV limit binds only below that, and is unlimited unless the +//! chain sets it. use alloy_primitives::TxHash; @@ -246,12 +256,25 @@ impl HardforkParams for ProtocolLimits { } } -/// The limits one block holds its transactions to. +/// The building policy one block is packed under: the limits only a builder applies, and the +/// caps it may put on the block's 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 chain's +/// schedule, 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. /// -/// [`Default`] carries the production data-size caps and leaves every other dimension unlimited. -/// [`no_limits`](Self::no_limits) clears the data-size caps too. A node sets the dimensions its -/// chain configures, and the block executor always sets -/// [`block_gas_limit`](Self::block_gas_limit) from the block environment. +/// - [`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. +/// - The four block budgets are the builder's caps on the protocol's: the block executor holds a +/// block to the smaller of the two. +/// - [`block_gas_limit`](Self::block_gas_limit) is the header's: the block executor always sets it +/// from the block environment. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct BlockLimits { /// The most gas a single transaction may declare. @@ -272,42 +295,43 @@ pub struct BlockLimits { /// The most execution gas the block's transactions may spend 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_execution_gas_limit`]. pub block_execution_gas_limit: u64, /// The most state gas the block's transactions may spend together. The transaction that /// reaches it is packed; after it, only a transaction that adds no state gas is, or a deposit, /// 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_state_gas_limit`]. pub block_state_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. /// - /// [`Default`] is [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT). 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 most write records the block's transactions may keep together: the block's KV count. - /// /// The transaction that reaches it is packed; after it, only a deposit is, which it never /// refuses and which counts towards it. - pub block_kv_update_limit: u64, - /// The limits every transaction of the block runs under, which the executor installs on the - /// EVM. /// - /// [`Default`] sets the transaction data-size limit to - /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) and leaves the frame cap unlimited, so a - /// frame's budget is the 98% share of what its parent has left; gas detention's caps are the - /// spec's, as [`EvmTxRuntimeLimits::default`] holds them. - pub tx_runtime_limits: EvmTxRuntimeLimits, + /// A builder's cap: the block is held to the smaller of this and + /// [`ProtocolLimits::block_kv_update_limit`]. + pub block_kv_update_limit: u64, } impl Default for BlockLimits { + /// No restriction: what a validator passes. fn default() -> Self { - Self::with_production_data_limits() + Self::no_limits() } } impl BlockLimits { - /// No limit at all, gas detention's caps included, so no transaction of the block is - /// detained ([`EvmTxRuntimeLimits::no_limits`]): for benches and tests, not for executing the - /// chain. + /// 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, @@ -320,25 +344,22 @@ impl BlockLimits { block_state_gas_limit: u64::MAX, block_txs_data_limit: u64::MAX, block_kv_update_limit: u64::MAX, - tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), } } - /// The limits a block runs under when its caller configures nothing else. - /// - /// Every dimension is unlimited except data size and gas detention's caps: the block holds - /// [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) bytes, each transaction holds - /// [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT), and a read of volatile data caps the - /// transaction's compute at the spec's caps. The block executor installs the transaction half - /// on the EVM. - pub const fn with_production_data_limits() -> Self { - let mut limits = Self::no_limits(); - limits.block_txs_data_limit = crate::constants::BLOCK_DATA_LIMIT; - limits.tx_runtime_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) - .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) - .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS); - limits + /// These limits held within `protocol`: each of the block's four budgets 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 one. The limits only a builder applies are kept as they are. + pub fn within(self, protocol: &ProtocolLimits) -> Self { + Self { + block_execution_gas_limit: self + .block_execution_gas_limit + .min(protocol.block_execution_gas_limit), + block_state_gas_limit: self.block_state_gas_limit.min(protocol.block_state_gas_limit), + 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), + ..self + } } /// Sets the per-transaction gas limit. @@ -380,41 +401,30 @@ impl BlockLimits { self } - /// Sets the block's execution-gas limit. + /// Caps the block's execution gas. pub const fn with_block_execution_gas_limit(mut self, limit: u64) -> Self { self.block_execution_gas_limit = limit; self } - /// Sets the block's state-gas limit. + /// Caps the block's state gas. pub const fn with_block_state_gas_limit(mut self, limit: u64) -> Self { self.block_state_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 block's KV limit: the most write records its transactions may keep together. + /// Caps the block's KV count: the write records its transactions may keep together. pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { self.block_kv_update_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) @@ -869,30 +879,89 @@ mod tests { .with_params(ProtocolLimits::no_limits()); } - /// A block that configures nothing holds the production data-size caps and gas detention's - /// caps, and nothing else. + /// 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_limits_are_the_production_data_size_caps() { - let limits = BlockLimits::default(); - assert_eq!(limits, BlockLimits::with_production_data_limits()); - assert_eq!(limits.block_txs_data_limit, crate::constants::BLOCK_DATA_LIMIT); - assert_eq!(limits.tx_runtime_limits.tx_data_size_limit, crate::constants::TX_DATA_LIMIT); + fn test_the_default_building_policy_restricts_nothing() { + assert_eq!(BlockLimits::default(), BlockLimits::no_limits()); + let BlockLimits { + tx_gas_limit, + block_gas_limit, + tx_encode_size_limit, + block_txs_encode_size_limit, + tx_da_size_limit, + block_da_size_limit, + block_execution_gas_limit, + block_state_gas_limit, + block_txs_data_limit, + block_kv_update_limit, + } = BlockLimits::default(); + for limit in [ + tx_gas_limit, + block_gas_limit, + tx_encode_size_limit, + block_txs_encode_size_limit, + tx_da_size_limit, + block_da_size_limit, + block_execution_gas_limit, + block_state_gas_limit, + block_txs_data_limit, + block_kv_update_limit, + ] { + assert_eq!(limit, u64::MAX); + } + assert_eq!( + BlockLimits::default().within(&ProtocolLimits::DEFAULT).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 a block 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::DEFAULT + .with_block_execution_gas_limit(100) + .with_block_state_gas_limit(200) + .with_block_txs_data_limit(300) + .with_block_kv_update_limit(400); + + let tighter = BlockLimits::no_limits() + .with_block_execution_gas_limit(10) + .with_block_state_gas_limit(20) + .with_block_txs_data_limit(30) + .with_block_kv_update_limit(40) + .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) + .with_block_gas_limit(6); + assert_eq!(tighter.within(&protocol), tighter, "every cap is below the protocol's"); + + let looser = BlockLimits::no_limits() + .with_block_execution_gas_limit(1_000) + .with_block_state_gas_limit(2_000) + .with_block_txs_data_limit(3_000) + .with_block_kv_update_limit(4_000); + let held = looser.within(&protocol); + assert_eq!( + ( + held.block_execution_gas_limit, + held.block_state_gas_limit, + held.block_txs_data_limit, + held.block_kv_update_limit, + ), + (100, 200, 300, 400), + "a cap above the protocol's gives way to it" + ); assert_eq!( - limits.tx_runtime_limits, - EvmTxRuntimeLimits::default().with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) + BlockLimits { tx_gas_limit: 7, ..held }, + BlockLimits { tx_gas_limit: 7, ..BlockLimits::no_limits().within(&protocol) }, + "nothing else changes" ); - assert_eq!(limits.tx_runtime_limits.frame_data_size_limit, u64::MAX); - assert_eq!(limits.tx_gas_limit, u64::MAX); - assert_eq!(limits.block_execution_gas_limit, u64::MAX); - assert_eq!(limits.block_state_gas_limit, u64::MAX); - assert_eq!(limits.block_kv_update_limit, u64::MAX); - assert_eq!(limits.tx_runtime_limits.tx_kv_update_limit, u64::MAX); - assert_eq!(limits.tx_runtime_limits.frame_kv_update_limit, u64::MAX); - - let unlimited = BlockLimits::no_limits(); - assert_eq!(unlimited.block_txs_data_limit, u64::MAX); - assert_eq!(unlimited.block_kv_update_limit, u64::MAX); - assert_eq!(unlimited.tx_runtime_limits, EvmTxRuntimeLimits::no_limits()); } fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { @@ -1171,7 +1240,7 @@ mod tests { /// The history ledger and the history bytes are accumulated, and no check refuses a /// transaction on them; nor on the state ledger or the write records, whose limits are - /// unlimited unless a node sets them. + /// unlimited unless the chain sets them. #[test] fn test_history_is_counted_but_not_enforced() { let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 0176019ab..97a430839 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -13,21 +13,24 @@ //! | [`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 block's default transaction limits | -//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the block's default data-size limit | -//! | [`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) | the default detention cap of the runtime limits | -//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits | +//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the default protocol limits | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the default 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) | the default detention cap of the runtime limits and of the protocol limits | +//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits and of the protocol limits | //! //! 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 state-gas limits are not fixed here either: the per-transaction one is +//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`] and the two detention caps are the defaults of the +//! Satin fork's parameters, [`ProtocolLimits::DEFAULT`](crate::ProtocolLimits::DEFAULT): a chain +//! carries its own in its configuration, and block execution reads them from there. The state-gas +//! limits have no constant at all: the per-transaction one is //! [`EvmTxRuntimeLimits::tx_state_gas_limit`](crate::EvmTxRuntimeLimits::tx_state_gas_limit) and //! the per-block one -//! [`BlockLimits::block_state_gas_limit`](crate::BlockLimits::block_state_gas_limit). A node sets -//! both, and both are unlimited by default. +//! [`ProtocolLimits::block_state_gas_limit`](crate::ProtocolLimits::block_state_gas_limit). A chain +//! sets both, and both are unlimited by default. use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 4214a9eb7..400e1e8e9 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -207,8 +207,10 @@ impl MegaEvm { /// 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. + /// Block execution installs the chain's limits this way before every transaction + /// ([`ProtocolLimits`](crate::ProtocolLimits)), so a block's transaction runs under them + /// whatever the caller configured on the EVM. Outside block execution — an RPC call, a tool, + /// a test — this is how the caller chooses the limits a transaction runs under. #[must_use] pub fn with_tx_runtime_limits(mut self, limits: crate::EvmTxRuntimeLimits) -> Self { self.set_tx_runtime_limits(limits); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 8851ee709..414f359d8 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -116,9 +116,11 @@ //! `m` times the minimum costs `m` times the schedule's entry, and reaches the limit that many //! times sooner. //! -//! Every limit is unlimited unless a caller sets it. A block executor installs the ones its block -//! limits carry, whose default holds a transaction to -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size and to nothing else. +//! Every limit is unlimited unless a caller sets it, gas detention's caps aside. A block executor +//! installs the chain's, the per-transaction half of the Satin fork's parameters +//! ([`ProtocolLimits`](crate::ProtocolLimits)), whose default holds a transaction to +//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, to detention's caps and to +//! nothing else. //! //! # The exemption //! @@ -256,6 +258,10 @@ pub struct LimitUsage { /// unlimited, the caps included, and a transaction whose caps are both unlimited is not detained: /// limits built from it do not execute the chain. /// +/// Every value here changes a transaction's result, so in block execution they are the chain's: +/// the per-transaction half of [`ProtocolLimits`](crate::ProtocolLimits), which the block executor +/// installs before every transaction. Set on a standalone EVM, they are its caller's choice. +/// /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -312,7 +318,8 @@ impl EvmTxRuntimeLimits { /// /// 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 [`Default`], which holds detention's caps at the spec's. + /// out; the chain executes on its own ([`ProtocolLimits`](crate::ProtocolLimits)), whose + /// detention caps must be finite. pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index b834d97c5..457153e35 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -14,7 +14,7 @@ use mega_evm::{ test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, - MegaTxEnvelope, PreBlockStateSource, + MegaTxEnvelope, PreBlockStateSource, ProtocolLimits, }; use op_alloy_consensus::TxDeposit; use revm::{ @@ -86,20 +86,35 @@ pub(crate) fn registry_config() -> SequencerRegistryConfig { } } -/// A schedule that activates Satin at genesis and can seed the `SequencerRegistry`. +/// A schedule that activates Satin at genesis, can seed the `SequencerRegistry`, and holds its +/// blocks to no limit at all. +/// +/// Its limits are [`ProtocolLimits::no_limits`], which no chain may carry, so they are attached +/// through the test-only unchecked route: most block tests exercise one mechanism and take the +/// limits out, and a test that holds a block or a transaction to a limit attaches its own +/// ([`chain_spec_with`]). pub(crate) fn chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated().with_params(registry_config()) + chain_spec_with(ProtocolLimits::no_limits()) +} + +/// [`chain_spec`], holding its blocks to `limits`, attached unchecked so a test may run under a +/// value no chain may carry. +pub(crate) fn chain_spec_with(limits: ProtocolLimits) -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated() + .with_params(registry_config()) + .with_params_unchecked(limits) } -/// The context of a block held to `limits`. +/// 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()) } @@ -113,16 +128,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`. @@ -142,6 +161,15 @@ pub(crate) fn executor_with_env( build(state, ctx, env, chain_spec()) } +/// An executor over `state`, for a block the chain holds to `limits`, 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(limits)) +} + /// An executor over `state`, for a block on the chain `spec` describes. pub(crate) fn executor_with_spec( state: &mut State, diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index 7ef966bd1..cf994c5ef 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -17,7 +17,7 @@ use mega_evm::{ SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, }, test_utils::MemoryDatabase, - MegaHardfork, MegaHardforkConfig, MegaHardforks, PreBlockStateSource, + MegaHardfork, MegaHardforkConfig, MegaHardforks, PreBlockStateSource, ProtocolLimits, }; use revm::{context::result::ExecutionResult, database::State, state::Account, Database}; @@ -259,7 +259,8 @@ fn test_foreign_code_at_a_system_address_fails_the_block() { #[test] fn test_missing_registry_params_fail_at_load_and_at_the_block() { let missing = MegaHardforkConfig::default() - .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)); + .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)) + .with_params(ProtocolLimits::DEFAULT); assert_eq!( missing.validate_schedule().unwrap_err().to_string(), "hardfork Satin is scheduled but its SequencerRegistryConfig params are not configured" diff --git a/crates/mega-evm/tests/block/detention.rs b/crates/mega-evm/tests/block/detention.rs index 2eab471a7..e7a5be16b 100644 --- a/crates/mega-evm/tests/block/detention.rs +++ b/crates/mega-evm/tests/block/detention.rs @@ -4,8 +4,8 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::Bytes; use mega_evm::{ - constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, BlockLimits, LimitCheck, - LimitKind, + constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, LimitCheck, LimitKind, + ProtocolLimits, }; use revm::{ bytecode::opcode::{JUMP, JUMPDEST, MCOPY, POP, PUSH0, TIMESTAMP}, @@ -13,7 +13,7 @@ use revm::{ database::State, }; -use crate::common::{self, block_ctx, executor_with_env, user_tx}; +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 { @@ -38,8 +38,13 @@ fn test_a_stopped_transaction_is_included_with_a_failed_receipt_that_bills_what_ 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 block's default holds the spec's detention caps. - let mut executor = executor_with_env(&mut state, block_ctx(BlockLimits::default()), env); + // The production limits: the chain's default holds the spec's detention caps. + let mut executor = executor_with_env_and_spec( + &mut state, + common::unlimited_ctx(), + env, + common::chain_spec_with(ProtocolLimits::DEFAULT), + ); executor.apply_pre_execution_changes().expect("the block starts"); let gas_limit = 29_000_000; diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 4ade89b4c..881a090b7 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -24,7 +24,7 @@ use mega_evm::{ pre_block_call_gas_limit, test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, - MegaHardforkConfig, MegaSpecId, PreBlockStateSource, + MegaHardforkConfig, MegaSpecId, PreBlockStateSource, ProtocolLimits, }; use revm::{ bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, @@ -191,16 +191,8 @@ fn test_the_pre_block_calls_are_held_to_no_limit() { .with_tx_kv_update_limit(0) .with_frame_kv_update_limit(0) .with_tx_state_gas_limit(0); - let ctx = MegaBlockExecutionCtx::new( - PARENT_HASH, - Some(PARENT_BEACON_ROOT), - Bytes::new(), - BlockLimits::no_limits().with_tx_runtime_limits(limits), - ); - assert_eq!( - pre_block_calls(common::chain_spec(), BLOCK_NUMBER, ctx), - (PARENT_HASH, PARENT_BEACON_ROOT) - ); + let spec = common::chain_spec_with(ProtocolLimits::no_limits().with_tx_runtime_limits(limits)); + assert_eq!(pre_block_calls(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 diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 9f2ee5147..bb4d48dde 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -1,10 +1,11 @@ //! 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 chain's: the schedule carries them +//! ([`ProtocolLimits`]), 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 the schedule's, +//! so a caller that did not pre-apply them, or applied others, does not run a block under +//! whatever limits the EVM happened to carry. use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, @@ -15,38 +16,43 @@ 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, 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. +/// A limit no default carries, so seeing it proves it travelled from the schedule. 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( +/// The chain's limits in these tests. +fn limits() -> ProtocolLimits { + ProtocolLimits::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. +/// A factory over a chain that carries [`limits`]. +fn factory() -> common::TestFactory { + common::factory_on(common::chain_spec_with(limits())) +} + +/// The factory trait installs the chain's limits on an EVM the caller built without them. #[test] -fn test_trait_path_applies_block_context_runtime_limits() { +fn test_trait_path_applies_the_chains_runtime_limits() { let mut state = common::state(); - let factory = common::factory(); + let factory = 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())); + let executor = factory.create_executor(evm, common::unlimited_ctx()); assert_eq!(executor.evm().tx_runtime_limits().tx_data_size_limit, TX_DATA_SIZE_LIMIT); } @@ -55,16 +61,17 @@ fn test_trait_path_applies_block_context_runtime_limits() { #[test] fn test_trait_path_applies_every_runtime_limit_field() { let mut state = common::state(); - let factory = common::factory(); + let factory = factory(); let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - 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 chain's limits" ); + assert_eq!(executor.protocol_limits(), Some(&limits())); } /// The two routes to an executor install the same limits, so neither is a way around them. @@ -72,26 +79,26 @@ fn test_trait_path_applies_every_runtime_limit_field() { fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let trait_path = { let mut state = common::state(); - let factory = common::factory(); + let factory = factory(); let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - let executor = factory.create_executor(evm, common::block_ctx(limits())); + let executor = factory.create_executor(evm, common::unlimited_ctx()); *executor.evm().tx_runtime_limits() }; let inspector_path = { let mut state = common::state(); - let factory = common::factory(); + let factory = factory(); 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, limits().tx_runtime_limits); + assert_eq!(inspector_path, limits().tx_runtime_limits); assert_eq!(trait_path, inspector_path); } @@ -100,21 +107,36 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { #[test] fn test_trait_path_idempotent_when_caller_pre_applied_runtime_limits() { let mut state = common::state(); - let factory = common::factory(); + let factory = factory(); + let evm = factory + .evm_factory() + .create_evm(&mut state, common::evm_env()) + .with_tx_runtime_limits(limits().tx_runtime_limits); + + let executor = factory.create_executor(evm, common::unlimited_ctx()); + + assert_eq!(*executor.evm().tx_runtime_limits(), limits().tx_runtime_limits); +} + +/// Limits a caller applied to the EVM are not the chain's, and the chain's replace them. +#[test] +fn test_trait_path_replaces_limits_the_caller_applied() { + let mut state = common::state(); + let factory = factory(); let evm = factory .evm_factory() .create_evm(&mut state, common::evm_env()) - .with_tx_runtime_limits(limits().to_evm_tx_runtime_limits()); + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(1)); - 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()); + assert_eq!(*executor.evm().tx_runtime_limits(), 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 chain'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_chains_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()); @@ -122,22 +144,23 @@ fn test_direct_construction_applies_block_context_runtime_limits() { let executor = MegaBlockExecutor::new( evm, - common::block_ctx(limits()), - common::chain_spec(), + common::unlimited_ctx(), + common::chain_spec_with(limits()), 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 chain'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`. +/// the chain allows is stopped with `MegaLimitExceeded`, even when the caller loosened the EVM's +/// limits after building the executor — every transaction runs under the chain's. #[test] -fn test_direct_construction_stops_a_transaction_over_the_block_data_size_limit() { +fn test_direct_construction_stops_a_transaction_over_the_chains_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; @@ -151,13 +174,16 @@ 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 an EVM + // that carries no limits of its own. + let mut executor = common::executor_with_limits( + &mut state, + ProtocolLimits::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"); + executor.evm_mut().set_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); let outcome = executor .execute_transaction_without_commit(&user_tx(0, 1_000_000)) diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index a8783f287..0b2b0a9e8 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -5,7 +5,7 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, EvmTxRuntimeLimits, LimitCheck, - LimitKind, MegaTransactionExt, MegaTxEnvelope, + LimitKind, MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, }; use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, @@ -278,11 +278,10 @@ fn test_the_block_data_size_limit_never_refuses_a_deposit() { fn test_the_transaction_data_size_limit_stops_a_deposit_that_is_still_included() { let limit = mega_evm::TX_BODY_SIZE + 10; let mut state = common::state(); - let mut executor = executor( + let mut executor = common::executor_with_limits( &mut state, - common::block_ctx(BlockLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - )), + ProtocolLimits::no_limits() + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), ); executor.apply_pre_execution_changes().expect("the block starts"); diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 473819e12..64556c1e2 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -260,7 +260,7 @@ const NEXT_ADMIN: Address = address!("0x6000000000000000000000000000000000000006 /// A Satin-at-genesis schedule whose registry is seeded with [`GENESIS_SYSTEM_ADDRESS`]. fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated().with_params(SequencerRegistryConfig { + common::chain_spec().with_params(SequencerRegistryConfig { initial_system_address: GENESIS_SYSTEM_ADDRESS, ..common::registry_config() }) diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 4c368ba76..887dd7a88 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -18,9 +18,9 @@ use mega_evm::{ constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, 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, BlockLimits, - EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, - MegaTransaction, MegaTransactionOutcome, VolatileDataAccess, + volatile_data_access_disabled_revert_data, write_record_history_gas, EvmTxRuntimeLimits, + LimitCheck, LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, ProtocolLimits, VolatileDataAccess, }; use revm::{ bytecode::opcode::*, @@ -839,7 +839,7 @@ fn test_a_callers_limits_set_the_caps() { } /// The default runtime limits detain: [`EvmTxRuntimeLimits::default`], and the transaction half -/// of [`BlockLimits::default`] that a block executor installs, hold each kind of read to the +/// of [`ProtocolLimits::DEFAULT`] that a block executor installs, hold each kind of read to the /// spec's cap. It is `no_limits` that turns detention off, with every other per-transaction limit. #[test] fn test_the_default_limits_detain() { @@ -847,7 +847,7 @@ fn test_the_default_limits_detain() { 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(), BlockLimits::default().tx_runtime_limits] { + for limits in [EvmTxRuntimeLimits::default(), ProtocolLimits::DEFAULT.tx_runtime_limits] { let run_under = |limits: EvmTxRuntimeLimits, code: &Bytes| { let db = MemoryDatabase::default() .account_code(CONTRACT, code.clone()) From 06740d13ff3627dabea6d806497058798da9bd2d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:18:16 -0400 Subject: [PATCH 335/458] test(block): a chain's limits bind its blocks, a builder's policy does not A block on a chain whose ProtocolLimits are not the defaults, attached through the checked route, stops a transaction at the chain's data-size limit and refuses one once it reached the chain's KV budget. A builder that packs under its own policy (a DA cap, a declared-gas cap, a block data-size cap below the chain's) and validators that re-execute its block under no policy or another one compute the same receipts, counters and state; the same block under different chain limits does not. --- crates/mega-evm/tests/block/main.rs | 1 + .../mega-evm/tests/block/protocol_limits.rs | 305 ++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 crates/mega-evm/tests/block/protocol_limits.rs diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 0a7c0f485..9030d94d7 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -11,6 +11,7 @@ mod external_envs; mod factory; mod inspector; mod limits; +mod protocol_limits; mod receipts; mod rules; mod salt; diff --git a/crates/mega-evm/tests/block/protocol_limits.rs b/crates/mega-evm/tests/block/protocol_limits.rs new file mode 100644 index 000000000..047196d45 --- /dev/null +++ b/crates/mega-evm/tests/block/protocol_limits.rs @@ -0,0 +1,305 @@ +//! The chain's limits and the builder's policy: the limits a block is held to are the ones its +//! schedule carries, whatever the node puts in the block context, and a builder's policy changes +//! which transactions it packs, never what a packed block computes. + +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, MegaHardforkConfig, 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"); + +/// 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) +} + +/// A schedule that carries `limits` the way a chain configuration does: through the checked +/// route, so the values are ones a chain may carry. +fn chain_with(limits: ProtocolLimits) -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated() + .with_params(common::registry_config()) + .with_params(limits) +} + +/// A chain whose limits are not the defaults is held to its own: a transaction that crosses the +/// chain's data-size limit is stopped at that limit, and the block refuses a transaction once it +/// reached the chain's KV budget. The node passed no limits at all. +#[test] +fn test_a_block_is_held_to_the_limits_its_chain_carries() { + // One storage write fits the transaction's data size; a second crosses it. + let tx_data_size_limit = TX_BODY_SIZE + WRITE_RECORD_SIZE; + let limits = ProtocolLimits::DEFAULT + .with_tx_runtime_limits( + ProtocolLimits::DEFAULT.tx_runtime_limits.with_tx_data_size_limit(tx_data_size_limit), + ) + .with_block_kv_update_limit(1); + assert_ne!(limits, ProtocolLimits::DEFAULT); + + let mut state = State::builder().with_database(database()).build(); + let mut executor = common::executor_with_spec( + &mut state, + common::block_ctx(BlockLimits::default()), + chain_with(limits), + ); + assert_eq!(executor.protocol_limits(), Some(&limits)); + assert_eq!(*executor.evm().tx_runtime_limits(), limits.tx_runtime_limits); + assert_eq!(executor.limiter().limits.block_kv_update_limit, 1); + executor.apply_pre_execution_changes().expect("the block starts"); + + // Two writes: stopped at the chain's transaction limit, and included with the stop. + let outcome = executor + .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), 1_000_000)) + .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 * WRITE_RECORD_SIZE, + frame_local: false, + }) + ); + executor.commit_transaction_outcome(outcome).expect("the stopped transaction is included"); + assert_eq!(executor.limiter().usage.write_records, 0, "the stop kept no record"); + + // One write fits, and fills the chain's KV budget. + let outcome = executor + .run_transaction(&tx_from(SENDERS[1], WRITES_ONE, Bytes::new(), 1_000_000)) + .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.write_records, 1); + + // The block has reached the chain's KV budget: the next transaction is refused. + let err = executor + .run_transaction(&tx_from(SENDERS[2], WRITES_ONE, Bytes::new(), 1_000_000)) + .expect_err("the block's write records have reached the chain's limit"); + assert!(err.to_string().contains("Block KV update limit reached"), "{err}"); + assert!(err.to_string().contains("limit=1"), "{err}"); + + // On the default chain the same two-write transaction keeps both writes. + let mut state = State::builder().with_database(database()).build(); + let mut executor = common::executor_with_spec( + &mut state, + common::unlimited_ctx(), + chain_with(ProtocolLimits::DEFAULT), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor + .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), 1_000_000)) + .expect("the transaction runs"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + assert_eq!(outcome.inner.limit_exceeded, None); +} + +/// 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 of the chain `limits` describes, 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 = + common::executor_with_spec(&mut state, common::block_ctx(policy), chain_with(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 chain'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. A +/// validator on a chain whose limits differ does not, which is why those travel with the chain. +#[test] +fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_block() { + let limits = ProtocolLimits::DEFAULT; + 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) + }; + let candidates = [ + writes(SENDERS[0], 1, 0, 200_000), + // Refused by the builder's data-availability cap on one transaction. + writes(SENDERS[1], 2, 4_000, 400_000), + // Refused by the builder's cap on a transaction's declared gas. + writes(SENDERS[2], 3, 0, 5_000_000), + // Packed: it is the transaction that reaches the builder's data-size cap. + writes(SENDERS[3], 4, 0, 200_000), + // Refused: the block has reached the builder's data-size cap, not the chain's. + writes(SENDERS[4], 5, 0, 200_000), + ]; + 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(1_000_000) + .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("Transaction gas limit exceeded: tx_gas_limit=5000000 > limit=1000000"), + "{}", + 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 chain'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 a chain whose limits differ computes a different result: the first + // transaction's write crosses that chain's data-size limit and is stopped. + let stricter = ProtocolLimits::DEFAULT.with_tx_runtime_limits( + ProtocolLimits::DEFAULT.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"); +} From 562fb89391742fad012d1ad008073cf81b36a12f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:20:24 -0400 Subject: [PATCH 336/458] docs: state the limits as protocol values carried by the Satin fork's parameters The spec page no longer says a node supplies the limits with each block: the per-transaction limits, the detention caps and the four block limits are protocol values the chain configuration carries as Satin's parameters, a configuration without them or with a value no chain can run on does not load, and a builder's transaction gas, encoded-size and data-availability limits are building policy a validator does not apply. AGENTS.md and the crate README describe ProtocolLimits, the building policy and the test-only route. --- AGENTS.md | 24 ++++++++++++++++-------- crates/mega-evm/README.md | 9 ++++++--- docs/spec/upgrades/satin.md | 29 ++++++++++++++++++----------- 3 files changed, 40 insertions(+), 22 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a6f9556b8..64728967c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,9 +106,9 @@ 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 (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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, 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`) | — | -| `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` with the production data-size caps as its default, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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`, the Satin params type carrying the limits every node shares (the per-transaction runtime limits and the four block budgets, today's values as its default), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default) | — | +| `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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default; in block execution the chain's, from `ProtocolLimits`) | — | | `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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 | @@ -160,21 +160,28 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). - A bare `MegaContext` sets no limit; a block executor installs its `BlockLimits`, whose default holds each transaction to `TX_DATA_LIMIT` and the block to `BLOCK_DATA_LIMIT`, 12.5 MiB each. + A bare `MegaContext` sets no limit but detention's caps; a block executor installs the chain's (see the protocol limits below), whose default 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 like the block's execution gas (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 162,306 gas, and keeping its record costs its 3,520 history on top. - A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0) and KV updates (1), counted on the lanes with a transaction limit and frame budgets; compute gas (2), gas detention's stop; and state growth (3), held as EIP-8037 state gas by a per-transaction limit. - The KV 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 — by the data-size limit's rules in its own unit: `EvmTxRuntimeLimits::tx_kv_update_limit` stops the transaction, and every frame gets a record budget, what the transaction has left for its own frame and 98% of what its parent has left for a child, under `frame_kv_update_limit`. 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 data size is checked before the records wherever both cross. - At the production data-size caps a transaction or a block keeps at most 327,680 records, so the KV limits bind only below that; both are unlimited unless a node sets them, and `BlockLimits::block_kv_update_limit` is the block's, a packing budget like its data size. + At the production data-size caps a transaction or a block keeps at most 327,680 records, so the KV limits bind only below that; both are unlimited unless the chain sets them, and `ProtocolLimits::block_kv_update_limit` is the block's, a packing budget like its data size. - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame revm refuses — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. - It is unlimited unless a node sets it; the per-block one is `BlockLimits::block_state_gas_limit`. + It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. +- The limits that change a result are protocol values, carried by the Satin fork's parameters: `ProtocolLimits` (`block/limit.rs`), attached to the schedule with `MegaHardforkConfig::with_params` and read at the block's timestamp with `MegaHardforks::protocol_limits`. + It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. + `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and an unlimited detention cap; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). + The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`). + 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 caps on the four 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/protocol_limits.rs`). + Tests that run blocks under limits no chain may carry (`ProtocolLimits::no_limits()`, detention off) attach them with `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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. @@ -184,7 +191,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 transaction through the latch, with `MegaLimitExceeded` of kind compute; 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 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 chain's `ProtocolLimits` and the builder's `BlockLimits`, and fills `BlockGasCounters`. A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. The KV limit refuses like the data-size one. None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. @@ -276,7 +283,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 `BlockLimits::default()` detain. + 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses an unlimited cap, so no chain 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. @@ -514,7 +521,8 @@ When the agent is requested to implement a new feature or bug fix, it should con 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. + 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, or with params their `validate()` refuses, is rejected at load time. + A fork may carry several params types (Satin carries `SequencerRegistryConfig` and `ProtocolLimits`): a schedule keeps one value per type, and `MegaHardforks::fork_params_any` answers by fork and `TypeId`. - **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 EIP-2935 and EIP-4788 calls and the post-block balance increments, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, and the block executor is what commits them. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 446c3f3e0..4d0b19b06 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -47,12 +47,15 @@ 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. -`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none; a block executor installs its `BlockLimits`, whose default holds each transaction and the block to 12.5 MiB of data size. +`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none but gas detention's caps; a block executor installs the chain's, whose default holds each transaction and the block to 12.5 MiB of data size. 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 and the history bytes they appended. +Every transaction is held to the chain'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: `ProtocolLimits`, the Satin fork's parameters, which a chain configuration carries beside `SequencerRegistryConfig` and block execution reads at the block's timestamp. +They are the per-transaction runtime limits and the block's execution-gas, state-gas, data-size and KV budgets; their default is today's values, and `validate_schedule` refuses a schedule that activates Satin without them or with a value no chain can run on. +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 caps that can lower a block 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. A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. @@ -137,7 +140,7 @@ Every record is forty bytes of data size, so at the production data-size caps a The transaction's KV count is in its outcome's usage and the block's in its result; a block can be held to a KV limit, a packing budget like its data size. A transaction's state growth is the EIP-8037 state gas it spends, so the state-gas limit is what holds it: `EvmTxRuntimeLimits::tx_state_gas_limit` holds the state gas a transaction holds, net of what it refilled and of what its failed frames rolled back, at every site state gas is charged, and a crossing anywhere on the call stack stops the transaction with `MegaLimitExceeded(3, limit)`. It is a limit on gas, so a slot or an account in a crowded SALT bucket reaches it sooner. -Every one of these limits is unlimited unless a node sets it. +Every one of these limits is unlimited unless the chain sets it in its `ProtocolLimits`. 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. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 5eb36558c..47092d2d7 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -66,7 +66,7 @@ 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 and the node's per-transaction gas-limit policy. + 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 as the node supplies it, and zero for a block that carries none. - The Karst block rules apply to MegaETH blocks: @@ -393,7 +393,9 @@ Three dimensions are limited per transaction; compute is not one of them (see [T - **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 per-transaction limits and the per-frame caps are execution parameters the node supplies with each block, and every node executing a chain MUST use the same values; the values above apply when none is set. +- The per-transaction limits and the per-frame caps are protocol values: the chain configuration carries them as parameters of the Satin hardfork, together with the detention caps and the block limits, and a node MUST hold every transaction to the values the chain configures, never to values it is handed with a block. + The values above are the defaults. + A chain configuration that activates Satin without these parameters MUST be refused when it is loaded, and so MUST one that sets a limit to zero, a transaction data-size limit below `TX_BODY_SIZE`, or an unlimited detention cap. The 98/100 share is not a parameter. At the default data-size limit a transaction keeps fewer than 327,680 write records (13,107,200 / 40), so a KV limit binds only below that. @@ -462,7 +464,7 @@ A contract can revert with the same bytes, so the revert data alone does not ide 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 execution parameters the node supplies with each block, 20,000,000 each when none is set. + The caps are protocol values the chain configuration carries with the other limits (see [Resource Limits](#10-resource-limits)), 20,000,000 each by default; a chain's caps MUST be finite. - **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`), 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). @@ -716,8 +718,11 @@ Four of those counts can be limited: - A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by any of the four, and MUST count towards all four. A Mega System Transaction is a legacy transaction in the block, so at block level it is held to these budgets and to the data-availability limits like any non-deposit transaction. - History gas has no block limit; the block's history bytes are reported, not limited. -- The pre-execution limits are unchanged in kind: the block gas limit (a transaction's declared gas limit must fit in what the block has left), the per-transaction gas limit, the encoded size, and the data-availability size, from which deposits are exempt. -- The limits are execution parameters the node supplies with each block; every node executing a chain MUST use the same values. +- The block gas limit is unchanged: a transaction's declared gas limit MUST fit in what the block has left. +- The four limits are protocol values the chain configuration carries as parameters of the Satin hardfork, with the per-transaction limits (see [Resource Limits](#10-resource-limits)); the defaults are the table's. + A node validating a block MUST hold it to the chain's 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 (from which deposits are exempt), hold the block to an encoded-size or data-availability budget, and hold any of the four limits below the chain's value, never above it. + 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. ### 21. Transaction and Block Refusals @@ -737,15 +742,16 @@ A transaction MUST be rejected before inclusion when: 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; -- it does not fit the block's encoded-size or data-availability budget; - its data-availability footprint does not fit in what the block's gas limit has left for footprints; -- the block has reached its execution-gas, data-size or KV budget; -- the block has reached its state-gas budget and the transaction adds state gas; +- the block has reached the chain's execution-gas, data-size or KV limit; +- the block has reached the chain's state-gas limit and the transaction adds state gas; - it is not a deposit and the block activates Satin or an Optimism fork from Jovian onward. A block that contains a transaction it should have skipped is invalid. -A transaction exceeding a per-transaction encoded-size, data-availability or gas-limit policy MUST be rejected permanently. +A block builder MAY also skip a 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 one of the four block limits held below the chain'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 is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). A failed bucket-capacity read or database read MUST fail the transaction with its cause rather than settle it at any price. @@ -786,8 +792,9 @@ Satin is a restatement rather than a delta, so a Rex6 rule this page does not ca The six system contracts keep their Rex6 bytecode and ABI; the Satin deploy step refuses, rather than upgrades, any other code at their addresses. A system-address transaction without the system shape is now executed as a user transaction instead of being refused; only the holder of the system key can send one. -The per-transaction and block limits and the detention caps are execution parameters the node supplies with each block: unless set, the KV-update and state-gas limits and the block's execution-gas limit are unlimited, the data-size limits are 13,107,200 bytes, and the detention caps are 20,000,000 each. -Every node executing a chain must use the same values. +The per-transaction and block limits and the detention caps are protocol values: the chain configuration carries them as parameters of the Satin hardfork, so every node executing a chain holds its blocks to the same ones, and a configuration that activates Satin without them does not load. +By default the KV-update and state-gas limits and the block's execution-gas limit are unlimited, the data-size limits are 13,107,200 bytes, and the detention caps are 20,000,000 each. +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. From 078098a0ef605d3f12bd7341858382366c3c7f5b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:24:21 -0400 Subject: [PATCH 337/458] test(block): run the protocol-limit block tests on gas any byte price covers The builder and validator test gave its candidates 200,000 gas, which a measurement build's higher byte prices exhaust, so the first write ran out of gas instead of being kept. Every transaction of the module now declares 2,000,000, and the builder's declared-gas cap is that figure. --- .../mega-evm/tests/block/protocol_limits.rs | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/tests/block/protocol_limits.rs b/crates/mega-evm/tests/block/protocol_limits.rs index 047196d45..b7f8c1532 100644 --- a/crates/mega-evm/tests/block/protocol_limits.rs +++ b/crates/mega-evm/tests/block/protocol_limits.rs @@ -28,6 +28,10 @@ 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] = [ @@ -115,7 +119,7 @@ fn test_a_block_is_held_to_the_limits_its_chain_carries() { // Two writes: stopped at the chain's transaction limit, and included with the stop. let outcome = executor - .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), 1_000_000)) + .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), GAS_LIMIT)) .expect("the transaction runs"); assert_eq!( outcome.inner.limit_exceeded, @@ -131,7 +135,7 @@ fn test_a_block_is_held_to_the_limits_its_chain_carries() { // One write fits, and fills the chain's KV budget. let outcome = executor - .run_transaction(&tx_from(SENDERS[1], WRITES_ONE, Bytes::new(), 1_000_000)) + .run_transaction(&tx_from(SENDERS[1], WRITES_ONE, Bytes::new(), GAS_LIMIT)) .expect("the transaction runs"); assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); executor.commit_transaction_outcome(outcome).expect("it is included"); @@ -139,7 +143,7 @@ fn test_a_block_is_held_to_the_limits_its_chain_carries() { // The block has reached the chain's KV budget: the next transaction is refused. let err = executor - .run_transaction(&tx_from(SENDERS[2], WRITES_ONE, Bytes::new(), 1_000_000)) + .run_transaction(&tx_from(SENDERS[2], WRITES_ONE, Bytes::new(), GAS_LIMIT)) .expect_err("the block's write records have reached the chain's limit"); assert!(err.to_string().contains("Block KV update limit reached"), "{err}"); assert!(err.to_string().contains("limit=1"), "{err}"); @@ -153,7 +157,7 @@ fn test_a_block_is_held_to_the_limits_its_chain_carries() { ); executor.apply_pre_execution_changes().expect("the block starts"); let outcome = executor - .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), 1_000_000)) + .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), GAS_LIMIT)) .expect("the transaction runs"); assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); assert_eq!(outcome.inner.limit_exceeded, None); @@ -228,16 +232,19 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl 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, 200_000), + writes(SENDERS[0], 1, 0, gas), // Refused by the builder's data-availability cap on one transaction. - writes(SENDERS[1], 2, 4_000, 400_000), + writes(SENDERS[1], 2, 4_000, gas), // Refused by the builder's cap on a transaction's declared gas. - writes(SENDERS[2], 3, 0, 5_000_000), + 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, 200_000), + writes(SENDERS[3], 4, 0, gas), // Refused: the block has reached the builder's data-size cap, not the chain's. - writes(SENDERS[4], 5, 0, 200_000), + 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)); @@ -249,7 +256,7 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl let builder_policy = BlockLimits::no_limits() .with_tx_da_size_limit(2_000) - .with_tx_gas_limit(1_000_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"); @@ -259,7 +266,10 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl refusal(1) ); assert!( - refusal(2).contains("Transaction gas limit exceeded: tx_gas_limit=5000000 > limit=1000000"), + refusal(2).contains(&format!( + "Transaction gas limit exceeded: tx_gas_limit={} > limit={gas}", + gas + 1 + )), "{}", refusal(2) ); From 2c6772f1c0f8181e8c560d04d535d60cf4ea0c7a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:32:28 -0400 Subject: [PATCH 338/458] feat(evme): run Satin in-tree and legacy specs on the released 1.7.1 CLI mega-evme rejoins the workspace. A command runs on the engine its spec names: Satin on the in-tree sources, ported to the Satin engine; a spec from Equivalence to Rex6 on the released mega-evme and mega-evm 1.7.1, linked under aliases, with the user's arguments handed over unchanged. Rex7 is refused. Satin output adds a `satin` object with the gas by ledger and keeps every legacy field. The legacy line is pinned to the 1.7.1 lockfile's versions, and the release build selects the tool by manifest path. --- .github/workflows/on-release.yml | 4 +- AGENTS.md | 13 +- Cargo.lock | 2481 ++++++++++++++--- Cargo.toml | 14 +- bin/mega-evme/AGENTS.md | 8 +- bin/mega-evme/Cargo.toml | 16 +- bin/mega-evme/src/cmd.rs | 59 +- bin/mega-evme/src/common/env.rs | 17 +- bin/mega-evme/src/common/error.rs | 14 +- bin/mega-evme/src/common/hardfork.rs | 49 - bin/mega-evme/src/common/mod.rs | 2 - bin/mega-evme/src/common/outcome.rs | 130 +- bin/mega-evme/src/common/provider/mod.rs | 33 +- bin/mega-evme/src/common/state.rs | 79 +- bin/mega-evme/src/common/trace.rs | 42 +- bin/mega-evme/src/common/tx.rs | 29 +- bin/mega-evme/src/common/tx_override.rs | 81 +- bin/mega-evme/src/engine.rs | 161 ++ bin/mega-evme/src/lib.rs | 2 + bin/mega-evme/src/main.rs | 12 +- bin/mega-evme/src/replay/cmd.rs | 311 +-- 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/cmd.rs | 22 +- bin/mega-evme/src/tx/cmd.rs | 18 +- .../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 | 65 + .../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 | 62 + bin/mega-evme/tests/legacy_line.rs | 105 + bin/mega-evme/tests/replay_dump.rs | 6 +- bin/mega-evme/tests/state.rs | 48 + 44 files changed, 3681 insertions(+), 1215 deletions(-) delete mode 100644 bin/mega-evme/src/common/hardfork.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 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 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/AGENTS.md b/AGENTS.md index a6f9556b8..740c2f5cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,11 +70,15 @@ Git submodules are required — clone with `--recursive` or run `git submodule u | `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 state-test runner on Satin: the equivalence gate, the report | | `state-test` | `crates/state-test` | yes | The runner's CLI | -| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | +| `mega-evme` | `bin/mega-evme` | yes | EVM execution CLI: Satin in-tree, legacy specs on the released 1.7.1 CLI | | `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | -The two tool binaries `mega-evme` and `mega-t8n` 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`. + +`mega-t8n` still targets the legacy engine. +It is outside `[workspace] members`, so no workspace command builds it; do not edit its sources until it is ported to Satin. ### Dependencies on the forks @@ -82,7 +86,8 @@ 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` 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`'s legacy leg (`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. diff --git a/Cargo.lock b/Cargo.lock index d3b935006..3855e69de 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" @@ -40,18 +51,44 @@ dependencies = [ "phf 0.14.0", ] +[[package]] +name = "alloy-consensus" +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.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b836b372d3b742b7c083d2617d6e68563cd5dadbd8752c461a935a756551e69" dependencies = [ - "alloy-eips", + "alloy-eips 2.4.2", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.4.2", "alloy-trie", - "alloy-tx-macros", + "alloy-tx-macros 2.4.2", "auto_impl", "borsh", "c-kzg", @@ -67,17 +104,31 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-consensus-any" +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.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1befb37485ea71e8599e32ffd76c98af7c3720a34741d30abd87f41c3148407" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.4.2", + "alloy-eips 2.4.2", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.4.2", "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" @@ -134,6 +199,29 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-eips" +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.4.2" @@ -143,10 +231,10 @@ dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", - "alloy-eip7928", + "alloy-eip7928 0.4.11", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.4.2", "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,16 +272,16 @@ 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.4.2", + "alloy-eips 2.4.2", + "alloy-hardforks 0.4.8", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-rpc-types-eth", + "alloy-rpc-types-eth 2.4.2", "alloy-sol-types", "auto_impl", "derive_more", - "revm", + "revm 40.0.3", "thiserror", "tracing", ] @@ -185,15 +292,28 @@ version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0680a2f7d4bbc6f48c0cb43368fa544918a1fa291e772bdb47c834ade338f363" dependencies = [ - "alloy-eips", + "alloy-eips 2.4.2", "alloy-primitives", - "alloy-serde", + "alloy-serde 2.4.2", "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" @@ -219,6 +339,21 @@ 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-json-rpc" version = "2.4.2" @@ -234,22 +369,48 @@ dependencies = [ "tracing", ] +[[package]] +name = "alloy-network" +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.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-consensus 2.4.2", + "alloy-consensus-any 2.4.2", + "alloy-eips 2.4.2", + "alloy-json-rpc 2.4.2", + "alloy-network-primitives 2.4.2", "alloy-primitives", - "alloy-rpc-types-any", - "alloy-rpc-types-eth", - "alloy-serde", - "alloy-signer", + "alloy-rpc-types-any 2.4.2", + "alloy-rpc-types-eth 2.4.2", + "alloy-serde 2.4.2", + "alloy-signer 2.4.2", "alloy-sol-types", "async-trait", "auto_impl", @@ -260,43 +421,84 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-network-primitives" +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.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8795eecf50374a0dd942caff57922c59333c9991ead9eccbbc1709f55d73c7c2" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.4.2", + "alloy-eips 2.4.2", "alloy-primitives", - "alloy-serde", + "alloy-serde 2.4.2", "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.4.2", + "alloy-eips 2.4.2", + "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", @@ -329,6 +531,45 @@ 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 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.4.2" @@ -336,20 +577,20 @@ 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-consensus 2.4.2", + "alloy-eips 2.4.2", + "alloy-json-rpc 2.4.2", + "alloy-network 2.4.2", + "alloy-network-primitives 2.4.2", "alloy-primitives", - "alloy-rpc-client", + "alloy-rpc-client 2.4.2", "alloy-rpc-types-debug", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", - "alloy-signer", + "alloy-rpc-types-eth 2.4.2", + "alloy-rpc-types-trace 2.4.2", + "alloy-signer 2.4.2", "alloy-sol-types", - "alloy-transport", - "alloy-transport-http", + "alloy-transport 2.4.2", + "alloy-transport-http 2.4.2", "async-stream", "async-trait", "auto_impl", @@ -358,10 +599,10 @@ dependencies = [ "futures", "futures-utils-wasm", "http", - "lru", + "lru 0.18.4", "parking_lot", "pin-project", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "thiserror", @@ -393,19 +634,42 @@ dependencies = [ "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 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.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98267c2d47f9c185b575bac3f772a8ca66bcbd712693535e50980c12eab80a42" dependencies = [ - "alloy-json-rpc", + "alloy-json-rpc 2.4.2", "alloy-primitives", - "alloy-transport", - "alloy-transport-http", + "alloy-transport 2.4.2", + "alloy-transport-http 2.4.2", "futures", "pin-project", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "tokio", @@ -416,17 +680,28 @@ dependencies = [ "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 1.1.0", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", +] + [[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-consensus-any 2.4.2", + "alloy-network-primitives 2.4.2", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.4.2", + "alloy-serde 2.4.2", "serde", "serde_json", ] @@ -450,11 +725,11 @@ version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a43d7b6b86be4885c7a76f1dfcde9651af2d419ff571e8ee7257de47101203b" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.4.2", + "alloy-eips 2.4.2", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.4.2", "derive_more", "ethereum_ssz", "ethereum_ssz_derive", @@ -463,19 +738,40 @@ dependencies = [ "strum", ] +[[package]] +name = "alloy-rpc-types-eth" +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.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756eb5803e70985be4066b636194ccb5f6629e5d141817c1f0c50cea8350bf5c" dependencies = [ - "alloy-consensus", - "alloy-consensus-any", - "alloy-eips", - "alloy-network-primitives", + "alloy-consensus 2.4.2", + "alloy-consensus-any 2.4.2", + "alloy-eips 2.4.2", + "alloy-network-primitives 2.4.2", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.4.2", "alloy-sol-types", "itertools 0.14.0", "serde", @@ -484,6 +780,20 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-rpc-types-trace" +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.4.2" @@ -491,13 +801,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1933d60c2f51b8906103484ea2ca2218357264dbf16f948f7c2dd4ac5818e1d8" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.4.2", + "alloy-serde 2.4.2", "serde", "serde_json", "thiserror", ] +[[package]] +name = "alloy-serde" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ece63b89294b8614ab3f483560c08d016930f842bf36da56bf0b764a15c11e" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + [[package]] name = "alloy-serde" version = "2.4.2" @@ -509,6 +830,21 @@ dependencies = [ "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-signer" version = "2.4.2" @@ -596,11 +932,11 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "2.4.2" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" +checksum = "cae82426d98f8bc18f53c5223862907cac30ab8fc5e4cd2bb50808e6d3ab43d8" dependencies = [ - "alloy-json-rpc", + "alloy-json-rpc 1.1.2", "auto_impl", "base64 0.22.1", "derive_more", @@ -618,15 +954,53 @@ dependencies = [ ] [[package]] -name = "alloy-transport-http" +name = "alloy-transport" version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" +checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" dependencies = [ - "alloy-json-rpc", - "alloy-transport", - "itertools 0.14.0", - "reqwest", + "alloy-json-rpc 2.4.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-http" +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.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" +dependencies = [ + "alloy-json-rpc 2.4.2", + "alloy-transport 2.4.2", + "itertools 0.14.0", + "reqwest 0.13.5", "serde_json", "tower", "tracing", @@ -649,6 +1023,18 @@ dependencies = [ "tracing", ] +[[package]] +name = "alloy-tx-macros" +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.4.2" @@ -786,7 +1172,7 @@ dependencies = [ "fnv", "hashbrown 0.15.4", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "zeroize", @@ -803,7 +1189,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", @@ -823,7 +1209,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", @@ -844,7 +1230,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "zeroize", @@ -886,7 +1272,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", @@ -898,7 +1284,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", @@ -911,7 +1297,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", @@ -944,7 +1330,7 @@ dependencies = [ "ark-relations", "ark-std 0.5.0", "educe", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "tracing", @@ -959,7 +1345,7 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber", + "tracing-subscriber 0.2.25", ] [[package]] @@ -980,7 +1366,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -993,7 +1379,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1049,6 +1435,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" @@ -1115,6 +1511,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" @@ -1139,6 +1541,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" @@ -1198,6 +1609,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" @@ -1482,7 +1915,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.59.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]] @@ -1524,6 +1969,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" @@ -1533,6 +1984,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" @@ -1631,6 +2092,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" @@ -1651,6 +2122,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" @@ -1678,6 +2164,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" @@ -1714,6 +2211,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" @@ -1852,6 +2367,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" @@ -1931,6 +2467,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" @@ -1964,7 +2515,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -2041,10 +2592,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" @@ -2069,12 +2637,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" @@ -2184,6 +2773,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" @@ -2235,6 +2830,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" @@ -2246,6 +2851,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" @@ -2256,6 +2880,12 @@ 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" @@ -2275,6 +2905,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" dependencies = [ "allocator-api2", + "equivalent", + "foldhash 0.1.5", ] [[package]] @@ -2285,7 +2917,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2368,6 +3000,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" @@ -2387,9 +3025,11 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2397,6 +3037,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" @@ -2415,9 +3087,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2596,6 +3270,18 @@ 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.12.2" @@ -2630,7 +3316,16 @@ dependencies = [ [[package]] name = "itertools" -version = "0.13.0" +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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ @@ -2737,7 +3432,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -2760,6 +3455,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" @@ -2778,6 +3487,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" @@ -2805,6 +3569,15 @@ 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 = "lru" version = "0.18.4" @@ -2825,30 +3598,171 @@ 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.4.2", + "alloy-eips 2.4.2", + "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-sol-types", "auto_impl", "codspeed-criterion-compat", "delegate", "derive_more", - "mega-evm", - "mega-system-contracts", - "op-alloy-consensus", - "op-revm", - "revm", - "revm-inspectors", + "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", + "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.4.2", + "alloy-eips 2.4.2", + "alloy-json-rpc 2.4.2", + "alloy-network 2.4.2", + "alloy-primitives", + "alloy-provider 2.4.2", + "alloy-rpc-client 2.4.2", + "alloy-rpc-types-eth 2.4.2", + "alloy-rpc-types-trace 2.4.2", + "alloy-serde 2.4.2", + "alloy-sol-types", + "alloy-transport 2.4.2", + "alloy-transport-http 2.4.2", + "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]] @@ -2857,8 +3771,8 @@ version = "2.0.0-alpha.1" dependencies = [ "alloy-rlp", "alloy-trie", - "mega-evm", - "revm", + "mega-evm 2.0.0-alpha.1", + "revm 40.0.3", "serde", "serde_json", "tempfile", @@ -2866,6 +3780,19 @@ dependencies = [ "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", +] + [[package]] name = "mega-system-contracts" version = "2.0.0-alpha.1" @@ -2883,6 +3810,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" @@ -2915,6 +3848,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" @@ -2936,13 +3886,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", @@ -2950,6 +3909,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" @@ -3001,7 +3971,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", ] @@ -3042,11 +4012,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" @@ -3088,25 +4065,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.4.2", + "alloy-eips 2.4.2", + "alloy-network 2.4.2", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.4.2", + "alloy-serde 2.4.2", "bytes", "derive_more", "reth-codecs", @@ -3116,17 +4111,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.4.2", + "alloy-network 2.4.2", + "alloy-provider 2.4.2", + "alloy-rpc-types-eth 2.4.2", + "op-alloy-consensus 2.0.0", + "op-alloy-rpc-types 2.0.0", ] [[package]] @@ -3134,29 +4151,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.4.2", "alloy-primitives", - "alloy-provider", + "alloy-provider 2.4.2", "alloy-rpc-types-engine", - "alloy-transport", + "alloy-transport 2.4.2", "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.4.2", + "alloy-eips 2.4.2", + "alloy-network 2.4.2", + "alloy-network-primitives 2.4.2", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.4.2", + "alloy-serde 2.4.2", "derive_more", - "op-alloy-consensus", + "op-alloy-consensus 2.0.0", "reth-rpc-traits", "serde", "serde_json", @@ -3168,31 +4204,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.4.2", + "alloy-eips 2.4.2", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-serde", + "alloy-serde 2.4.2", "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.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" @@ -3202,7 +4305,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]] @@ -3280,13 +4504,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", ] @@ -3300,14 +4535,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" dependencies = [ - "fastrand", - "phf_shared 0.13.1", + "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", ] [[package]] @@ -3316,13 +4574,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" @@ -3389,6 +4656,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" @@ -3658,6 +4934,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" @@ -3707,6 +4994,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" @@ -3744,8 +5077,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.4.2", + "alloy-eips 2.4.2", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -3774,19 +5107,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.4.2", + "alloy-eips 2.4.2", "alloy-genesis", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth", + "alloy-rpc-types-eth 2.4.2", "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", @@ -3798,11 +5131,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.4.2", + "alloy-network 2.4.2", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-signer", + "alloy-rpc-types-eth 2.4.2", + "alloy-signer 2.4.2", "reth-primitives-traits", "thiserror", ] @@ -3816,25 +5149,56 @@ 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.4#b706bb1a0f1359ee0a73825e4743300c260494ec" 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", "revm-statetest-types", ] +[[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", +] + [[package]] name = "revm-bytecode" version = "11.0.1" @@ -3842,7 +5206,23 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f 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", ] @@ -3854,11 +5234,27 @@ 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", ] @@ -3871,10 +5267,27 @@ 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-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]] @@ -3882,13 +5295,30 @@ name = "revm-database" version = "15.0.2" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ - "alloy-eips", + "alloy-eips 2.4.2", + "alloy-provider 2.4.2", + "alloy-transport 2.4.2", "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]] @@ -3898,10 +5328,30 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f 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]] @@ -3911,15 +5361,33 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f 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]] @@ -3929,14 +5397,32 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f 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]] @@ -3946,29 +5432,69 @@ 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.4.2", + "alloy-rpc-types-trace 2.4.2", "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.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" @@ -3986,11 +5512,23 @@ 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]] @@ -4003,16 +5541,28 @@ dependencies = [ "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.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", ] @@ -4021,13 +5571,13 @@ 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", + "alloy-eip7928 0.4.11", "k256", - "revm-context", - "revm-context-interface", - "revm-database", - "revm-primitives", - "revm-state", + "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", @@ -4043,6 +5593,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" @@ -4062,6 +5626,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" @@ -4075,7 +5678,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", @@ -4112,31 +5715,64 @@ checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" name = "rustc_version" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver 1.0.26", +] + +[[package]] +name = "rustix" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" +dependencies = [ + "bitflags 2.11.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.23.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" dependencies = [ - "semver 0.11.0", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", ] [[package]] -name = "rustc_version" -version = "0.4.1" +name = "rustls-pki-types" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" dependencies = [ - "semver 1.0.26", + "zeroize", ] [[package]] -name = "rustix" -version = "1.0.8" +name = "rustls-webpki" +version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ - "bitflags 2.11.1", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.60.2", + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -4157,6 +5793,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" @@ -4166,6 +5808,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" @@ -4252,6 +5903,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" @@ -4289,6 +5963,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" @@ -4323,6 +6006,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" @@ -4366,6 +6061,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" @@ -4397,6 +6105,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" @@ -4450,6 +6167,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" @@ -4471,7 +6240,7 @@ name = "state-test" version = "2.0.0-alpha.1" dependencies = [ "clap", - "mega-state-test", + "mega-state-test 2.0.0-alpha.1", "serde_json", "tempfile", ] @@ -4590,6 +6359,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" @@ -4629,6 +6419,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" @@ -4701,6 +6500,7 @@ version = "1.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", @@ -4720,6 +6520,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" @@ -4741,6 +6561,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -4848,6 +6669,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" @@ -4902,6 +6749,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" @@ -4933,6 +6786,12 @@ 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" @@ -5077,13 +6936,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.59.0", ] [[package]] @@ -5095,8 +6964,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]] @@ -5133,6 +7002,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" @@ -5142,6 +7022,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" @@ -5151,22 +7040,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]] @@ -5184,30 +7082,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]] @@ -5216,96 +7098,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" @@ -5324,6 +7158,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 26954bd6e..ca9d94180 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,9 @@ [workspace] -# The tool crates `bin/mega-evme` and `bin/mega-t8n` still target the legacy -# engine; their sources are kept untouched and each rejoins the workspace when it -# is ported to Satin. +# `bin/mega-t8n` still targets the legacy engine; its sources are kept untouched and it +# rejoins the workspace when it is ported to Satin, as `bin/mega-evme` has. members = [ + "bin/mega-evme", "crates/mega-evm", "crates/mega-state-test", "crates/state-test", @@ -124,7 +124,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 @@ -184,11 +190,13 @@ 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. diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 7dc0e9460..29ea5d897 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -2,10 +2,12 @@ ## 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/cmd.rs`: argument parsing, engine selection, and dispatch; a legacy spec's arguments are handed unchanged to the 1.7.1 CLI. +- `src/engine.rs`: which engine a spec or a block runs on; the hand-off to the legacy CLI. - `src/common/`: shared CLI args, state loading, tracing, tx parsing, output printers. - `src/run/`: bytecode execution command. - `src/tx/`: full transaction execution command with raw-tx override support. @@ -18,7 +20,11 @@ CLI toolbox for direct MegaEVM execution (`run`, `tx`, `replay`) with optional f - Logging is structured via tracing macros, with explicit progress milestones. - Output paths keep both human-readable summaries and optional machine artifacts (trace/state dump). +- 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 use `cargo ... -p mega-evme`: the name also matches the linked 1.7.1 package. Use `--manifest-path bin/mega-evme/Cargo.toml`. - 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. 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/src/cmd.rs b/bin/mega-evme/src/cmd.rs index d70d496e5..c3b671ee6 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -1,7 +1,12 @@ -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 crate::{ + common::{EvmeError, LogArgs}, + engine::Engine, +}; /// Main CLI for the mega-evme tool #[derive(Parser, Debug)] @@ -36,11 +41,57 @@ 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. +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 cmd = MainCmd::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); + + let engine = match cmd.command.engine().await { + Ok(engine) => engine, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + match engine { + Engine::Legacy => { + crate::engine::run_legacy(args, spec_is_default).await?; + Ok(()) + } + Engine::Satin => cmd.run().await, + } +} + +/// 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, + } + } } 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(); diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 170dd425f..7d3b35546 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -37,17 +37,18 @@ pub struct ChainArgs { } 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) } @@ -106,6 +107,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 @@ -199,10 +201,9 @@ impl EnvArgs { let block = self.create_block_env()?; let external_envs = self.create_external_envs()?; - 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_block(block)) } } diff --git a/bin/mega-evme/src/common/error.rs b/bin/mega-evme/src/common/error.rs index c3956c064..69ca5bc05 100644 --- a/bin/mega-evme/src/common/error.rs +++ b/bin/mega-evme/src/common/error.rs @@ -1,6 +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::{ + alloy_evm::block::BlockExecutionError, + revm::{bytecode::BytecodeDecodeError, database_interface::bal::EvmDatabaseError}, +}; /// Error types for the replay command #[derive(Debug, thiserror::Error)] @@ -70,5 +73,14 @@ pub enum EvmeError { // 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; 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/mod.rs b/bin/mega-evme/src/common/mod.rs index 96ddf3e2e..2f43222f7 100644 --- a/bin/mega-evme/src/common/mod.rs +++ b/bin/mega-evme/src/common/mod.rs @@ -1,6 +1,5 @@ mod env; mod error; -mod hardfork; mod hex; mod logging; mod outcome; @@ -12,7 +11,6 @@ mod tx_override; pub use env::*; pub use error::*; -pub use hardfork::*; pub use hex::*; pub use logging::*; pub use outcome::*; diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index 906c9315b..af12da409 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -12,7 +12,7 @@ use clap::Parser; use mega_evm::{ op_revm::OpHaltReason, revm::{context::result::ExecutionResult, state::EvmState}, - MegaHaltReason, MegaTxType, + LimitCheck, LimitKind, MegaHaltReason, MegaTransactionOutcome, MegaTxType, }; use op_alloy_consensus::{OpDepositReceipt, OpReceiptEnvelope}; use serde::Serialize; @@ -33,6 +33,79 @@ 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, Copy, 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 transaction-level limit that stopped the transaction, if one did. + pub limit_exceeded: Option, +} + +/// A transaction-level limit that stopped a Satin transaction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct LimitStop { + /// The dimension: `data_size`, `kv_update`, `compute_gas` or `state_growth`. + pub kind: &'static str, + /// The limit crossed, in the dimension's unit. + pub limit: u64, + /// The usage that 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, + }, + } + } +} + +/// 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::KVUpdate => "kv_update", + LimitKind::ComputeGas => "compute_gas", + LimitKind::StateGrowth => "state_growth", + } } impl EvmeOutcome { @@ -44,7 +117,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 +127,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, @@ -123,8 +197,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 +214,13 @@ 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)); } - ExecutionResult::Halt { gas_used, reason } => { + ExecutionResult::Halt { reason, .. } => { println!("Status: Halted"); println!("Gas Used: {}", gas_used); println!("Execution Time: {:?}", exec_time); @@ -154,6 +229,23 @@ 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); + } +} + /// Decode revert reason from output bytes using alloy's built-in decoders. /// /// Supports: @@ -185,14 +277,6 @@ 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 { match reason { OpHaltReason::Base(eth_reason) => format!("{:?}", eth_reason), _ => format!("{:?}", reason), @@ -274,6 +358,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 +406,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 +423,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() } + } } } } diff --git a/bin/mega-evme/src/common/provider/mod.rs b/bin/mega-evme/src/common/provider/mod.rs index 94369a6fc..1b1d0c13d 100644 --- a/bin/mega-evme/src/common/provider/mod.rs +++ b/bin/mega-evme/src/common/provider/mod.rs @@ -151,7 +151,7 @@ impl RpcArgs { EvmeError::InvalidInput("No RPC URL provided. Pass '--rpc '.".to_string()) })?; - let url: reqwest::Url = rpc_url_str.parse().map_err(|e| { + let url: alloy_transport_http::reqwest::Url = rpc_url_str.parse().map_err(|e| { EvmeError::RpcError(format!("Invalid RPC URL '{}': {}", rpc_url_str, e)) })?; @@ -246,6 +246,29 @@ 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: alloy_transport_http::reqwest::Url = rpc_url_str.parse().map_err(|e| { + EvmeError::RpcError(format!("Invalid RPC URL '{}': {}", rpc_url_str, e)) + })?; + 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,7 +323,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| { + let url: alloy_transport_http::reqwest::Url = rpc_url_str.parse().map_err(|e| { EvmeError::RpcError(format!("Invalid RPC URL '{}': {}", rpc_url_str, e)) })?; @@ -372,7 +395,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 +405,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,7 +427,7 @@ 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 { + async fn resolve_chain_id(&self, url: alloy_transport_http::reqwest::Url) -> Result { let url_str = url.as_str().to_string(); let bare = build_bare_op_provider(self.build_retry_client(url)); bare.get_chain_id().await.map_err(|e| { diff --git a/bin/mega-evme/src/common/state.rs b/bin/mega-evme/src/common/state.rs index acc655180..56c2f4d79 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}; @@ -224,10 +224,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); @@ -252,7 +250,7 @@ impl PreStateArgs { .entry(address) .or_default() .storage - .insert(slot, EvmStorageSlot::new(value, 0)); + .insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); } // Set balance for the sender if specified (overrides prestate) @@ -438,11 +436,22 @@ impl AccountState { .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)) } } +/// 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 @@ -540,39 +549,27 @@ where /// 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)))); + self.prestate.entry(address).or_default().storage.extend( + storage + .into_iter() + .map(|(slot, value)| (slot, EvmStorageSlot::new(value, TransactionId::ZERO))), + ); } - /// 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, - }; - - // 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) { + /// Installs the code of Satin's predeploys: the six system contracts and the EIP-7997 factory. + /// + /// `run` and `tx` execute no block, so nothing deploys them; the code is applied as a raw + /// state patch, over whatever a forked state holds at those addresses. The factory gets the + /// nonce its deployment gives it. The `SequencerRegistry`'s storage is not seeded: a local run + /// has no chain configuration to seed it from, and a forked run reads the chain's. + pub fn deploy_system_contracts(&mut self) { + use mega_evm::system::{system_contract_specs, SequencerRegistryConfig}; + + for contract in system_contract_specs(&SequencerRegistryConfig::placeholder()) { 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)); + if contract.nonce != 0 { + self.set_account_nonce(contract.address, contract.nonce); + } } } } @@ -651,7 +648,7 @@ where EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) })?; trace!(address = %address, account = ?account, "Loaded account basic from forked state"); - Ok(account) + Ok(account.filter(|info| !rpc_reads_as_absent(info))) } } } @@ -772,7 +769,7 @@ where EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) })?; trace!(address = %address, account = ?account, "Loaded account basic from forked state"); - Ok(account) + Ok(account.filter(|info| !rpc_reads_as_absent(info))) } } } diff --git a/bin/mega-evme/src/common/trace.rs b/bin/mega-evme/src/common/trace.rs index 0086f07e4..b093b57f4 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)] @@ -150,7 +146,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 +164,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 +210,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 +226,34 @@ 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)) } } } diff --git a/bin/mega-evme/src/common/tx.rs b/bin/mega-evme/src/common/tx.rs index ca8de9968..e52d677d3 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}; @@ -348,7 +352,7 @@ impl TxArgs { 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 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) @@ -397,14 +401,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 @@ -493,7 +497,7 @@ impl DecodedRawTx { /// /// 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 }; @@ -605,5 +609,6 @@ 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)), } } diff --git a/bin/mega-evme/src/common/tx_override.rs b/bin/mega-evme/src/common/tx_override.rs index 1ab6d4add..fa42a42db 100644 --- a/bin/mega-evme/src/common/tx_override.rs +++ b/bin/mega-evme/src/common/tx_override.rs @@ -5,13 +5,9 @@ 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}; @@ -77,9 +73,8 @@ 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`. +/// All fields are `Copy`, as `OverriddenTx` is. The input override is stored in a +/// thread-local (`INPUT_OVERRIDE`) since `Bytes` is not `Copy`. #[derive(Debug, Clone, Copy, Default)] pub struct TxOverrides { /// Override for gas limit. @@ -107,10 +102,10 @@ impl TxOverrides { } } -/// 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. +/// 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, Copy)] pub struct OverriddenTx { inner: T, @@ -124,55 +119,33 @@ impl OverriddenTx { } } -// 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(); - self.overrides.apply(&mut tx); - tx - } -} - -// Delegate RecoveredTx to inner -impl + Copy> RecoveredTx for OverriddenTx { - fn tx(&self) -> &Tx { - self.inner.tx() - } +// The block executor builds the environment through `into_parts`; this is where the overrides +// apply. +impl ExecutableTxParts for OverriddenTx +where + T: ExecutableTxParts + Copy, +{ + type Recovered = T::Recovered; - fn signer(&self) -> &Address { - self.inner.signer() - } -} - -// Delegate Typed2718 to inner (required as the `Encodable2718` supertrait below). -impl Typed2718 for OverriddenTx { - fn ty(&self) -> u8 { - self.inner.ty() + fn into_parts(self) -> (MegaTransaction, Self::Recovered) { + let (mut tx, recovered) = self.inner.into_parts(); + self.overrides.apply(&mut tx); + (tx, recovered) } } -// 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() +// 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 encode_2718_len(&self) -> usize { - self.inner.encode_2718_len() + fn tx_size(&self) -> u64 { + self.inner.tx_size() } - fn encode_2718(&self, out: &mut dyn alloy_primitives::bytes::BufMut) { - self.inner.encode_2718(out) - } -} - -// 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() + fn estimated_da_size(&self) -> u64 { + self.inner.estimated_da_size() } } diff --git a/bin/mega-evme/src/engine.rs b/bin/mega-evme/src/engine.rs new file mode 100644 index 000000000..e9e0b2ede --- /dev/null +++ b/bin/mega-evme/src/engine.rs @@ -0,0 +1,161 @@ +//! 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::{chain_activation, ChainActivation, MegaSpecId, ParseMegaSpecError}; + +use crate::common::{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. An unknown chain runs the + /// Satin engine's fallback rung, Satin, from genesis. + pub fn of_block(chain_id: u64, timestamp: u64) -> Self { + Self::under(chain_activation(chain_id), timestamp) + } + + /// The engine a block with timestamp `timestamp` runs on under `activation`, the activation + /// table of its chain (`None` for an unknown chain). + fn under(activation: Option, timestamp: u64) -> Self { + match activation { + None => Self::Satin, + Some(ChainActivation { satin: Some(satin), .. }) if timestamp >= satin => 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. + pub fn of_chain(chain_id: u64) -> Option { + match chain_activation(chain_id) { + None => Some(Self::Satin), + Some(ChainActivation { satin: None, .. }) => Some(Self::Legacy), + Some(ChainActivation { satin: Some(_), .. }) => None, + } + } + + /// The engine's name in output. + pub const fn name(self) -> &'static str { + match self { + Self::Satin => "satin", + Self::Legacy => "legacy", + } + } +} + +/// Runs `args` on the released 1.7.1 CLI. +/// +/// `append_default_spec` appends `--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, append_default_spec: bool) -> Result<()> { + use clap::Parser; + + if append_default_spec { + args.push("--spec".into()); + args.push(DEFAULT_SPEC.into()); + } + mega_evme_legacy::cmd::MainCmd::parse_from(args) + .run() + .await + .map_err(|e| EvmeError::Other(format!("legacy engine: {e}"))) +} + +/// Refuses a legacy spec in a build without the legacy leg. +#[cfg(not(feature = "legacy"))] +pub async fn run_legacy(_args: Vec, _append_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); + } + + #[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. An unknown chain runs Satin from genesis. + #[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), Some(Engine::Legacy)); + assert_eq!(Engine::of_block(chain_id, 0), Engine::Legacy); + assert_eq!(Engine::of_block(chain_id, u64::MAX), Engine::Legacy); + } + assert_eq!(Engine::of_chain(1_337), Some(Engine::Satin)); + assert_eq!(Engine::of_block(1_337, 0), Engine::Satin); + } + + /// Once a known chain schedules Satin, its blocks before the timestamp stay legacy and the + /// block at the timestamp is the first Satin one. + #[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), Engine::Legacy); + assert_eq!(Engine::under(Some(scheduled), 1_800_000_000), Engine::Satin); + assert_eq!(Engine::under(None, 0), Engine::Satin); + } +} diff --git a/bin/mega-evme/src/lib.rs b/bin/mega-evme/src/lib.rs index 02c41cb56..9d06e0553 100644 --- a/bin/mega-evme/src/lib.rs +++ b/bin/mega-evme/src/lib.rs @@ -11,6 +11,8 @@ 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. diff --git a/bin/mega-evme/src/main.rs b/bin/mega-evme/src/main.rs index da36f3dec..24b395198 100644 --- a/bin/mega-evme/src/main.rs +++ b/bin/mega-evme/src/main.rs @@ -2,16 +2,12 @@ //! //! 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::{cmd::Error, set_thread_panic_hook}; -#[tokio::main] +#[tokio::main(flavor = "multi_thread")] async fn main() -> std::result::Result<(), Error> { set_thread_panic_hook(); - MainCmd::parse().run().await.inspect_err(|e| println!("{e:?}")) + mega_evme::cmd::run_cli(std::env::args_os().collect()).await.inspect_err(|e| println!("{e:?}")) } diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 572bb722c..721a5545b 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}; @@ -9,27 +9,28 @@ use mega_evm::{ alloy_evm::{block::BlockExecutor, Evm, EvmEnv}, alloy_op_evm::block::OpAlloyReceiptBuilder, revm::{ - context::{result::ExecutionResult, BlockEnv, ContextTr}, + context::{result::ExecutionResult, BlockEnv, CfgEnv}, database::{states::bundle_state::BundleRetention, StateBuilder}, primitives::eip4844, DatabaseRef, }, - BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, - MegaEvmFactory, MegaHardforks, MegaSpecId, + system::SequencerRegistryConfig, + BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, + MegaHardforkConfig, 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, + print_execution_trace, print_receipt, print_satin_report, BuildProviderOutput, + EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, ExternalEnvSnapshot, OpTxReceipt, + RpcCacheStore, SatinReport, TxOverrideArgs, }, - replay::get_hardfork_config, - run, ChainArgs, EvmeState, + engine::Engine, + run, EvmeState, }; use super::{ReplayError, Result}; @@ -78,7 +79,8 @@ pub struct Cmd { /// 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`. + /// 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 +100,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 +112,59 @@ 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 block's timestamp, from the source the replay itself reads, + /// through a provider that persists nothing. + pub async fn engine(&self) -> Result { + if let Some(spec) = &self.spec_override { + return Engine::of_spec(spec); + } + let (provider, chain_id) = self.rpc_args.build_lookup_provider().await?; + if let Some(engine) = Engine::of_chain(chain_id) { + return Ok(engine); + } + let tx = provider + .get_transaction_by_hash(self.tx_hash) + .await + .map_err(|e| ReplayError::RpcError(format!("Failed to fetch transaction: {e}")))? + .ok_or(ReplayError::TransactionNotFound(self.tx_hash))?; + let timestamp = match tx.block_number { + Some(number) => provider + .get_block_by_number(number.into()) + .await + .map_err(|e| ReplayError::RpcError(format!("RPC transport error: {e}")))? + .ok_or(ReplayError::BlockNotFound(number))? + .header + .timestamp(), + // A pending transaction executes on top of the latest block, at a later timestamp. + None => u64::MAX, + }; + Ok(Engine::of_block(chain_id, timestamp)) + } + + /// Replay a historical transaction on the Satin 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. + // 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() { - 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(), - )); - } + 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 +189,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 +203,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 @@ -340,7 +353,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 +364,9 @@ 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_hardforks(ctx.chain_id, timestamp); + 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,117 +379,35 @@ 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 limits a Satin block runs under when its node configures nothing else: the + // production data-size caps and gas detention's caps; the block's gas limit comes from + // its header. 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(), ); 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. + let mut inspector = DeclaredObserver::new(self.trace_args.create_inspector()); 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, ); @@ -502,12 +433,7 @@ impl Cmd { .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; } - // 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 +441,30 @@ 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. + block_executor.evm_mut().inspector_mut().0.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 satin = SatinReport::of(&outcome.inner); 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") } } @@ -543,48 +475,16 @@ impl Cmd { let trace_data = self.trace_args.is_tracing_enabled().then(|| { self.trace_args.generate_trace( - block_executor.inspector(), + &block_executor.inspector().0, &result_and_state, - block_executor.evm().db_ref(), + block_executor.evm().db(), ) }); - // 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, - }; - - 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 @@ -620,9 +520,9 @@ impl Cmd { state: evm_state, exec_time: duration, trace_data, + satin, }, receipt, - fixture, }) } @@ -637,6 +537,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); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") @@ -647,6 +548,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 +562,24 @@ impl Cmd { } } +/// The hardfork schedule a Satin replay of a block of `chain_id` at `timestamp` runs under. +/// +/// A block the chain's own schedule runs on Satin runs under that schedule. Any other block is a +/// counterfactual: it runs as if Satin were active from genesis, with the placeholder registry +/// parameters, which only a registry deployed from scratch reads; a chain whose registry is +/// already deployed keeps the roles in its storage. +pub(crate) fn satin_hardforks(chain_id: u64, timestamp: u64) -> MegaHardforkConfig { + let schedule = mega_evm::hardfork_schedule(chain_id); + if schedule.spec_id(timestamp) == Some(MegaSpecId::SATIN) && + schedule.fork_params::().is_some() + { + return schedule; + } + MegaHardforkConfig::new() + .with_all_activated() + .with_params(SequencerRegistryConfig::placeholder()) +} + /// Build a [`BlockEnv`] from the RPC block header. /// /// Reads `excess_blob_gas` directly from the header rather than using a @@ -675,6 +595,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(|| { 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/cmd.rs b/bin/mega-evme/src/run/cmd.rs index 90bc33402..68671f242 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,10 +73,9 @@ 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"); @@ -107,19 +107,20 @@ 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, evm_state, trace_data, satin) = self.trace_args.execute_transaction(evm_context, tx)?; 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 +131,7 @@ impl Cmd { state: evm_state, exec_time, trace_data, + satin, }; // Step 4: Output results (including state dump if requested) @@ -151,6 +153,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); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") @@ -158,6 +161,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(), diff --git a/bin/mega-evme/src/tx/cmd.rs b/bin/mega-evme/src/tx/cmd.rs index 6e2d43390..dd50a1a3d 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; @@ -92,7 +92,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 +102,20 @@ 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, evm_state, trace_data, satin) = self.trace_args.execute_transaction(evm_context, tx.clone())?; 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,6 +126,7 @@ impl Cmd { state: evm_state, exec_time, trace_data, + satin, }; // Step 4: Output results (including state dump if requested) @@ -164,7 +166,7 @@ impl Cmd { receiver, contract_address, effective_gas_price, - outcome.exec_result.gas_used(), + outcome.exec_result.tx_gas_used(), None, None, 0, @@ -173,6 +175,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); summary.receipt = Some(serde_json::to_value(&receipt).expect("failed to serialize receipt")); println!( @@ -182,6 +185,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/fixtures/test_satin_run_basic_return.json b/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json new file mode 100644 index 000000000..b4faea4d7 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json @@ -0,0 +1,26 @@ +{ + "description": "Satin: basic bytecode: PUSH1 0x42, MSTORE, RETURN 32 bytes", + "args": [ + "run", + "0x604260005260206000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 42298, + "output": "0x0000000000000000000000000000000000000000000000000000000000000042", + "logs_count": 0, + "satin": { + "regular_gas": 15018, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json b/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json new file mode 100644 index 000000000..78f6b9894 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json @@ -0,0 +1,27 @@ +{ + "description": "Satin: read bytecode from a hex file (--codefile)", + "args": [ + "run", + "--codefile", + "{fixtures}/test_bytecode.hex", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 42298, + "output": "0x0000000000000000000000000000000000000000000000000000000000000042", + "logs_count": 0, + "satin": { + "regular_gas": 15018, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_create.json b/bin/mega-evme/tests/fixtures/test_satin_run_create.json new file mode 100644 index 000000000..5ed7f9687 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_create.json @@ -0,0 +1,29 @@ +{ + "description": "Satin: cREATE mode deploys contract, returns runtime bytecode and contract address", + "args": [ + "run", + "--create", + "true", + "0x60fe60005360016000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 241060, + "output": "0xfe", + "contract_address": "0x5fbdb2315678afecb367f032d93f642f64180aa3", + "logs_count": 0, + "satin": { + "regular_gas": 24162, + "state_gas": 185130, + "history_gas": 31768, + "history_bytes": 361, + "reservoir_remaining": 0, + "floor_gas": 24640, + "data_size": 361, + "write_records": 1, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json new file mode 100644 index 000000000..ccb9d1fd1 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json @@ -0,0 +1,65 @@ +{ + "description": "Satin: --json --dump includes state dump in JSON output (SSTORE 0xaa to slot 0)", + "args": [ + "run", + "--dump", + "0x60aa600055", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 165826, + "logs_count": 0, + "state": { + "0x0000000000000000000000000000000000000000": { + "balance": "0x0", + "nonce": "0x0", + "code": "0x60aa600055", + "codeHash": "0x8ef4cddb47b24b8b9f526597577fffec4a5e5794eaf33895ec4f057766257adc", + "storage": { + "0x0": "0xaa" + } + }, + "0x4200000000000000000000000000000000000019": { + "balance": "0x0", + "nonce": "0x0", + "code": "0x", + "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + "storage": {} + }, + "0x420000000000000000000000000000000000001a": { + "balance": "0x0", + "nonce": "0x0", + "code": "0x", + "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + "storage": {} + }, + "0x420000000000000000000000000000000000001b": { + "balance": "0x0", + "nonce": "0x0", + "code": "0x", + "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + "storage": {} + }, + "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": { + "balance": "0x0", + "nonce": "0x1", + "code": "0x", + "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + "storage": {} + } + }, + "satin": { + "regular_gas": 37106, + "state_gas": 97920, + "history_gas": 30800, + "history_bytes": 350, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 350, + "write_records": 1, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_input.json b/bin/mega-evme/tests/fixtures/test_satin_run_input.json new file mode 100644 index 000000000..8f7b22975 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_input.json @@ -0,0 +1,28 @@ +{ + "description": "Satin: calldata is passed to bytecode and echoed back via CALLDATACOPY + RETURN", + "args": [ + "run", + "--input", + "0xdeadbeef", + "0x366000600037366000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 42718, + "output": "0xdeadbeef", + "logs_count": 0, + "satin": { + "regular_gas": 15086, + "state_gas": 0, + "history_gas": 27632, + "history_bytes": 314, + "reservoir_remaining": 0, + "floor_gas": 15256, + "data_size": 314, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json b/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json new file mode 100644 index 000000000..dce4facb0 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json @@ -0,0 +1,34 @@ +{ + "description": "Satin: --prestate loads dumped state: SLOAD reads 0xaa from slot 0 of preloaded account", + "args": [ + "run", + "--prestate", + "{fixtures}/prestate_data.json", + "--sender", + "0x1111111111111111111111111111111111111111", + "--sender.balance", + "1ether", + "--receiver", + "0x0000000000000000000000000000000000000000", + "0x60005460005260206000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 44398, + "output": "0x00000000000000000000000000000000000000000000000000000000000000aa", + "logs_count": 0, + "satin": { + "regular_gas": 17118, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_revert.json b/bin/mega-evme/tests/fixtures/test_satin_run_revert.json new file mode 100644 index 000000000..f4435570a --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_revert.json @@ -0,0 +1,26 @@ +{ + "description": "Satin: rEVERT with empty data", + "args": [ + "run", + "0x5f5ffd", + "--spec", + "Satin" + ], + "expected": { + "success": false, + "gas_used": 42284, + "logs_count": 0, + "revert_reason": "(empty)", + "satin": { + "regular_gas": 15004, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json b/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json new file mode 100644 index 000000000..8d9f2bb51 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json @@ -0,0 +1,34 @@ +{ + "description": "Satin: rpcArgs flag surface regression: parses cache/retry flags on the run command without --fork", + "args": [ + "run", + "0x604260005260206000f3", + "--rpc.cache-size", + "100", + "--rpc.max-retries", + "3", + "--rpc.backoff-ms", + "500", + "--rpc.rate-limit", + "660", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 42298, + "output": "0x0000000000000000000000000000000000000000000000000000000000000042", + "logs_count": 0, + "satin": { + "regular_gas": 15018, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json b/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json new file mode 100644 index 000000000..c18022340 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json @@ -0,0 +1,28 @@ +{ + "description": "Satin: --storage overrides slot 0, SLOAD reads it back as 0x42", + "args": [ + "run", + "--storage", + "0x0000000000000000000000000000000000000000:0x0=0x42", + "0x60005460005260206000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 44398, + "output": "0x0000000000000000000000000000000000000000000000000000000000000042", + "logs_count": 0, + "satin": { + "regular_gas": 17118, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json b/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json new file mode 100644 index 000000000..d57a7d645 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json @@ -0,0 +1,112 @@ +{ + "description": "Satin: --json --trace includes opcode trace in JSON (PUSH1 0x42, MSTORE, RETURN)", + "args": [ + "run", + "--trace", + "--tracer", + "opcode", + "0x604260005260206000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 42298, + "output": "0x0000000000000000000000000000000000000000000000000000000000000042", + "logs_count": 0, + "trace": { + "failed": false, + "gas": 42298, + "returnValue": "0x0000000000000000000000000000000000000000000000000000000000000042", + "structLogs": [ + { + "pc": 0, + "op": "PUSH1", + "gas": 9957720, + "gasCost": 3, + "depth": 1, + "stack": [], + "memory": [], + "refund": 0 + }, + { + "pc": 2, + "op": "PUSH1", + "gas": 9957717, + "gasCost": 3, + "depth": 1, + "stack": [ + "0x42" + ], + "memory": [], + "refund": 0 + }, + { + "pc": 4, + "op": "MSTORE", + "gas": 9957714, + "gasCost": 6, + "depth": 1, + "stack": [ + "0x42", + "0x0" + ], + "memory": [], + "refund": 0 + }, + { + "pc": 5, + "op": "PUSH1", + "gas": 9957708, + "gasCost": 3, + "depth": 1, + "stack": [], + "memory": [ + "0x0000000000000000000000000000000000000000000000000000000000000042" + ], + "refund": 0 + }, + { + "pc": 7, + "op": "PUSH1", + "gas": 9957705, + "gasCost": 3, + "depth": 1, + "stack": [ + "0x20" + ], + "memory": [ + "0x0000000000000000000000000000000000000000000000000000000000000042" + ], + "refund": 0 + }, + { + "pc": 9, + "op": "RETURN", + "gas": 9957702, + "gasCost": 0, + "depth": 1, + "stack": [ + "0x20", + "0x0" + ], + "memory": [ + "0x0000000000000000000000000000000000000000000000000000000000000042" + ], + "refund": 0 + } + ] + }, + "satin": { + "regular_gas": 15018, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_create.json b/bin/mega-evme/tests/fixtures/test_satin_tx_create.json new file mode 100644 index 000000000..1ad13be06 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_tx_create.json @@ -0,0 +1,50 @@ +{ + "description": "Satin: tx --json --create deploys contract, receipt includes contractAddress", + "args": [ + "tx", + "--sender", + "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "--sender.balance", + "1ether", + "--create", + "true", + "--data", + "0x60fe60005360016000f3", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 241060, + "output": "0xfe", + "contract_address": "0x5fbdb2315678afecb367f032d93f642f64180aa3", + "logs_count": 0, + "receipt": { + "type": "0x0", + "status": "0x1", + "cumulativeGasUsed": "0x3ada4", + "logs": [], + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "blockHash": null, + "blockNumber": "0x1", + "gasUsed": "0x3ada4", + "effectiveGasPrice": "0x0", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": null, + "contractAddress": "0x5fbdb2315678afecb367f032d93f642f64180aa3" + }, + "satin": { + "regular_gas": 24162, + "state_gas": 185130, + "history_gas": 31768, + "history_bytes": 361, + "reservoir_remaining": 0, + "floor_gas": 24640, + "data_size": 361, + "write_records": 1, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json b/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json new file mode 100644 index 000000000..e44ece4c8 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json @@ -0,0 +1,51 @@ +{ + "description": "Satin: tx --json calling infinite loop with low gas: success=false, halt_reason=OutOfGas, receipt status=0x0", + "args": [ + "tx", + "--prestate", + "{fixtures}/prestate_contracts.json", + "--sender", + "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "--sender.balance", + "1ether", + "--receiver", + "0x0000000000000000000000000000000000c00002", + "--gas-limit", + "60100", + "--spec", + "Satin" + ], + "expected": { + "success": false, + "gas_used": 60100, + "logs_count": 0, + "halt_reason": "Base(OutOfGas(Basic))", + "receipt": { + "type": "0x0", + "status": "0x0", + "cumulativeGasUsed": "0xeac4", + "logs": [], + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "blockHash": null, + "blockNumber": "0x1", + "gasUsed": "0xeac4", + "effectiveGasPrice": "0x0", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x0000000000000000000000000000000000c00002", + "contractAddress": null + }, + "satin": { + "regular_gas": 32820, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json b/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json new file mode 100644 index 000000000..b95064882 --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json @@ -0,0 +1,49 @@ +{ + "description": "Satin: tx --json calling a contract that REVERTs: success=false, revert_reason present, receipt status=0x0", + "args": [ + "tx", + "--prestate", + "{fixtures}/prestate_contracts.json", + "--sender", + "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "--sender.balance", + "1ether", + "--receiver", + "0x0000000000000000000000000000000000c00001", + "--spec", + "Satin" + ], + "expected": { + "success": false, + "gas_used": 42284, + "logs_count": 0, + "revert_reason": "(empty)", + "receipt": { + "type": "0x0", + "status": "0x0", + "cumulativeGasUsed": "0xa52c", + "logs": [], + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "blockHash": null, + "blockNumber": "0x1", + "gasUsed": "0xa52c", + "effectiveGasPrice": "0x0", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x0000000000000000000000000000000000c00001", + "contractAddress": null + }, + "satin": { + "regular_gas": 15004, + "state_gas": 0, + "history_gas": 27280, + "history_bytes": 310, + "reservoir_remaining": 0, + "floor_gas": 15000, + "data_size": 310, + "write_records": 0, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json b/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json new file mode 100644 index 000000000..65161804b --- /dev/null +++ b/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json @@ -0,0 +1,65 @@ +{ + "description": "Satin: simple value transfer: send 1000 wei to address 0x01", + "args": [ + "tx", + "--sender", + "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "--receiver", + "0x0000000000000000000000000000000000000001", + "--value", + "1000", + "--sender.balance", + "1ether", + "--spec", + "Satin" + ], + "expected": { + "success": true, + "gas_used": 238400, + "logs_count": 1, + "receipt": { + "type": "0x0", + "status": "0x1", + "cumulativeGasUsed": "0x3a340", + "logs": [ + { + "address": "0xfffffffffffffffffffffffffffffffffffffffe", + "topics": [ + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", + "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "0x0000000000000000000000000000000000000000000000000000000000000001" + ], + "data": "0x00000000000000000000000000000000000000000000000000000000000003e8", + "blockHash": null, + "blockNumber": "0x1", + "blockTimestamp": "0x1", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "logIndex": "0x0", + "removed": false + } + ], + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000008000000000000000000040000000000000000000000000000000000002000000100000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000200008000000000000000000002000000000000000000040400000000000000000000000000000000000000000000000000000000000000000", + "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "transactionIndex": "0x0", + "blockHash": null, + "blockNumber": "0x1", + "gasUsed": "0x3a340", + "effectiveGasPrice": "0x0", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x0000000000000000000000000000000000000001", + "contractAddress": null + }, + "satin": { + "regular_gas": 24000, + "state_gas": 183600, + "history_gas": 30800, + "history_bytes": 350, + "reservoir_remaining": 0, + "floor_gas": 21000, + "data_size": 510, + "write_records": 1, + "limit_exceeded": null + } + } +} diff --git a/bin/mega-evme/tests/integration.rs b/bin/mega-evme/tests/integration.rs index b4497fba0..1322c2c05 100644 --- a/bin/mega-evme/tests/integration.rs +++ b/bin/mega-evme/tests/integration.rs @@ -76,3 +76,65 @@ fn test_fixture( ) { check(&path); } + +/// Every field a legacy run prints, a Satin run of the same command prints too, at the same path +/// and of the same JSON kind: Satin's extra output is additive only. +/// +/// Each `test_satin_.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}]")); + } + } + _ => {} + } +} diff --git a/bin/mega-evme/tests/legacy_line.rs b/bin/mega-evme/tests/legacy_line.rs new file mode 100644 index 000000000..22ae71426 --- /dev/null +++ b/bin/mega-evme/tests/legacy_line.rs @@ -0,0 +1,105 @@ +//! 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. + +/// 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"), +]; + +/// 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 + } +} + +#[test] +fn test_the_legacy_line_is_at_its_released_versions() { + let locked = locked_packages(LOCKFILE); + for &(name, pinned) in LEGACY_LINE { + let line = compatibility_line(pinned); + let versions: Vec<&str> = locked + .iter() + .filter(|(n, v)| *n == name && compatibility_line(v) == line) + .map(|(_, v)| *v) + .collect(); + assert_eq!( + versions, + [pinned], + "{name}: the legacy line resolves {versions:?}, the 1.7.1 release shipped {pinned}" + ); + } +} + +#[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/replay_dump.rs b/bin/mega-evme/tests/replay_dump.rs index 516e06619..3783dddf7 100644 --- a/bin/mega-evme/tests/replay_dump.rs +++ b/bin/mega-evme/tests/replay_dump.rs @@ -7,6 +7,10 @@ //! 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/`.) +//! +//! 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 +82,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/state.rs b/bin/mega-evme/tests/state.rs index bb811a915..76c2b3768 100644 --- a/bin/mega-evme/tests/state.rs +++ b/bin/mega-evme/tests/state.rs @@ -319,3 +319,51 @@ 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)); +} From c31d88e3f3c1abeb7eee7ef41731738c139b187e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:47:09 -0400 Subject: [PATCH 339/458] feat(evme): replay whole blocks on either engine, compared with the chain `replay --block N[..M]` runs each block on the engine its spec names and compares every receipt and the receipts root with the chain's; --verify turns a difference into exit code 2. One driver loads the block, its receipts and the state its parent left from a block cache or over RPC, and hands the engine plain data: the legacy executor reaches the 1.7.1 line only through its re-exports, the Satin one runs the counterfactual. Reads the recorded pre-state lacks fall back to the parent block over RPC and are folded into the cache. --- bin/mega-evme/src/block/cmd.rs | 306 ++++++++++ bin/mega-evme/src/block/exec.rs | 82 +++ bin/mega-evme/src/block/inputs.rs | 359 +++++++++++ bin/mega-evme/src/block/legacy.rs | 204 +++++++ bin/mega-evme/src/block/mod.rs | 22 + bin/mega-evme/src/block/record.rs | 235 ++++++++ bin/mega-evme/src/block/satin.rs | 139 +++++ bin/mega-evme/src/block/state.rs | 567 ++++++++++++++++++ bin/mega-evme/src/cmd.rs | 7 +- bin/mega-evme/src/common/outcome.rs | 4 +- bin/mega-evme/src/lib.rs | 2 + bin/mega-evme/src/replay/cmd.rs | 57 +- bin/mega-evme/src/replay/mod.rs | 1 + bin/mega-evme/tests/block_replay.rs | 333 ++++++++++ .../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 49 files changed, 2306 insertions(+), 12 deletions(-) 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 create mode 100644 bin/mega-evme/tests/block_replay.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 diff --git a/bin/mega-evme/src/block/cmd.rs b/bin/mega-evme/src/block/cmd.rs new file mode 100644 index 000000000..94cd1a288 --- /dev/null +++ b/bin/mega-evme/src/block/cmd.rs @@ -0,0 +1,306 @@ +//! `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, 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>, + 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 inputs = source.load(number, &mut codes).await?; + let engine = forced_engine + .unwrap_or_else(|| Engine::of_block(inputs.chain_id, inputs.header.timestamp)); + 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, &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: {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. +pub fn execute_block( + engine: Engine, + inputs: &super::inputs::BlockInputs, + bucket_capacities: &[(u32, u64)], + spec_override: Option<&str>, + state: &mut BlockState, +) -> Result<(super::exec::ExecutedBlock, String)> { + match engine { + Engine::Satin => { + let executed = satin::execute( + inputs.chain_id, + &inputs.header, + &inputs.transactions, + bucket_capacities, + state, + )?; + Ok((executed, mega_evm::MegaSpecId::SATIN.to_string())) + } + 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.map_or_else(String::new, |satin| { + format!( + " [regular {} state {} history {}]", + 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..344b8c8a8 --- /dev/null +++ b/bin/mega-evme/src/block/exec.rs @@ -0,0 +1,82 @@ +//! 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 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, +} + +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..9b307bab3 --- /dev/null +++ b/bin/mega-evme/src/block/inputs.rs @@ -0,0 +1,359 @@ +//! 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, and the +/// pre-state built from its trace. +#[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 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, + /// Whether the inputs came from the block 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, + 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, + 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(), + } + } +} + +/// 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, + 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, false) + } + + /// 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..d2235db7d --- /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 }) + }; + 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..1fb212668 --- /dev/null +++ b/bin/mega-evme/src/block/record.rs @@ -0,0 +1,235 @@ +//! 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; + 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(|| sum_satin(txs.iter().filter_map(|t| t.satin))); + 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(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, + }) +} + +#[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..44c0dfa01 --- /dev/null +++ b/bin/mega-evme/src/block/satin.rs @@ -0,0 +1,139 @@ +//! 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, MegaSpecId, + MegaTxEnvelope, +}; + +use super::{ + exec::{ExecStatus, ExecutedBlock, ReceiptData, TxResult}, + inputs::{HeaderFields, TxInput}, + state::{BlockState, SatinDb}, +}; +use crate::{ + common::{ + decode_revert_reason, format_halt_reason, EvmeError, EvmeExternalEnvs, Result, SatinReport, + }, + replay::satin_hardforks, +}; + +/// Executes the block `header` describes, with `transactions`, on Satin over `state`. +/// +/// The block runs as a node runs a Satin block it configures nothing else for: the chain's own +/// schedule when it activates Satin at the block, otherwise every fork active (a counterfactual), +/// the production data-size caps and gas detention's caps, the block's gas limit from its header. +/// 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, + transactions: &[TxInput], + bucket_capacities: &[(u32, u64)], + state: &mut BlockState, +) -> Result { + let hardforks = satin_hardforks(chain_id, header.timestamp); + 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 block_ctx = MegaBlockExecutionCtx::new( + header.parent_hash, + header.parent_beacon_block_root, + header.extra_data.clone(), + BlockLimits::default(), + ); + + 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 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 }) + }; + 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 +} 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 c3b671ee6..a7f9447af 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -54,7 +54,12 @@ pub async fn run_cli(args: Vec) -> Result<(), Error> { let spec_is_default = spec_is_default(&matches); let cmd = MainCmd::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); - let engine = match cmd.command.engine().await { + // 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, + }; + let engine = match engine { Ok(engine) => engine, Err(e) => { eprintln!("{e}"); diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index af12da409..1f4a9903a 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -252,7 +252,7 @@ pub fn print_satin_report(report: &SatinReport) { /// - `Error(string)` via `alloy_sol_types::Revert` /// - `Panic(uint256)` via `alloy_sol_types::Panic` /// - Raw hex fallback -fn decode_revert_reason(output: &Bytes) -> String { +pub fn decode_revert_reason(output: &Bytes) -> String { if output.is_empty() { return "(empty)".to_string(); } @@ -276,7 +276,7 @@ fn decode_revert_reason(output: &Bytes) -> String { } /// Format halt reason for display. -fn format_halt_reason(reason: &MegaHaltReason) -> String { +pub fn format_halt_reason(reason: &MegaHaltReason) -> String { match reason { OpHaltReason::Base(eth_reason) => format!("{:?}", eth_reason), _ => format!("{:?}", reason), diff --git a/bin/mega-evme/src/lib.rs b/bin/mega-evme/src/lib.rs index 9d06e0553..b7a7911af 100644 --- a/bin/mega-evme/src/lib.rs +++ b/bin/mega-evme/src/lib.rs @@ -6,6 +6,8 @@ //! 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 diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 721a5545b..2fef5401b 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -39,8 +39,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)] @@ -119,6 +123,7 @@ impl Cmd { /// at a scheduled timestamp, the block's timestamp, from the source the replay itself reads, /// through a provider that persists nothing. pub async fn engine(&self) -> Result { + let tx_hash = self.tx_hash(); if let Some(spec) = &self.spec_override { return Engine::of_spec(spec); } @@ -127,10 +132,10 @@ impl Cmd { return Ok(engine); } let 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(ReplayError::TransactionNotFound(self.tx_hash))?; + .ok_or(ReplayError::TransactionNotFound(tx_hash))?; let timestamp = match tx.block_number { Some(number) => provider .get_block_by_number(number.into()) @@ -145,8 +150,41 @@ impl Cmd { Ok(Engine::of_block(chain_id, timestamp)) } - /// Replay a historical transaction on the Satin engine. + /// 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<()> { + 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.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. @@ -242,12 +280,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_else(|| 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 { @@ -280,7 +319,7 @@ impl Cmd { let mut preceding_tx_hashes = vec![]; if !is_pending { for hash in block.transactions.hashes() { - if hash == self.tx_hash { + if hash == tx_hash { break; } preceding_tx_hashes.push(hash); diff --git a/bin/mega-evme/src/replay/mod.rs b/bin/mega-evme/src/replay/mod.rs index 5afe64fbb..57640ef83 100644 --- a/bin/mega-evme/src/replay/mod.rs +++ b/bin/mega-evme/src/replay/mod.rs @@ -5,6 +5,7 @@ mod cmd; +pub(crate) use cmd::satin_hardforks; pub use cmd::Cmd; // Re-export EvmeError and Result from common module diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs new file mode 100644 index 000000000..9ac8ae209 --- /dev/null +++ b/bin/mega-evme/tests/block_replay.rs @@ -0,0 +1,333 @@ +//! `mega-evme replay --block`: whole blocks on either engine, compared with the chain. +//! +//! The fixtures under `tests/fixtures/blocks` 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. +#![cfg(feature = "legacy")] + +use std::{path::Path, process::Command}; + +use alloy_primitives::{address, Address, B256, U256}; +use mega_evme::block::{CachedBlock, PreAccount}; +use serde_json::Value; + +/// The recorded blocks. +const BLOCKS: [u64; 3] = [26_400_001, 26_400_007, 26_400_110]; + +/// The EIP-7997 factory, which Satin's pre-block changes deploy and the legacy engine never +/// reads: the one account a Satin replay reads that the recording does not hold. +const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); + +fn fixtures() -> &'static Path { + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) +} + +/// A copy of the recorded block cache, so no test can write to the fixtures. +fn cache_copy() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + copy_dir(fixtures(), dir.path()); + dir +} + +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(); + } + } +} + +fn block_path(dir: &Path, number: u64) -> std::path::PathBuf { + dir.join("blocks").join((number / 10_000).to_string()).join(format!("{number}.json.zst")) +} + +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() +} + +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(); +} + +/// Adds the factory to the recorded pre-state of every block, absent. +fn with_absent_factory(dir: &Path) { + for number in BLOCKS { + let mut block = read_block(dir, number); + block.prestate.accounts.insert(FACTORY, PreAccount::default()); + write_block(dir, number, &block); + } +} + +/// Runs `mega-evme` with `args`, returning its exit code and its JSON lines. +fn run(args: &[&str]) -> (i32, Vec, String) { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); + let stdout = String::from_utf8(output.stdout).unwrap(); + let records = + stdout.lines().filter_map(|line| serde_json::from_str::(line).ok()).collect(); + (output.status.code().unwrap(), records, String::from_utf8(output.stderr).unwrap()) +} + +fn blocks_of(records: &[Value]) -> Vec<&Value> { + records.iter().filter(|r| r["kind"] == "block").collect() +} + +/// 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 dir = cache.path().to_str().unwrap(); + let before = std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(); + for number in BLOCKS { + let (code, records, stderr) = run(&[ + "replay", + "--block", + &number.to_string(), + "--block-cache", + dir, + "--verify", + "--json", + ]); + assert_eq!(code, 0, "block {number}: {stderr}"); + 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, _) = run(&["replay", "--block", "26400007", "--block-cache", dir, "--json"]); + 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 the EIP-7997 factory, which the recording lacks: +/// offline, the block fails and names the account, and the exit code is 1. +#[test] +fn test_a_read_the_recording_lacks_fails_the_block_offline() { + let cache = cache_copy(); + let (code, records, _) = run(&[ + "replay", + "--block", + &BLOCKS[0].to_string(), + "--block-cache", + cache.path().to_str().unwrap(), + "--override.spec", + "Satin", + "--json", + ]); + assert_eq!(code, 1); + let error = records[0]["error"].as_str().unwrap(); + assert!(error.contains("no RPC to read it"), "{error}"); + assert!(error.to_lowercase().contains(&format!("{FACTORY:#x}")), "{error}"); +} + +/// The Satin counterfactual of the recorded blocks: every block runs, nothing is refused, every +/// record carries the legacy columns and 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(); + with_absent_factory(cache.path()); + let dir = cache.path().to_str().unwrap(); + for number in BLOCKS { + let (code, records, stderr) = run(&[ + "replay", + "--block", + &number.to_string(), + "--block-cache", + dir, + "--override.spec", + "Satin", + "--json", + ]); + assert_eq!(code, 0, "{stderr}"); + let block = blocks_of(&records)[0]; + assert_eq!(block["engine"], "satin"); + assert_eq!(block["spec"], "Satin"); + assert_eq!(block["refused"], 0); + assert_eq!(block["matches_chain"], false); + assert!(block["satin"]["history_gas"].as_u64().unwrap() > 0); + } + + let (_, legacy, _) = + run(&["replay", "--block", &BLOCKS[0].to_string(), "--block-cache", dir, "--json"]); + let (code, satin, _) = run(&[ + "replay", + "--block", + &BLOCKS[0].to_string(), + "--block-cache", + dir, + "--override.spec", + "Satin", + "--verify", + "--json", + ]); + assert_eq!(code, 2, "a counterfactual differs from the chain"); + 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}"); + } + assert!(s.contains_key("satin"), "{satin}"); + } +} + +/// Whichever state the factory had on chain, the Satin rows of the recorded blocks are the +/// same: no transaction reads the factory, and the pre-block deploy that reads it is no +/// transaction. +#[test] +fn test_the_factory_state_does_not_change_the_satin_rows() { + let absent = cache_copy(); + with_absent_factory(absent.path()); + let present = cache_copy(); + for number in BLOCKS { + let mut block = read_block(present.path(), number); + block.prestate.accounts.insert( + FACTORY, + PreAccount { + balance: U256::ZERO, + nonce: 1, + code_hash: Some(mega_evm::system::CREATE2_FACTORY_CODE_HASH), + storage: Default::default(), + }, + ); + write_block(present.path(), number, &block); + } + let hash = mega_evm::system::CREATE2_FACTORY_CODE_HASH.to_string(); + let code_dir = present.path().join("codes").join(&hash[2..4]); + std::fs::create_dir_all(&code_dir).unwrap(); + std::fs::write( + code_dir.join(format!("{}.bin", &hash[2..])), + mega_evm::system::CREATE2_FACTORY_CODE, + ) + .unwrap(); + + for number in BLOCKS { + let replay = |dir: &Path| { + let (code, records, stderr) = run(&[ + "replay", + "--block", + &number.to_string(), + "--block-cache", + dir.to_str().unwrap(), + "--override.spec", + "Satin", + "--json", + ]); + assert_eq!(code, 0, "{stderr}"); + records + }; + assert_eq!(replay(absent.path()), replay(present.path()), "block {number}"); + } +} + +/// 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. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + let number = BLOCKS[2]; + 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 { + let hex = hash.to_string(); + let code = std::fs::read( + fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..])), + ) + .unwrap(); + entry["code"] = Value::String(alloy_primitives::hex::encode_prefixed(code)); + } + 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 }), + ) + }) + }; + 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: only the factory, which does not exist. + respond("eth_getBalance", serde_json::json!("0x0")).mount(&server).await; + respond("eth_getTransactionCount", serde_json::json!("0x0")).mount(&server).await; + respond("eth_getCode", serde_json::json!("0x")).mount(&server).await; + + let cache = tempfile::tempdir().unwrap(); + let dir = cache.path().to_str().unwrap().to_string(); + let uri = server.uri(); + let block = number.to_string(); + let run_blocking = move |args: Vec| { + std::thread::spawn(move || { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + run(&args) + }) + .join() + .unwrap() + }; + let args = |extra: &[&str]| -> Vec { + ["replay", "--block", &block, "--block-cache", &dir, "--json"] + .iter() + .chain(extra) + .map(|s| s.to_string()) + .collect() + }; + + let (code, records, stderr) = run_blocking(args(&["--rpc", &uri, "--verify"])); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(blocks_of(&records)[0]["matches_chain"], true); + assert!(block_path(cache.path(), number).exists(), "the fetched block is cached"); + + let (code, records, stderr) = run_blocking(args(&["--rpc", &uri, "--override.spec", "Satin"])); + assert_eq!(code, 0, "{stderr}"); + assert!(blocks_of(&records)[0]["rpc_reads"].as_u64().unwrap() > 0, "the factory came over RPC"); + + // Offline now: the cache holds the block and the factory the Satin replay read. + drop(server); + let (code, records, stderr) = run_blocking(args(&["--verify"])); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(blocks_of(&records)[0]["matches_chain"], true); + let (code, records, stderr) = run_blocking(args(&["--override.spec", "Satin"])); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(blocks_of(&records)[0]["rpc_reads"], 0); + assert!(read_block(cache.path(), number).prestate.accounts.contains_key(&FACTORY)); +} 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@ Date: Tue, 29 Sep 2026 01:49:07 -0400 Subject: [PATCH 340/458] test(evme): hold a transaction replayed alone to the block replay's row The single-transaction replay forks state lazily over RPC; the block replay runs on the recorded pre-state. A mock RPC answering only from a recorded block serves the first, and on both engines four transactions must agree with the block replay's rows: gas, status, logs, cumulative gas, and on Satin the ledgers. --- bin/mega-evme/tests/replay_paths.rs | 264 ++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 bin/mega-evme/tests/replay_paths.rs diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs new file mode 100644 index 000000000..3cde40543 --- /dev/null +++ b/bin/mega-evme/tests/replay_paths.rs @@ -0,0 +1,264 @@ +//! 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 one exception is the EIP-7997 factory, which Satin's +//! pre-block changes read and no recording holds; it is served as absent, which +//! `block_replay.rs` shows changes no transaction row. +#![cfg(feature = "legacy")] + +use std::{path::Path, process::Command, sync::Arc}; + +use alloy_primitives::{address, Address, B256, U256}; +use mega_evme::block::{CachedBlock, PreAccount}; +use serde_json::{json, Value}; +use wiremock::{matchers, Mock, MockServer, Respond, ResponseTemplate}; + +const BLOCK: u64 = 26_400_110; +const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); + +fn fixtures() -> &'static Path { + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) +} + +fn read_block(dir: &Path) -> CachedBlock { + let path = + dir.join("blocks").join((BLOCK / 10_000).to_string()).join(format!("{BLOCK}.json.zst")); + let compressed = std::fs::read(path).unwrap(); + serde_json::from_slice(&zstd::decode_all(compressed.as_slice()).unwrap()).unwrap() +} + +fn code_of(hash: B256) -> Vec { + let hex = hash.to_string(); + std::fs::read(fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..]))) + .unwrap() +} + +/// Answers JSON-RPC from the recorded block alone. +struct Recording { + block: CachedBlock, +} + +impl Recording { + fn account(&self, address: Address) -> Option { + match self.block.prestate.accounts.get(&address) { + Some(account) => Some(account.clone()), + None if address == FACTORY => Some(PreAccount::default()), + 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!([]); + 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| alloy_primitives::hex::encode_prefixed(code_of(hash))) + .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 { + let server = MockServer::start().await; + Mock::given(matchers::method("POST")) + .respond_with(Recording { block }) + .mount(&server) + .await; + Self(Arc::new(server)) + } +} + +/// Runs `mega-evme` on its own thread (the mock serves on this test's runtime). +fn run(args: Vec) -> (i32, String, String) { + std::thread::spawn(move || { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(&args).output().unwrap(); + ( + output.status.code().unwrap(), + String::from_utf8(output.stdout).unwrap(), + String::from_utf8(output.stderr).unwrap(), + ) + }) + .join() + .unwrap() +} + +fn strings(args: &[&str]) -> Vec { + args.iter().map(|s| s.to_string()).collect() +} + +/// The block replay's transaction records, on `spec`'s engine. +fn block_rows(spec: Option<&str>) -> Vec { + let cache = tempfile::tempdir().unwrap(); + for entry in ["blocks", "codes"] { + copy_dir(&fixtures().join(entry), &cache.path().join(entry)); + } + let mut block = read_block(cache.path()); + block.prestate.accounts.insert(FACTORY, PreAccount::default()); + let path = cache + .path() + .join("blocks") + .join((BLOCK / 10_000).to_string()) + .join(format!("{BLOCK}.json.zst")); + std::fs::write( + path, + zstd::encode_all(serde_json::to_vec(&block).unwrap().as_slice(), 3).unwrap(), + ) + .unwrap(); + let mut args = strings(&["replay", "--block", &BLOCK.to_string(), "--json", "--block-cache"]); + args.push(cache.path().to_str().unwrap().to_string()); + if let Some(spec) = spec { + args.extend(strings(&["--override.spec", spec])); + } + let (code, stdout, stderr) = run(args); + assert_eq!(code, 0, "{stderr}"); + stdout + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .filter(|record| record["kind"] == "tx") + .collect() +} + +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(); + } + } +} + +/// The transactions checked: the first user transaction, the plain value transfer, one in the +/// middle and the last. +fn checked(rows: &[Value]) -> Vec { + let transfer = rows.iter().position(|row| row["logs"] == 0 && row["index"] != 0).unwrap_or(1); + let mut picks = vec![1, transfer, rows.len() / 2, rows.len() - 1]; + 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()); + let server = Server::start(recorded).await; + let uri = server.0.uri(); + + for (spec, engine) in [(None, "legacy"), (Some("Satin"), "satin")] { + let rows = block_rows(spec); + for index in checked(&rows) { + let row = &rows[index]; + let mut args = strings(&["replay", row["hash"].as_str().unwrap(), "--rpc", &uri]); + args.extend(strings(&["--rpc.no-cache-file", "--rpc.max-retries", "0", "--json"])); + if let Some(spec) = spec { + args.extend(strings(&["--override.spec", spec])); + } + let (code, stdout, stderr) = run(args); + assert_eq!(code, 0, "{engine} tx {index}: {stderr}{stdout}"); + let single: Value = serde_json::from_str(&stdout).unwrap(); + 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"); + } + } + } +} From c3258dc2b0ccf98a8afe2de48b037929391e1eb5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:52:18 -0400 Subject: [PATCH 341/458] test(evme): share the recorded-block helpers between the replay tests --- bin/mega-evme/tests/block_replay.rs | 237 +++++++-------------------- bin/mega-evme/tests/common/blocks.rs | 117 +++++++++++++ bin/mega-evme/tests/common/mod.rs | 5 +- bin/mega-evme/tests/replay_paths.rs | 105 +++--------- 4 files changed, 204 insertions(+), 260 deletions(-) create mode 100644 bin/mega-evme/tests/common/blocks.rs diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 9ac8ae209..0fde00db9 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -1,104 +1,48 @@ -//! `mega-evme replay --block`: whole blocks on either engine, compared with the chain. -//! -//! The fixtures under `tests/fixtures/blocks` 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. +//! `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")] -use std::{path::Path, process::Command}; +mod common; -use alloy_primitives::{address, Address, B256, U256}; -use mega_evme::block::{CachedBlock, PreAccount}; -use serde_json::Value; - -/// The recorded blocks. -const BLOCKS: [u64; 3] = [26_400_001, 26_400_007, 26_400_110]; - -/// The EIP-7997 factory, which Satin's pre-block changes deploy and the legacy engine never -/// reads: the one account a Satin replay reads that the recording does not hold. -const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); - -fn fixtures() -> &'static Path { - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) -} - -/// A copy of the recorded block cache, so no test can write to the fixtures. -fn cache_copy() -> tempfile::TempDir { - let dir = tempfile::tempdir().unwrap(); - copy_dir(fixtures(), dir.path()); - dir -} - -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(); - } - } -} - -fn block_path(dir: &Path, number: u64) -> std::path::PathBuf { - dir.join("blocks").join((number / 10_000).to_string()).join(format!("{number}.json.zst")) -} - -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() -} +use std::path::Path; -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(); -} - -/// Adds the factory to the recorded pre-state of every block, absent. -fn with_absent_factory(dir: &Path) { - for number in BLOCKS { - let mut block = read_block(dir, number); - block.prestate.accounts.insert(FACTORY, PreAccount::default()); - write_block(dir, number, &block); - } -} - -/// Runs `mega-evme` with `args`, returning its exit code and its JSON lines. -fn run(args: &[&str]) -> (i32, Vec, String) { - let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); - let stdout = String::from_utf8(output.stdout).unwrap(); - let records = - stdout.lines().filter_map(|line| serde_json::from_str::(line).ok()).collect(); - (output.status.code().unwrap(), records, String::from_utf8(output.stderr).unwrap()) -} +use alloy_primitives::{B256, U256}; +use common::blocks::{ + block_path, cache_copy, cache_copy_with_absent_factory, code_of, fixtures, read_block, + run_evme, write_block, BLOCKS, FACTORY, +}; +use mega_evme::block::PreAccount; +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 dir = cache.path().to_str().unwrap(); let before = std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(); for number in BLOCKS { - let (code, records, stderr) = run(&[ - "replay", - "--block", - &number.to_string(), - "--block-cache", - dir, - "--verify", - "--json", - ]); - assert_eq!(code, 0, "block {number}: {stderr}"); + 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]; @@ -113,7 +57,7 @@ fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { 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, _) = run(&["replay", "--block", "26400007", "--block-cache", dir, "--json"]); + 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); } @@ -123,17 +67,9 @@ fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { #[test] fn test_a_read_the_recording_lacks_fails_the_block_offline() { let cache = cache_copy(); - let (code, records, _) = run(&[ - "replay", - "--block", - &BLOCKS[0].to_string(), - "--block-cache", - cache.path().to_str().unwrap(), - "--override.spec", - "Satin", - "--json", - ]); - assert_eq!(code, 1); + let run = replay(BLOCKS[0], cache.path(), &["--override.spec", "Satin"]); + assert_eq!(run.code, 1); + let records = run.records(); let error = records[0]["error"].as_str().unwrap(); assert!(error.contains("no RPC to read it"), "{error}"); assert!(error.to_lowercase().contains(&format!("{FACTORY:#x}")), "{error}"); @@ -144,21 +80,11 @@ fn test_a_read_the_recording_lacks_fails_the_block_offline() { /// from the chain with exit code 2. #[test] fn test_the_satin_counterfactual_of_recorded_blocks() { - let cache = cache_copy(); - with_absent_factory(cache.path()); - let dir = cache.path().to_str().unwrap(); + let cache = cache_copy_with_absent_factory(); for number in BLOCKS { - let (code, records, stderr) = run(&[ - "replay", - "--block", - &number.to_string(), - "--block-cache", - dir, - "--override.spec", - "Satin", - "--json", - ]); - assert_eq!(code, 0, "{stderr}"); + 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"); @@ -167,20 +93,10 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { assert!(block["satin"]["history_gas"].as_u64().unwrap() > 0); } - let (_, legacy, _) = - run(&["replay", "--block", &BLOCKS[0].to_string(), "--block-cache", dir, "--json"]); - let (code, satin, _) = run(&[ - "replay", - "--block", - &BLOCKS[0].to_string(), - "--block-cache", - dir, - "--override.spec", - "Satin", - "--verify", - "--json", - ]); - assert_eq!(code, 2, "a counterfactual differs from the chain"); + 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!() }; @@ -196,8 +112,7 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { /// transaction. #[test] fn test_the_factory_state_does_not_change_the_satin_rows() { - let absent = cache_copy(); - with_absent_factory(absent.path()); + let absent = cache_copy_with_absent_factory(); let present = cache_copy(); for number in BLOCKS { let mut block = read_block(present.path(), number); @@ -222,21 +137,12 @@ fn test_the_factory_state_does_not_change_the_satin_rows() { .unwrap(); for number in BLOCKS { - let replay = |dir: &Path| { - let (code, records, stderr) = run(&[ - "replay", - "--block", - &number.to_string(), - "--block-cache", - dir.to_str().unwrap(), - "--override.spec", - "Satin", - "--json", - ]); - assert_eq!(code, 0, "{stderr}"); - records + let rows = |dir: &Path| { + let run = replay(number, dir, &["--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + run.records() }; - assert_eq!(replay(absent.path()), replay(present.path()), "block {number}"); + assert_eq!(rows(absent.path()), rows(present.path()), "block {number}"); } } @@ -254,12 +160,7 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { 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 { - let hex = hash.to_string(); - let code = std::fs::read( - fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..])), - ) - .unwrap(); - entry["code"] = Value::String(alloy_primitives::hex::encode_prefixed(code)); + entry["code"] = Value::String(alloy_primitives::hex::encode_prefixed(code_of(hash))); } let storage: serde_json::Map<_, _> = account .storage @@ -293,41 +194,27 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { respond("eth_getCode", serde_json::json!("0x")).mount(&server).await; let cache = tempfile::tempdir().unwrap(); - let dir = cache.path().to_str().unwrap().to_string(); let uri = server.uri(); - let block = number.to_string(); - let run_blocking = move |args: Vec| { - std::thread::spawn(move || { - let args: Vec<&str> = args.iter().map(String::as_str).collect(); - run(&args) - }) - .join() - .unwrap() - }; - let args = |extra: &[&str]| -> Vec { - ["replay", "--block", &block, "--block-cache", &dir, "--json"] - .iter() - .chain(extra) - .map(|s| s.to_string()) - .collect() - }; - let (code, records, stderr) = run_blocking(args(&["--rpc", &uri, "--verify"])); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(blocks_of(&records)[0]["matches_chain"], true); + 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 (code, records, stderr) = run_blocking(args(&["--rpc", &uri, "--override.spec", "Satin"])); - assert_eq!(code, 0, "{stderr}"); - assert!(blocks_of(&records)[0]["rpc_reads"].as_u64().unwrap() > 0, "the factory came over RPC"); + let run = replay(number, cache.path(), &["--rpc", &uri, "--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert!( + blocks_of(&run.records())[0]["rpc_reads"].as_u64().unwrap() > 0, + "the factory came over RPC" + ); // Offline now: the cache holds the block and the factory the Satin replay read. drop(server); - let (code, records, stderr) = run_blocking(args(&["--verify"])); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(blocks_of(&records)[0]["matches_chain"], true); - let (code, records, stderr) = run_blocking(args(&["--override.spec", "Satin"])); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(blocks_of(&records)[0]["rpc_reads"], 0); + 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); assert!(read_block(cache.path(), number).prestate.accounts.contains_key(&FACTORY)); } diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs new file mode 100644 index 000000000..10a21c81e --- /dev/null +++ b/bin/mega-evme/tests/common/blocks.rs @@ -0,0 +1,117 @@ +//! 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}; +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 pre-block changes deploy and the legacy engine never +/// reads: the one account a Satin replay reads that the recording does not hold. +pub(crate) const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); + +/// 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. +pub(crate) fn code_of(hash: B256) -> Vec { + let hex = hash.to_string(); + std::fs::read(fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..]))) + .unwrap() +} + +/// 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 the factory, absent: +/// what a Satin replay needs offline. `block_replay.rs` shows the factory's state changes no +/// transaction row. +pub(crate) fn cache_copy_with_absent_factory() -> tempfile::TempDir { + let dir = cache_copy(); + for number in BLOCKS { + let mut block = read_block(dir.path(), number); + block.prestate.accounts.insert(FACTORY, PreAccount::default()); + write_block(dir.path(), number, &block); + } + dir +} + +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() + } +} + +/// 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() +} diff --git a/bin/mega-evme/tests/common/mod.rs b/bin/mega-evme/tests/common/mod.rs index 54dfc716f..fc71cf425 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}; diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index 3cde40543..1c83462d2 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -12,32 +12,19 @@ //! `block_replay.rs` shows changes no transaction row. #![cfg(feature = "legacy")] -use std::{path::Path, process::Command, sync::Arc}; +mod common; -use alloy_primitives::{address, Address, B256, U256}; +use std::sync::Arc; + +use alloy_primitives::{Address, B256, U256}; +use common::blocks::{ + cache_copy_with_absent_factory, code_of, fixtures, read_block, run_evme, FACTORY, +}; use mega_evme::block::{CachedBlock, PreAccount}; use serde_json::{json, Value}; use wiremock::{matchers, Mock, MockServer, Respond, ResponseTemplate}; const BLOCK: u64 = 26_400_110; -const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); - -fn fixtures() -> &'static Path { - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) -} - -fn read_block(dir: &Path) -> CachedBlock { - let path = - dir.join("blocks").join((BLOCK / 10_000).to_string()).join(format!("{BLOCK}.json.zst")); - let compressed = std::fs::read(path).unwrap(); - serde_json::from_slice(&zstd::decode_all(compressed.as_slice()).unwrap()).unwrap() -} - -fn code_of(hash: B256) -> Vec { - let hex = hash.to_string(); - std::fs::read(fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..]))) - .unwrap() -} /// Answers JSON-RPC from the recorded block alone. struct Recording { @@ -154,67 +141,17 @@ impl Server { } } -/// Runs `mega-evme` on its own thread (the mock serves on this test's runtime). -fn run(args: Vec) -> (i32, String, String) { - std::thread::spawn(move || { - let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(&args).output().unwrap(); - ( - output.status.code().unwrap(), - String::from_utf8(output.stdout).unwrap(), - String::from_utf8(output.stderr).unwrap(), - ) - }) - .join() - .unwrap() -} - -fn strings(args: &[&str]) -> Vec { - args.iter().map(|s| s.to_string()).collect() -} - /// The block replay's transaction records, on `spec`'s engine. fn block_rows(spec: Option<&str>) -> Vec { - let cache = tempfile::tempdir().unwrap(); - for entry in ["blocks", "codes"] { - copy_dir(&fixtures().join(entry), &cache.path().join(entry)); - } - let mut block = read_block(cache.path()); - block.prestate.accounts.insert(FACTORY, PreAccount::default()); - let path = cache - .path() - .join("blocks") - .join((BLOCK / 10_000).to_string()) - .join(format!("{BLOCK}.json.zst")); - std::fs::write( - path, - zstd::encode_all(serde_json::to_vec(&block).unwrap().as_slice(), 3).unwrap(), - ) - .unwrap(); - let mut args = strings(&["replay", "--block", &BLOCK.to_string(), "--json", "--block-cache"]); - args.push(cache.path().to_str().unwrap().to_string()); + let cache = cache_copy_with_absent_factory(); + let mut args = vec!["replay", "--block", "26400110", "--json", "--block-cache"]; + args.push(cache.path().to_str().unwrap()); if let Some(spec) = spec { - args.extend(strings(&["--override.spec", spec])); - } - let (code, stdout, stderr) = run(args); - assert_eq!(code, 0, "{stderr}"); - stdout - .lines() - .map(|line| serde_json::from_str::(line).unwrap()) - .filter(|record| record["kind"] == "tx") - .collect() -} - -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(); - } + args.extend(["--override.spec", spec]); } + 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 @@ -229,7 +166,7 @@ fn checked(rows: &[Value]) -> Vec { #[tokio::test(flavor = "multi_thread")] async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { - let recorded = read_block(fixtures()); + let recorded = read_block(fixtures(), BLOCK); let server = Server::start(recorded).await; let uri = server.0.uri(); @@ -237,14 +174,14 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { let rows = block_rows(spec); for index in checked(&rows) { let row = &rows[index]; - let mut args = strings(&["replay", row["hash"].as_str().unwrap(), "--rpc", &uri]); - args.extend(strings(&["--rpc.no-cache-file", "--rpc.max-retries", "0", "--json"])); + 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(strings(&["--override.spec", spec])); + args.extend(["--override.spec", spec]); } - let (code, stdout, stderr) = run(args); - assert_eq!(code, 0, "{engine} tx {index}: {stderr}{stdout}"); - let single: Value = serde_json::from_str(&stdout).unwrap(); + let run = run_evme(&args); + assert_eq!(run.code, 0, "{engine} tx {index}: {}{}", run.stderr, run.stdout); + let single: Value = serde_json::from_str(&run.stdout).unwrap(); 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}"); From bc8743f89f4c77fc873bb59f10cf9ae138f72338 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 01:54:18 -0400 Subject: [PATCH 342/458] test(evme): pin the expected differences between Satin and the legacy engine tests/satin-differences.md is rendered from what the two engines produce on the same inputs and compared with the checked-in file: every run and tx fixture on both engines, and the three recorded mainnet blocks, per block and per call target. UPDATE_EVME_DIFFERENCES=1 rewrites it. --- bin/mega-evme/tests/differences.rs | 327 +++++++++++++++++++++++ bin/mega-evme/tests/satin-differences.md | 78 ++++++ 2 files changed, 405 insertions(+) create mode 100644 bin/mega-evme/tests/differences.rs create mode 100644 bin/mega-evme/tests/satin-differences.md diff --git a/bin/mega-evme/tests/differences.rs b/bin/mega-evme/tests/differences.rs new file mode 100644 index 000000000..08fde4345 --- /dev/null +++ b/bin/mega-evme/tests/differences.rs @@ -0,0 +1,327 @@ +//! 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_with_absent_factory, 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_with_absent_factory(); + 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"])); + let state_gas = sum(&|p| 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, with the entries EIP-8038 \ + repriced back at Osaka's) 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/satin-differences.md b/bin/mega-evme/tests/satin-differences.md new file mode 100644 index 000000000..d449c9a30 --- /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, with the entries EIP-8038 repriced back at Osaka's) 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 165826 | +83720 | 37106 | 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 | 12252942 | 1.15 | 7185347 | 0 | 5065016 | 13 | 138 -> 121 | 0 | +| 26400007 | 25 | 8428932 | 8956346 | 1.06 | 4457736 | 0 | 4493720 | 0 | 119 -> 119 | 0 | +| 26400110 | 27 | 8051381 | 8678731 | 1.07 | 4182321 | 0 | 4491520 | 0 | 121 -> 121 | 0 | + +## 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 | 853864 | 0.33 | 0 | 0 | 0 -> 0 | +| 0x897a33a0af45b3ba097bd6045187d622252e6acd | 0x9aec351f | 30 | 18019164 | 21657264 | 1.20 | 0 | 0 | 330 -> 330 | +| deposit | - | 3 | 304908 | 120588 | 0.39 | 0 | 0 | 0 -> 0 | +| 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x21d5c9bb | 2 | 601407 | 643335 | 1.06 | 0 | 0 | 6 -> 6 | +| 0x57677bdc4f24d5c08ddce87e06670c26a00cac0b | 0xb7a16251 | 2 | 1559890 | 1509424 | 0.96 | 0 | 0 | 19 -> 19 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fad7 | 2 | 151028 | 121524 | 0.80 | 0 | 0 | 0 -> 0 | +| 0x0b5cca2dd7bcc50b17213aa4828fc8e4bf9bcfc2 | 0xf7a30806 | 1 | 161042 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x93ca625d | 1 | 314985 | 340081 | 1.07 | 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 | 593610 | 0.91 | 0 | 0 | 0 -> 0 | +| 0x609ca0a22ed2e361a2787939f4903b1fd4bc54ca | 0x38dd01ff | 1 | 235544 | 400000 | 1.69 | 0 | 1 | 2 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fadc | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fadd | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb42 | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb43 | 1 | 75514 | 60762 | 0.80 | 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 | 186001 | 0.98 | 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 | From 633c4755af3a91a2043101007c2e502d4705997c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:00:46 -0400 Subject: [PATCH 343/458] fix(evme): print an engine hand-off error once, as other errors are --- bin/mega-evme/src/cmd.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index a7f9447af..a3acaffa7 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -68,7 +68,10 @@ pub async fn run_cli(args: Vec) -> Result<(), Error> { }; match engine { Engine::Legacy => { - crate::engine::run_legacy(args, spec_is_default).await?; + if let Err(e) = crate::engine::run_legacy(args, spec_is_default).await { + eprintln!("{e}"); + std::process::exit(1); + } Ok(()) } Engine::Satin => cmd.run().await, From 94fc38a82a1f764f42506301d8989b2dd3c9b340 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:04:07 -0400 Subject: [PATCH 344/458] docs(evme): document the two engines, Satin output and block replay The docs, the crate README, the help text and the agent files describe how a spec picks the engine, the additive `satin` output, replay's engine auto-detection (an unknown chain now runs Satin, where 1.7.1 ran Rex7), --dump-fixture being legacy-only, and replay --block with its cache, records and exit codes. The build command selects the tool by manifest path. --- AGENTS.md | 1 + bin/mega-evme/AGENTS.md | 4 +- bin/mega-evme/README.md | 51 +++++++-- bin/mega-evme/src/cmd.rs | 2 +- bin/mega-evme/src/common/env.rs | 7 +- bin/mega-evme/src/replay/cmd.rs | 3 +- docs/mega-evme/commands/replay.md | 100 +++++++++++++++++- docs/mega-evme/commands/run.md | 25 ++--- docs/mega-evme/commands/tx.md | 4 +- .../mega-evme/configuration/chain-and-spec.md | 38 ++++++- docs/mega-evme/cookbook.md | 31 ++++++ docs/mega-evme/overview.md | 25 ++++- 12 files changed, 256 insertions(+), 35 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 740c2f5cd..6df356222 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ cargo build cargo test # all tests 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 diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 29ea5d897..5cb2c38b6 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -11,7 +11,9 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - `src/common/`: shared CLI args, state loading, tracing, tx parsing, output printers. - `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`), 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. diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index 4b91bcd5c..338ad29b5 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -17,11 +17,23 @@ 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`). +`tests/integration.rs` checks that on every fixture pair, and `tests/satin-differences.md` pins what the two engines produce on the same inputs. + +The legacy leg is the default feature `legacy`; `--no-default-features` builds a Satin-only binary. ## Installation @@ -34,10 +46,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 @@ -200,6 +215,7 @@ mega-evme tx --tx-type 4 \ ### 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 @@ -246,6 +262,27 @@ 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. + +| 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 +mega-evme replay --block 26400000..26400199 --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 +302,7 @@ These options are available across all commands. | Option | Default | Description | | ---------------------- | ------- | ----------------------------------------- | -| `--spec ` | Rex6 | Spec: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`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) | | `--chain-id ` | 6342 | Chain ID | ### Block Environment diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index a3acaffa7..d633a9f56 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -29,7 +29,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), } diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 7d3b35546..880daac9a 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -25,9 +25,10 @@ use super::{EvmeError, Result}; #[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` (`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) #[arg(long = "spec", default_value = "Rex6")] pub spec: String, diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 2fef5401b..a085b460b 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -62,7 +62,8 @@ 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, diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index fa27f7b3c..de6a2027d 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 @@ -112,6 +115,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. @@ -143,26 +147,92 @@ state-test --bench /tmp/tx.json ## 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 `Rex6`. -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. + +Any other chain runs Satin from genesis, the rung the Satin engine pins for an unrecognized chain. +The 1.7.1 tool ran such a chain through `Rex7`, the legacy line's unstable spec, which Satin supersedes. +Use `--override.spec` below to replay a chain that runs a legacy spec. ### `--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. ``` 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 deploys, which MegaETH mainnet and testnet reach at `Rex6`. +On an older block Satin's own deploy check refuses to overwrite them, and the replay fails with an error naming the contract. + +## 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. + +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. +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. + +| 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`, `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 the limits a Satin block runs under by default. +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. +Satin's pre-block changes deploy the EIP-7997 factory at `0x4e59b44847b379578588920cA78FbF26c0B4956C`, which no legacy spec reads, so a block cached from a legacy replay does not hold it; the first Satin replay of the block reads it over RPC and adds it to the cache. + ## Transaction Overrides Override flags let you modify the transaction before re-executing it. @@ -234,6 +304,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, offline once they are cached** + +```bash +mega-evme replay --block 26400000..26400199 --block-cache ./blocks \ + --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 f54d392a0..0b2700a80 100644 --- a/docs/mega-evme/commands/run.md +++ b/docs/mega-evme/commands/run.md @@ -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,7 +328,7 @@ RPC Options: Chain Options: --spec - Name of spec to use, possible values: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (`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) [default: Rex6] diff --git a/docs/mega-evme/commands/tx.md b/docs/mega-evme/commands/tx.md index 5ef142c85..3add30594 100644 --- a/docs/mega-evme/commands/tx.md +++ b/docs/mega-evme/commands/tx.md @@ -79,7 +79,7 @@ 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 | | --------- | ---------------- | --------------------------------------------------------------------------- | @@ -213,7 +213,7 @@ RPC Options: --rpc.rate-limit Retry-layer compute-units-per-second budget [default: 660] Chain Options: - --spec Spec [default: Rex6] + --spec Spec: `Satin`, or a legacy spec `Equivalence` to `Rex6` [default: Rex6] --chain-id Chain ID [default: 6342] [aliases: --chainid] Block Options: diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index e254b8b6d..d2a8308ed 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -4,7 +4,7 @@ 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)). @@ -21,6 +21,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) | @@ -33,6 +34,38 @@ Spec names are case-sensitive. | `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` 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`, `kv_update`, `compute_gas`, `state_growth`), `limit`, `used` | + +In text mode the same numbers follow the summary under `=== Satin Gas ===`. +A legacy run has no `satin` field. + ## Examples ```bash @@ -44,4 +77,7 @@ 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 ``` diff --git a/docs/mega-evme/cookbook.md b/docs/mega-evme/cookbook.md index f554220de..93562e36b 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -46,6 +46,37 @@ 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, offline once the first Satin run has cached what Satin reads beyond the legacy replay, and keep the per-transaction records: + +```bash +mega-evme replay --block 26400000..26400099 --block-cache ./blocks \ + --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..ddf5b4f7b 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. From 7605bd6a488584d67097bc6b64e1d72ee0dd05e4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:04:58 -0400 Subject: [PATCH 345/458] docs(evme): give the first Satin block replay the RPC it needs A cache a legacy replay wrote lacks the EIP-7997 factory Satin's pre-block changes read, so the Satin examples pass --rpc, and say that later runs can drop it. --- bin/mega-evme/README.md | 5 +++-- docs/mega-evme/commands/replay.md | 4 ++-- docs/mega-evme/cookbook.md | 5 +++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index 338ad29b5..ce40d5654 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -277,8 +277,9 @@ mega-evme replay 0x1234...txhash --override.input-file calldata.hex # 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 -mega-evme replay --block 26400000..26400199 --block-cache ./blocks --override.spec Satin --json > satin.ndjson +# The same blocks on Satin, as NDJSON (the first Satin run reads the EIP-7997 factory 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. diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index de6a2027d..d3b041a2e 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -317,11 +317,11 @@ mega-evme replay --block 26400000..26400199 \ --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify ``` -**Replay the recorded blocks on Satin, offline once they are cached** +**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 \ - --override.spec Satin --json > satin.ndjson + --rpc https://mainnet.megaeth.com/rpc --override.spec Satin --json > satin.ndjson ``` ## See Also diff --git a/docs/mega-evme/cookbook.md b/docs/mega-evme/cookbook.md index 93562e36b..20da454c5 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -68,11 +68,12 @@ mega-evme replay --block 26400000..26400099 \ --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify ``` -Replay the same blocks on Satin, offline once the first Satin run has cached what Satin reads beyond the legacy replay, and keep the per-transaction records: +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 EIP-7997 factory its pre-block changes deploy) 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 \ - --override.spec Satin --json > satin.ndjson + --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`). From df217b580fb444c734cf277da2917cd458163901 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:13:50 -0400 Subject: [PATCH 346/458] fix(evme): report a Satin command's error once, and a legacy one as 1.7.1 did A `?` inside each dispatch arm returned before the report, so an error fell through to main and printed its Debug form twice. Satin commands now print the message once to stderr and exit 1. A legacy command's error is printed as the 1.7.1 binary printed it: Debug to stdout, then `Error:` with the Debug form to stderr, exit 1. --- bin/mega-evme/src/cmd.rs | 23 ++++++++--------------- bin/mega-evme/src/engine.rs | 12 ++++++++---- bin/mega-evme/tests/integration.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 19 deletions(-) diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index d633a9f56..c78c180e0 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -104,21 +104,14 @@ impl MainCmd { // 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); diff --git a/bin/mega-evme/src/engine.rs b/bin/mega-evme/src/engine.rs index e9e0b2ede..6730368af 100644 --- a/bin/mega-evme/src/engine.rs +++ b/bin/mega-evme/src/engine.rs @@ -96,10 +96,14 @@ pub async fn run_legacy(mut args: Vec, append_default_spec: bool) -> R args.push("--spec".into()); args.push(DEFAULT_SPEC.into()); } - mega_evme_legacy::cmd::MainCmd::parse_from(args) - .run() - .await - .map_err(|e| EvmeError::Other(format!("legacy engine: {e}"))) + if let Err(e) = mega_evme_legacy::cmd::MainCmd::parse_from(args).run().await { + // What the 1.7.1 binary's `main` does with an error its command returns: print it to + // stdout, then return it from `main`, which prints it to stderr and exits with code 1. + println!("{e:?}"); + eprintln!("Error: {e:?}"); + std::process::exit(1); + } + Ok(()) } /// Refuses a legacy spec in a build without the legacy leg. diff --git a/bin/mega-evme/tests/integration.rs b/bin/mega-evme/tests/integration.rs index 1322c2c05..0d98e4929 100644 --- a/bin/mega-evme/tests/integration.rs +++ b/bin/mega-evme/tests/integration.rs @@ -138,3 +138,30 @@ fn assert_superset(satin: &serde_json::Value, legacy: &serde_json::Value, name: _ => {} } } + +/// An error prints as the engine that ran the command prints it: on a legacy spec exactly as the +/// 1.7.1 binary did (its `Debug` form to stdout, then `Error: ...` to stderr), on Satin once, to +/// stderr, as a 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!(stdout.starts_with("Evme(FileRead(Os {"), "{stdout}"); + assert!(stderr.starts_with("Error: Evme(FileRead(Os {"), "{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)"] + ); +} From 75c44a6b87de107633e76c7643f5121061c1b4c5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:19:43 -0400 Subject: [PATCH 347/458] test(evm): size the unit tests' transactions at the byte prices in effect --- crates/mega-evm/src/evm/mod.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 400e1e8e9..76b62f743 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -598,11 +598,17 @@ mod tests { } /// 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() From 6d25da548f81a4f917f11dc291470bfc88131db6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:19:43 -0400 Subject: [PATCH 348/458] test(block): hold the block tests at any byte price A transaction's gas limit covers its body's history, the state it adds and the records it keeps at the prices in effect, and a call 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 gas to cross a limit with is skipped where a state byte costs nothing. --- crates/mega-evm/tests/block/common.rs | 55 ++++++++++- crates/mega-evm/tests/block/counters.rs | 21 +++- crates/mega-evm/tests/block/deploy.rs | 10 +- crates/mega-evm/tests/block/deposits.rs | 23 ++++- crates/mega-evm/tests/block/factory.rs | 8 +- crates/mega-evm/tests/block/inspector.rs | 20 ++-- crates/mega-evm/tests/block/limits.rs | 97 +++++++++++++------ crates/mega-evm/tests/block/receipts.rs | 8 +- crates/mega-evm/tests/block/rules.rs | 26 +++-- crates/mega-evm/tests/block/salt.rs | 20 +++- crates/mega-evm/tests/block/schedule.rs | 4 +- .../tests/block/sequencer_registry.rs | 17 +++- crates/mega-evm/tests/block/state_gas.rs | 87 +++++++++++------ crates/mega-evm/tests/block/transfer_logs.rs | 17 +++- 14 files changed, 311 insertions(+), 102 deletions(-) diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 457153e35..cb48a92f8 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -19,6 +19,7 @@ use mega_evm::{ use op_alloy_consensus::TxDeposit; use revm::{ context::{BlockEnv, CfgEnv}, + context_interface::cfg::GasId, database::State, inspector::NoOpInspector, state::EvmState, @@ -220,6 +221,19 @@ pub(crate) fn pre_block_states(log: &PreBlockLog) -> Vec<(PreBlockStateSource, E log.lock().expect("pre-block observer").clone() } +/// 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 [`CALLER`]. pub(crate) fn tx(nonce: u64, to: Address, input: Bytes, gas_limit: u64) -> MegaTxEnvelope { let tx_legacy = TxLegacy { @@ -243,12 +257,51 @@ 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; the notice goes to stderr once, since the harness keeps a passing test's +/// output to itself. +pub(crate) fn state_is_free() -> bool { + use std::io::Write; + + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the cases that need state gas, because 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), + tx(0, ORACLE_CONTRACT_ADDRESS, input.into(), 1_000_000 + new_account_state_gas()), MEGA_SYSTEM_ADDRESS, ) } diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 92fe3e8db..8f2489b32 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -32,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()); @@ -40,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 @@ -53,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; @@ -79,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(); @@ -190,11 +201,11 @@ fn test_the_state_and_history_ledgers_refuse_nothing() { 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"); + executor.execute_transaction(&user_tx(nonce, writer_gas())).expect("nothing refuses these"); } let counters = *executor.gas(); - assert!(counters.state > 0, "the Satin gas table prices state gas, and these writes draw it"); + 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 + diff --git a/crates/mega-evm/tests/block/deploy.rs b/crates/mega-evm/tests/block/deploy.rs index cf994c5ef..92317ed33 100644 --- a/crates/mega-evm/tests/block/deploy.rs +++ b/crates/mega-evm/tests/block/deploy.rs @@ -287,13 +287,21 @@ fn test_a_create2_round_trip_through_the_factory() { 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), - 1_000_000, + gas_limit, ))) .expect("the factory call runs"); match &outcome.result { diff --git a/crates/mega-evm/tests/block/deposits.rs b/crates/mega-evm/tests/block/deposits.rs index e8cda2ea1..64dcec28a 100644 --- a/crates/mega-evm/tests/block/deposits.rs +++ b/crates/mega-evm/tests/block/deposits.rs @@ -25,11 +25,18 @@ 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"); -const GAS_LIMIT: u64 = 1_000_000; - /// 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() @@ -54,7 +61,7 @@ fn input(slot: u64) -> Bytes { /// A deposit that fills the fresh `slot`: execution gas, state gas, data size and a write record, /// all four. fn deposit(slot: u64) -> Recovered { - common::deposit_tx_to(WRITER, input(slot), GAS_LIMIT) + common::deposit_tx_to(WRITER, input(slot), gas_limit()) } /// An ordinary transaction that fills the fresh `slot`, so each of the four limits has something @@ -64,7 +71,7 @@ fn ordinary(slot: u64) -> Recovered { chain_id: Some(CHAIN_ID), nonce: 0, gas_price: 1_000_000, - gas_limit: GAS_LIMIT, + gas_limit: gas_limit(), to: TxKind::Call(WRITER), value: U256::ZERO, input: input(slot), @@ -86,7 +93,8 @@ fn one_deposit() -> (BlockGasCounters, LimitUsage) { 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 && gas.state > 0 && usage.data_size > 0, "{gas:?} {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) } @@ -155,6 +163,11 @@ enum Route { fn test_no_block_limit_refuses_a_deposit_and_every_deposit_counts() { let (gas, usage) = one_deposit(); for cap in [Cap::ExecutionGas, Cap::StateGas, Cap::DataSize, Cap::KvUpdates, Cap::All] { + // A deposit that adds no state gas cannot cross a state-gas cap, and the ordinary + // transaction after it adds none to be refused for. + if matches!(cap, Cap::StateGas) && common::state_is_free() { + continue; + } for route in [Route::OneByOne, Route::CheckedCommit, Route::TraitCommit] { let name = format!("{cap:?} by {route:?}"); let limits = cap.limits(&gas, &usage); diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index bb4d48dde..82774bae1 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -185,8 +185,14 @@ fn test_direct_construction_stops_a_transaction_over_the_chains_data_size_limit( 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!( diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index afb182163..8d1bd8399 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -35,7 +35,7 @@ use std::{ sync::{Arc, Mutex}, }; -use crate::common::{self, system_tx, 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. @@ -54,7 +54,7 @@ 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); @@ -128,12 +128,15 @@ 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"); @@ -154,14 +157,17 @@ fn test_the_unchecked_commit_commits_what_ran_under_the_gate() { 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, 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); 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, 100_000))), "nothing runs after"); + assert!( + is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), + "nothing runs after" + ); assert_eq!(executor.receipts().len(), 1); } @@ -178,7 +184,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"); diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 0b2b0a9e8..c267c3dea 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -16,7 +16,7 @@ use revm::{ Database as _, }; -use crate::common::{self, executor, incompressible, user_tx, CALLER, CONTRACT}; +use crate::common::{self, empty_call_gas, executor, incompressible, user_tx, CALLER, CONTRACT}; const CALLER2: Address = address!("0x2000000000000000000000000000000000000003"); const CALLER3: Address = address!("0x2000000000000000000000000000000000000004"); @@ -31,6 +31,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, @@ -61,11 +70,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"); @@ -73,7 +82,7 @@ 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}"); } @@ -89,7 +98,7 @@ fn test_block_multiple_transactions_within_limits() { executor.apply_pre_execution_changes().expect("the block starts"); for nonce in 0..5 { - let tx = user_tx(nonce, 1_000_000); + let tx = user_tx(nonce, log_call_gas(100)); let gas = executor.execute_transaction(&tx).expect("the transaction is packed"); assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); } @@ -110,10 +119,10 @@ fn test_block_data_limit_exceeded_mid_block() { 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, log_call_gas(2_000))).expect("packed"); } assert!( - executor.execute_transaction(&user_tx(3, 1_000_000)).is_err(), + executor.execute_transaction(&user_tx(3, log_call_gas(2_000))).is_err(), "the block has no data-size left" ); @@ -138,6 +147,16 @@ fn incrementing_contract(writes: u64) -> Bytes { code.stop().build() } +/// 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") +} + /// A state whose callee keeps `writes` write records on every call. fn state_with_incrementing_contract( writes: u64, @@ -152,17 +171,24 @@ fn state_with_incrementing_contract( #[test] fn test_block_custom_kv_update_limit() { let mut state = state_with_incrementing_contract(50); - let mut executor = executor( + // Room in the block's gas for both transactions whatever fifty slots cost, so the block's + // write records are what refuses the second. + 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().with_block_kv_update_limit(1)), + env, ); executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&user_tx(0, 10_000_000)).expect("the crossing transaction"); + executor + .execute_transaction(&user_tx(0, incrementing_gas(50))) + .expect("the crossing transaction"); assert_eq!(executor.limiter().usage.write_records, 50, "the block has crossed its limit"); let err = executor - .execute_transaction(&user_tx(1, 10_000_000)) + .execute_transaction(&user_tx(1, incrementing_gas(50))) .expect_err("the block has no write records left"); assert!(format!("{err}").contains("Block KV update limit reached"), "{err}"); assert!(format!("{err}").contains("block_used=50"), "{err}"); @@ -180,12 +206,12 @@ fn test_block_kv_limit_exceeded_mid_block() { executor.apply_pre_execution_changes().expect("the block starts"); for nonce in 0..3 { - let tx = user_tx(nonce, 10_000_000); + let tx = user_tx(nonce, incrementing_gas(1)); let gas = executor.execute_transaction(&tx).expect("packed"); assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); } assert!( - executor.execute_transaction(&user_tx(3, 10_000_000)).is_err(), + executor.execute_transaction(&user_tx(3, incrementing_gas(1))).is_err(), "the block has no write records left" ); @@ -263,7 +289,7 @@ fn test_the_block_data_size_limit_never_refuses_a_deposit() { ); let err = executor - .execute_transaction(&user_tx(3, 100_000)) + .execute_transaction(&user_tx(3, empty_call_gas())) .expect_err("the deposits used the room an ordinary transaction would need"); assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); assert!(format!("{err}").contains(&format!("block_used={}", per_deposit * 3)), "{err}"); @@ -315,7 +341,8 @@ fn test_block_tx_size_limit_default_unlimited() { 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); + 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"); @@ -384,8 +411,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); @@ -403,7 +434,9 @@ 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"); } /// The block's counters may move between a transaction executing and its commit, so what it @@ -413,7 +446,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(); @@ -430,11 +466,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(); @@ -442,9 +478,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"); @@ -611,7 +647,9 @@ fn test_mixed_deposit_and_regular_transactions() { ); 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(&user_tx(0, empty_call_gas())) + .expect("a small user transaction fits"); executor .execute_transaction(&common::deposit_tx(incompressible(100_000), 3_000_000)) .expect("a deposit is exempt"); @@ -632,17 +670,18 @@ fn test_mixed_deposit_and_regular_transactions() { #[test] fn test_commit_time_da_footprint_check_parallel_simulation() { const SCALAR: u16 = u16::MAX; - // Above what two thousand calldata bytes cost: the intrinsic charge and the body's history. - const TX_GAS_LIMIT: u64 = 300_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/receipts.rs b/crates/mega-evm/tests/block/receipts.rs index 868dd4f40..bfbefe046 100644 --- a/crates/mega-evm/tests/block/receipts.rs +++ b/crates/mega-evm/tests/block/receipts.rs @@ -6,7 +6,9 @@ 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}; +use crate::common::{ + self, deposit_tx, empty_call_gas, 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 { @@ -25,10 +27,10 @@ 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"); diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index 7ad139019..1ee2c1ad3 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -18,8 +18,8 @@ use revm::{ }; use crate::common::{ - self, deposit_tx, executor, system_tx, 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 @@ -89,7 +89,7 @@ fn test_activation_block_rejects_a_user_transaction() { executor.apply_pre_execution_changes().expect("the block starts"); let err = executor - .execute_transaction(&user_tx(0, 100_000)) + .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}"); @@ -136,7 +136,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"); @@ -151,8 +151,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); @@ -272,7 +272,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(); @@ -300,7 +300,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!( @@ -347,7 +349,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!( @@ -371,7 +375,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), 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 f26c0c5a6..d6f3fe5bb 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -8,7 +8,7 @@ use mega_evm::{ MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, }; -use crate::common::{self, registry_config, user_tx}; +use crate::common::{self, empty_call_gas, registry_config, 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 @@ -82,7 +82,7 @@ fn test_a_schedule_missing_its_fork_params_is_refused_at_load() { 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"); + executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); } /// A fork the schedule does not activate needs no parameters. diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 64556c1e2..f0464555e 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -266,6 +266,17 @@ fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { }) } +/// 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 @@ -273,16 +284,18 @@ fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { /// 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(), 1_000_000), + 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(), 1_000_000), + common::tx(0, SEQUENCER_REGISTRY_ADDRESS, input.into(), gas_limit), sender, ) } diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index da15d6a83..66e4ce37c 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -33,8 +33,15 @@ const TOGGLER: Address = address!("0x1000000000000000000000000000000000000004"); /// Runs [`reverting_slot_writer`]. const REVERTER: Address = address!("0x1000000000000000000000000000000000000005"); -/// Below the execution cap, where the reservoir is empty and state gas spills onto regular gas. -const GAS_LIMIT: u64 = 1_000_000; +/// Below the execution cap, where the reservoir is empty and state gas spills onto regular gas: +/// 1,000,000 of regular gas on top of what one fresh slot, its record and the body cost at the +/// byte prices in effect. +fn gas_limit() -> 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") +} /// Above the execution cap, where the reservoir pays state gas first. const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; @@ -120,14 +127,20 @@ fn writes(nonce: u64, slot: u64, gas_limit: u64) -> Recovered { } /// The state gas a transaction that fills one fresh slot spends, read off a probe block. -fn one_slot() -> u64 { +/// +/// `None` when a state byte costs nothing: no transaction adds state gas then, and the block's +/// state-gas limit has nothing to hold. +fn one_slot() -> Option { + if common::state_is_free() { + return None; + } 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(&writes(0, 1, GAS_LIMIT)).expect("the probe executes"); + probe.execute_transaction(&writes(0, 1, gas_limit())).expect("the probe executes"); let slot = probe.gas().state; - assert!(slot > 0, "a fresh slot draws state gas"); - slot + assert_eq!(slot, common::slot_state_gas(), "a fresh slot draws its state gas"); + Some(slot) } /// A block with room for one slot and a half: the second slot crosses the limit. @@ -140,19 +153,19 @@ fn limits(slot: u64) -> BlockLimits { /// behind. A transaction after it that adds none still fits. #[test] fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipped() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let mut state = state(); let mut executor = executor(&mut state, common::block_ctx(limits(slot))); executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&writes(0, 1, GAS_LIMIT)).expect("the block has room"); + executor.execute_transaction(&writes(0, 1, gas_limit())).expect("the block has room"); executor - .execute_transaction(&writes(1, 2, GAS_LIMIT)) + .execute_transaction(&writes(1, 2, gas_limit())) .expect("the transaction that crosses the limit is still packed"); assert_eq!(executor.gas().state, 2 * slot, "the block overshoots by that one transaction"); let err = executor - .execute_transaction(&writes(2, 3, GAS_LIMIT)) + .execute_transaction(&writes(2, 3, gas_limit())) .expect_err("the next transaction adds state gas"); assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); assert_eq!( @@ -163,10 +176,10 @@ fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipp // The same nonce again, now writing a slot that already holds its value: no state gas. executor - .execute_transaction(&writes(2, 1, GAS_LIMIT)) + .execute_transaction(&writes(2, 1, gas_limit())) .expect("a transaction that adds no state gas still fits"); executor - .execute_transaction(&tx_from(CALLER, 3, EMPTY, Bytes::new(), GAS_LIMIT)) + .execute_transaction(&tx_from(CALLER, 3, EMPTY, Bytes::new(), gas_limit())) .expect("and so does one that writes nothing at all"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); @@ -179,13 +192,13 @@ fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipp /// so an ordinary transaction after the deposits finds the room they used. #[test] fn test_a_deposit_is_never_refused_by_the_state_gas_limit() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let mut state = state(); let mut executor = executor(&mut state, common::block_ctx(limits(slot))); executor.apply_pre_execution_changes().expect("the block starts"); let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - let deposit = |slot: u64| common::deposit_tx_to(CONTRACT, slot_word(slot), GAS_LIMIT); + let deposit = |slot: u64| common::deposit_tx_to(CONTRACT, slot_word(slot), gas_limit()); executor.execute_transaction(&deposit(1)).expect("the block has room"); executor.execute_transaction(&deposit(2)).expect("the deposit that crosses the limit"); @@ -197,7 +210,7 @@ fn test_a_deposit_is_never_refused_by_the_state_gas_limit() { assert_eq!(executor.gas().state, 3 * slot, "and it counts"); let err = executor - .execute_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(4), GAS_LIMIT)) + .execute_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(4), gas_limit())) .expect_err("an ordinary transaction that adds state gas finds no room left"); assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); assert!(format!("{err}").contains(&format!("block_used={}", 3 * slot)), "{err}"); @@ -211,19 +224,19 @@ fn test_a_deposit_is_never_refused_by_the_state_gas_limit() { /// the same rule at commit: the block's state gas may have been reached while a candidate waited. #[test] fn test_the_state_gas_limit_is_checked_again_at_commit() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let mut state = state(); let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); let mut executor = executor(&mut state, common::block_ctx(limits)); executor.apply_pre_execution_changes().expect("the block starts"); let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - let first = executor.run_transaction(&writes(0, 1, GAS_LIMIT)).expect("the block has room"); + let first = executor.run_transaction(&writes(0, 1, gas_limit())).expect("the block has room"); let second = executor - .run_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), GAS_LIMIT)) + .run_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), gas_limit())) .expect("nothing has committed yet"); let third = executor - .run_transaction(&tx_from(CALLER3, 0, EMPTY, Bytes::new(), GAS_LIMIT)) + .run_transaction(&tx_from(CALLER3, 0, EMPTY, Bytes::new(), gas_limit())) .expect("nothing has committed yet"); assert!(second.gas.state > 0 && third.gas.state == 0); @@ -264,14 +277,14 @@ impl Inspector for PeakStateGas { /// of its own: the most its frame's state gas rose while it ran. The transaction ends with none. fn state_gas_drawn_partway(to: Address, input: Bytes) -> u64 { let ctx = MegaContext::new(state(), MegaSpecId::SATIN) - .with_block(BlockEnv { gas_limit: GAS_LIMIT, ..Default::default() }) + .with_block(BlockEnv { gas_limit: gas_limit(), ..Default::default() }) .with_chain(zero_fee_l1_block_info()); let mut evm = MegaEvm::new(ctx).with_inspector(PeakStateGas::default()); let tx = OpTx(op_transaction(TxEnv { caller: CALLER2, kind: TxKind::Call(to), data: input, - gas_limit: GAS_LIMIT, + gas_limit: gas_limit(), ..Default::default() })); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); @@ -285,12 +298,12 @@ fn state_gas_drawn_partway(to: Address, input: Bytes) -> u64 { /// transaction ends with, not what it drew on the way. Below the execution cap and above it. #[test] fn test_a_transaction_whose_state_gas_comes_back_to_zero_still_fits() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); assert_eq!(state_gas_drawn_partway(TOGGLER, slot_word(7)), slot, "the write-back's"); assert_eq!(state_gas_drawn_partway(REVERTER, slot_word(8)), slot, "the reverted write's"); - for gas_limit in [GAS_LIMIT, ABOVE_CAP] { + for gas_limit in [gas_limit(), ABOVE_CAP] { let mut state = state(); let mut env = common::evm_env(); env.block_env = BlockEnv { gas_limit: 10_000_000_000, ..env.block_env }; @@ -334,9 +347,8 @@ fn test_a_transaction_whose_state_gas_comes_back_to_zero_still_fits() { /// refuses. The trait's commit makes the same check in a debug build and trips on it. #[cfg(debug_assertions)] #[test] -#[should_panic(expected = "an outcome the block no longer has room for")] fn test_the_trait_commit_trips_on_an_outcome_the_block_has_no_room_for() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let mut state = state(); let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); let mut executor = executor(&mut state, common::block_ctx(limits)); @@ -344,23 +356,40 @@ fn test_the_trait_commit_trips_on_an_outcome_the_block_has_no_room_for() { let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); let first = executor - .execute_transaction_without_commit(&writes(0, 1, GAS_LIMIT)) + .execute_transaction_without_commit(&writes(0, 1, gas_limit())) .expect("the block has room"); let second = executor - .execute_transaction_without_commit(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), GAS_LIMIT)) + .execute_transaction_without_commit(&tx_from( + CALLER2, + 0, + CONTRACT, + slot_word(2), + gas_limit(), + )) .expect("nothing has committed yet"); assert!(second.gas.state > 0); BlockExecutor::commit_transaction(&mut executor, first); assert_eq!(executor.gas().state, slot, "the block has spent exactly its limit"); - BlockExecutor::commit_transaction(&mut executor, second); + // Caught rather than expected of the whole test, which returns early where no transaction + // adds state gas. + 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}"); } /// Above the execution cap the reservoir pays the state gas, and the block counts and caps it the /// same way: the ledger is the state gas spent, whichever pool paid it. #[test] fn test_the_state_gas_limit_counts_what_the_reservoir_paid() { - let slot = one_slot(); + let Some(slot) = one_slot() else { return }; let mut state = state(); let mut env = common::evm_env(); env.block_env = BlockEnv { gas_limit: 10_000_000_000, ..env.block_env }; diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs index fedbf3bad..5dbce049c 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -53,6 +53,19 @@ fn state() -> State { 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, @@ -65,7 +78,7 @@ fn legacy( chain_id: Some(CHAIN_ID), nonce, gas_price: 1_000_000, - gas_limit: 1_000_000, + gas_limit: gas_limit(), to, value: U256::from(value), input, @@ -87,7 +100,7 @@ fn deposit(mint: u128, value: u64) -> Recovered { 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: 1_000_000, + gas_limit: gas_limit(), is_system_transaction: false, input: Bytes::new(), }; From bdd61b5c067b9018bbc5d82a0d0325737adcf8d3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:25:17 -0400 Subject: [PATCH 349/458] fix(block): no building policy refuses a deposit --- AGENTS.md | 2 +- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/block/limit.rs | 151 +++++++++++++++++++------- crates/mega-evm/tests/block/limits.rs | 38 +++++++ docs/spec/upgrades/satin.md | 6 +- 5 files changed, 153 insertions(+), 46 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64728967c..877622eec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -179,7 +179,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and an unlimited detention cap; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`). - 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 caps on the four 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. + 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 four 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/protocol_limits.rs`). Tests that run blocks under limits no chain may carry (`ProtocolLimits::no_limits()`, detention off) attach them with `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 4d0b19b06..fadba8e8d 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -55,7 +55,7 @@ Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecut Every transaction is held to the chain'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: `ProtocolLimits`, the Satin fork's parameters, which a chain configuration carries beside `SequencerRegistryConfig` and block execution reads at the block's timestamp. They are the per-transaction runtime limits and the block's execution-gas, state-gas, data-size and KV budgets; their default is today's values, and `validate_schedule` refuses a schedule that activates Satin without them or with a value no chain can run on. -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 caps that can lower a block budget and never raise it, so a validator that leaves it at its default computes the block a builder packed under any policy. +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 a block 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. A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index d37df486a..9f1c7b0fe 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -40,11 +40,13 @@ //! # 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 a deposit is exempt from both data-availability limits -//! and does not count towards the block's. The execution-gas, state-gas, data-size and KV limits -//! are packing budgets for the transactions the builder chooses, so none of them refuses a deposit -//! either. A deposit still counts towards all four, so the transactions after it find the room it -//! used. +//! 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 execution-gas, +//! state-gas, data-size and KV limits are packing budgets for the transactions the builder +//! chooses, so none of them refuses a deposit either. A deposit still counts towards all four, 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. //! //! The per-transaction limits the block installs on the EVM — data size, write records, state gas //! — are not block limits: they hold a deposit's own execution the way they hold any @@ -277,15 +279,16 @@ impl HardforkParams for ProtocolLimits { /// from the block environment. #[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, @@ -446,8 +449,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 and the - /// execution-gas, state-gas, data-size and KV limits never refuse. + /// 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, } @@ -502,8 +505,9 @@ impl BlockLimiter { /// Whether `tx` may execute in this block. /// /// Checks the transaction against its own limits, and against what the block has left; a - /// deposit is held to neither data-availability limit, nor to the execution-gas, the data-size - /// or the KV limit. It reads the counters and changes nothing; + /// deposit is held to the block's gas limit alone — to no limit only a builder applies, and to + /// neither the execution-gas, the data-size nor the KV limit. It reads the counters and changes + /// nothing; /// [`post_execution_check`](Self::post_execution_check) checks what only the transaction's /// execution reveals, and [`post_execution_update`](Self::post_execution_update) advances the /// counters once the transaction commits. @@ -522,7 +526,12 @@ impl BlockLimiter { da_size: u64, is_deposit: bool, ) -> Result<(), BlockExecutionError> { - if gas_limit > self.limits.tx_gas_limit { + // 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 it — its declared gas, its encoded size and its data-availability size, and what + // those add to the block — and it does not count towards the block's data-availability + // size. The block's gas limit, the header's, holds it as it holds every transaction. + if !is_deposit && gas_limit > self.limits.tx_gas_limit { return Err(invalid_tx( tx_hash, MegaTxLimitExceededError::TransactionGasLimit { @@ -540,6 +549,14 @@ impl BlockLimiter { .into()); } + // The packing budgets below are the dimensions a transaction's own execution reveals. The + // transaction that crossed one is already packed, so what they refuse is the next one — + // never a deposit, which is not the builder's to refuse either. Every committed + // transaction counts towards them, a deposit included, in `post_execution_update`. + if is_deposit { + return Ok(()); + } + if tx_size > self.limits.tx_encode_size_limit { return Err(invalid_tx( tx_hash, @@ -562,37 +579,25 @@ 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 packing budgets: 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 — never a deposit, which is not the builder's to refuse. Every committed - // transaction counts towards them, a deposit included, in `post_execution_update`. - if is_deposit { - return Ok(()); + 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 self.gas.execution >= self.limits.block_execution_gas_limit { @@ -1215,6 +1220,68 @@ 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); + // 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 = BlockLimiter::new(limits_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)); + 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] diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 0b2b0a9e8..ba2b9e465 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -595,6 +595,44 @@ fn test_deposit_exempt_from_block_da_limit() { assert_eq!(result.receipts().len(), 1); } +/// 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_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(policy)); + executor.apply_pre_execution_changes().expect("the block starts"); + + 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", + ), + (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(), 1, "the deposit alone is packed"); +} + /// The three cases in one block: a small user transaction, a large deposit, a large user /// transaction. #[test] diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 47092d2d7..44d81c6db 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -721,7 +721,9 @@ Four of those counts can be limited: - The block gas limit is unchanged: a transaction's declared gas limit MUST fit in what the block has left. - The four limits are protocol values the chain configuration carries as parameters of the Satin hardfork, with the per-transaction limits (see [Resource Limits](#10-resource-limits)); the defaults are the table's. A node validating a block MUST hold it to the chain's 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 (from which deposits are exempt), hold the block to an encoded-size or data-availability budget, and hold any of the four limits below the chain's value, never above it. +- 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 four limits below the chain'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. + A deposit counts towards the block's encoded size and not towards its data-availability size; the block gas limit holds it 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. ### 21. Transaction and Block Refusals @@ -749,7 +751,7 @@ A transaction MUST be skipped for the current block, and MAY be included in a la A block that contains a transaction it should have skipped is invalid. -A block builder MAY also skip a 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 one of the four block limits held below the chain's value. +A block builder MAY also skip a transaction other than a deposit 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 one of the four block limits held below the chain'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. From 39ee32506ecf62051b3125d258f552f4299dd637 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:25:17 -0400 Subject: [PATCH 350/458] refactor(limit): keep the exemption on the layer, not in the verdict LimitCheck loses its Exempt variant: no outcome ever carried it, and it made within_limit and exceeded_limit both false for one value. The layer keeps the exemption as its own sticky flag, and an exempt transaction's verdict is WithinLimit whatever it crosses. --- AGENTS.md | 2 +- crates/mega-evm/src/limit/limit.rs | 56 ++++++++++++++++-------------- crates/mega-evm/src/limit/mod.rs | 47 ++++++++----------------- 3 files changed, 45 insertions(+), 60 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64728967c..9ae5e7356 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,7 +182,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 caps on the four 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/protocol_limits.rs`). Tests that run blocks under limits no chain may carry (`ProtocolLimits::no_limits()`, detention off) attach them with `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. -- 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. +- 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, KV or state-gas limit and no frame budget stops them, and they are never latched. 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). diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d5adb1310..d88b65a7f 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -19,7 +19,7 @@ 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 state gas the transaction holds outside each frame, the /// record the Host staged for the running opcode, and where the transaction stands with its -/// limits — within them, latched by one, or exempt from all of them. +/// limits — within them or latched by one — and whether it is exempt from all of them. /// /// 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) @@ -42,8 +42,9 @@ use crate::storage_call_stipend; /// 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, which answers an exempt transaction with [`LimitCheck::Exempt`] whatever -/// it crossed — a transaction limit or a frame budget, in any dimension — and never latches it. +/// comes from one place, which answers an exempt transaction with [`LimitCheck::WithinLimit`] +/// whatever it crossed — a transaction limit or a frame budget, in any dimension — and never +/// latches it. /// What the transaction uses is counted all the same, so its usage is reported as any other /// transaction's is. #[derive(Clone, Debug, Default)] @@ -51,10 +52,12 @@ pub struct AdditionalLimit { pub(crate) tracker: FrameLimitTracker, staged: Option, limits: EvmTxRuntimeLimits, - /// Where the transaction stands with its limits: within them, stopped by the transaction-level - /// limit it latched, or exempt from all of them. The latter two are sticky for the - /// transaction. + /// Where the transaction stands with its limits: within them, or stopped by the + /// transaction-level limit it latched, which is sticky for the transaction. standing: LimitCheck, + /// 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, @@ -122,6 +125,7 @@ impl AdditionalLimit { self.tracker.reset(); self.staged = None; self.standing = LimitCheck::WithinLimit; + self.exempt = false; self.resume_stop = None; self.target_is_authority = false; self.sender = Address::ZERO; @@ -156,13 +160,13 @@ impl AdditionalLimit { pub const fn latched(&self) -> Option<&LimitCheck> { match &self.standing { latched @ LimitCheck::ExceedsLimit { .. } => Some(latched), - LimitCheck::WithinLimit | LimitCheck::Exempt => None, + LimitCheck::WithinLimit => None, } } /// Whether the running transaction is exempt from every per-transaction limit. pub const fn is_exempt(&self) -> bool { - self.standing.is_exempt() + self.exempt } /// Exempts the running transaction from every per-transaction limit, until the next @@ -171,13 +175,13 @@ impl AdditionalLimit { /// 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.standing = LimitCheck::Exempt; + self.exempt = true; } /// 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, and an exempt transaction is not - /// latched at all: the verdict is then [`LimitCheck::Exempt`]. + /// latched at all: the verdict is then [`LimitCheck::WithinLimit`]. pub fn latch(&mut self, kind: LimitKind, limit: u64, used: u64) -> LimitCheck { self.crossed(kind, limit, used, false) } @@ -186,17 +190,19 @@ impl AdditionalLimit { /// which reverts the running frame alone, and the transaction's latch otherwise. /// /// Every stop the layer hands out comes from here, so this is where the exemption applies: an - /// exempt transaction's verdict is [`LimitCheck::Exempt`], whatever it crossed. + /// exempt transaction's verdict is [`LimitCheck::WithinLimit`], whatever it crossed. fn crossed(&mut self, kind: LimitKind, limit: u64, used: u64, frame_local: bool) -> LimitCheck { - match self.standing { - LimitCheck::Exempt => LimitCheck::Exempt, - _ if frame_local => LimitCheck::ExceedsLimit { kind, limit, used, frame_local }, - LimitCheck::WithinLimit => { - self.standing = LimitCheck::ExceedsLimit { kind, limit, used, frame_local }; - self.standing - } - latched @ LimitCheck::ExceedsLimit { .. } => latched, + if self.exempt { + return LimitCheck::WithinLimit; + } + let crossed = LimitCheck::ExceedsLimit { kind, limit, used, frame_local }; + if frame_local { + return crossed; } + if !self.standing.exceeded_limit() { + self.standing = crossed; + } + self.standing } /// Checks the limits after the running frame counted something: what the transaction keeps @@ -926,9 +932,7 @@ impl AdditionalLimit { if !self.frame_began { let body = self.body_bytes; self.tracker.reset(); - if self.standing.exceeded_limit() { - self.standing = LimitCheck::WithinLimit; - } + self.standing = LimitCheck::WithinLimit; self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); return; } @@ -1324,14 +1328,14 @@ mod tests { } /// An exempt transaction is stopped by no limit, in any dimension, at the transaction or at a - /// frame: every verdict is `Exempt`, nothing is latched and no caller is stopped. What it uses - /// is counted all the same. + /// frame: every verdict is within the limits, nothing is latched 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::Exempt; 3]); - assert_eq!(limit.latch(LimitKind::DataSize, 0, 1), LimitCheck::Exempt); + assert_eq!(count_a_transaction(&mut limit), [LimitCheck::WithinLimit; 3]); + assert_eq!(limit.latch(LimitKind::DataSize, 0, 1), LimitCheck::WithinLimit); assert_eq!(limit.latched(), None); assert_eq!(limit.stop_before_run(), None); assert_eq!( diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 414f359d8..864b57d00 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -126,12 +126,13 @@ //! //! 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 — run under [`LimitCheck::Exempt`], sticky for the transaction, which the one place -//! every stop comes from answers whatever they cross: the data size, the KV count, the state gas -//! and the frame budgets of the first two. 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. +//! 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, the KV count, the state gas and the frame budgets of the first two. 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 //! @@ -506,8 +507,8 @@ impl LimitKind { /// /// 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. +/// budget) reverts the frame alone and its caller resumes. 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. @@ -531,29 +532,21 @@ pub enum LimitCheck { /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, }, - /// The transaction is exempt from every per-transaction limit: it is the protocol's own work. - 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 { @@ -566,7 +559,7 @@ 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(), } } } @@ -655,18 +648,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()); @@ -679,9 +661,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, From a25aabd8733f7394bdf8a5674e438940a8a2aeda Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:26:44 -0400 Subject: [PATCH 351/458] fix(block): report a missing chain parameter as an internal error --- AGENTS.md | 2 +- crates/mega-evm/src/block/executor.rs | 93 ++++++++++++++++++++++++++- 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 877622eec..4405beff1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,7 +178,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The limits that change a result are protocol values, carried by the Satin fork's parameters: `ProtocolLimits` (`block/limit.rs`), attached to the schedule with `MegaHardforkConfig::with_params` and read at the block's timestamp with `MegaHardforks::protocol_limits`. It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and an unlimited detention cap; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). - The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`). + The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`), as an internal error: a gap in the node's configuration, like a missing `SequencerRegistryConfig`, is not a verdict on the block. 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 four 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/protocol_limits.rs`). Tests that run blocks under limits no chain may carry (`ProtocolLimits::no_limits()`, detention off) attach them with `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index d0d7ed066..bfc88791a 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -206,9 +206,13 @@ pub enum MegaBlockExecutionError { found: B256, }, /// Satin is scheduled but the schedule does not carry a [`SequencerRegistryConfig`]. + /// + /// A gap in the node's configuration, not a verdict on the block: an internal error. MissingSequencerRegistryConfig, /// The schedule carries no [`ProtocolLimits`] for the block's timestamp: no `MegaETH` fork is /// active there, or the fork active there carries none. + /// + /// A gap in the node's configuration, not a verdict on the block: an internal error. MissingProtocolLimits { /// The block's timestamp. timestamp: u64, @@ -280,8 +284,24 @@ impl fmt::Display for MegaBlockExecutionError { impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { + /// A block refused for what the node's configuration lacks is an internal error: a schedule + /// without a parameter the block needs says nothing about the block, and a node must not mark + /// a block invalid because its own configuration is incomplete. 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::MissingSequencerRegistryConfig | + MegaBlockExecutionError::MissingProtocolLimits { .. } => Self::other(error), + MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | + MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | + MegaBlockExecutionError::RewritingInspector | + MegaBlockExecutionError::ForeignSystemContractCode { .. } | + MegaBlockExecutionError::ZeroFactoryNonce { .. } | + MegaBlockExecutionError::UsedEmptyAccount { .. } | + MegaBlockExecutionError::ApplyPendingChangesFailed { .. } => { + Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) + } + } } } @@ -1066,8 +1086,9 @@ mod tests { assert_eq!(executor.protocol_limits(), None); let error = executor.apply_pre_execution_changes().expect_err("no limits, no block"); assert_eq!( - error.to_string(), - MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 }.to_string() + internal(&error), + &MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 }, + "a gap in the node's configuration is not a verdict on the block" ); assert_eq!( error.to_string(), @@ -1076,6 +1097,72 @@ mod tests { assert!(executor.receipts().is_empty()); } + /// 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:?}")) + } + + /// A schedule that activates Satin without a `SequencerRegistryConfig` refuses the block at + /// the deploy, as an internal error: the registry cannot be seeded, and that is the node's + /// configuration, not the block. + #[test] + fn test_a_block_without_the_registry_config_is_an_internal_error() { + 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), + MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::default(), + ), + MegaHardforkConfig::default().with_all_activated().with_params(ProtocolLimits::DEFAULT), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ); + + let error = executor.apply_pre_execution_changes().expect_err("no registry, no block"); + assert_eq!(internal(&error), &MegaBlockExecutionError::MissingSequencerRegistryConfig); + } + + /// Every refusal but a configuration gap is a verdict on the block: a validation error. + #[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::RewritingInspector, + MegaBlockExecutionError::ForeignSystemContractCode { + address, + expected: B256::ZERO, + found: B256::repeat_byte(1), + }, + MegaBlockExecutionError::ZeroFactoryNonce { address }, + MegaBlockExecutionError::UsedEmptyAccount { address, nonce: 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)); + } + for gap in [ + MegaBlockExecutionError::MissingSequencerRegistryConfig, + MegaBlockExecutionError::MissingProtocolLimits { timestamp: 1 }, + ] { + assert_eq!(internal(&BlockExecutionError::from(gap.clone())), &gap); + } + } + /// The executor prints whether a pre-block observer is installed. A trait object has no /// `Debug`, so the observer is reported as a flag rather than dropped: a reader of a node's /// log can tell a block whose pre-block states were witnessed from one whose were not. From 100736fd93a203abd6d0d8753267504259562a27 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:30:55 -0400 Subject: [PATCH 352/458] fix(limit): hold detention's caps below the compute no transaction reaches --- AGENTS.md | 6 +-- crates/mega-evm/src/access/mod.rs | 5 +- crates/mega-evm/src/block/limit.rs | 59 +++++++++++++++--------- crates/mega-evm/src/constants.rs | 19 +++++++- crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/tests/satin/detention.rs | 57 +++++++++++++++++++++++ docs/spec/upgrades/satin.md | 5 +- 7 files changed, 124 insertions(+), 31 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4405beff1..a30b5f8cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default; in block execution the chain's, from `ProtocolLimits`) | — | | `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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 | +| `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`, `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`) | — | @@ -177,7 +177,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. - The limits that change a result are protocol values, carried by the Satin fork's parameters: `ProtocolLimits` (`block/limit.rs`), attached to the schedule with `MegaHardforkConfig::with_params` and read at the block's timestamp with `MegaHardforks::protocol_limits`. It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. - `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and an unlimited detention cap; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). + `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and a detention cap no transaction's compute reaches — at or above `TX_COMPUTE_GAS_BOUND`, the execution cap less EIP-2780's base cost of 12,000; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`), as an internal error: a gap in the node's configuration, like a missing `SequencerRegistryConfig`, is not a verdict on the block. 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 four 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/protocol_limits.rs`). @@ -283,7 +283,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses an unlimited cap, so no chain 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses a cap at or above `TX_COMPUTE_GAS_BOUND`, which never binds, so no chain 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. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index d48f7ef11..0ff1f2557 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -19,8 +19,9 @@ //! [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) and //! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default. In block //! execution they are the chain's ([`ProtocolLimits`](crate::ProtocolLimits)), which must be -//! finite; a standalone EVM's caller may set either. A cap of `u64::MAX` caps nothing, and a -//! transaction whose caps are both unlimited — under +//! below [`TX_COMPUTE_GAS_BOUND`](crate::constants::TX_COMPUTE_GAS_BOUND), a compute no +//! transaction reaches; a standalone EVM's caller may set either. 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. diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 9f1c7b0fe..c9a53db1b 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -71,9 +71,9 @@ use std::{boxed::Box, format}; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ - BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, HardforkParamsError, LimitUsage, - MegaBlockLimitExceededError, MegaGasUsage, MegaHardfork, MegaTxLimitExceededError, - TX_BODY_SIZE, + constants::TX_COMPUTE_GAS_BOUND, BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, + HardforkParamsError, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, MegaHardfork, + MegaTxLimitExceededError, TX_BODY_SIZE, }; /// The limits the protocol holds every block and every transaction to: the Satin fork's @@ -199,8 +199,9 @@ impl HardforkParams for ProtocolLimits { /// stops or refuses every transaction that uses the dimension; /// - a transaction data-size limit below [`TX_BODY_SIZE`], the bytes every transaction's body /// counts, which stops every transaction before it runs; - /// - an unlimited gas-detention cap: `u64::MAX` caps nothing, and a read of volatile data must - /// be held to a finite one on a chain. + /// - a gas-detention cap at or above [`TX_COMPUTE_GAS_BOUND`], which no transaction's compute + /// reaches: such a cap never stops a read of volatile data, `u64::MAX` among them, and a + /// chain's caps must be able to. /// /// `u64::MAX` is a valid value for every other limit: it leaves the dimension unlimited. fn validate(&self) -> Result<(), HardforkParamsError> { @@ -247,10 +248,11 @@ impl HardforkParams for ProtocolLimits { )); } for (name, cap) in detention_caps { - if cap == u64::MAX { + if cap >= TX_COMPUTE_GAS_BOUND { return invalid(format!( - "ProtocolLimits.{name} must be finite: u64::MAX leaves a read of volatile \ - data undetained" + "ProtocolLimits.{name} must be below {TX_COMPUTE_GAS_BOUND}, which no \ + transaction's compute reaches: a cap there leaves a read of volatile data \ + undetained" )); } } @@ -782,8 +784,8 @@ mod tests { } /// Every limit refuses zero, the value a field left out of a configuration reads as; the - /// transaction's data size refuses less than a body; the detention caps refuse `u64::MAX`, - /// and every other limit accepts it. + /// transaction's data size refuses less than a body; the detention caps refuse a value no + /// transaction's compute reaches, and every other limit accepts `u64::MAX`. #[test] fn test_validate_refuses_what_no_chain_can_run_on() { let base = ProtocolLimits::DEFAULT; @@ -836,21 +838,34 @@ mod tests { name != "tx_runtime_limits.tx_data_size_limit", "{name} at one" ); - let unlimited = set(base, u64::MAX).validate(); if name.ends_with("compute_gas_limit") { + // A cap no transaction's compute reaches is refused, the execution cap and + // `u64::MAX` among them; one below the bound is accepted. + for cap in [ + TX_COMPUTE_GAS_BOUND, + crate::constants::TX_GAS_LIMIT_CAP, + u64::MAX - 1, + u64::MAX, + ] { + assert_eq!( + set(base, cap).validate(), + Err(HardforkParamsError { + message: std::format!( + "ProtocolLimits.{name} must be below {TX_COMPUTE_GAS_BOUND}, \ + which no transaction's compute reaches: a cap there leaves a \ + read of volatile data undetained" + ) + }), + "{name} at {cap}" + ); + } assert_eq!( - unlimited, - Err(HardforkParamsError { - message: std::format!( - "ProtocolLimits.{name} must be finite: u64::MAX leaves a read of \ - volatile data undetained" - ) - }), - "{name}" + set(base, TX_COMPUTE_GAS_BOUND - 1).validate(), + Ok(()), + "{name} just below" ); - assert_eq!(set(base, u64::MAX - 1).validate(), Ok(()), "{name} just below"); } else { - assert_eq!(unlimited, Ok(()), "{name} may be unlimited"); + assert_eq!(set(base, u64::MAX).validate(), Ok(()), "{name} may be unlimited"); } } @@ -877,7 +892,7 @@ mod tests { #[test] #[should_panic(expected = "Invalid params for fork Satin: \ ProtocolLimits.tx_runtime_limits.block_env_access_compute_gas_limit must be \ - finite")] + below 199988000")] fn test_a_schedule_refuses_the_unlimited_protocol_limits() { let _ = MegaHardforkConfig::default() .with_all_activated() diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 97a430839..a3dbf3b3c 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -17,6 +17,7 @@ //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the default 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) | the default detention cap of the runtime limits and of the protocol limits | //! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits and of the protocol limits | +//! | [`TX_COMPUTE_GAS_BOUND`] | 199,988,000 | a bound no transaction's compute reaches: the execution cap less EIP-2780's base cost | the protocol limits, whose detention caps must be 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 @@ -32,7 +33,10 @@ //! [`ProtocolLimits::block_state_gas_limit`](crate::ProtocolLimits::block_state_gas_limit). A chain //! sets both, and both are unlimited by default. -use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; +use revm::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; @@ -80,6 +84,18 @@ pub const BLOCK_ENV_ACCESS_COMPUTE_GAS: u64 = 20_000_000; /// specs capped an Oracle read at 1,000,000. Provisional. pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; +/// A bound no transaction's compute reaches: the execution cap less EIP-2780's base cost, the +/// intrinsic regular gas every transaction pays before its first frame. Derived from +/// [`TX_GAS_LIMIT_CAP`]. +/// +/// Compute is the regular gas a transaction's frames spend, and their regular gas is what the +/// execution cap leaves once the intrinsic gas is paid, so a gas-detention cap at or above this +/// bound never stops a transaction, however early it read: a chain's caps must be below it. A +/// frame that runs code pays a little more before its first instruction — at least a warm account +/// access, for the recipient or the delegate it runs — so the most compute a transaction can +/// spend is a little below the bound. +pub const TX_COMPUTE_GAS_BOUND: u64 = TX_GAS_LIMIT_CAP - eip2780::TX_BASE_COST; + #[cfg(test)] mod tests { use super::*; @@ -98,5 +114,6 @@ mod tests { assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); assert_eq!(BLOCK_ENV_ACCESS_COMPUTE_GAS, 20_000_000); assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, 20_000_000); + assert_eq!(TX_COMPUTE_GAS_BOUND, 199_988_000); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 414f359d8..f05cda8e2 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -319,7 +319,9 @@ impl EvmTxRuntimeLimits { /// 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 own ([`ProtocolLimits`](crate::ProtocolLimits)), whose - /// detention caps must be finite. + /// detention caps must be below + /// [`TX_COMPUTE_GAS_BOUND`](crate::constants::TX_COMPUTE_GAS_BOUND), which no transaction's + /// compute reaches. pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 887dd7a88..7f8aecc70 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1598,3 +1598,60 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { 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 [`TX_COMPUTE_GAS_BOUND`], because no transaction's compute +/// reaches it. The transaction closest to it pays the least intrinsic gas a frame that runs code +/// can — 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 +/// the bound less the warm access, so a cap at the bound 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_no_transactions_compute_reaches_the_bound_on_the_caps() { + use mega_evm::constants::TX_COMPUTE_GAS_BOUND; + const WARM_ACCESS: u64 = 100; + let intrinsic = TX_GAS_LIMIT_CAP - TX_COMPUTE_GAS_BOUND + WARM_ACCESS; + 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(TX_COMPUTE_GAS_BOUND, answers_gas); + assert_eq!(run.limit, Some(TX_COMPUTE_GAS_BOUND), "detained from the start"); + let output = run.outcome.result.output().expect("the frame returns"); + assert_eq!(U256::from_be_slice(output), U256::from(TX_COMPUTE_GAS_BOUND - WARM_ACCESS - 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(TX_COMPUTE_GAS_BOUND, spinner.clone()); + assert_eq!(run.limit, Some(TX_COMPUTE_GAS_BOUND)); + assert_eq!(run.outcome.limit_exceeded, None, "a cap at the bound never stops it"); + assert!( + matches!(run.outcome.result, ExecutionResult::Halt { .. }), + "it runs out of its own gas: {:?}", + run.outcome.result + ); + + let cap = TX_COMPUTE_GAS_BOUND - WARM_ACCESS - 10_000; + let run = run_under(cap, spinner); + assert_eq!(assert_stopped(&run, intrinsic, Charges::default().spin(0).left(cap)), cap); +} diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 44d81c6db..a4a183a21 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -395,7 +395,7 @@ Three dimensions are limited per transaction; compute is not one of them (see [T 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 per-transaction limits and the per-frame caps are protocol values: the chain configuration carries them as parameters of the Satin hardfork, together with the detention caps and the block limits, and a node MUST hold every transaction to the values the chain configures, never to values it is handed with a block. The values above are the defaults. - A chain configuration that activates Satin without these parameters MUST be refused when it is loaded, and so MUST one that sets a limit to zero, a transaction data-size limit below `TX_BODY_SIZE`, or an unlimited detention cap. + A chain configuration that activates Satin without these parameters MUST be refused when it is loaded, and so MUST one that sets a limit to zero, a transaction data-size limit below `TX_BODY_SIZE`, or a detention cap no transaction's compute reaches (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). The 98/100 share is not a parameter. At the default data-size limit a transaction keeps fewer than 327,680 write records (13,107,200 / 40), so a KV limit binds only below that. @@ -464,7 +464,8 @@ A contract can revert with the same bytes, so the revert data alone does not ide 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 the chain configuration carries with the other limits (see [Resource Limits](#10-resource-limits)), 20,000,000 each by default; a chain's caps MUST be finite. + The caps are protocol values the chain configuration carries with the other limits (see [Resource Limits](#10-resource-limits)), 20,000,000 each by default. + A chain's caps MUST be below 199,988,000: the execution cap less the 12,000 of intrinsic regular gas every transaction pays under EIP-2780, which bounds what a transaction's frames can spend, so a cap at or above it never stops a transaction. - **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`), 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). From 214656185222332a363b5405b7e5af123cf80436 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:32:13 -0400 Subject: [PATCH 353/458] refactor(evm): answer every start past the call-stack limit in the depth guard The guard answered CALL and STATICCALL only; every other start past the limit reached the count and then revm's CallTooDeep, and a creation's count had to be taken back for the nonce revm never bumped. The guard now gives revm's own answer for every scheme and for a creation before anything counts the start, so the creator's nonce snapshot, creation_did_not_bump_nonce, undo_frame_start and drop_caller_record go. No transaction reaches the limit. --- AGENTS.md | 4 +- crates/mega-evm/src/evm/execution.rs | 68 ++++++++++--------- crates/mega-evm/src/limit/frame_limit.rs | 48 ------------- crates/mega-evm/src/limit/limit.rs | 49 +------------ .../tests/satin/synthetic_frame_gas.rs | 57 +++++++++++++++- 5 files changed, 95 insertions(+), 131 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9ae5e7356..b396ba3bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,7 +155,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 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 creation revm answers without bumping its creator's nonce keeps nothing its start counted, whatever the answer. + 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. @@ -171,7 +171,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame revm refuses — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ae91db13c..b15d23d04 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -412,8 +412,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm { - Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) - } - _ => None, - }; #[cfg(debug_assertions)] let counted = ( ctx.additional_limit.frame_start_transfer_log(&frame_init.frame_input), @@ -525,11 +517,6 @@ impl EvmTr for MegaEvm { - if let Some((creator, nonce)) = creator { - if account_nonce(ctx, creator) == nonce { - ctx.additional_limit.creation_did_not_bump_nonce(); - } - } if let PrecompileHold::Clamped(withheld) = hold { Detention::restore_forward(result.interpreter_result_mut(), withheld); } @@ -1125,16 +1112,21 @@ fn stop_before_building( 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. +/// 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 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. +/// 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. +/// +/// 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, @@ -1155,7 +1147,9 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { /// 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. -/// A built frame has run no instruction yet, so the move is all revm has done. An answered call +/// 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 @@ -1166,6 +1160,10 @@ fn assert_start_as_counted( (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, @@ -1353,14 +1351,6 @@ fn caller_refuses( }) } -/// 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 @@ -1773,6 +1763,20 @@ mod tests { 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 diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 00e9c83b6..7fbcb806a 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -272,38 +272,6 @@ impl FrameLimitTracker { 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); - } - - /// Takes back everything the running frame's start counted, its caller's record included - /// ([`drop_caller_record`](Self::drop_caller_record)): the start did not happen after all, so - /// the lane keeps nothing whatever the frame's answer, and its caller gets back all it paid - /// for the records. Must run before the frame runs, when its start is all the lane holds. - pub(crate) fn undo_frame_start(&mut self) { - self.drop_caller_record(); - let Some(lane) = self.lanes.last_mut() else { return }; - debug_assert_eq!( - lane.refund, - LimitUsage::ZERO, - "a frame that has not run took nothing back" - ); - debug_assert_eq!(lane.log_and_code_bytes, 0, "a frame that has not run logged nothing"); - self.total_used = self.total_used.saturating_sub(lane.used); - lane.used = LimitUsage::ZERO; - lane.records_made = false; - } - /// 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 @@ -682,22 +650,6 @@ mod tests { assert_eq!(empty.depth(), 0); } - /// 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, UNLIMITED, 0)); - t.push(Lane::new(None, true, UNLIMITED, 0)); - t.record_caller(true, 0); - 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()); - } - /// 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] diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d88b65a7f..5aa46359b 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -581,7 +581,8 @@ impl AdditionalLimit { /// So the count is a prediction of what revm will do, and it is called only for a start revm /// makes as far as the caller's account decides it. A start revm refuses there — a value its /// caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes - /// nothing, and gets an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)). + /// nothing, and gets an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)); so + /// does a start past the call-stack limit, which the depth guard answers before it is counted. /// The one refusal decided after the count is a creation onto an occupied address: revm reads /// the created address's account only once it builds the frame. Its records and transfer log /// are counted, a crossing they cause stops the creation before revm could refuse it, and @@ -668,21 +669,6 @@ impl AdditionalLimit { forwarded.min(self.limits.frame_usage_limit()) } - /// Takes back what a creation's start counted: revm answered the creation without bumping its - /// creator's nonce, so the start wrote nothing and moved nothing — no creator's nonce, no - /// created account, no transfer log. - /// - /// A failure would discard the lane anyway, but not the creator's record, which outlives a - /// failed creation once the nonce was bumped. And one answer of this kind is a success: a - /// creator whose nonce cannot be bumped is answered with a `Return` and no address, which - /// would merge the lane into the caller's. Such a start is predicted and counts nothing in - /// the first place ([`on_frame_init`](Self::on_frame_init)); this holds the lane to revm's - /// answer whatever was counted. The caller gets back all it paid for the records when the - /// frame returns. - pub(crate) fn creation_did_not_bump_nonce(&mut self) { - self.tracker.undo_frame_start(); - } - fn push_lane(&mut self, input: &FrameInput, depth: usize) { self.state_gas.push(); let budget = self.frame_budget(); @@ -1402,37 +1388,6 @@ mod tests { ))) } - /// A creation revm answers without bumping its creator's nonce keeps nothing its start - /// counted, whatever the answer: a failure, and the success a creator whose nonce cannot be - /// bumped is answered with. The created account's record, the transfer log and the creator's - /// record all go, the caller gets back all it paid for them, and the creator's account is no - /// longer counted as recorded, so its next value transfer records it. - #[test] - fn test_a_creation_that_did_not_bump_the_nonce_keeps_nothing() { - let inner = creation(CALLEE, U256::from(1)); - for answer in [InstructionResult::Return, InstructionResult::OutOfFunds] { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); - limit.on_frame_init(&inner, 1); - assert_eq!( - limit.usage(), - LimitUsage { - data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - write_records: 2, - }, - "{answer:?}: the created account, the creator and the log", - ); - - limit.creation_did_not_bump_nonce(); - let mut result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); - assert_eq!(limit.on_frame_return(&mut result), 3_000, "{answer:?}: all of it back"); - assert_eq!(limit.usage(), LimitUsage::ZERO, "{answer:?}: nothing kept"); - let next = limit.frame_start_records(&call_from_to(CALLEE, TARGET, U256::from(1))); - assert!(next.caller, "{answer:?}: the creator is not recorded"); - } - } - /// 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 diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 974dba37b..69c751d0d 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, LimitKind, 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, @@ -104,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.get(&CALLER).is_none(), "{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() { From 62b11f95331cd80738a092209fa66cfb24d9f29a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:32:29 -0400 Subject: [PATCH 354/458] test(satin): read the caller's absence from the journal with contains_key --- crates/mega-evm/tests/satin/synthetic_frame_gas.rs | 2 +- 1 file changed, 1 insertion(+), 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 69c751d0d..7554e1c86 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -153,7 +153,7 @@ fn test_depth_guard_answers_a_creation_and_every_call_scheme() { assert_eq!(outcome.address, None, "{what}"); } assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO, "{what}: counted"); - assert!(evm.ctx().journal_ref().state.get(&CALLER).is_none(), "{what}: no nonce bumped"); + assert!(!evm.ctx().journal_ref().state.contains_key(&CALLER), "{what}: no nonce bumped"); } } From d23e50c80cb001e10a716534afdca3a97493a379 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:33:25 -0400 Subject: [PATCH 355/458] fix(limit): bound detention's caps by the most compute a transaction can spend --- AGENTS.md | 4 +-- crates/mega-evm/src/access/mod.rs | 6 ++--- crates/mega-evm/src/block/limit.rs | 33 +++++++++++------------- crates/mega-evm/src/constants.rs | 33 +++++++++++++----------- crates/mega-evm/src/limit/mod.rs | 4 +-- crates/mega-evm/tests/satin/detention.rs | 33 ++++++++++++------------ docs/spec/upgrades/satin.md | 2 +- 7 files changed, 57 insertions(+), 58 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a30b5f8cd..ee8858165 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,7 +177,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. - The limits that change a result are protocol values, carried by the Satin fork's parameters: `ProtocolLimits` (`block/limit.rs`), attached to the schedule with `MegaHardforkConfig::with_params` and read at the block's timestamp with `MegaHardforks::protocol_limits`. It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. - `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and a detention cap no transaction's compute reaches — at or above `TX_COMPUTE_GAS_BOUND`, the execution cap less EIP-2780's base cost of 12,000; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). + `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and a detention cap no transaction's compute reaches — at or above `MAX_TX_COMPUTE_GAS`, 199,987,900: the execution cap less EIP-2780's base cost of 12,000 and the warm access a frame that runs code pays at least; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`), as an internal error: a gap in the node's configuration, like a missing `SequencerRegistryConfig`, is not a verdict on the block. 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 four 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/protocol_limits.rs`). @@ -283,7 +283,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses a cap at or above `TX_COMPUTE_GAS_BOUND`, which never binds, so no chain 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses a cap at or above `MAX_TX_COMPUTE_GAS`, which never binds, so no chain 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. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 0ff1f2557..10daee3de 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -19,9 +19,9 @@ //! [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) and //! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), by default. In block //! execution they are the chain's ([`ProtocolLimits`](crate::ProtocolLimits)), which must be -//! below [`TX_COMPUTE_GAS_BOUND`](crate::constants::TX_COMPUTE_GAS_BOUND), a compute no -//! transaction reaches; a standalone EVM's caller may set either. A cap of `u64::MAX` caps nothing, -//! and a transaction whose caps are both unlimited — under +//! below [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a +//! transaction can spend; a standalone EVM's caller may set either. 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. diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index c9a53db1b..e19fc2a28 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -71,7 +71,7 @@ use std::{boxed::Box, format}; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ - constants::TX_COMPUTE_GAS_BOUND, BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, + constants::MAX_TX_COMPUTE_GAS, BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, HardforkParamsError, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, MegaHardfork, MegaTxLimitExceededError, TX_BODY_SIZE, }; @@ -199,8 +199,8 @@ impl HardforkParams for ProtocolLimits { /// stops or refuses every transaction that uses the dimension; /// - a transaction data-size limit below [`TX_BODY_SIZE`], the bytes every transaction's body /// counts, which stops every transaction before it runs; - /// - a gas-detention cap at or above [`TX_COMPUTE_GAS_BOUND`], which no transaction's compute - /// reaches: such a cap never stops a read of volatile data, `u64::MAX` among them, and a + /// - a gas-detention cap at or above [`MAX_TX_COMPUTE_GAS`], the most compute a transaction can + /// spend: such a cap never stops a read of volatile data, `u64::MAX` among them, and a /// chain's caps must be able to. /// /// `u64::MAX` is a valid value for every other limit: it leaves the dimension unlimited. @@ -248,10 +248,10 @@ impl HardforkParams for ProtocolLimits { )); } for (name, cap) in detention_caps { - if cap >= TX_COMPUTE_GAS_BOUND { + if cap >= MAX_TX_COMPUTE_GAS { return invalid(format!( - "ProtocolLimits.{name} must be below {TX_COMPUTE_GAS_BOUND}, which no \ - transaction's compute reaches: a cap there leaves a read of volatile data \ + "ProtocolLimits.{name} must be below {MAX_TX_COMPUTE_GAS}, the most compute \ + a transaction can spend: a cap there leaves a read of volatile data \ undetained" )); } @@ -840,27 +840,24 @@ mod tests { ); if name.ends_with("compute_gas_limit") { // A cap no transaction's compute reaches is refused, the execution cap and - // `u64::MAX` among them; one below the bound is accepted. - for cap in [ - TX_COMPUTE_GAS_BOUND, - crate::constants::TX_GAS_LIMIT_CAP, - u64::MAX - 1, - u64::MAX, - ] { + // `u64::MAX` among them; one below the most compute is accepted. + for cap in + [MAX_TX_COMPUTE_GAS, crate::constants::TX_GAS_LIMIT_CAP, u64::MAX - 1, u64::MAX] + { assert_eq!( set(base, cap).validate(), Err(HardforkParamsError { message: std::format!( - "ProtocolLimits.{name} must be below {TX_COMPUTE_GAS_BOUND}, \ - which no transaction's compute reaches: a cap there leaves a \ - read of volatile data undetained" + "ProtocolLimits.{name} must be below {MAX_TX_COMPUTE_GAS}, the \ + most compute a transaction can spend: a cap there leaves a read \ + of volatile data undetained" ) }), "{name} at {cap}" ); } assert_eq!( - set(base, TX_COMPUTE_GAS_BOUND - 1).validate(), + set(base, MAX_TX_COMPUTE_GAS - 1).validate(), Ok(()), "{name} just below" ); @@ -892,7 +889,7 @@ mod tests { #[test] #[should_panic(expected = "Invalid params for fork Satin: \ ProtocolLimits.tx_runtime_limits.block_env_access_compute_gas_limit must be \ - below 199988000")] + below 199987900")] fn test_a_schedule_refuses_the_unlimited_protocol_limits() { let _ = MegaHardforkConfig::default() .with_all_activated() diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index a3dbf3b3c..8f2e5d469 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -17,7 +17,7 @@ //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the default 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) | the default detention cap of the runtime limits and of the protocol limits | //! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits and of the protocol limits | -//! | [`TX_COMPUTE_GAS_BOUND`] | 199,988,000 | a bound no transaction's compute reaches: the execution cap less EIP-2780's base cost | the protocol limits, whose detention caps must be below it | +//! | [`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 | the protocol limits, whose detention caps must be 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 @@ -33,9 +33,12 @@ //! [`ProtocolLimits::block_state_gas_limit`](crate::ProtocolLimits::block_state_gas_limit). A chain //! sets both, and both are unlimited by default. -use revm::primitives::{ - eip2780, - 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. @@ -84,17 +87,17 @@ pub const BLOCK_ENV_ACCESS_COMPUTE_GAS: u64 = 20_000_000; /// specs capped an Oracle read at 1,000,000. Provisional. pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; -/// A bound no transaction's compute reaches: the execution cap less EIP-2780's base cost, the -/// intrinsic regular gas every transaction pays before its first frame. Derived from -/// [`TX_GAS_LIMIT_CAP`]. +/// 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 their regular gas is what the -/// execution cap leaves once the intrinsic gas is paid, so a gas-detention cap at or above this -/// bound never stops a transaction, however early it read: a chain's caps must be below it. A -/// frame that runs code pays a little more before its first instruction — at least a warm account -/// access, for the recipient or the delegate it runs — so the most compute a transaction can -/// spend is a little below the bound. -pub const TX_COMPUTE_GAS_BOUND: u64 = TX_GAS_LIMIT_CAP - eip2780::TX_BASE_COST; +/// 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 (Satin +/// keeps Osaka's). A gas-detention cap at or above this never stops a transaction, however early +/// it read, so a chain's caps must be 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 { @@ -114,6 +117,6 @@ mod tests { assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); assert_eq!(BLOCK_ENV_ACCESS_COMPUTE_GAS, 20_000_000); assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, 20_000_000); - assert_eq!(TX_COMPUTE_GAS_BOUND, 199_988_000); + assert_eq!(MAX_TX_COMPUTE_GAS, 199_987_900); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index f05cda8e2..4a11dd651 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -320,8 +320,8 @@ impl EvmTxRuntimeLimits { /// execution-spec gate's equivalence mode installs, and what tests use to take the limits /// out; the chain executes on its own ([`ProtocolLimits`](crate::ProtocolLimits)), whose /// detention caps must be below - /// [`TX_COMPUTE_GAS_BOUND`](crate::constants::TX_COMPUTE_GAS_BOUND), which no transaction's - /// compute reaches. + /// [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a + /// transaction can spend. pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 7f8aecc70..b9fe1520e 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1599,18 +1599,17 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { assert_stopped(&run, intrinsic(BELOW), left); } -/// A chain's caps must be below [`TX_COMPUTE_GAS_BOUND`], because no transaction's compute -/// reaches it. The transaction closest to it pays the least intrinsic gas a frame that runs code -/// can — 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 -/// the bound less the warm access, so a cap at the bound never stops it, and it runs out of its +/// 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_no_transactions_compute_reaches_the_bound_on_the_caps() { - use mega_evm::constants::TX_COMPUTE_GAS_BOUND; - const WARM_ACCESS: u64 = 100; - let intrinsic = TX_GAS_LIMIT_CAP - TX_COMPUTE_GAS_BOUND + WARM_ACCESS; +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() @@ -1635,23 +1634,23 @@ fn test_no_transactions_compute_reaches_the_bound_on_the_caps() { .push_number(32_u8) .append_many([PUSH0, RETURN]) .build(); - let run = run_under(TX_COMPUTE_GAS_BOUND, answers_gas); - assert_eq!(run.limit, Some(TX_COMPUTE_GAS_BOUND), "detained from the start"); + 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(TX_COMPUTE_GAS_BOUND - WARM_ACCESS - 2)); + 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(TX_COMPUTE_GAS_BOUND, spinner.clone()); - assert_eq!(run.limit, Some(TX_COMPUTE_GAS_BOUND)); - assert_eq!(run.outcome.limit_exceeded, None, "a cap at the bound never stops it"); + 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 = TX_COMPUTE_GAS_BOUND - WARM_ACCESS - 10_000; + 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/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index a4a183a21..8035cabfc 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -465,7 +465,7 @@ A contract can revert with the same bytes, so the revert data alone does not ide - **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 the chain configuration carries with the other limits (see [Resource Limits](#10-resource-limits)), 20,000,000 each by default. - A chain's caps MUST be below 199,988,000: the execution cap less the 12,000 of intrinsic regular gas every transaction pays under EIP-2780, which bounds what a transaction's frames can spend, so a cap at or above it never stops a transaction. + A chain's caps MUST be 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`), 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). From 138e8f4b59263baa23106a291c904ac27ee6c775 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:37:03 -0400 Subject: [PATCH 356/458] fix(block): refuse a block under limits their own check refuses --- AGENTS.md | 3 +- crates/mega-evm/src/block/executor.rs | 85 ++++++++++++----- crates/mega-evm/src/block/hardfork.rs | 12 ++- crates/mega-evm/src/block/limit.rs | 34 ++++++- crates/mega-evm/tests/block/common.rs | 27 ++++-- crates/mega-evm/tests/block/eips.rs | 23 ++--- crates/mega-evm/tests/block/factory.rs | 9 +- crates/mega-evm/tests/block/limits.rs | 8 +- crates/mega-evm/tests/block/schedule.rs | 121 +++++++++++++++++++++++- 9 files changed, 256 insertions(+), 66 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ee8858165..2eb4d4f84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -181,7 +181,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`), as an internal error: a gap in the node's configuration, like a missing `SequencerRegistryConfig`, is not a verdict on the block. 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 four 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/protocol_limits.rs`). - Tests that run blocks under limits no chain may carry (`ProtocolLimits::no_limits()`, detention off) attach them with `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. + The executor checks the limits again (`validate()`) and refuses a block under limits the check refuses (`InvalidProtocolLimits`, internal), whatever the schedule's type: a node's own schedule type attaches its params without `with_params`, and `validate_schedule` runs only when the node calls it. + Tests that run blocks without holding them to a limit attach `ProtocolLimits::loosest()`, the loosest limits a chain may carry (every limit unlimited, detention's caps at `MAX_TX_COMPUTE_GAS - 1`); `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`, builds a schedule carrying a value no chain may carry, to test what refuses it; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index bfc88791a..7b2931c1f 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -11,8 +11,10 @@ //! ([`MegaHardforks::protocol_limits`]), installs their per-transaction half on the EVM before //! every transaction, and holds the block to their four budgets. The node's context adds only the //! builder's policy ([`BlockLimits`]), which can tighten a budget and never loosen one; a validator -//! leaves it at its default. A block whose schedule carries no limits at its timestamp is refused -//! before anything runs. +//! leaves it at its default. A block whose schedule carries no limits at its timestamp, or limits +//! their own check refuses ([`HardforkParams::validate`](crate::HardforkParams::validate)), is +//! refused before anything runs, as an internal error: the schedule is the node's configuration, +//! and a node's own schedule type may hand the executor values nothing checked at load. //! //! # The block rules of the Karst base //! @@ -123,9 +125,9 @@ use crate::{ is_apply_pending_changes_due, system_contract_specs, transact_apply_pending_changes, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, }, - BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, - MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, - ProtocolLimits, + BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, HardforkParams, + MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, + MegaTransaction, MegaTransactionExt, ProtocolLimits, }; /// What the node hands block execution beside the EVM. @@ -217,6 +219,17 @@ pub enum MegaBlockExecutionError { /// The block's timestamp. timestamp: u64, }, + /// The schedule carries [`ProtocolLimits`] for the block's timestamp that their own check + /// refuses ([`HardforkParams::validate`](crate::HardforkParams::validate)): limits no chain + /// may carry, which a schedule checked at load cannot hold. + /// + /// A gap in the node's configuration, not a verdict on the block: an internal error. + InvalidProtocolLimits { + /// The block's timestamp. + timestamp: u64, + /// What the check reported. + message: String, + }, /// The EIP-7997 factory holds the right runtime but nonce 0. ZeroFactoryNonce { /// The factory address. @@ -266,6 +279,11 @@ impl fmt::Display for MegaBlockExecutionError { f, "the schedule carries no ProtocolLimits for the block at timestamp {timestamp}" ), + Self::InvalidProtocolLimits { timestamp, message } => write!( + f, + "the schedule's ProtocolLimits for the block at timestamp {timestamp} are \ + invalid: {message}" + ), Self::ZeroFactoryNonce { address } => write!( f, "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" @@ -291,7 +309,8 @@ impl From for BlockExecutionError { fn from(error: MegaBlockExecutionError) -> Self { match error { MegaBlockExecutionError::MissingSequencerRegistryConfig | - MegaBlockExecutionError::MissingProtocolLimits { .. } => Self::other(error), + MegaBlockExecutionError::MissingProtocolLimits { .. } | + MegaBlockExecutionError::InvalidProtocolLimits { .. } => Self::other(error), MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | MegaBlockExecutionError::RewritingInspector | @@ -372,9 +391,9 @@ pub struct MegaBlockExecutor { /// 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 schedule holds this block to, read at the block's timestamp; `None` when it - /// carries none there, which refuses the block. - protocol_limits: Option, + /// The limits the schedule holds this block to, read at the block's timestamp and checked; + /// the refusal of the block when the schedule carries none there, or limits the check refuses. + protocol_limits: Result, /// 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. @@ -437,9 +456,15 @@ where /// number consensus holds the block to, and it is also the budget the data-availability /// footprint of the block's transactions is held to. /// - /// A schedule with no limits at the block's timestamp builds an executor all the same; the - /// block is refused at its first entry point - /// ([`MegaBlockExecutionError::MissingProtocolLimits`]). + /// A schedule with no limits at the block's timestamp, or with limits their own check refuses + /// ([`HardforkParams::validate`](crate::HardforkParams::validate)), builds an executor all + /// the same, which installs nothing on the EVM; the block is refused at its first entry point + /// ([`MegaBlockExecutionError::MissingProtocolLimits`], + /// [`MegaBlockExecutionError::InvalidProtocolLimits`]). The check is made here, whatever the + /// schedule's type: a node's own implementation of [`MegaHardforks`] attaches its parameters + /// without [`MegaHardforkConfig::with_params`](crate::MegaHardforkConfig::with_params), and + /// [`validate_schedule`](MegaHardforks::validate_schedule) checks them only when a node calls + /// it. pub fn new( mut evm: MegaEvm, ctx: MegaBlockExecutionCtx, @@ -450,13 +475,22 @@ where let block = evm.ctx().block(); (block.timestamp().saturating_to(), block.gas_limit()) }; - let protocol_limits = spec.protocol_limits(timestamp); + let protocol_limits = match spec.protocol_limits(timestamp) { + None => Err(MegaBlockExecutionError::MissingProtocolLimits { timestamp }), + Some(limits) => match limits.validate() { + Ok(()) => Ok(limits), + Err(error) => Err(MegaBlockExecutionError::InvalidProtocolLimits { + timestamp, + message: error.message, + }), + }, + }; let policy = match &protocol_limits { - Some(protocol) => { + Ok(protocol) => { evm.set_tx_runtime_limits(protocol.tx_runtime_limits); ctx.block_limits.within(protocol) } - None => ctx.block_limits, + Err(_) => ctx.block_limits, }; let limits = policy.with_block_gas_limit(block_gas_limit); Self { @@ -473,9 +507,13 @@ where } } - /// The limits the schedule holds this block to, read at the block's timestamp. + /// The limits the schedule holds this block to, read at the block's timestamp; `None` when it + /// carries none there, or limits their own check refuses, either of which refuses the block. pub const fn protocol_limits(&self) -> Option<&ProtocolLimits> { - self.protocol_limits.as_ref() + match &self.protocol_limits { + Ok(limits) => Some(limits), + Err(_) => None, + } } } @@ -555,14 +593,12 @@ where } /// The limits the schedule holds this block to, or the refusal of a block whose schedule - /// carries none at its timestamp. + /// carries none at its timestamp, or limits their own check refuses. fn require_protocol_limits(&self) -> Result { - self.protocol_limits.ok_or_else(|| { - MegaBlockExecutionError::MissingProtocolLimits { - timestamp: self.evm.block().timestamp().saturating_to(), - } - .into() - }) + match &self.protocol_limits { + Ok(limits) => Ok(*limits), + Err(refusal) => Err(refusal.clone().into()), + } } /// Refuses an EVM that runs an inspector which may rewrite what execution produces. @@ -1158,6 +1194,7 @@ mod tests { for gap in [ MegaBlockExecutionError::MissingSequencerRegistryConfig, MegaBlockExecutionError::MissingProtocolLimits { timestamp: 1 }, + MegaBlockExecutionError::InvalidProtocolLimits { timestamp: 1, message: String::new() }, ] { assert_eq!(internal(&BlockExecutionError::from(gap.clone())), &gap); } diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 7313fcf88..4e8fdfccb 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -385,10 +385,14 @@ impl MegaHardforkConfig { /// Attaches `params` to the fork they belong to without checking them. /// - /// Test tooling, behind the `test-utils` feature: it lets a test run block execution under a - /// value no chain may carry, such as limits that leave gas detention off. A production build - /// has no such route: [`with_params`](Self::with_params) checks every value it attaches, and - /// [`validate_schedule`](MegaHardforks::validate_schedule) checks them again at load. + /// Test tooling, behind the `test-utils` feature: it lets a test build a schedule that carries + /// a value no chain may carry, such as limits that leave gas detention off, to test what + /// refuses it. It is not the only way such a value reaches block execution: a node's own + /// implementation of [`MegaHardforks`] attaches its parameters without + /// [`with_params`](Self::with_params) and hands the block executor whatever it holds. What + /// stands in the way is [`validate_schedule`](MegaHardforks::validate_schedule), which a node + /// runs when it loads its chain configuration, and the block executor, which refuses a block + /// whose [`ProtocolLimits`] their own check refuses. /// /// # Panics /// diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index e19fc2a28..0e167c05b 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -146,8 +146,9 @@ impl ProtocolLimits { /// No limit at all, gas detention's caps included, so no transaction is detained /// ([`EvmTxRuntimeLimits::no_limits`]). /// - /// For tests and equivalence runs: [`validate`](HardforkParams::validate) refuses it, so no - /// chain configuration carries it. + /// For tests of what refuses it: [`validate`](HardforkParams::validate) refuses it, so no + /// chain configuration carries it, and the block executor refuses a block under it. A test + /// that runs blocks without holding them to a limit uses [`loosest`](Self::loosest). pub const fn no_limits() -> Self { Self { tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), @@ -158,6 +159,22 @@ impl ProtocolLimits { } } + /// The loosest limits a chain may carry: every limit unlimited, and gas detention's caps at + /// the largest [`validate`](HardforkParams::validate) accepts, one below + /// [`MAX_TX_COMPUTE_GAS`]. + /// + /// A read of volatile data still detains the transaction, but a cap that high stops only a + /// transaction that spends the most compute any can. For tests and test chains that run blocks + /// without holding them to a limit. + pub const fn loosest() -> Self { + let cap = MAX_TX_COMPUTE_GAS - 1; + Self::no_limits().with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_block_env_access_compute_gas_limit(cap) + .with_oracle_access_compute_gas_limit(cap), + ) + } + /// Sets the limits every transaction runs under. pub const fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { self.tx_runtime_limits = limits; @@ -881,8 +898,19 @@ mod tests { Ok(()) ); - // The unlimited set of tests and equivalence runs is refused. + // The unlimited set is refused; the loosest a chain may carry is unlimited but for + // detention's caps, one below the most compute a transaction can spend. assert!(ProtocolLimits::no_limits().validate().is_err()); + assert_eq!(ProtocolLimits::loosest().validate(), Ok(())); + let cap = MAX_TX_COMPUTE_GAS - 1; + assert_eq!( + ProtocolLimits::loosest(), + ProtocolLimits::no_limits().with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_block_env_access_compute_gas_limit(cap) + .with_oracle_access_compute_gas_limit(cap) + ) + ); } /// A schedule refuses to carry the unlimited set, so no validated chain configuration does. diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 457153e35..f59e1aa70 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -12,7 +12,7 @@ use alloy_sol_types::SolCall; use mega_evm::{ system::{IOracle, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::MemoryDatabase, - BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, MegaBlockExecutor, + BlockLimits, EmptyExternalEnv, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, PreBlockStateSource, ProtocolLimits, }; @@ -87,23 +87,30 @@ pub(crate) fn registry_config() -> SequencerRegistryConfig { } /// A schedule that activates Satin at genesis, can seed the `SequencerRegistry`, and holds its -/// blocks to no limit at all. +/// blocks to the loosest limits a chain may carry. /// -/// Its limits are [`ProtocolLimits::no_limits`], which no chain may carry, so they are attached -/// through the test-only unchecked route: most block tests exercise one mechanism and take the -/// limits out, and a test that holds a block or a transaction to a limit attaches its own -/// ([`chain_spec_with`]). +/// Its limits are [`ProtocolLimits::loosest`]: most block tests exercise one mechanism and take +/// the limits out, and a test that holds a block or a transaction to a limit attaches its own +/// ([`chain_spec_with`]). Every limit is unlimited but gas detention's caps, which no transaction +/// of a block this size reaches, so a transaction that reads volatile data is detained and never +/// stopped. pub(crate) fn chain_spec() -> MegaHardforkConfig { - chain_spec_with(ProtocolLimits::no_limits()) + chain_spec_with(ProtocolLimits::loosest()) } -/// [`chain_spec`], holding its blocks to `limits`, attached unchecked so a test may run under a -/// value no chain may carry. +/// [`chain_spec`], holding its blocks to `limits`, which must be limits a chain may carry: the +/// block executor refuses a block under any other. pub(crate) fn chain_spec_with(limits: ProtocolLimits) -> MegaHardforkConfig { MegaHardforkConfig::default() .with_all_activated() .with_params(registry_config()) - .with_params_unchecked(limits) + .with_params(limits) +} + +/// The per-transaction half of [`ProtocolLimits::loosest`], for a test that holds a block's +/// transactions to one limit and no other. +pub(crate) const fn loosest_tx() -> EvmTxRuntimeLimits { + ProtocolLimits::loosest().tx_runtime_limits } /// The context of a block the builder packs under `policy`. diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 881a090b7..b61bdb7e2 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -23,8 +23,8 @@ use mega_evm::{ constants::SLOT_STATE_GAS, pre_block_call_gas_limit, test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, - BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, - MegaHardforkConfig, MegaSpecId, PreBlockStateSource, ProtocolLimits, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, PreBlockStateSource, ProtocolLimits, }; use revm::{ bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, @@ -181,17 +181,18 @@ 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 -/// limits their bodies, their writes and their state gas each cross, both calls still record. +/// The pre-block calls are the protocol's own work, held to no per-transaction limit: under the +/// smallest limits a chain may carry, which their bodies, their writes and their state gas cross, +/// both calls still record. #[test] fn test_the_pre_block_calls_are_held_to_no_limit() { - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(0) - .with_frame_data_size_limit(0) - .with_tx_kv_update_limit(0) - .with_frame_kv_update_limit(0) - .with_tx_state_gas_limit(0); - let spec = common::chain_spec_with(ProtocolLimits::no_limits().with_tx_runtime_limits(limits)); + let limits = common::loosest_tx() + .with_tx_data_size_limit(mega_evm::TX_BODY_SIZE) + .with_frame_data_size_limit(1) + .with_tx_kv_update_limit(1) + .with_frame_kv_update_limit(1) + .with_tx_state_gas_limit(1); + let spec = common::chain_spec_with(ProtocolLimits::loosest().with_tx_runtime_limits(limits)); assert_eq!(pre_block_calls(spec, BLOCK_NUMBER, ctx()), (PARENT_HASH, PARENT_BEACON_ROOT)); } diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index bb4d48dde..feb4e2bf5 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -31,8 +31,8 @@ const FRAME_DATA_SIZE_LIMIT: u64 = 7_654_321; /// The chain's limits in these tests. fn limits() -> ProtocolLimits { - ProtocolLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() + ProtocolLimits::loosest().with_tx_runtime_limits( + common::loosest_tx() .with_tx_data_size_limit(TX_DATA_SIZE_LIMIT) .with_frame_data_size_limit(FRAME_DATA_SIZE_LIMIT), ) @@ -178,9 +178,8 @@ fn test_direct_construction_stops_a_transaction_over_the_chains_data_size_limit( // that carries no limits of its own. let mut executor = common::executor_with_limits( &mut state, - ProtocolLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(DATA_SIZE_LIMIT), - ), + ProtocolLimits::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"); executor.evm_mut().set_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index ba2b9e465..f8bf5f95f 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -4,8 +4,8 @@ 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, EvmTxRuntimeLimits, LimitCheck, - LimitKind, MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, + test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, LimitCheck, LimitKind, + MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, }; use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, @@ -280,8 +280,8 @@ fn test_the_transaction_data_size_limit_stops_a_deposit_that_is_still_included() let mut state = common::state(); let mut executor = common::executor_with_limits( &mut state, - ProtocolLimits::no_limits() - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), + ProtocolLimits::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_data_size_limit(limit)), ); executor.apply_pre_execution_changes().expect("the block starts"); diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index f26c0c5a6..cdeb59ec2 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -1,11 +1,19 @@ //! 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 core::any::{Any, TypeId}; + +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor}, + Evm, EvmFactory, +}; +use alloy_hardforks::{EthereumHardfork, EthereumHardforks, ForkCondition}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_op_hardforks::{OpHardfork, OpHardforks}; use mega_evm::{ chain_activation, mainnet_hardforks, system::SequencerRegistryConfig, testnet_hardforks, - MegaHardfork, MegaHardforkConfig, MegaHardforks, ProtocolLimits, ScheduleError, - MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, + HardforkParams, MegaBlockExecutionError, MegaBlockExecutor, MegaEvmFactory, MegaHardfork, + MegaHardforkConfig, MegaHardforks, ProtocolLimits, ScheduleError, MAINNET_CHAIN_ID, + TESTNET_CHAIN_ID, }; use crate::common::{self, registry_config, user_tx}; @@ -94,3 +102,108 @@ fn test_an_unscheduled_fork_needs_no_params() { assert_eq!(unscheduled.require_params::(), Ok(())); assert_eq!(unscheduled.validate_schedule(), Ok(())); } + +/// A node's own schedule type: it attaches its parameters without `with_params`, and answers with +/// whatever it holds, checked or not. This one holds `limits` for Satin and answers everything +/// else as [`common::chain_spec`] does. +struct NodeSchedule { + inner: MegaHardforkConfig, + limits: ProtocolLimits, +} + +impl EthereumHardforks for NodeSchedule { + fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { + self.inner.ethereum_fork_activation(fork) + } +} + +impl OpHardforks for NodeSchedule { + fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { + self.inner.op_fork_activation(fork) + } +} + +impl MegaHardforks for NodeSchedule { + fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { + self.inner.mega_fork_activation(fork) + } + + fn fork_params_any( + &self, + fork: MegaHardfork, + params: TypeId, + ) -> Option<&(dyn Any + Send + Sync)> { + if fork == MegaHardfork::Satin && params == TypeId::of::() { + Some(&self.limits) + } else { + self.inner.fork_params_any(fork, params) + } + } +} + +/// The refusal of this engine an internal error carries. +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:?}")) +} + +/// Limits their own check refuses run no block, even when they reach the block executor without +/// the load-time check: a node's own schedule type hands them over as it holds them. The executor +/// installs nothing on the EVM and refuses the block at every entry point, as an internal error — +/// the schedule is the node's configuration, not the block. +#[test] +fn test_limits_the_check_refuses_run_no_block() { + let invalid = ProtocolLimits::no_limits(); + let schedule = NodeSchedule { inner: common::chain_spec(), limits: invalid }; + let message = invalid.validate().expect_err("no chain may carry them").message; + assert_eq!( + schedule.validate_schedule(), + Err(ScheduleError::InvalidParams { + fork: MegaHardfork::Satin, + params: "ProtocolLimits", + message: message.clone(), + }), + "the load-time check refuses them, for a node that runs it" + ); + + let mut state = common::state(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + let built_with = *evm.tx_runtime_limits(); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + &schedule, + OpAlloyReceiptBuilder::default(), + ); + assert_eq!(executor.protocol_limits(), None); + assert_eq!(*executor.evm().tx_runtime_limits(), built_with, "nothing is installed"); + + let refusal = MegaBlockExecutionError::InvalidProtocolLimits { + timestamp: common::BLOCK_TIMESTAMP, + message, + }; + let error = executor.apply_pre_execution_changes().expect_err("the block does not start"); + assert_eq!(internal(&error), &refusal); + assert!(executor.evm().db().bundle_state.state.is_empty(), "no pre-block step ran"); + let error = + executor.execute_transaction(&user_tx(0, 100_000)).expect_err("no transaction runs either"); + assert_eq!(internal(&error), &refusal); + assert!(executor.receipts().is_empty()); + + // The same schedule holding limits a chain may carry runs the block. + let schedule = NodeSchedule { inner: common::chain_spec(), limits: ProtocolLimits::DEFAULT }; + assert_eq!(schedule.validate_schedule(), Ok(())); + let mut state = common::state(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + &schedule, + OpAlloyReceiptBuilder::default(), + ); + assert_eq!(executor.protocol_limits(), Some(&ProtocolLimits::DEFAULT)); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); +} From d8dcf394335ac3d008d08f756db3aae82a9914ae Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:38:05 -0400 Subject: [PATCH 357/458] fix(block): refuse to finish a block whose schedule carries no valid limits --- crates/mega-evm/src/block/executor.rs | 15 ++++++++++++++- crates/mega-evm/tests/block/schedule.rs | 7 +++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 7b2931c1f..8059ad0d4 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -1036,10 +1036,15 @@ where /// 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. + /// + /// A block whose schedule carries no limits at its timestamp, or limits their own check + /// refuses, is refused here too, before the post-block balance increments: a caller that never + /// started the block cannot finish it either. pub fn finish_with_counters( mut self, ) -> Result, BlockExecutionError> { self.check_admission()?; + self.require_protocol_limits()?; let balance_increments = post_block_balance_increments::
(&self.spec, self.evm.block(), &[], None); @@ -1102,7 +1107,8 @@ mod tests { } /// A schedule that carries no limits at the block's timestamp refuses the block before any - /// pre-block step runs: the block is not executed under limits nobody chose. + /// pre-block step runs, and refuses to finish it: the block is not executed under limits + /// nobody chose. #[test] fn test_a_block_without_protocol_limits_is_refused_before_it_starts() { let ctx = @@ -1131,6 +1137,13 @@ mod tests { "the schedule carries no ProtocolLimits for the block at timestamp 7" ); assert!(executor.receipts().is_empty()); + + // Nor can it be finished: the post-block balance increments do not run on it. + let Err(error) = executor.finish() else { panic!("no limits, no finished block") }; + assert_eq!( + internal(&error), + &MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 } + ); } /// The `MegaBlockExecutionError` an internal error carries; panics on a validation error. diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index cdeb59ec2..0a935c3e7 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -151,8 +151,9 @@ fn internal(error: &BlockExecutionError) -> &MegaBlockExecutionError { /// Limits their own check refuses run no block, even when they reach the block executor without /// the load-time check: a node's own schedule type hands them over as it holds them. The executor -/// installs nothing on the EVM and refuses the block at every entry point, as an internal error — -/// the schedule is the node's configuration, not the block. +/// installs nothing on the EVM and refuses the block at every entry point — its start, a +/// transaction, its end — as an internal error: the schedule is the node's configuration, not the +/// block. #[test] fn test_limits_the_check_refuses_run_no_block() { let invalid = ProtocolLimits::no_limits(); @@ -191,6 +192,8 @@ fn test_limits_the_check_refuses_run_no_block() { executor.execute_transaction(&user_tx(0, 100_000)).expect_err("no transaction runs either"); assert_eq!(internal(&error), &refusal); assert!(executor.receipts().is_empty()); + let Err(error) = executor.finish() else { panic!("nor is the block finished") }; + assert_eq!(internal(&error), &refusal); // The same schedule holding limits a chain may carry runs the block. let schedule = NodeSchedule { inner: common::chain_spec(), limits: ProtocolLimits::DEFAULT }; From c27cc6c33c1c4b6e97c54f36f7b8ed28abc4db80 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:40:25 -0400 Subject: [PATCH 358/458] test(satin): hold the Satin tests at any byte price Gas limits cover what a scenario adds at the prices in effect, a call or creation that forwards all but a 64th keeps 64 times the history of the records it pays for, and a bill is the larger of the charge and the EIP-7623 floor where a cheap history byte lets the floor bind. A test whose scenario is state or history gas to cross, scale or give back returns early where that byte costs nothing, and says so once on stderr. --- crates/mega-evm/tests/satin/common.rs | 69 +++++++++++++ crates/mega-evm/tests/satin/compute_gas.rs | 8 +- crates/mega-evm/tests/satin/contract_size.rs | 22 +++-- crates/mega-evm/tests/satin/data_size.rs | 68 ++++++++++--- crates/mega-evm/tests/satin/deposit_charge.rs | 18 +++- crates/mega-evm/tests/satin/detention.rs | 5 + crates/mega-evm/tests/satin/equivalence.rs | 44 ++++++--- crates/mega-evm/tests/satin/inspector.rs | 42 +++++--- .../tests/satin/inspector_cheatcodes.rs | 7 +- .../tests/satin/inspector_settlement.rs | 19 +++- crates/mega-evm/tests/satin/intrinsic.rs | 19 +++- .../mega-evm/tests/satin/limit_exemption.rs | 9 +- crates/mega-evm/tests/satin/outcome.rs | 18 +++- crates/mega-evm/tests/satin/salt.rs | 44 ++++++++- .../mega-evm/tests/satin/salt_delegation.rs | 13 ++- 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 | 65 +++++++++--- crates/mega-evm/tests/satin/schedule.rs | 69 ++++++++----- .../mega-evm/tests/satin/state_gas_limit.rs | 65 +++++++++++- crates/mega-evm/tests/satin/stops.rs | 31 ++++-- crates/mega-evm/tests/satin/strategic_stop.rs | 12 ++- crates/mega-evm/tests/satin/system_call.rs | 18 +++- crates/mega-evm/tests/satin/transfer_logs.rs | 24 +++-- .../mega-evm/tests/satin/volatile_access.rs | 21 ++-- crates/mega-evm/tests/satin/withheld_gas.rs | 53 +++++++--- crates/mega-evm/tests/satin/write_records.rs | 98 ++++++++++--------- 27 files changed, 694 insertions(+), 217 deletions(-) diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 88d6b0a65..c62d6f603 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -132,3 +132,72 @@ pub(crate) fn runs_at_measurement_prices() -> bool { }); 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; the notice goes +/// to stderr once, like [`runs_at_measurement_prices`]'s. +pub(crate) fn state_is_free() -> bool { + use std::io::Write; + + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the tests that need state gas, because 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 { + use std::io::Write; + + if active_satin_prices().cphb.milli_gas() != 0 { + return false; + } + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the tests that need history gas, because MEGA_SATIN_CPHB prices a \ + history byte at nothing" + ); + }); + 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. +pub(crate) fn history(bytes: u64) -> u64 { + mega_evm::history_gas(bytes).expect("the bytes have a price") +} + +/// 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. +pub(crate) fn body_history(calldata_len: u64) -> u64 { + history(mega_evm::tx_body_history_bytes(calldata_len, 0, 0, 0)) +} diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index dbcf3de9b..8f8314a99 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -333,7 +333,13 @@ fn test_a_refund_does_not_lower_the_compute_figure() { for gas_limit in GAS_LIMITS { let cleared = writes(0, gas_limit); let overwritten = writes(2, gas_limit); - assert_eq!(overwritten.gas_used - cleared.gas_used, SSTORE_CLEARS_SCHEDULE); + // EIP-3529 caps the refund at a fifth of what the transaction spent, which the two spend + // alike before it; the history the transaction pays lifts the cap past the refund at the + // spec's prices. + let cap = overwritten.gas_used / + mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::max_refund_quotient()); + assert_eq!(overwritten.gas_used - cleared.gas_used, SSTORE_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()); } diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs index c8e9c136c..cb0e4f916 100644 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -8,7 +8,7 @@ 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, }; @@ -18,14 +18,22 @@ use revm::{ 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 +53,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. @@ -169,7 +177,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 { diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 275f34973..323812c68 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -31,7 +31,10 @@ use revm::{ Database, Inspector, }; -use crate::common::{call, call_with_data, context, create}; +use crate::common::{ + account_state_gas, body_history, call, call_with_data, context, create, history, + slot_state_gas, state_is_free, +}; const CALLER: Address = address!("0000000000000000000000000000000000300000"); const A: Address = address!("0000000000000000000000000000000000300001"); @@ -41,6 +44,12 @@ 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) +} + /// 98% of `remaining`, the share a child frame is given. fn share(remaining: u64) -> u64 { (u128::from(remaining) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / @@ -103,7 +112,8 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { let run = |data_len: u64| { let db = chain(log0(data_len)); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + 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().latched().copied(), @@ -512,7 +522,13 @@ fn test_code_return_create_refuses_is_not_counted() { // The same length, deployable and paid for: counted, and it crosses. let deployable = constructor_returning_from(0x00, len.min(max)); - let (stopped, _) = run(&deployable, inspect, TX_GAS_LIMIT_CAP + 2_000_000_000); + // 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 (stopped, _) = run(&deployable, inspect, roomy); assert_eq!( stopped.limit_exceeded, Some(LimitCheck::ExceedsLimit { @@ -741,9 +757,20 @@ 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. +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(1_000_000, |gas| { + smallest_gas_limit(high_bound(), |gas| { !matches!(bound_at(code, gas, data_limit), Bound::Rejected | Bound::OutOfGas) }) } @@ -805,8 +832,12 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { 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}"); - assert!(matches!(bound_at(&code, counted_at, fits), Bound::OutOfGas), "{name}"); - assert!(matches!(bound_at(&code, kept_at - 1, fits), Bound::OutOfGas), "{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}"); } } @@ -954,15 +985,22 @@ fn test_a_body_over_the_limit_is_the_stop_at_the_smallest_valid_gas_limit() { "{name}: the limit does not move validation" ); - let unlimited = outcome_at(tx(valid), u64::MAX).unwrap(); - assert!( - matches!( - unlimited.result, - ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } - ), - "{name}: without a limit the start runs out of gas, got {:?}", - unlimited.result - ); + // Where a state byte and a record's history are both free the start costs nothing past + // the intrinsic gas, and there is no out-of-gas for the stop to stand in for. + if !(state_is_free() && history(WRITE_RECORD_SIZE) == 0) { + let unlimited = outcome_at(tx(valid), u64::MAX).unwrap(); + assert!( + matches!( + unlimited.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), + .. + } + ), + "{name}: without a limit the start runs out of gas, got {:?}", + unlimited.result + ); + } let stopped = outcome_at(tx(valid), limit).unwrap(); assert_stopped(&stopped, limit, body); diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 7ac2c2eef..cf6cf4383 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -36,7 +36,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{call, context}; +use crate::common::{call, context, history_is_free, state_is_free}; const CALLER: Address = address!("0000000000000000000000000000000000a00000"); /// Calls `B` with a chosen gas, keeps what `B` answers in slot 1, then writes slot 0. @@ -54,9 +54,10 @@ const B: Address = address!("0000000000000000000000000000000000a00002"); /// the records whatever the prices, where a kilobyte does only while a state byte is dear. const CODE_LEN: u16 = 6 * 1_024; -/// Below the execution cap: there is no reservoir, and every state charge is paid out of regular -/// gas. -const BELOW_CAP: u64 = 100_000_000; +/// At the execution cap: the whole gas limit is regular gas, there is no reservoir, and every state +/// charge is paid out of regular gas. Half of it pays for the creation's deposit at any byte price +/// up to several times the dearest one considered. +const BELOW_CAP: u64 = TX_GAS_LIMIT_CAP; /// Above the execution cap: the reservoir pays every state and history charge. const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; @@ -319,6 +320,10 @@ fn assert_data_size_limit_stands_aside(setup: Setup) { /// cannot pay the hash of its code runs out of gas on it, whatever the state-gas limit. #[test] fn test_a_creation_that_cannot_pay_the_hash_runs_out_of_gas_under_the_state_gas_limit() { + // A deposit that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let setup = Setup::Satin(ABOVE_CAP); let (enough, _) = boundary(setup); let end = creation_end(setup, enough - 1); @@ -333,6 +338,11 @@ fn test_a_creation_that_cannot_pay_the_hash_runs_out_of_gas_under_the_state_gas_ /// it never reaches. #[test] fn test_a_creation_that_cannot_pay_its_history_runs_out_of_gas_under_the_state_gas_limit() { + // A deposit that pays no history has no history to run out of gas on, and one that adds no + // state gas has no state-gas limit to cross. + if history_is_free() || state_is_free() { + return; + } let setup = Setup::Satin(BELOW_CAP); let (enough, _) = boundary(setup); let end = creation_end(setup, enough - 1); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 887dd7a88..6db3f9ba3 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1540,6 +1540,11 @@ 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); diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index ae6ba4bad..7d62dc3fa 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -48,7 +48,9 @@ use revm::{ 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"); @@ -128,7 +130,7 @@ fn both_evms( /// ([`test_fees_match_op_revm`]). fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { let history = mega.gas.history; - assert!(history > 0, "every Satin transaction pays for its own body"); + 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"); @@ -220,7 +222,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); @@ -232,9 +235,7 @@ fn test_value_transfer_matches_op_revm() { 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. - if !runs_at_measurement_prices() { - assert_eq!(mega.gas.history, (TX_BODY_SIZE + WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE); - } + 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. @@ -324,19 +325,26 @@ 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_eq!( @@ -381,9 +389,11 @@ fn test_refund_matches_op_revm() { assert!(mega.result.gas().inner_refunded() > 0, "the clear is refunded"); // 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. - // EIP-8037 state gas raises the same cap; this is that rule applied to the third ledger. + // 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, @@ -391,8 +401,8 @@ fn test_refund_matches_op_revm() { ); assert_eq!( mega.result.gas().inner_refunded(), - satin_gas_params().get(GasId::sstore_clearing_slot_refund()), - "Satin keeps the whole clearing refund", + 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); } @@ -503,7 +513,8 @@ fn test_a_system_address_transaction_diverges_from_op_revm() { 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() @@ -539,7 +550,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() }; @@ -555,8 +566,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!( diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index 98fea9e49..98a72cd6b 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -5,7 +5,7 @@ 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, + DeclaredObserver, MegaContext, MegaEvm, FORBIDDEN_CREATE_REVIVAL, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, @@ -19,13 +19,25 @@ use revm::{ }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; -use crate::common::{call, context}; +use crate::common::{account_state_gas, body_history, call, context, 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 +155,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 +209,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(), @@ -268,7 +280,7 @@ fn test_a_creation_its_frame_budget_stops_is_refused_its_revival() { |records: u64| mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(records); let plain = |records: u64| { MegaEvm::new(context(db()).with_tx_runtime_limits(under(records))) - .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())) .unwrap() }; let created = |outcome: &mega_evm::MegaTransactionOutcome| { @@ -290,7 +302,7 @@ fn test_a_creation_its_frame_budget_stops_is_refused_its_revival() { let limits = under(3); let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }); - match evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)) { + match evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())) { Err(EVMError::Custom(message)) => { assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") } @@ -306,7 +318,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. @@ -319,7 +331,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. @@ -331,10 +343,10 @@ 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"); @@ -400,7 +412,7 @@ 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) }; @@ -506,10 +518,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); @@ -573,7 +585,7 @@ impl Inspector, EthInterpreter> for Writer { 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. diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 89f2ee517..7bec7ef3a 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -324,7 +324,12 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { let unpaused = region(BytecodeBuilder::default()).stop().build(); let (metered, _) = run(db(unpaused), false); - assert!(metered.gas.state > 0 && metered.gas.gas_used > 0, "unpaused, the region pays"); + 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` diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index ead43d3db..5d7ae65ae 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -39,9 +39,12 @@ use revm::{ Inspector, }; -use crate::salt::{ - create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, - SaltEnvs, CALLER, CONTRACT, EMPTY, +use crate::{ + common::state_is_free, + salt::{ + create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, + value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, + }, }; /// A contract `CONTRACT` calls. @@ -214,7 +217,11 @@ fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { 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!(kept.gas.state > 0, "kept, the fresh slot costs state gas"); + 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()); @@ -415,6 +422,10 @@ fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { /// together stops the caller whose call ran, and not the one whose call was answered. #[test] fn test_an_answered_call_holds_nothing_against_the_state_gas_limit() { + // A slot and an account that add no state gas have no state-gas limit to cross. + if state_is_free() { + return; + } let caller = || value_call(EMPTY).append(POP).sstore(U256::from(1), U256::from(1)).stop().build(); let slot = entry(GasId::sstore_set_state_gas()); diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 468610bc3..cee332aec 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -134,16 +134,21 @@ 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. 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. +/// 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 = 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 - zeros.gas_used, - 1_024 * 12, + non_zeros.gas_used, + bill(16), "only the intrinsic token rate, four against sixteen, tells them apart", ); } @@ -214,9 +219,11 @@ fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { Ok(EMPTY_CALL + address_bytes + key_bytes * keys), "{keys} keys: the floor counts every byte at the same rate" ); + // The floor binds only where a history byte is cheap: the bill is the larger of the two. + let floor = EMPTY_CALL + address_bytes + key_bytes * keys; assert_eq!( gas_used(funded(), with_access_list(keys as usize)), - Ok(EMPTY_CALL + 2_400 + 1_900 * keys + body_history(20 + 32 * keys)), + Ok((EMPTY_CALL + 2_400 + 1_900 * keys + body_history(20 + 32 * keys)).max(floor)), "{keys} keys: the intrinsic charge and the entry's bytes of history" ); } @@ -259,9 +266,11 @@ fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { let db = funded().account_balance(CALLER, U256::from(10u128.pow(24))); 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) + (EMPTY_CALL + 4 * LARGEST_CALLDATA + body_history(LARGEST_CALLDATA)).max(floor) ); let expected = format!( diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index 6d5dae83e..b7bb5603f 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -23,7 +23,7 @@ use revm::{ context::TxEnv, }; -use crate::common::context; +use crate::common::{context, slot_state_gas, state_is_free}; const CALLER: Address = address!("0000000000000000000000000000000000b00000"); /// A contract the program calls, which writes a slot of its own. @@ -123,7 +123,7 @@ 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!(free.gas.state > 0); + assert!(free.gas.state >= 3 * slot_state_gas(), "at least its three slots' state gas"); for (name, limits) in limits() { let outcome = execute(db(), tx(), limits); @@ -200,6 +200,11 @@ fn test_a_deposit_and_a_user_call_to_a_system_contract_are_held_to_the_limits() ), ]; for (name, tx, limits, kind) in cases { + // A transaction that adds no state gas, where a state byte is free, crosses no state-gas + // limit. + if kind == LimitKind::StateGrowth && state_is_free() { + continue; + } let outcome = execute(db(), tx, limits); let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}, {kind:?}: stopped")); assert!( diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 62d34a089..4a29fe5c4 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -9,7 +9,9 @@ use mega_evm::{ MegaLimitExceeded, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use crate::common::{call, context, runs_at_measurement_prices}; +use crate::common::{ + body_history, call, context, history, runs_at_measurement_prices, slot_state_gas, +}; const CALLER: Address = address!("0000000000000000000000000000000000600000"); const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); @@ -23,6 +25,12 @@ 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, @@ -79,7 +87,7 @@ fn test_outcome_reports_the_stop() { let outcome = execute( writer(), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + 40), - 1_000_000, + writer_gas(), ); assert!(!outcome.result.is_success()); assert_eq!( @@ -132,12 +140,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/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 86c64fc14..ae2f1e558 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -19,6 +19,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, @@ -35,7 +36,7 @@ use revm::{ context_interface::cfg::GasId, }; -use crate::common::{block, runs_at_measurement_prices}; +use crate::common::{block, runs_at_measurement_prices, state_is_free}; /// The sender of every probe. pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000c00000"); @@ -418,6 +419,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 +434,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 +466,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 = @@ -535,6 +553,10 @@ fn test_a_transaction_from_the_system_address_prices_at_the_minimum_bucket() { /// 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() { + // 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); @@ -679,6 +701,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 +735,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 +760,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() @@ -987,13 +1021,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..4f69695bc 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. @@ -215,6 +218,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. 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..d24bdf376 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -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::state_is_free, + 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, + }, }; /// 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()) @@ -413,6 +430,10 @@ fn test_the_refund_classes_side_by_side() { /// 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() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let bucket = slot_bucket(CONTRACT, U256::from(SLOT)); let envs = minimal_envs().with_bucket_capacity(bucket, capacity(8)); let code = BytecodeBuilder::default() @@ -438,8 +459,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 +487,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 +543,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 +558,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 +570,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 +588,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); @@ -607,6 +638,10 @@ 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); diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 80ede9f8d..856ba71b6 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -20,19 +20,33 @@ use revm::{ context::result::{ExecutionResult, HaltReason}, }; -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, the state gas inside it and the history gas the schedule does not -/// price. +/// 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 { @@ -47,7 +61,12 @@ fn spend(db: MemoryDatabase, tx: mega_evm::MegaTransaction) -> Spend { 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 } + 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`. @@ -66,7 +85,7 @@ 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)); + 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); } @@ -76,7 +95,7 @@ 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)); + let spent = spend(db, call(CALLER, CALLEE, U256::from(7), gas_limit())); assert_eq!(spent.schedule_gas(), 21_000); assert_eq!(spent.state, 0); } @@ -89,7 +108,7 @@ 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.schedule_gas(), 21_000 + ACCOUNT_STATE_GAS); } @@ -99,7 +118,7 @@ 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)); + let spent = spend(db, call(CALLER, CALLER, U256::from(7), gas_limit())); assert_eq!(spent.schedule_gas(), 12_000); assert_eq!(spent.state, 0); } @@ -113,7 +132,7 @@ 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.schedule_gas() - spent.state, 24_000, "the fixed part"); } @@ -121,6 +140,9 @@ fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_g /// 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; @@ -129,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.schedule_gas() - spent.state, - fixed + token * len + word * words, + spent.gas_used, + (charged + spent.state + spent.history).max(spent.floor), "{len} bytes of init code" ); } @@ -148,11 +171,11 @@ fn test_a_new_slot_draws_the_slot_state_gas() { 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)); + 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)); + let again = spend(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert_eq!(again.state, 0, "the slot already holds the value"); } @@ -163,8 +186,8 @@ fn test_deployed_code_draws_state_gas_by_the_byte() { 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)); + 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"); @@ -184,7 +207,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; @@ -209,7 +232,7 @@ 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)) + .transact_raw(create(CALLER, depositing_an_ef_byte(), gas_limit())) .expect("the transaction is valid") .result; @@ -242,7 +265,7 @@ 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"); } @@ -255,7 +278,7 @@ fn test_a_creation_depositing_no_code_pays_for_the_account_alone() { return; } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, create(CALLER, deploying(0), GAS_LIMIT)); + let spent = spend(db, create(CALLER, deploying(0), gas_limit())); assert_eq!(spent.state, ACCOUNT_STATE_GAS); } @@ -264,7 +287,7 @@ fn test_a_creation_depositing_no_code_pays_for_the_account_alone() { /// 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 } @@ -304,7 +327,7 @@ fn test_slotnum_pushes_the_blocks_slot_number() { 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)) + .transact_raw(call_with_data(CALLER, CALLEE, Bytes::new(), gas_limit())) .expect("the transaction is valid") .result; assert!(result.is_success(), "{name}: {result:?}"); diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index b410c7910..d3e8e8708 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -9,7 +9,9 @@ //! it happens: there are no frame budgets. //! //! The figures are read off the engine rather than written out: each case first runs without a -//! limit, and the state gas it reports is what the limit is set against. +//! limit, and the state gas it reports is what the limit is set against. Where a state byte costs +//! nothing, which only a measurement build arranges, no transaction adds state gas and the limit +//! has nothing to hold, so the cases that need a crossing return early. use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ @@ -27,7 +29,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{authorizing_call, call, context, create}; +use crate::common::{authorizing_call, call, context, create, state_is_free}; const CALLER: Address = address!("0000000000000000000000000000000000600000"); const A: Address = address!("0000000000000000000000000000000000600001"); @@ -183,6 +185,9 @@ fn sites(gas_limit: u64) -> Vec<(&'static str, MemoryDatabase, MegaTransaction)> /// the figure it reports. The stop keeps none of it, below and above the execution cap alike. #[test] fn test_every_site_is_held_to_the_limit_at_the_state_gas_it_reports() { + if state_is_free() { + return; + } for gas_limit in [BELOW_CAP, ABOVE_CAP] { for (name, db, tx) in sites(gas_limit) { let name = format!("{name}, gas limit {gas_limit}"); @@ -213,6 +218,9 @@ fn test_every_site_is_held_to_the_limit_at_the_state_gas_it_reports() { /// halts; the stop spends none of it. #[test] fn test_the_crossing_charge_is_where_the_transaction_stops() { + if state_is_free() { + return; + } let deployed = constructor_returning(32); let cases: [(&str, BytecodeBuilder); 5] = [ ("a fresh slot", write_slots(BytecodeBuilder::default(), 0, 1)), @@ -242,6 +250,9 @@ fn test_the_crossing_charge_is_where_the_transaction_stops() { /// the transaction's own or a nested one: the limit is held before `return_create` commits it. #[test] fn test_deployed_code_that_crosses_is_not_left_deployed() { + if state_is_free() { + return; + } let deployed = constructor_returning(32); let nested = funded() .account_code(A, then_create(BytecodeBuilder::default(), &deployed, false).stop().build()); @@ -348,6 +359,9 @@ fn then_create_with(builder: BytecodeBuilder, create2: bool, value: u64) -> Byte /// and the unit tests of the frame lifecycle pin it. #[test] fn test_a_frame_revm_refuses_is_not_held_for_its_upfront_charge() { + if state_is_free() { + return; + } let account = one_account(); let empty_init = Bytes::new(); let taken = |address: Address| funded().account_nonce(address, 1); @@ -428,6 +442,9 @@ impl Inspector, EthInterpreter> for CallsToEmpty { /// its records given back. #[test] fn test_a_frame_revm_decides_is_held_for_its_upfront_charge() { + if state_is_free() { + return; + } let account = one_account(); let body = mega_evm::history_gas(TX_BODY_SIZE).expect("a body has a price"); let cases: [(&str, BytecodeBuilder); 3] = [ @@ -465,6 +482,9 @@ fn test_a_frame_revm_decides_is_held_for_its_upfront_charge() { /// state-gas limit that charge would have crossed is not. #[test] fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { + if state_is_free() { + return; + } let account = one_account(); let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; let db = @@ -498,6 +518,9 @@ fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { /// of three slots is crossed in `C`, with the three slots as the figure. #[test] fn test_a_childs_crossing_latches_the_transaction() { + if state_is_free() { + return; + } let slot = one_slot(); let db = funded() .account_code( @@ -526,6 +549,9 @@ fn test_a_childs_crossing_latches_the_transaction() { /// transaction creates and a slot its frame writes cross a limit neither crosses alone. #[test] fn test_charges_before_the_first_frame_and_in_it_add_up() { + if state_is_free() { + return; + } let slot = one_slot(); let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); let tx = authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]); @@ -548,6 +574,9 @@ fn test_charges_before_the_first_frame_and_in_it_add_up() { /// carried and that frame's own record come back with the frame. #[test] fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { + if state_is_free() { + return; + } let delegation = |outcome: &MegaTransactionOutcome| { outcome.state[&AUTHORITY_1].info.code.as_ref().map(|code| code.original_bytes()) }; @@ -589,6 +618,9 @@ fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { /// deposit's mint and the state gas charged for the account. #[test] fn test_a_stopped_deposit_keeps_the_caller_it_created() { + if state_is_free() { + return; + } let fresh = address!("00000000000000000000000000000000006000ff"); let deposit = |code: Bytes| { let mut tx = call(fresh, A, U256::ZERO, BELOW_CAP); @@ -706,6 +738,9 @@ fn test_what_is_given_back_gives_its_room_back() { /// slots in minimal buckets but crosses on the second when the first is in the crowded one. #[test] fn test_a_crowded_bucket_reaches_the_limit_sooner() { + if state_is_free() { + return; + } use crate::salt::{crowded_slot, minimal_envs, salt_context}; let slot = one_slot(); @@ -780,6 +815,9 @@ fn account_and_delegation() -> (u64, u64) { /// 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); @@ -879,9 +917,13 @@ fn test_an_authorization_adds_state_only_when_it_applies() { fn test_a_crowded_authority_moves_the_state_ledger_alone() { use crate::salt::{crowded_account, minimal_envs, salt_context}; let (account, delegation) = account_and_delegation(); + // Room below the execution cap for the authority at the crowded price. + let gas_limit = BELOW_CAP + 100 * (account + delegation); let run = |envs| { + let mut tx = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + tx.0.base.gas_limit = gas_limit; MegaEvm::new(salt_context(funded().account_code(A, Bytes::from_static(&[STOP])), envs)) - .execute_transaction(authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)])) + .execute_transaction(tx) .unwrap() }; let minimal = run(minimal_envs()); @@ -899,6 +941,9 @@ fn test_a_crowded_authority_moves_the_state_ledger_alone() { /// 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)]); @@ -921,7 +966,10 @@ fn test_an_authority_the_transaction_cannot_pay_for_is_not_applied() { authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), "the authorization was taken back: {authority:?}" ); - assert!(run(crowded_account(minimal_envs(), AUTHORITY_1, 100), BELOW_CAP).result.is_success()); + // 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 @@ -951,6 +999,9 @@ fn test_an_authority_that_is_the_recipient_pays_for_one_account() { /// in that alone spend the same gas. #[test] fn test_authorities_crossing_any_limit_are_not_applied() { + if state_is_free() { + return; + } let (account, delegation) = account_and_delegation(); let both = [(Some(AUTHORITY_1), 0, 0), (Some(AUTHORITY_2), 0, 0)]; let fresh = || funded().account_code(A, Bytes::from_static(&[STOP])); @@ -1092,6 +1143,9 @@ fn test_a_destruction_grows_state_only_when_it_creates_its_beneficiary() { /// fourth `SSTORE`, and none of the four is kept. #[test] fn test_fresh_slots_fit_a_limit_of_their_state_gas_and_one_more_stops() { + if state_is_free() { + return; + } let slot = one_slot(); let run = |slots| { run_under( @@ -1118,6 +1172,9 @@ fn test_fresh_slots_fit_a_limit_of_their_state_gas_and_one_more_stops() { /// that crosses the state-gas and data-size limits at once is the state-gas limit's stop. #[test] fn test_a_slot_crossing_both_limits_reports_the_state_gas() { + if state_is_free() { + return; + } let slot = one_slot(); let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); let outcome = MegaEvm::new( diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index c8dcb1d80..2b7288254 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -52,7 +52,7 @@ use revm::{ }; use crate::{ - common::{call, call_with_data, create}, + common::{body_history, call, call_with_data, create, state_is_free}, detention::{context, work, Charges, BENEFICIARY}, withheld_gas::{priced, Runs, PRICED}, }; @@ -99,6 +99,12 @@ enum Limit { impl Limit { const ALL: [Self; 4] = [Self::DataSize, Self::KvUpdates, Self::StateGas, Self::Compute]; + /// Whether a transaction can cross this limit at the byte prices in effect: where a state byte + /// is free no transaction adds state gas, and the state-gas limit has nothing to hold. + fn crossable(self) -> bool { + !(self == Self::StateGas && state_is_free()) + } + const fn kind(self) -> LimitKind { match self { Self::DataSize => LimitKind::DataSize, @@ -364,7 +370,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { #[test] fn test_every_limit_stops_the_transaction_at_every_depth_and_tier() { let slot = one_slot(); - for limit in Limit::ALL { + for limit in Limit::ALL.into_iter().filter(|limit| limit.crossable()) { for crossing in [0, 3] { for gas_limit in TIERS { assert_cell(limit, crossing, gas_limit, slot); @@ -400,7 +406,7 @@ fn test_an_inspector_cannot_turn_a_stop_into_a_halt() { InstructionResult::PrecompileOOG, InstructionResult::InvalidFEOpcode, ]; - for limit in Limit::ALL { + for limit in Limit::ALL.into_iter().filter(|limit| limit.crossable()) { for crossing in [0, 3] { for gas_limit in TIERS { let (configured, _) = limits_of(limit, crossing, slot); @@ -542,7 +548,7 @@ fn test_a_revived_creation_reports_the_stop() { (Creation::NestedStart, [Limit::DataSize, Limit::KvUpdates, Limit::StateGas].as_slice()), ]; for (creation, limits) in cases { - for &limit in limits { + for &limit in limits.iter().filter(|limit| limit.crossable()) { for gas_limit in TIERS { let case = format!("{creation:?}, {limit:?}, gas limit {gas_limit}"); let configured = creation_limits(creation, limit, gas_limit); @@ -1217,7 +1223,11 @@ fn test_detained_gas_is_restored() { .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, "{}", detained.gas.gas_used); + assert!( + detained.gas.gas_used < 50_000 + body_history(0), + "what it ran and its body's history: {}", + detained.gas.gas_used + ); } /// A body over the transaction's data-size limit stops the transaction before its first frame: a @@ -1268,7 +1278,11 @@ fn test_data_limit_exceed_in_nested_call() { outcome.result ); assert_eq!(outcome.limit_exceeded, Some(stop)); - assert!(outcome.gas.gas_used < 200_000, "the stop burns nothing: {}", outcome.gas.gas_used); + assert!( + outcome.gas.gas_used < 200_000 + body_history(0), + "the stop burns nothing: {}", + outcome.gas.gas_used + ); } /// A value transfer to a contract that writes a slot, under a limit one byte above the body: the @@ -1723,6 +1737,11 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { #[test] fn test_an_answer_three_calls_down_stops_the_transaction_at_either_tier() { for answered in [Answered::PastTheAllowance, Answered::Precompile, Answered::NewAccount] { + // A new account that adds no state gas, where a state byte is free, crosses no state-gas + // limit. + if answered == Answered::NewAccount && state_is_free() { + continue; + } for gas_limit in TIERS { assert_answered_cell(answered, gas_limit); } diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 90fcc1b03..69eb97f23 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, runs_at_measurement_prices}; +use crate::common::{call, context, history, runs_at_measurement_prices, slot_state_gas}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const A: Address = address!("00000000000000000000000000000000000000A0"); @@ -575,7 +575,7 @@ 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, mega_evm::TX_BODY_SIZE + 180); @@ -593,7 +593,13 @@ fn test_outcome_reports_history_gas() { execute_with(chain(), EvmTxRuntimeLimits::no_limits(), Charger::default(), GAS_LIMIT); assert!(kept.result.is_success()); assert_eq!(kept.gas.history, plain.gas.history + 700); - assert!(plain.gas.history > body_history(), "the chain's own writes are history too"); + 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); diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 2694bc5c7..f607f0e45 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -53,7 +53,7 @@ use revm::{ Journal, }; -use crate::common::runs_at_measurement_prices; +use crate::common::{runs_at_measurement_prices, state_is_free}; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CONTRACT: Address = address!("0x5000000000000000000000000000000000000001"); @@ -237,6 +237,10 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { /// reservoir did not hold. #[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() { + return; + } if !runs_at_measurement_prices() { assert_eq!(SLOT_STATE_GAS, slot()); assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); @@ -277,7 +281,9 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { /// leaves all of it. #[test] fn test_reservoir_remaining_is_what_the_writes_left() { - for writes in [0, 1, 5] { + // 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)), @@ -396,8 +402,12 @@ fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { ); assert!(mega.result.is_success(), "{:?}", mega.result); assert_eq!(mega.result.gas().reservoir_remaining(), 0); - assert!(mega.result.gas().state_gas_spent_final() > 0, "the change wrote fresh slots"); - assert_eq!(mega.result.gas().state_gas_spent_final() % slot(), 0, "at m = 1"); + // 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); } diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index d52c2b640..f640c9054 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -50,7 +50,7 @@ use revm::{ Database, Inspector, }; -use crate::common::context; +use crate::common::{account_state_gas, context}; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); /// The contract a nested site's transaction calls: it calls [`ACTOR`] and returns what that @@ -295,7 +295,9 @@ fn deposit(kind: TxKind, mint: u128, value: u64) -> MegaTransaction { caller: DEPOSITOR, kind, value: U256::from(value), - gas_limit: 1_000_000, + // 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() })); @@ -708,10 +710,16 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { })) }; // 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. + // 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(); - assert!(150_000 / 64 < records, "the actor keeps less than the records cost"); - let gas_limit = 21_000 + history_gas(transaction_body_bytes(&tx(0))).unwrap() + 150_000; + 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(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); assert!(refused.result.is_success(), "{:?}", refused.result); @@ -1009,7 +1017,11 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { let body = transaction_body_bytes(&tx); let free = execute(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); assert!(free.result.is_halt(), "{kind:?}: {:?}", free.result); - assert_eq!(free.result.tx_gas_used(), 1_000_000, "{kind:?}: the gas limit is spent"); + 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; diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index f30aad0c1..d332fecff 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -20,10 +20,13 @@ use mega_evm::{ }; use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult, state::Bytecode}; -use crate::detention::{ - 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, +use crate::{ + common::body_history, + detention::{ + 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, + }, }; /// A second contract, never the beneficiary. @@ -144,8 +147,12 @@ fn test_a_read_within_the_cap_bills_what_ran() { ); assert!(run.outcome.result.is_success(), "{opcode:#04x}"); assert!(run.limit.is_some(), "{opcode:#04x}"); + // What it ran is well under 100,000; the body's history comes on top. let used = run.outcome.result.gas().tx_gas_used(); - assert!(used < 100_000, "{opcode:#04x}: {used}, not the gas it was given"); + assert!( + used < 100_000 + body_history(0), + "{opcode:#04x}: {used}, not the gas it was given" + ); } let code = BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).stop().build(); let run = execute( @@ -153,7 +160,7 @@ fn test_a_read_within_the_cap_bills_what_ran() { tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success()); - assert!(run.outcome.result.gas().tx_gas_used() < 100_000); + assert!(run.outcome.result.gas().tx_gas_used() < 100_000 + body_history(0)); } } @@ -188,7 +195,7 @@ fn test_a_read_two_frames_down_caps_every_caller() { tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success()); - assert!(run.outcome.result.gas().tx_gas_used() < 200_000); + assert!(run.outcome.result.gas().tx_gas_used() < 200_000 + body_history(0)); } } diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index f4cc338cd..2f02e6814 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -30,7 +30,7 @@ use mega_evm::{ }, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, - MegaContext, MegaEvm, MegaHaltReason, VolatileDataAccess, + MegaContext, MegaEvm, MegaHaltReason, VolatileDataAccess, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::*, @@ -49,10 +49,13 @@ use revm::{ Database, Inspector, }; -use crate::detention::{ - assert_stopped, burn, context, execute, fresh_write_spill, intrinsic, memory_cost, op, run_on, - spin, stop_data, tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, - CONTRACT, FRESH_WRITE, TIERS, +use crate::{ + common::history, + detention::{ + assert_stopped, burn, context, execute, fresh_write_spill, intrinsic, memory_cost, op, + run_on, spin, stop_data, tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, + CAP, CHILD, CONTRACT, FRESH_WRITE, TIERS, + }, }; /// A contract between the transaction's frame and `CHILD`. @@ -211,7 +214,9 @@ fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { .stop() .build(); let bound = u32::try_from(3 * FRESH_WRITE + fresh_write_spill()).expect("a bound in a push"); - for (gas_limit, status) in [(BELOW, 0), (ABOVE, 1)] { + // 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)); @@ -287,7 +292,12 @@ fn test_a_creation_that_cannot_pay_its_deposit_halts_as_without_the_read() { 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); - assert!(gas_limit > 2 * CAP, "the transaction holds more than the cap: {gas_limit}"); + // 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) @@ -341,8 +351,10 @@ fn test_a_callees_out_of_gas_is_caught_as_without_the_read() { /// 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 400,000, 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. Above the +/// 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] @@ -370,13 +382,23 @@ 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); for gas_limit in TIERS { for (name, callee) in &cases { let records = name.starts_with("a value call"); - if records && gas_limit == ABOVE { + if records && (gas_limit == ABOVE || middle_gas < 100_000) { continue; } - let (to, gas) = if records { (MIDDLE, Some(400_000)) } else { (CHILD, None) }; + 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)); @@ -389,12 +411,13 @@ fn test_what_a_halting_callee_burns_is_not_compute() { 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 400,000; the rest of the regular ledger is compute, and - // it leaves the limit less than the 63/64 `MIDDLE` forwarded, so counting that + // `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) - 400_000; + let compute = plain.outcome.gas.regular - intrinsic(gas_limit) - middle_gas; let margin = detained.limit.unwrap() - compute; - assert!(margin < 150_000, "{name}: {margin} short of the limit"); + let forwarded = (middle_gas - 40_000) * 63 / 64; + assert!(margin < forwarded, "{name}: {margin} short of the limit"); } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index d39dcaa63..1b217110f 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -31,15 +31,18 @@ use revm::{ 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 { @@ -90,7 +93,7 @@ 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, @@ -105,7 +108,7 @@ 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, @@ -120,7 +123,7 @@ 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, @@ -136,7 +139,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, gas_limit())); assert!(result.result.is_success(), "the outer call succeeds although the child halts"); assert_eq!(usage, body_only()); } @@ -161,7 +164,7 @@ 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, gas_limit())); assert!(result.result.is_success()); assert_eq!( usage, @@ -187,7 +190,7 @@ fn reverting_creations(n: usize) -> Bytes { #[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)); + 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"); } @@ -197,7 +200,7 @@ fn test_reverted_nested_create_keeps_the_creator_nonce_record() { #[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)); } @@ -214,7 +217,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, gas_limit())); assert!(result.result.is_success()); assert_eq!(usage, body_only()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); @@ -226,8 +229,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) } @@ -272,7 +275,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 }; @@ -316,7 +319,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}"); } @@ -343,7 +346,7 @@ 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); } @@ -362,7 +365,7 @@ fn test_log_counts_its_bytes() { .build(); let (result, usage) = run( MemoryDatabase::default().account_code(CALLEE, code), - call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + call(CALLER, CALLEE, U256::ZERO, gas_limit()), ); assert!(result.result.is_success()); assert_eq!(result.result.logs().len(), 1); @@ -387,7 +390,7 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { 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}"); } @@ -398,12 +401,12 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { 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, 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, with_extra(body_only(), 1)); } @@ -467,7 +470,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)); @@ -488,7 +491,7 @@ 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, body_only(), "a failed opcode's write is not counted"); @@ -499,7 +502,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"); @@ -539,7 +542,7 @@ fn authorizing_call( caller: CALLER, kind: alloy_primitives::TxKind::Call(to), value: U256::from(value), - gas_limit: GAS_LIMIT, + gas_limit: gas_limit(), gas_priority_fee: Some(0), authorization_list, ..Default::default() @@ -637,7 +640,7 @@ 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!( @@ -669,7 +672,7 @@ 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"); @@ -682,7 +685,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"); @@ -706,7 +709,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"); @@ -778,7 +781,10 @@ fn one_short_of_the_runtime_phase() -> u64 { // 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) = (0u64, 1_000_000u64); + // 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; @@ -850,7 +856,7 @@ 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!( @@ -880,7 +886,7 @@ 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, @@ -909,7 +915,7 @@ 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!( @@ -929,7 +935,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(), gas_limit()); tx.0.base.value = U256::from(5); tx }; @@ -956,7 +962,7 @@ 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, with_extra(records(1), TRANSFER_LOG_SIZE), "CONTRACT2 and its log only"); @@ -998,7 +1004,7 @@ 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!( @@ -1071,7 +1077,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, gas_limit()); let calling = |target, value| { append_value_call(BytecodeBuilder::default(), target, value) .append(POP) @@ -1142,7 +1148,7 @@ 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, gas_limit()), 0, 1, ), @@ -1171,7 +1177,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]), gas_limit()), 0, 0, ), @@ -1180,7 +1186,7 @@ fn paired_corpus() -> Vec { ..case( "a value transaction", funded(), - call(CALLER, CONTRACT, U256::from(1), GAS_LIMIT), + call(CALLER, CONTRACT, U256::from(1), gas_limit()), 0, 1, ) @@ -1188,22 +1194,22 @@ 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), gas_limit()), 0, 0, ), - case("a creation transaction", funded(), create(CALLER, Bytes::new(), GAS_LIMIT), 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), gas_limit()), 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), gas_limit()), 0, 0, ), @@ -1219,7 +1225,7 @@ fn paired_corpus() -> Vec { CALLER, ORACLE_CONTRACT_ADDRESS, send_hint(b"a hint the transaction pays data size for"), - GAS_LIMIT, + gas_limit(), ), 0, 0, @@ -1234,7 +1240,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), gas_limit()); tx.0.base.gas_price = 10; tx }, @@ -1326,7 +1332,7 @@ 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, gas_limit()); match inspector { Some(inspector) => { let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); From 7800c003646d5ea664f39cbb7844363593cad4fc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:42:15 -0400 Subject: [PATCH 359/458] feat(evm): resolve the chain's limits in the EVM factory --- AGENTS.md | 3 +- crates/mega-evm/README.md | 5 +- crates/mega-evm/src/block/factory.rs | 5 + crates/mega-evm/src/evm/factory.rs | 257 +++++++++++++++++++++++-- crates/mega-evm/src/evm/mod.rs | 6 +- crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/tests/block/factory.rs | 29 ++- 7 files changed, 284 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2eb4d4f84..86f64deca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,7 +182,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 four 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/protocol_limits.rs`). The executor checks the limits again (`validate()`) and refuses a block under limits the check refuses (`InvalidProtocolLimits`, internal), whatever the schedule's type: a node's own schedule type attaches its params without `with_params`, and `validate_schedule` runs only when the node calls it. - Tests that run blocks without holding them to a limit attach `ProtocolLimits::loosest()`, the loosest limits a chain may carry (every limit unlimited, detention's caps at `MAX_TX_COMPUTE_GAS - 1`); `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`, builds a schedule carrying a value no chain may carry, to test what refuses it; a standalone EVM (an RPC call, a tool, the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. + Tests that run blocks without holding them to a limit attach `ProtocolLimits::loosest()`, the loosest limits a chain may carry (every limit unlimited, detention's caps at `MAX_TX_COMPUTE_GAS - 1`); `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`, builds a schedule carrying a value no chain may carry, to test what refuses it. + An EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) runs under the limits block execution would hold its block to without being told: the factory given the chain's schedule (`with_schedule`) resolves them at the block's timestamp, and without one, or where the schedule carries no valid limits there, installs `ProtocolLimits::DEFAULT`'s; `MegaEvmFactory::with_tx_runtime_limits` is the explicit opt-out for equivalence and tests, and a `MegaContext` built by hand (the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index fadba8e8d..3980ff178 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -186,13 +186,14 @@ 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 block's limits on the EVM; given the same schedule, the EVM factory runs the EVMs it creates outside block execution — an RPC call, a simulation — under the chain's limits too: ```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 evm_factory = MegaEvmFactory::new().with_schedule(chain_spec.clone()); +let factory = MegaBlockExecutorFactory::new(receipt_builder, chain_spec, evm_factory); let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_block_root, extra_data, BlockLimits::no_limits()); let mut executor = factory.create_executor(evm, ctx); diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index 7b452d100..7db565920 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -28,6 +28,11 @@ 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 the limits `spec` carries, whatever the EVM they run on + /// was created with. A node gives the EVM factory the same schedule + /// ([`MegaEvmFactory::with_schedule`]), so the EVMs it creates outside block execution run + /// under the same limits. pub const fn new(receipt_builder: R, spec: Spec, evm_factory: EvmF) -> Self { Self { receipt_builder, spec, evm_factory } } diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 74106362f..be9d62faa 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -1,6 +1,11 @@ //! Factory of Satin EVMs for alloy-evm consumers. +#[cfg(not(feature = "std"))] +use alloc as std; +use std::sync::Arc; + use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; +use alloy_primitives::BlockTimestamp; use core::fmt; use op_revm::OpHaltReason; use revm::{ @@ -10,19 +15,64 @@ use revm::{ }; use crate::{ - DynPrecompilesBuilder, EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, - MegaTransaction, MegaTransactionError, + DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, + HardforkParams, MegaContext, MegaEvm, MegaHardforks, MegaSpecId, MegaTransaction, + MegaTransactionError, ProtocolLimits, }; +/// Reads the limits a chain's schedule carries at a block's timestamp. +type ProtocolLimitsResolver = Arc Option + Send + Sync>; + +/// Where the EVMs a factory creates take their per-transaction limits from. +#[derive(Clone, Default)] +enum TxRuntimeLimitsSource { + /// The protocol's defaults, [`ProtocolLimits::DEFAULT`]: the factory holds no schedule. + #[default] + ProtocolDefault, + /// The chain's, read from its schedule at the block's timestamp. + Schedule(ProtocolLimitsResolver), + /// The caller's, whatever the block. + Fixed(EvmTxRuntimeLimits), +} + +impl fmt::Debug for TxRuntimeLimitsSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ProtocolDefault => f.write_str("ProtocolDefault"), + Self::Schedule(_) => f.write_str("Schedule"), + Self::Fixed(limits) => f.debug_tuple("Fixed").field(limits).finish(), + } + } +} + /// 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, and the optional builder of the dynamic precompiles a -/// node adds on top of the Satin set. +/// environments of the block it executes, the optional builder of the dynamic precompiles a node +/// adds on top of the Satin set, and where the EVMs take their per-transaction limits from. +/// +/// # The limits an EVM runs under +/// +/// An EVM the factory creates runs under the limits block execution would hold its block's +/// transactions to, so an RPC call, a simulation or a tool built on the factory stops what the +/// chain stops without having to be told: +/// +/// - given the chain's schedule ([`with_schedule`](Self::with_schedule)), the limits the schedule +/// carries at the block's timestamp ([`MegaHardforks::protocol_limits`]); +/// - without one, the protocol's defaults ([`ProtocolLimits::DEFAULT`]), which is what block +/// execution runs on a chain that keeps them; +/// - where the schedule carries no limits at the timestamp, or limits their own check refuses +/// ([`HardforkParams::validate`]), the protocol's defaults too: block execution refuses such a +/// block, and an EVM cannot refuse to be built. +/// +/// [`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 chain's limits on the EVM whatever it was created with. #[derive(Clone, Default)] pub struct MegaEvmFactory { external_env_factory: ExtEnvFactory, dyn_precompiles_builder: Option, + tx_runtime_limits: TxRuntimeLimitsSource, } impl fmt::Debug for MegaEvmFactory { @@ -30,14 +80,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 the protocol's + /// default 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: TxRuntimeLimitsSource::ProtocolDefault, + } } } @@ -55,6 +111,7 @@ impl MegaEvmFactory { MegaEvmFactory { external_env_factory, dyn_precompiles_builder: self.dyn_precompiles_builder, + tx_runtime_limits: self.tx_runtime_limits, } } @@ -64,6 +121,44 @@ impl MegaEvmFactory { self.dyn_precompiles_builder = Some(builder); self } + + /// Gives the factory the chain's schedule: every EVM it creates runs under the limits the + /// schedule carries at the block's timestamp, as block execution holds that block's + /// transactions to them. It replaces limits set with + /// [`with_tx_runtime_limits`](Self::with_tx_runtime_limits). + /// + /// A node hands it the schedule it hands its block executor factory, so the EVMs it builds + /// outside block execution — an RPC call, a simulation — stop what the chain stops. + pub fn with_schedule(mut self, spec: Spec) -> Self + where + Spec: MegaHardforks + Send + Sync + 'static, + { + self.tx_runtime_limits = TxRuntimeLimitsSource::Schedule(Arc::new(move |timestamp| { + spec.protocol_limits(timestamp) + })); + self + } + + /// Runs every EVM the factory creates under exactly `limits`, whatever the block and whatever + /// the chain's schedule says: the explicit opt-out, for the execution-spec gate's equivalence + /// mode ([`EvmTxRuntimeLimits::no_limits`]) and for tests. It replaces a schedule given with + /// [`with_schedule`](Self::with_schedule). + pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.tx_runtime_limits = TxRuntimeLimitsSource::Fixed(limits); + self + } + + /// The limits an EVM the factory creates for a block at `timestamp` runs under. + pub fn tx_runtime_limits(&self, timestamp: BlockTimestamp) -> EvmTxRuntimeLimits { + let protocol_default = ProtocolLimits::DEFAULT.tx_runtime_limits; + match &self.tx_runtime_limits { + TxRuntimeLimitsSource::ProtocolDefault => protocol_default, + TxRuntimeLimitsSource::Schedule(resolve) => resolve(timestamp) + .filter(|limits| limits.validate().is_ok()) + .map_or(protocol_default, |limits| limits.tx_runtime_limits), + TxRuntimeLimitsSource::Fixed(limits) => *limits, + } + } } impl alloy_evm::EvmFactory for MegaEvmFactory { @@ -78,7 +173,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 the factory resolves for the block's timestamp + /// ([`tx_runtime_limits`](MegaEvmFactory::tx_runtime_limits)). /// /// The configuration fields the spec fixes are set from the spec (see /// [`MegaContext::with_cfg`]). @@ -90,10 +187,12 @@ 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 limits = self.tx_runtime_limits(block_env.timestamp.saturating_to()); let spec = cfg_env.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)), @@ -121,7 +220,7 @@ mod tests { use crate::{ satin_precompiles, test_utils::{op_transaction, MemoryDatabase}, - ExternalEnvs, SaltEnv, TestExternalEnvs, + ExternalEnvs, MegaHardforkConfig, SaltEnv, TestExternalEnvs, }; use alloy_evm::{precompiles::DynPrecompile, Evm, EvmFactory}; use alloy_op_evm::OpTx; @@ -204,24 +303,152 @@ 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. + /// The factory prints its external environment factory, whether a precompile builder is + /// installed and where its EVMs take their limits from. A closure has no `Debug`, so the + /// builder and the schedule are reported by name 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: ProtocolDefault }" ); 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: ProtocolDefault }" ); + + let on_schedule = with_builder.with_schedule(MegaHardforkConfig::default()); + assert!(format!("{on_schedule:?}").ends_with("tx_runtime_limits: Schedule }")); + let fixed = on_schedule.with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + assert!(format!("{fixed:?}").contains("tx_runtime_limits: Fixed(EvmTxRuntimeLimits {")); + } + + /// A timestamp from which a chain's schedule activates Satin in these tests. + const SATIN_AT: u64 = 1_000; + + /// A chain that activates Satin at [`SATIN_AT`] and holds its transactions to `limits`, + /// attached unchecked so a test may hand it limits no chain may carry. + fn chain(limits: ProtocolLimits) -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with(crate::MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(SATIN_AT)) + .with_params_unchecked(limits) + } + + /// A chain's own limits, which no default carries. + fn chain_limits() -> ProtocolLimits { + ProtocolLimits::DEFAULT.with_tx_runtime_limits( + ProtocolLimits::DEFAULT + .tx_runtime_limits + .with_tx_data_size_limit(crate::TX_BODY_SIZE + 40) + .with_tx_kv_update_limit(7), + ) + } + + /// An EVM the factory creates for a block at `timestamp`. + fn evm_at(factory: &MegaEvmFactory, timestamp: u64) -> MegaEvm { + let block_env = BlockEnv { timestamp: U256::from(timestamp), ..evm_env().block_env }; + factory + .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env: evm_env().cfg_env, block_env }) + } + + /// Without a schedule the factory's EVMs run under the protocol's default limits, which is + /// what block execution runs on a chain that keeps them — not a bare context's, which leave + /// the data size unlimited. + #[test] + fn test_without_a_schedule_an_evm_runs_under_the_protocols_defaults() { + let evm = evm_at(&MegaEvmFactory::new(), SATIN_AT); + assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); + assert_ne!(*evm.tx_runtime_limits(), EvmTxRuntimeLimits::default()); + } + + /// Given the chain's schedule, the factory's EVMs run under the limits it carries at the + /// block's timestamp; where it carries none, or limits their own check refuses — both of which + /// block execution refuses — under the protocol's defaults. + #[test] + fn test_an_evm_runs_under_the_limits_the_schedule_carries_at_its_block() { + let factory = MegaEvmFactory::new().with_schedule(chain(chain_limits())); + assert_eq!( + *evm_at(&factory, SATIN_AT).tx_runtime_limits(), + chain_limits().tx_runtime_limits + ); + assert_eq!(factory.tx_runtime_limits(SATIN_AT + 1), chain_limits().tx_runtime_limits); + assert_eq!( + factory.tx_runtime_limits(SATIN_AT - 1), + ProtocolLimits::DEFAULT.tx_runtime_limits, + "before Satin the schedule carries no limits" + ); + + let refused = MegaEvmFactory::new().with_schedule(chain(ProtocolLimits::no_limits())); + assert_eq!( + *evm_at(&refused, SATIN_AT).tx_runtime_limits(), + ProtocolLimits::DEFAULT.tx_runtime_limits, + "limits their own check refuses run no EVM" + ); + } + + /// The opt-out: limits given to the factory are what every EVM runs under, whatever the + /// schedule says; the last of the two settings made is the one that holds. + #[test] + fn test_limits_given_to_the_factory_replace_the_schedules() { + let factory = MegaEvmFactory::new() + .with_schedule(chain(chain_limits())) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + for timestamp in [SATIN_AT - 1, SATIN_AT] { + assert_eq!( + *evm_at(&factory, timestamp).tx_runtime_limits(), + EvmTxRuntimeLimits::no_limits() + ); + } + + let factory = factory.with_schedule(chain(chain_limits())); + assert_eq!( + *evm_at(&factory, SATIN_AT).tx_runtime_limits(), + chain_limits().tx_runtime_limits + ); + } + + /// And the EVM enforces them, as block execution does: a call that keeps two writes where the + /// chain allows one is stopped on an EVM from a factory given the schedule, and keeps both on + /// one from a factory without it. + #[test] + fn test_an_evm_from_the_factory_stops_what_the_chain_stops() { + use crate::{test_utils::BytecodeBuilder, LimitCheck, LimitKind}; + const WRITER: Address = address!("0x0000000000000000000000000000000000077700"); + 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 block_env = BlockEnv { timestamp: U256::from(SATIN_AT), ..evm_env().block_env }; + let mut evm = factory.create_evm(db, EvmEnv { cfg_env: evm_env().cfg_env, block_env }); + evm.execute_transaction(call(WRITER)).expect("the call is valid") + }; + + let stopped = run(&MegaEvmFactory::new().with_schedule(chain(chain_limits()))); + 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 diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 400e1e8e9..f4a8769ce 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -209,8 +209,10 @@ impl MegaEvm { /// /// Block execution installs the chain's limits this way before every transaction /// ([`ProtocolLimits`](crate::ProtocolLimits)), so a block's transaction runs under them - /// whatever the caller configured on the EVM. Outside block execution — an RPC call, a tool, - /// a test — this is how the caller chooses the limits a transaction runs under. + /// whatever the caller configured on the EVM. An EVM from + /// [`MegaEvmFactory`](crate::MegaEvmFactory) already runs under the limits the factory + /// resolved for its block; outside block execution — an RPC call, a tool, a test — this is how + /// a caller chooses others. #[must_use] pub fn with_tx_runtime_limits(mut self, limits: crate::EvmTxRuntimeLimits) -> Self { self.set_tx_runtime_limits(limits); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 4a11dd651..52095ea9c 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -260,7 +260,9 @@ pub struct LimitUsage { /// /// Every value here changes a transaction's result, so in block execution they are the chain's: /// the per-transaction half of [`ProtocolLimits`](crate::ProtocolLimits), which the block executor -/// installs before every transaction. Set on a standalone EVM, they are its caller's choice. +/// installs before every transaction. [`MegaEvmFactory`](crate::MegaEvmFactory) resolves the same +/// for an EVM it creates outside block execution; set on a standalone EVM, they are its caller's +/// choice. /// /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index feb4e2bf5..7e241753b 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -48,9 +48,10 @@ fn factory() -> common::TestFactory { fn test_trait_path_applies_the_chains_runtime_limits() { let mut state = common::state(); let factory = factory(); - // Built without any caller-side limits: the case a caller that forgot them produces. + // Built by an EVM factory that was not given the chain's schedule: the case a caller that + // forgot it produces, whose EVM runs under the protocol's defaults, not the chain's. let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); + assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); let executor = factory.create_executor(evm, common::unlimited_ctx()); @@ -138,9 +139,10 @@ fn test_trait_path_replaces_limits_the_caller_applied() { #[test] fn test_direct_construction_applies_the_chains_runtime_limits() { let mut state = common::state(); - // Built without any caller-side limits: the case a caller that forgot them produces. + // Built by an EVM factory that was not given the chain's schedule: the case a caller that + // forgot it produces, whose EVM runs under the protocol's defaults, not the chain's. let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); + assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); let executor = MegaBlockExecutor::new( evm, @@ -207,3 +209,22 @@ fn test_direct_construction_stops_a_transaction_over_the_chains_data_size_limit( other => panic!("expected a revert-class stop, got {other:?}"), } } + +/// A node gives its EVM factory the schedule it gives its block executor factory: an EVM the +/// factory creates, for a block or for an RPC call, then runs under the chain's limits before any +/// executor installs them, and the executor installs the same. +#[test] +fn test_an_evm_factory_on_the_chains_schedule_creates_evms_under_its_limits() { + let spec = common::chain_spec_with(limits()); + let factory = mega_evm::MegaBlockExecutorFactory::new( + OpAlloyReceiptBuilder::default(), + spec.clone(), + MegaEvmFactory::new().with_schedule(spec), + ); + let mut state = common::state(); + 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 executor = factory.create_executor(evm, common::unlimited_ctx()); + assert_eq!(*executor.evm().tx_runtime_limits(), limits().tx_runtime_limits); +} From 232bcbd3641a1969c1efd8b13f6eb17b7e4621f1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:43:21 -0400 Subject: [PATCH 360/458] docs: note what the limits leave to the node and the report --- crates/mega-evm/src/block/hardfork.rs | 4 +++- crates/mega-evm/src/block/limit.rs | 3 +++ crates/mega-state-test/src/mode.rs | 4 +++- docs/spec/upgrades/satin.md | 1 + 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 4e8fdfccb..dc977015e 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -133,7 +133,9 @@ pub trait MegaHardforks: OpHardforks { /// active there carries, or `None` when no `MegaETH` fork is active there or the fork carries /// none. /// - /// This is where block execution reads them; a later fork that changes a limit answers here. + /// This is where block execution reads them; a later fork that changes a limit answers here, + /// with a params type of its own, since a params type belongs to one fork + /// ([`HardforkParams::FORK`]). fn protocol_limits(&self, timestamp: BlockTimestamp) -> Option { match self.hardfork(timestamp)? { MegaHardfork::Satin => self.fork_params::().copied(), diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 0e167c05b..44726c7af 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -372,6 +372,9 @@ impl BlockLimits { /// These limits held within `protocol`: each of the block's four budgets 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 one. 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_execution_gas_limit: self diff --git a/crates/mega-state-test/src/mode.rs b/crates/mega-state-test/src/mode.rs index 2734db365..7861c65ec 100644 --- a/crates/mega-state-test/src/mode.rs +++ b/crates/mega-state-test/src/mode.rs @@ -33,7 +33,9 @@ pub enum Mode { 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. + /// The fixture's chain id and blob limit are kept. Its runtime limits are a bare context's — + /// gas detention at the spec's caps and nothing else — not the protocol's defaults, so the + /// transaction data-size limit is not held. Satin, } diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 8035cabfc..881dbe99e 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -726,6 +726,7 @@ Four of those counts can be limited: 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. A deposit counts towards the block's encoded size and not towards its data-availability size; the block gas limit holds it 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 From 05b5d366bfd0f260a053241c5e97d93d90b90415 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:45:59 -0400 Subject: [PATCH 361/458] refactor(limit): keep the state gas held outside a frame on its lane The state-gas limit kept what the transaction holds outside each frame in a stack of its own, pushed and popped beside the lanes and aligned with them by a debug assertion, and took the caller's state gas through a handoff field set at the child's frame init. It is now a field of the lane it was pushed with, computed from the caller's lane and what the caller held when it suspended, which the caller's lane records where the frame suspends. --- AGENTS.md | 6 +- crates/mega-evm/src/evm/execution.rs | 28 ++--- crates/mega-evm/src/limit/frame_limit.rs | 100 +++++++++++++++++- crates/mega-evm/src/limit/limit.rs | 23 ++-- crates/mega-evm/src/limit/mod.rs | 5 +- crates/mega-evm/src/limit/state_gas.rs | 129 ----------------------- 6 files changed, 121 insertions(+), 170 deletions(-) delete mode 100644 crates/mega-evm/src/limit/state_gas.rs diff --git a/AGENTS.md b/AGENTS.md index b396ba3bc..22fd9b36d 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 | `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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, 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`) | — | | `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`, the Satin params type carrying the limits every node shares (the per-transaction runtime limits and the four block budgets, today's values as its default), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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 latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; what the state-gas limit counts, a frame's state gas held outside it (`state_gas.rs`); `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default; in block execution the chain's, from `ProtocolLimits`) | — | +| `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, the log and code bytes of the history byte count and the state gas held outside each frame, which is what the state-gas limit counts (`frame_limit.rs`), staging, the latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default; in block execution the chain's, from `ProtocolLimits`) | — | | `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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 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 | @@ -169,7 +169,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 data size is checked before the records wherever both cross. At the production data-size caps a transaction or a block keeps at most 327,680 records, so the KV limits bind only below that; both are unlimited unless the chain sets them, and `ProtocolLimits::block_kv_update_limit` is the block's, a packing budget like its data size. - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. - `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/state_gas.rs`). + `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/frame_limit.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. @@ -352,7 +352,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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. 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 state-gas limit's entry of what is held outside each frame is pushed and popped with the lane. + What the state-gas limit holds outside each frame is on its lane: a lane pushed holds what its caller's holds plus what its caller held when it suspended on it. - **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. The rewrite takes every result, whatever produced it — revm, an interceptor, or an inspector that turned it into a success or a halt (`AdditionalLimit::apply_latch`): no frame runs an instruction under the latch, so a halt there can only be an inspector's. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index b15d23d04..9db7ad054 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -446,9 +446,9 @@ impl EvmTr for MegaEvm( } /// 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. +/// for the child's start to add to the transaction's, and its state gas on its lane for the +/// child's to hold outside it; 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 @@ -782,6 +783,7 @@ fn after_frame_run( match next { Ok(ItemOrResult::Item(_)) => { ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); + ctx.additional_limit.on_frame_suspend(frame.interpreter.gas.state_gas_spent()); } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); @@ -987,19 +989,11 @@ impl MegaEvm { /// start ([`answer_before_building`]), with the empty lane that stands in for it. It comes /// before the keyless dispatch, so the dispatch never sees a latched transaction; on the /// inspected path it comes after the inspector's `frame_start`. - /// - /// Before it, the state gas the caller holds is noted: it is held outside the frame it starts. - /// The caller is the frame on top of the stack, suspended on this frame's input; the - /// transaction's own frame has none, and starts on what was charged before it. #[inline] fn answered_before_building( &mut self, frame_init: &FrameInit, ) -> Result, ContextDbError>> { - if self.inner.frame_stack.index().is_some() { - let held = self.inner.frame_stack.get().interpreter.gas.state_gas_spent(); - self.inner.ctx.additional_limit.note_caller_state_gas(held); - } let answer = answer_before_building(&mut self.inner.ctx, frame_init)?; if answer.is_some() { self.inner.ctx.additional_limit.push_empty_frame(); @@ -1024,9 +1018,9 @@ impl MegaEvm { /// frame that later fails gives the charge back too, but by then it has started, and a crossing /// inside a frame that later fails is a crossing. /// -/// The frame's own entry is on top by now, and holds what its caller held, the charge included; -/// the frame itself holds nothing yet. Every other charge was held where it was made, so only the -/// upfront one can cross here. +/// The frame's own lane is on top by now, and holds outside it what its caller held, the charge +/// included; the frame itself holds nothing yet. Every other charge was held where it was made, so +/// only the upfront one can cross here. fn hold_upfront_state_gas( ctx: &mut MegaContext, answer: Option<&mut FrameResult>, @@ -1498,13 +1492,13 @@ mod tests { } /// A context under a state-gas limit of 99, with the transaction's own frame on the call stack - /// holding 100 — the upfront charge of the frame it starts — and the entry of that frame + /// holding 100 — the upfront charge of the frame it starts — and the lane of that frame /// pushed. fn starting_a_frame_charged_100() -> MegaContext { let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(99)); let _ = ctx.additional_limit.on_frame_init(&call(CALLER, CALLER, 0, false), 0); - ctx.additional_limit.note_caller_state_gas(100); + ctx.additional_limit.on_frame_suspend(100); ctx.additional_limit.push_empty_frame(); ctx } diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 7fbcb806a..d7545c673 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -10,6 +10,19 @@ //! 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. //! +//! The lanes also carry what the state-gas limit counts: the state gas the transaction holds. +//! EIP-8037 charges state gas for exactly the state a transaction adds — a fresh slot, a new +//! account, the bytes of deployed code, a delegation — at the state's own price, scaled by the +//! SALT bucket it lands in. So the state a transaction grows is the state gas it spends, and a +//! limit on that gas is the limit on its growth; nothing counts new accounts and slots beside it. +//! revm keeps state gas on each frame's own gas, net of what the frame refilled, and merges a +//! frame's into its caller's when the frame succeeds; a frame that fails rolls its own back. What +//! the transaction holds at any point is therefore what it was charged before its first frame, +//! plus what every frame on the call stack holds. The first part is fixed once the first frame +//! starts, and every frame below the running one is suspended, so each frame's share of the rest +//! is fixed while it runs: each lane keeps what the transaction holds outside its frame, and the +//! running frame adds what it holds itself ([`FrameLimitTracker::state_gas_held`]). +//! //! Every operation is O(1): the totals are cached and kept in step with each change. #[cfg(not(feature = "std"))] @@ -61,6 +74,13 @@ pub(crate) struct Lane { /// 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, + /// The state gas the transaction holds outside the frame: what was charged before the first + /// frame, and what each frame below it held when the frame above it started. Set when the + /// lane is pushed ([`FrameLimitTracker::push`]). + pub(crate) state_gas_outside: i64, + /// The state gas the frame held when it last suspended on a child, which that child's lane + /// holds outside it beyond this lane's own. + pub(crate) state_gas_at_suspension: i64, } impl Lane { @@ -85,6 +105,8 @@ impl Lane { budget, stipend_remaining: 0, log_and_code_bytes: 0, + state_gas_outside: 0, + state_gas_at_suspension: 0, } } @@ -156,6 +178,9 @@ pub(crate) struct FrameLimitTracker { total_refund: LimitUsage, /// The log and code bytes the outermost frame kept, plus every lane's. log_and_code_bytes: u64, + /// The state gas the transaction was charged before its first frame, which the first frame's + /// lane holds outside it. + state_gas_before_frames: i64, } impl FrameLimitTracker { @@ -167,6 +192,7 @@ impl FrameLimitTracker { self.total_used = LimitUsage::ZERO; self.total_refund = LimitUsage::ZERO; self.log_and_code_bytes = 0; + self.state_gas_before_frames = 0; } /// The number of lanes, which is the number of frames on the call stack. @@ -214,13 +240,41 @@ impl FrameLimitTracker { drawn } - /// Pushes the lane of a frame that starts. - pub(crate) fn push(&mut self, lane: Lane) { + /// Pushes the lane of a frame that starts. It holds outside its frame what its caller's lane + /// holds outside the caller, plus what the caller held when it suspended on this frame; the + /// transaction's own frame holds what was charged before any frame. + pub(crate) fn push(&mut self, mut lane: Lane) { + lane.state_gas_outside = match self.lanes.last() { + Some(caller) => caller.state_gas_outside.saturating_add(caller.state_gas_at_suspension), + None => self.state_gas_before_frames, + }; self.total_used = self.total_used.saturating_add(lane.used); self.total_refund = self.total_refund.saturating_add(lane.refund); self.lanes.push(lane); } + /// Records the state gas the transaction was charged before its first frame. + pub(crate) const fn set_state_gas_before_frames(&mut self, spent: i64) { + self.state_gas_before_frames = spent; + } + + /// Records the state gas `held` by the running frame as it suspends on a child. + pub(crate) fn set_state_gas_at_suspension(&mut self, held: i64) { + if let Some(lane) = self.lanes.last_mut() { + lane.state_gas_at_suspension = held; + } + } + + /// The state gas the transaction holds while the running frame holds `running`; outside any + /// frame, `running` is all of it. + /// + /// A frame can hold less than nothing — it refilled a slot a caller of its filled — but never + /// by more than its callers hold, so the sum is never below zero. + pub(crate) fn state_gas_held(&self, running: i64) -> u64 { + let outside = self.lanes.last().map_or(0, |lane| lane.state_gas_outside); + u64::try_from(outside.saturating_add(running)).unwrap_or_default() + } + /// 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() { @@ -281,7 +335,10 @@ impl FrameLimitTracker { /// all the same: the lane follows the checkpoint, not the result. pub(crate) fn discard_running_lane(&mut self) { let Some(lane) = self.pop(false) else { return }; - self.lanes.push(Lane::empty(lane.history_refund(false))); + self.lanes.push(Lane { + state_gas_outside: lane.state_gas_outside, + ..Lane::empty(lane.history_refund(false)) + }); } /// Takes the record of the running frame's own account back from its lane, where a child @@ -516,6 +573,43 @@ mod tests { assert_eq!(t.log_and_code_bytes(), 0); } + /// Each lane holds outside its frame the state gas charged before the first frame and what + /// each caller held when it suspended on the frame above it. A frame that returned leaves its + /// caller where it was, a caller that suspends again hands its next child what it holds then, + /// and a lane discarded before its frame returns keeps what its frame held outside it. + #[test] + fn test_each_lane_holds_what_its_callers_held_when_it_started() { + let mut t = FrameLimitTracker::default(); + assert_eq!(t.state_gas_held(7), 7, "outside any frame, what is charged is all of it"); + + t.set_state_gas_before_frames(100); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + assert_eq!(t.state_gas_held(0), 100, "the first frame starts on what was charged before"); + assert_eq!(t.state_gas_held(20), 120); + + t.set_state_gas_at_suspension(20); + t.push(Lane::new(None, false, UNLIMITED, 0)); + assert_eq!(t.state_gas_held(5), 125, "a child counts its caller's twenty"); + t.set_state_gas_at_suspension(5); + t.push(Lane::empty(0)); + assert_eq!(t.state_gas_held(-5), 120, "a grandchild that refilled its caller's fill"); + assert_eq!(t.depth(), 3); + + t.discard_running_lane(); + assert_eq!(t.state_gas_held(0), 125, "the discarded lane keeps what it holds outside"); + t.pop(false); + t.pop(true); + assert_eq!(t.state_gas_held(30), 130, "the first frame, holding its child's merged gas"); + + t.set_state_gas_at_suspension(30); + t.push(Lane::new(None, false, UNLIMITED, 0)); + assert_eq!(t.state_gas_held(0), 130, "the next child starts on what its caller holds now"); + + t.reset(); + t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + assert_eq!(t.state_gas_held(0), 0, "a reset forgets what was charged before the frames"); + } + /// A refund larger than the usage clamps the net at zero. #[test] fn test_net_usage_saturates_when_refund_exceeds_used() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 5aa46359b..0fe549854 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -10,7 +10,6 @@ use revm::{ use super::{ frame_limit::{FrameLimitTracker, Lane}, record::{HistoryBytes, RecordEffect, StagedRecord}, - state_gas::StateGasMeter, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, }; @@ -97,8 +96,6 @@ pub struct AdditionalLimit { history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, - /// The state gas the transaction holds outside the running frame, for the state-gas limit. - state_gas: StateGasMeter, /// 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, @@ -138,7 +135,6 @@ impl AdditionalLimit { self.pending_start_refused = None; self.history_gas_spent = 0; self.history_bytes = 0; - self.state_gas.reset(); self.transfer_logs = false; } @@ -532,8 +528,7 @@ impl AdditionalLimit { /// what a failed frame rolled back, is out of what it holds, so a write taken back gives its /// room back. pub(crate) fn check_state_gas(&mut self, running: i64) -> LimitCheck { - debug_assert_eq!(self.state_gas.depth(), self.tracker.depth(), "one entry per lane"); - let used = self.state_gas.held(running); + let used = self.tracker.state_gas_held(running); let limit = self.limits.tx_state_gas_limit; if used > limit { return self.latch(LimitKind::StateGrowth, limit, used); @@ -545,14 +540,15 @@ impl AdditionalLimit { /// holds it to the limit. A crossing latches the transaction, and its first frame is answered /// with the stop before it is built. pub(crate) fn on_state_gas_before_frames(&mut self, spent: i64) { - self.state_gas.set_before_frames(spent); + self.tracker.set_state_gas_before_frames(spent); self.check_state_gas(spent); } - /// Records the state gas `held` by the frame that is starting the next one, which the next - /// frame counts as held outside it. - pub(crate) const fn note_caller_state_gas(&mut self, held: i64) { - self.state_gas.note_caller(held); + /// Records the state gas `held` by the running frame as it suspends on a child, which the + /// child's lane counts as held outside it. + #[inline] + pub(crate) fn on_frame_suspend(&mut self, held: i64) { + self.tracker.set_state_gas_at_suspension(held); } /* Frame lanes */ @@ -670,7 +666,6 @@ impl AdditionalLimit { } fn push_lane(&mut self, input: &FrameInput, depth: usize) { - self.state_gas.push(); 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 @@ -724,7 +719,7 @@ impl AdditionalLimit { } } // No frame starts from an empty input: revm's own frame init is `unreachable!` on - // one. The state-gas entry pushed above is the lane's, one per lane. + // one. FrameInput::Empty => unreachable!( "a frame input always names a call or a creation, as revm's frame init asserts" ), @@ -844,7 +839,6 @@ impl AdditionalLimit { /// 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.state_gas.push(); let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); } @@ -884,7 +878,6 @@ impl AdditionalLimit { 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)); - self.state_gas.pop(); let unchecked = lane.is_some_and(|lane| self.tracker.hands_unchecked(&lane, success)); self.resume_stop = if unchecked { let check = self.check(); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 864b57d00..344511bcd 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -87,8 +87,8 @@ //! grows is the state gas it spends: [`EvmTxRuntimeLimits::tx_state_gas_limit`] holds it, and //! nothing counts new accounts and slots beside it. What is held is net — what a frame refilled //! and what a failed frame rolled back is out of it — and is the state gas charged before the -//! first frame plus what every frame on the call stack holds (the `state_gas` module). The limit is -//! per transaction, with no frame budget: a crossing anywhere stops the transaction, reported as +//! first frame plus what every frame on the call stack holds (the `frame_limit` module). The limit +//! is per transaction, with no frame budget: a crossing anywhere stops the transaction, reported as //! [`LimitKind::StateGrowth`] with the limit in gas. //! //! The limit holds each charge where it is made, once it is made, so a charge the frame cannot @@ -160,7 +160,6 @@ mod frame_limit; #[allow(clippy::module_inception)] mod limit; mod record; -mod state_gas; pub use limit::AdditionalLimit; pub(crate) use limit::FrameStartRecords; diff --git a/crates/mega-evm/src/limit/state_gas.rs b/crates/mega-evm/src/limit/state_gas.rs deleted file mode 100644 index c452c7979..000000000 --- a/crates/mega-evm/src/limit/state_gas.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! What the state-gas limit counts: the state gas the running transaction holds. -//! -//! EIP-8037 charges state gas for exactly the state a transaction adds — a fresh storage slot, a -//! new account, the bytes of deployed code, a delegation — at the state's own price, scaled by the -//! SALT bucket it lands in. So the state a transaction grows is the state gas it spends, and a -//! limit on that gas is the limit on its growth; nothing counts new accounts and slots beside it. -//! -//! revm keeps state gas on each frame's own gas, net of what the frame refilled, and merges a -//! frame's into its caller's when the frame succeeds; a frame that fails rolls its own back. What -//! the transaction holds at any point is therefore what it was charged before its first frame, -//! plus what every frame on the call stack holds. The first part is fixed once the first frame -//! starts, and every frame below the running one is suspended, so each frame's share of the rest -//! is fixed while it runs: [`StateGasMeter`] keeps, for each frame, what the transaction holds -//! outside it, and the running frame adds what it holds itself. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -/// The state gas the running transaction holds outside the running frame. -/// -/// One entry per frame on the call stack, pushed and popped with the frame's lane. -#[derive(Clone, Debug, Default)] -pub(crate) struct StateGasMeter { - /// The state gas charged before the first frame: the account a deposit-like transaction - /// creates for its caller, the applied EIP-7702 authorities, and the recipient or created - /// account EIP-2780 charges the first frame for. - before_frames: i64, - /// For each frame on the call stack, the state gas the transaction holds outside it: what was - /// charged before the first frame, and what each frame below it held when the frame above it - /// started. - outside: Vec, - /// The state gas the frame starting the next frame holds, until that frame's entry is pushed. - caller: i64, -} - -impl StateGasMeter { - /// Clears the meter for a new transaction, keeping its allocation. - pub(crate) fn reset(&mut self) { - self.before_frames = 0; - self.outside.clear(); - self.caller = 0; - } - - /// Records the state gas charged before the first frame. - pub(crate) const fn set_before_frames(&mut self, spent: i64) { - self.before_frames = spent; - } - - /// Records the state gas the frame starting the next frame holds. - pub(crate) const fn note_caller(&mut self, held: i64) { - self.caller = held; - } - - /// Pushes the entry of a frame about to start: what the transaction holds outside it is what - /// it holds outside its caller plus what its caller holds, or, for the first frame, what was - /// charged before any frame. - /// - /// A frame no caller noted anything for — one an inspector answered before it reached frame - /// init — never runs, so what it is given is never read. - pub(crate) fn push(&mut self) { - let caller = core::mem::take(&mut self.caller); - let outside = match self.outside.last() { - Some(outside) => outside.saturating_add(caller), - None => self.before_frames, - }; - self.outside.push(outside); - } - - /// Pops the entry of the frame that returned. - pub(crate) fn pop(&mut self) { - self.outside.pop(); - } - - /// The state gas the transaction holds while the running frame holds `running`; outside any - /// frame, `running` is all of it. - /// - /// A frame can hold less than nothing — it refilled a slot a caller of its filled — but never - /// by more than its callers hold, so the sum is never below zero. - pub(crate) fn held(&self, running: i64) -> u64 { - let outside = self.outside.last().copied().unwrap_or_default(); - u64::try_from(outside.saturating_add(running)).unwrap_or_default() - } - - /// The number of entries, which is the number of frames on the call stack. - pub(crate) fn depth(&self) -> usize { - self.outside.len() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Each frame is given what the transaction holds outside it: the state gas charged before - /// the first frame, and what each caller held when it started the next frame. A frame that - /// returned leaves its caller where it was. - #[test] - fn test_each_frame_holds_what_its_callers_held_when_it_started() { - let mut meter = StateGasMeter::default(); - assert_eq!(meter.held(7), 7, "outside any frame, what is charged is all of it"); - - meter.set_before_frames(100); - meter.push(); - assert_eq!(meter.held(0), 100, "the first frame starts on what was charged before it"); - assert_eq!(meter.held(20), 120); - - meter.note_caller(20); - meter.push(); - assert_eq!(meter.held(5), 125, "a child counts its caller's twenty"); - meter.note_caller(5); - meter.push(); - assert_eq!(meter.held(-5), 120, "a grandchild that refilled its caller's fill"); - assert_eq!(meter.depth(), 3); - - meter.pop(); - meter.pop(); - assert_eq!(meter.held(30), 130, "the first frame, holding its child's merged gas"); - - // A frame nobody noted a caller for starts on what its caller's caller left it. - meter.push(); - assert_eq!(meter.held(0), 100); - - meter.reset(); - assert_eq!(meter.depth(), 0); - meter.push(); - assert_eq!(meter.held(0), 0, "a reset forgets what was charged before the frames"); - } -} From 6c2eeb47b3fff3877b1ac00d1f8d214e28d00682 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 02:48:59 -0400 Subject: [PATCH 362/458] test(system): hold the system contract tests at any byte price Keyless deployments are signed with gas above the state their start adds, the tier below the execution cap is left out where a mebibyte body cannot pay for itself there, and what a call spent beside its body is what is compared with the overhead. A figure the EIP-7623 floor can bind is read as what the transaction paid. A case whose scenario is state gas to cross or scale returns early where a state byte costs nothing. --- crates/mega-evm/tests/system/common.rs | 41 +++++++++++ .../mega-evm/tests/system/keyless/charges.rs | 7 +- .../tests/system/keyless/detention.rs | 6 +- .../tests/system/keyless/differential.rs | 44 ++++++------ .../mega-evm/tests/system/keyless/dispatch.rs | 16 +++-- .../mega-evm/tests/system/keyless/limits.rs | 23 ++++++- crates/mega-evm/tests/system/keyless/mod.rs | 14 ++++ .../tests/system/keyless/precedence.rs | 61 ++++++++++------- crates/mega-evm/tests/system/keyless/rules.rs | 68 +++++++++++++------ .../tests/system/remaining_compute_gas.rs | 17 +++-- crates/mega-evm/tests/system/system_tx.rs | 27 ++++++-- 11 files changed, 242 insertions(+), 82 deletions(-) diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs index 1e734d540..2b35e2c07 100644 --- a/crates/mega-evm/tests/system/common.rs +++ b/crates/mega-evm/tests/system/common.rs @@ -134,3 +134,44 @@ 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; the notice +/// goes to stderr once, since the harness keeps a passing test's output to itself. +pub(crate) fn state_is_free() -> bool { + use std::io::Write; + + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the tests that need state gas, because 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. +pub(crate) fn history(bytes: u64) -> u64 { + mega_evm::history_gas(bytes).expect("the bytes have a price") +} + +/// 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. +pub(crate) fn body_history(calldata_len: u64) -> u64 { + history(mega_evm::tx_body_history_bytes(calldata_len, 0, 0, 0)) +} diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 7920816cb..bcb331e23 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -9,6 +9,7 @@ use mega_evm::{constants::MAX_INITCODE_SIZE, system::keyless::KEYLESS_DEPLOY_OVE 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; @@ -162,7 +163,7 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { 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 [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_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); @@ -250,6 +251,10 @@ fn test_the_upfront_charges_scale_with_their_buckets() { /// 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 { diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index 73435d997..c4c9d005e 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -37,7 +37,7 @@ use revm::{ }; use super::*; -use crate::common::{call_tx, context, CALLER as RELAYER}; +use crate::common::{call_tx, context, state_is_free, CALLER as RELAYER}; /// The block beneficiary of the cases where nobody in the transaction is the beneficiary. const BENEFICIARY: Address = address!("0x0000000000000000000000000000000000beef02"); @@ -626,6 +626,10 @@ fn test_a_failed_deployment_keeps_the_reads_its_creation_made() { /// room for stops the transaction on state growth, not on compute. #[test] fn test_a_deployment_another_limit_stops_keeps_the_reads_its_creation_made() { + // A deployment that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let prefix = BytecodeBuilder::default().append_many([TIMESTAMP, POP]).sstore(U256::ZERO, U256::ONE); let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index e540e95f5..88b424e7c 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -47,7 +47,7 @@ use revm::{ }; use super::{detention::reads_then_burns, *}; -use crate::common::{context, CALLER as RELAYER}; +use crate::common::{context, state_is_free, CALLER as RELAYER}; /// Where the record is written, when set. const RECORD_PATH: &str = "MEGA_KEYLESS_RECORD"; @@ -544,15 +544,19 @@ fn scenarios() -> Vec { let signer = if nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; let used = signer + entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()); - all.push( - Scenario::deploying( - format!("limit: state gas, nonce {nonce}"), - db(&slot), - &slot, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(used - 1)), - ); + // A deployment that adds no state gas, where a state byte is free, crosses no + // state-gas limit. + if !state_is_free() { + all.push( + Scenario::deploying( + format!("limit: state gas, nonce {nonce}"), + db(&slot), + &slot, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(used - 1)), + ); + } all.push( Scenario::deploying( format!("limit: compute, nonce {nonce}"), @@ -610,15 +614,17 @@ fn scenarios() -> Vec { .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 40)), ); let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); - all.push( - Scenario::deploying( - format!("limit: upfront state gas, nonce {nonce}"), - db(&small), - &small, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1)), - ); + if !state_is_free() { + all.push( + Scenario::deploying( + format!("limit: upfront state gas, nonce {nonce}"), + db(&small), + &small, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1)), + ); + } } all.push( Scenario::deploying("limit: a latched body", system_db(), &small, gas_limit) diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index 0d9b47f5e..e877fe363 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -21,8 +21,8 @@ use revm::{ 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. @@ -104,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", ); } @@ -129,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(), ); @@ -142,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; diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 69fbc2a5e..d1a7c7837 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -34,7 +34,7 @@ use super::{ detention::{crossing_left, reads_then_burns}, *, }; -use crate::common::context; +use crate::common::{context, state_is_free}; /// Init code that logs `len` bytes of data and deploys a one-byte runtime. fn logging(len: u64) -> Bytes { @@ -295,6 +295,10 @@ fn test_a_deployment_crossing_its_kv_budget_reverts_alone() { /// transaction before the init code runs. #[test] fn test_the_upfront_state_gas_is_held_to_the_state_gas_limit() { + // A deployment that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let deployment = Deployment::new(deploying(&runtime(1))); let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); for gas_limit in GAS_LIMITS { @@ -311,6 +315,10 @@ fn test_the_upfront_state_gas_is_held_to_the_state_gas_limit() { /// A slot the constructor fills counts on top of the upfront state gas. #[test] fn test_a_deployment_crossing_the_state_gas_limit_stops_it() { + // A deployment that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let deployment = Deployment::new(filling_a_slot()); let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); let limit = upfront + entry(GasId::sstore_set_state_gas()) - 1; @@ -329,6 +337,10 @@ fn test_a_deployment_crossing_the_state_gas_limit_stops_it() { /// code is written. #[test] fn test_the_deposited_code_is_held_to_the_state_gas_limit() { + // A deployment that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let deployment = Deployment::new(deploying(&runtime(5))); let limit = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()) + @@ -630,7 +642,10 @@ fn plain_and_rewritten( /// transaction reports. #[test] fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { - for crossing in Crossing::ALL { + // A deployment that adds no state gas, where a state byte is free, crosses no state-gas limit. + let free = state_is_free(); + for crossing in Crossing::ALL.into_iter().filter(|c| !(free && matches!(c, Crossing::StateGas))) + { let deployment = Deployment::new(crossing.init_code()); for signer_nonce in [0, 1] { let (limits, expected) = crossing.limits(&deployment, signer_nonce); @@ -732,6 +747,10 @@ fn crowded_run( /// limit that holds the rest deploys it. #[test] fn test_the_upfront_charges_are_held_once_at_their_bucket_prices() { + // A deployment that adds no state gas has no state-gas limit to cross. + if state_is_free() { + return; + } let deployment = Deployment::new(deploying(&runtime(1))); assert_ne!(bucket(deployment.signer), bucket(deployment.address)); let created = entry(GasId::create_state_gas()) + satin_gas_params().code_deposit_state_gas(1); diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index ddbf775d2..1e854e3bc 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -41,6 +41,20 @@ 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; diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index d2ea3e3d1..2f32bbbbf 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -19,9 +19,14 @@ use mega_evm::{ }; use super::*; +use crate::common::state_is_free; -/// The gas limit the matrix's deployments are signed with. -const SIGNED: u64 = 500_000; +/// 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)] @@ -79,10 +84,10 @@ fn leaving(data: &Bytes, left: u64) -> u64 { left } -/// `GasLimitTooLow` for a deployment signed with [`SIGNED`], with `provided`. -const fn too_low(provided: u64) -> Answer { +/// `GasLimitTooLow` for a deployment signed with [`signed_gas`], with `provided`. +fn too_low(provided: u64) -> Answer { Answer::Refused(KeylessDeployError::GasLimitTooLow { - tx_gas_limit: SIGNED, + tx_gas_limit: signed_gas(), provided_gas_limit: provided, }) } @@ -91,17 +96,17 @@ const fn too_low(provided: u64) -> Answer { /// 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, 0); - let carrying = signed(SIGNED, 1); + 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 - 1), + data: plain.call_data(signed_gas() - 1), gas_limit, - answer: too_low(SIGNED - 1), + answer: too_low(signed_gas() - 1), }, Case { rules: "the signer's nonce, and an occupied address", @@ -177,9 +182,9 @@ fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { #[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()); - let plain = signed(SIGNED, 0); - let carrying = signed(SIGNED, 1); - let carrying_two = signed(SIGNED, 2); + 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); @@ -202,23 +207,23 @@ fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_bala 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 - 1), - answer: too_low(SIGNED - 1), + 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 - 1), - answer: too_low(SIGNED - 1), + 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 - 1), - answer: too_low(SIGNED - 1), + gas_limit: leaving(&data(&carrying_two), signed_gas() - 1), + answer: too_low(signed_gas() - 1), }, Case { rules: @@ -226,7 +231,7 @@ fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_bala signed gas limit", db: occupied(funded(system_db(), &plain), &plain), data: data(&plain), - gas_limit: leaving(&data(&plain), SIGNED), + gas_limit: leaving(&data(&plain), signed_gas()), answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), }, Case { @@ -241,7 +246,7 @@ fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_bala take below the signed gas limit", db: system_db(), data: data(&carrying), - gas_limit: leaving(&data(&carrying), new_account + SIGNED), + gas_limit: leaving(&data(&carrying), new_account + signed_gas()), answer: Answer::Refused(KeylessDeployError::InsufficientBalance), }, Case { @@ -252,7 +257,15 @@ fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_bala answer: Answer::Refused(KeylessDeployError::InsufficientBalance), }, ]; - cases.into_iter().for_each(Case::check); + // 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 @@ -299,7 +312,7 @@ fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { /// `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, 0); + 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()) + @@ -317,8 +330,8 @@ fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { 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), - answer: too_low(SIGNED - charges), + gas_limit: leaving(&data(&plain), signed_gas()), + answer: too_low(signed_gas() - charges), }, ]; cases.into_iter().for_each(Case::check); diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 11520a871..7323dd554 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -15,7 +15,7 @@ use alloy_primitives::{address, keccak256, Signature}; use mega_evm::{ active_satin_prices, alloy_consensus::TxEip1559, - constants::{MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, + constants::MAX_INITCODE_SIZE, system::keyless::{ tests::{ CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, @@ -39,6 +39,7 @@ use revm::{ }; 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 { @@ -191,6 +192,13 @@ fn gas_limit_forwarding(deployment: &Deployment, init_len: usize, forward: u64) 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() @@ -236,10 +244,15 @@ fn test_a_forward_at_the_signed_gas_limit_deploys() { /// 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() { - let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + // 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(), 500_000 + new_account / 2); + 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"); @@ -247,8 +260,8 @@ fn test_the_signers_account_can_take_the_forward_below_the_signed_gas_limit() { assert_eq!( refusal(&empty), KeylessDeployError::GasLimitTooLow { - tx_gas_limit: 500_000, - provided_gas_limit: 500_000 + new_account / 2 - new_account, + tx_gas_limit: signed, + provided_gas_limit: signed + new_account / 2 - new_account, }, ); assert_nothing_written(&empty, &deployment, 0); @@ -384,7 +397,7 @@ 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 [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + 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), @@ -403,7 +416,7 @@ fn test_init_code_over_the_limit_is_refused() { #[test] fn test_init_code_at_the_limit_is_admitted() { let deployment = Deployment::new(vec![0; MAX_INITCODE_SIZE].into()); - for gas_limit in [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + 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 { .. }), @@ -1026,6 +1039,10 @@ fn test_a_call_below_the_overhead_reads_nothing() { /// 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(); @@ -1047,9 +1064,14 @@ fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { /// `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() { - let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + // 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(), 500_000); + 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, _] = @@ -1065,17 +1087,21 @@ fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { /// 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, 500_000, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let refused = submit( - system_db(), - &deployment.tx, - LARGE_OVERRIDE, - gas_limit_forwarding(&deployment, 3, 500_000), - ); - assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); - assert_eq!(nonce(&refused, deployment.signer), 0); - assert_eq!(refused.gas.state, 0); + 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); @@ -1158,6 +1184,10 @@ fn assert_db_error( /// 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] { diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index 2e6b11f0c..cbd768b03 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -24,7 +24,7 @@ use revm::{ Inspector, }; -use crate::common::{system_db, CALLER}; +use crate::common::{body_history, system_db, CALLER}; const CONTRACT: Address = address!("0x0000000000000000000000000000000000300001"); const CONTRACT2: Address = address!("0x0000000000000000000000000000000000300002"); @@ -139,10 +139,17 @@ fn test_direct_tx_remaining_compute_gas() { ) .unwrap(); if gas_limit < TX_GAS_LIMIT_CAP { - assert_eq!(answer, gas_limit - outcome.result.tx_gas_used(), "below the 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!(outcome.gas.history > 0, "the body's history came out of the reservoir"); + assert_eq!( + outcome.gas.history, + body_history(SELECTOR.len() as u64), + "the body's history came out of the reservoir", + ); } } } @@ -198,7 +205,7 @@ fn test_remaining_compute_gas_exact_value_matches_tracker() { outcome.result.output().unwrap(), ) .unwrap(); - assert_eq!(answer, 1_000_000 - outcome.result.tx_gas_used()); + 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 @@ -297,7 +304,7 @@ fn test_a_detained_transactions_own_call_hears_the_cap() { outcome.result.output().unwrap(), ) .unwrap(); - assert_eq!(answer, 10_000_000 - outcome.result.tx_gas_used()); + 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 diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index c84cc39a0..2d7366931 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -25,7 +25,9 @@ use revm::{ DatabaseCommit, }; -use crate::common::{block, context, system_db, CALLER, GAS_LIMIT}; +use crate::common::{ + account_state_gas, block, body_history, context, state_is_free, system_db, CALLER, GAS_LIMIT, +}; /// The chain the tests run on. const CHAIN_ID: u64 = 4326; @@ -263,7 +265,7 @@ fn test_another_shape_from_the_system_address_is_an_ordinary_transaction() { assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); assert!(!evm.ctx().is_system_originated(), "{shape}"); assert!(outcome.state[&MEGA_SYSTEM_ADDRESS].info.balance < U256::from(FUNDS), "{shape}"); - assert!(outcome.gas.history > 0, "{shape} pays history"); + assert!(outcome.gas.history >= body_history(0), "{shape} pays history"); } } @@ -557,7 +559,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))); @@ -587,7 +589,11 @@ fn test_a_deposit_with_an_existing_caller_pays_nothing_extra() { 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}"); + assert_eq!( + fresh, + existing + account_state_gas(), + "{fresh} is not one account above {existing}" + ); } /// A deposit whose recipient is its own caller pays for that one account once: by the time the @@ -629,6 +635,10 @@ fn test_a_deposit_that_creates_two_accounts_pays_for_both() { /// as a transaction that runs out in its runtime phase is. #[test] fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { + // An account that costs nothing is one any deposit can pay for. + if state_is_free() { + return; + } 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; @@ -646,6 +656,10 @@ fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { /// out-of-gas halt, and the halt is not a data-size stop. #[test] fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_halts() { + // An account that costs nothing is one any deposit can pay for. + if state_is_free() { + return; + } let sender = address!("0x00000000000000000000000000000000000f0008"); let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); tx.0.base.gas_limit = 30_000; @@ -758,8 +772,9 @@ 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", ); } From 22c9fa23049c4cc8fdc81f139b9db3a748dd69be Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:04:15 -0400 Subject: [PATCH 363/458] fix(evm): hold the first frame's upfront state gas once revm has decided the frame The account EIP-2780 charges the transaction's own frame for was held to the state-gas limit before revm built or answered that frame, so a first frame revm answers with a failure - a value transfer to a precompile that fails, whose account charge comes back - was stopped for an account nobody adds. Before the first frame only what stands whatever it does is held now; the first frame's charge is held after revm decided it, as every frame's upfront charge is. A success answer of the transaction's own frame that the stop rewrites has its journal taken back to where its start began, since no caller's revert follows it. A frame start's records are then held before its upfront state gas, as at every other frame start. --- AGENTS.md | 2 +- crates/mega-evm/src/evm/execution.rs | 83 ++++++--- crates/mega-evm/src/evm/inspector.rs | 2 +- crates/mega-evm/src/limit/limit.rs | 13 +- crates/mega-evm/src/limit/mod.rs | 13 +- crates/mega-evm/tests/satin/common.rs | 11 ++ .../mega-evm/tests/satin/state_gas_limit.rs | 157 +++++++++++++++++- docs/spec/upgrades/satin.md | 2 +- 8 files changed, 243 insertions(+), 40 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 22fd9b36d..7505f4370 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,7 +171,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/frame_limit.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), EIP-2780's charge for the first frame's recipient or created account (the frame is answered with the stop), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a `CALL`, `CREATE` or `CREATE2` is charged for upfront, once revm has decided the frame it starts (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. + It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a frame's start adds — EIP-2780's charge for the first frame's recipient or created account, and the account a `CALL`, `CREATE` or `CREATE2` is charged for upfront — once revm has decided the frame (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — or answered with a failure, such as a value transfer to a precompile that fails, gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded; the transaction's own frame has no caller whose revert takes an answer's writes back, so its answer is taken back to where its start began) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9db7ad054..b93199e46 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -24,7 +24,7 @@ use revm::{ }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, + journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, Host, }, handler::{ @@ -50,7 +50,9 @@ use crate::{ access::ComputeStop, evm::{ history::transaction_body_bytes, - inspector::{frame_end_checked, journal_position, ResultSource, StepGuard}, + inspector::{ + frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, + }, }, history_gas, synthetic_frame_result, system::keyless, @@ -246,12 +248,13 @@ where /// out-of-gas in place of the stop that bound first. The input carries no charged flag, so /// the stop's settlement gives nothing back that was not charged. /// - /// Once revm has built the first frame, the state gas the transaction has been charged is all - /// it holds outside its frames: the account a deposit-like transaction creates for its caller, - /// the applied authorities, and the new account EIP-2780 charges the first frame's start for. - /// It is held to the state-gas limit there, and a crossing latches the transaction: the frame - /// is answered with the stop before it runs, and its settlement gives the start's charge back - /// as it does for any first frame that fails. + /// Once revm has prepared the first frame, the state gas the transaction has been charged is + /// all it holds outside its frames: the account a deposit-like transaction creates for its + /// caller, the applied authorities, and the new account EIP-2780 charges the first frame's + /// start for. The first two stand whatever the first frame does, and are held to the + /// state-gas limit here: a crossing latches the transaction, and the frame is answered with the + /// stop before it is built. The third is the first frame's upfront charge, held as every + /// frame's is, once revm has decided the frame ([`hold_upfront_state_gas`]). fn first_frame_input( &mut self, evm: &mut Self::Evm, @@ -260,8 +263,10 @@ where if evm.ctx_ref().additional_limit.latched().is_some() { return Ok(Some(unbuilt_first_frame(evm.ctx_ref(), gas))); } + let stands = gas.state_gas_spent(); let frame = self.op.first_frame_input(evm, gas)?; - evm.ctx_mut().additional_limit.on_state_gas_before_frames(gas.state_gas_spent()); + let spent = gas.state_gas_spent(); + evm.ctx_mut().additional_limit.on_state_gas_before_frames(stands, spent); evm.ctx_mut().mark_beneficiary_delegate(); Ok(frame) } @@ -427,7 +432,10 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm MegaEvm { } /// Holds the state gas the caller was charged upfront for the frame that is starting — the new -/// account a value `CALL` adds, a creation's account — to the state-gas limit, once revm has -/// decided the frame. `answer` is the frame's result when it was answered without running; a -/// frame revm built has none yet. +/// account a value `CALL` adds, a creation's account, or, for the transaction's own frame, the +/// recipient or created account EIP-2780 charges the transaction for — to the state-gas limit, +/// once revm has decided the frame. `answer` is the frame's result when it was answered without +/// running; a frame revm built has none yet. /// -/// revm's `CALL`, `CREATE` and `CREATE2` make that charge before anything knows whether the frame -/// can start, and a frame that adds no account gives it back when its answer returns -/// ([`FrameResult::refundable_state_gas_charge`]): a value call its caller cannot fund, a call past -/// the call-stack limit, an answer that fails. Such a charge is never held. A charge that stands — -/// the frame is built, or answered with a success, as a value call to an account with no code is -/// — is held, and a crossing latches the transaction: a built frame returns the stop before its -/// first instruction, and an answer is rewritten to it here, so an inspector sees the answer the -/// caller gets. The writes the frame's start made go with the frames the stop reverts. A built -/// frame that later fails gives the charge back too, but by then it has started, and a crossing -/// inside a frame that later fails is a crossing. +/// revm's `CALL`, `CREATE` and `CREATE2`, and its EIP-2780 phase for the first frame, make that +/// charge before anything knows whether the frame can start, and a frame that adds no account +/// gives it back when its answer returns ([`FrameResult::refundable_state_gas_charge`]): a value +/// call its caller cannot fund, a call past the call-stack limit, an answer that fails. Such a +/// charge is never held. A charge that stands — the frame is built, or answered with a success, as +/// a value call to an account with no code is — is held, and a crossing latches the transaction: a +/// built frame returns the stop before its first instruction, and an answer is rewritten to it +/// here, so an inspector sees the answer the caller gets. The writes the frame's start made go with +/// the frames the stop reverts; an answer of the transaction's own frame, which no frame's revert +/// follows, is taken back by its start ([`take_back_a_stopped_answer`]). A built frame that later +/// fails gives the charge back too, but by then it has started, and a crossing inside a frame that +/// later fails is a crossing. /// /// The frame's own lane is on top by now, and holds outside it what its caller held, the charge /// included; the frame itself holds nothing yet. Every other charge was held where it was made, so @@ -1036,6 +1053,26 @@ fn hold_upfront_state_gas( } } +/// Takes the journal back to `start`, where the transaction's own frame began, when revm answered +/// that 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. Below the transaction's own frame the stop +/// reverts every caller, and the caller's checkpoint takes the answer's writes back with its own; +/// the transaction's own frame has no caller, so its answer's writes are taken back here, as revm +/// takes back a frame that fails. The journal's depth is left as it is. +fn take_back_a_stopped_answer( + ctx: &mut MegaContext, + start: JournalCheckpoint, + succeeded: bool, + result: &FrameResult, +) { + if succeeded && !result.instruction_result().is_ok() { + revert_journal_to(ctx, start); + } +} + /// Settles `output`, the answer the inspector gave the frame `frame_init` starts in its place. /// 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. diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 716afb04f..ad18731c2 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -606,7 +606,7 @@ pub(crate) fn journal_position( /// 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. -fn revert_journal_to( +pub(crate) fn revert_journal_to( context: &mut MegaContext, checkpoint: JournalCheckpoint, ) { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 0fe549854..8b9f1a158 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -536,12 +536,15 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// Records the state gas the transaction was charged before its first frame, `spent`, and - /// holds it to the limit. A crossing latches the transaction, and its first frame is answered - /// with the stop before it is built. - pub(crate) fn on_state_gas_before_frames(&mut self, spent: i64) { + /// Records the state gas the transaction was charged before its first frame, `spent`, which + /// the first frame's lane holds outside it, and holds to the limit the part of it that stands + /// whatever the first frame does, `stands`: all of it but the account EIP-2780 charges the + /// first frame's start for, which is held once revm has decided the frame, as every frame's + /// upfront charge is. A crossing latches the transaction, and its first frame is answered with + /// the stop before it is built. + pub(crate) fn on_state_gas_before_frames(&mut self, stands: i64, spent: i64) { self.tracker.set_state_gas_before_frames(spent); - self.check_state_gas(spent); + self.check_state_gas(stands); } /// Records the state gas `held` by the running frame as it suspends on a child, which the diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 344511bcd..75d4e5252 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -93,12 +93,13 @@ //! //! The limit holds each charge where it is made, once it is made, so a charge the frame cannot //! pay is an out-of-gas whatever the limit: the authorities' before the first frame, which are -//! taken back on a crossing; the first frame's recipient or created account, which the first frame -//! is then answered with the stop for; a fresh slot and a destruction's new beneficiary, which -//! stop the frame; and a new account a `CALL`, `CREATE` or `CREATE2` adds, which its opcode is -//! charged for upfront and the limit holds once revm has decided the frame. A frame revm refuses — -//! a value call its caller cannot fund, one past the call-stack limit — gives that charge back and -//! is never held for it; a frame revm builds, or answers with a success, returns the stop. +//! taken back on a crossing; a fresh slot and a destruction's new beneficiary, which stop the +//! frame; and a new account a frame's start adds — the first frame's recipient or created account, +//! which EIP-2780 charges the transaction for, and the account a `CALL`, `CREATE` or `CREATE2` +//! adds, which its opcode is charged for — held once revm has decided the frame. A frame refused — +//! a value its caller cannot fund, one past the call-stack limit — or answered with a failure gives +//! that charge back and is never held for it; a frame revm builds, or answers with a success, +//! returns the stop, and an answer of the transaction's own frame takes its writes back with it. //! //! Deployed code is held once `return_create` has charged every part of its deposit and before it //! commits the creation, as its bytes are ([`ContextTr::admit_code_deposit`]), so a crossing diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 88d6b0a65..e78994338 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -39,6 +39,17 @@ pub(crate) fn call_with_data( tx(caller, TxKind::Call(to), data, U256::ZERO, gas_limit) } +/// A call from `caller` to `to` carrying `value` and `data`. +pub(crate) fn call_with_value_and_data( + caller: Address, + to: Address, + value: U256, + data: Bytes, + gas_limit: u64, +) -> MegaTransaction { + tx(caller, TxKind::Call(to), data, value, 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) diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index b410c7910..2db0fc277 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -15,7 +15,7 @@ use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaTransaction, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, AUTHORIZATION_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ @@ -23,11 +23,14 @@ use revm::{ CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, STOP, }, - interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, + InterpreterResult, + }, Database, Inspector, }; -use crate::common::{authorizing_call, call, context, create}; +use crate::common::{authorizing_call, call, call_with_value_and_data, context, create}; const CALLER: Address = address!("0000000000000000000000000000000000600000"); const A: Address = address!("0000000000000000000000000000000000600001"); @@ -491,6 +494,154 @@ fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { assert_eq!(outcome.gas.state, 0); } +/* ---------- the first frame's upfront charge, held once revm has decided the frame ---------- */ + +/// The identity precompile, which answers any input with a success. +const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); +/// The BN254 pairing precompile, which rejects an input that is not a whole number of pairs. +const BN254_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + +/// A transaction of one wei from [`CALLER`] to `to` carrying `data`. +fn one_wei_to(to: Address, data: &[u8]) -> MegaTransaction { + call_with_value_and_data(CALLER, to, U256::from(1), Bytes::copy_from_slice(data), BELOW_CAP) +} + +/// The transaction's own frame is held for the account EIP-2780 charges its start for as every +/// frame is held for its opcode's upfront charge: once revm has decided the frame. A first frame +/// revm answers with a failure — a value transfer to a precompile that rejects its input — adds no +/// account, and its charge comes back, so no limit holds it: the transaction halts exactly as it +/// does without a limit, and nothing moves. +#[test] +fn test_a_first_frame_revm_answers_with_a_failure_is_not_held_for_its_upfront_charge() { + let account = one_account(); + let tx = one_wei_to(BN254_PAIRING, &[1]); + let free = run_under(funded(), tx.clone(), u64::MAX); + assert!(free.result.is_halt(), "the pairing rejects a one-byte input: {:?}", free.result); + assert_eq!(free.gas.state, 0, "the account charge came back"); + for limit in [account - 1, 0] { + let limited = run_under(funded(), tx.clone(), limit); + assert_eq!(limited.limit_exceeded, None, "limit {limit}"); + assert_eq!(limited.result, free.result, "limit {limit}: as without the limit"); + assert_eq!(limited.gas, free.gas, "limit {limit}"); + assert!( + limited.state.get(&BN254_PAIRING).is_none_or(|account| account.info.balance.is_zero()), + "limit {limit}: nothing moved" + ); + } +} + +/// A first frame revm builds, or answers with a success, adds the account EIP-2780 charged its +/// start for, so the charge is held once revm has decided the frame, and a crossing stops the +/// transaction: a built frame before its first instruction, an answer by being rewritten to the +/// stop. The stop keeps none of what the start wrote — no value moved, no account added, the +/// record and the transfer log not counted, the record's history given back — and bills what ran, +/// as a stop below the first frame does: a precompile answered with a success ran, and its price +/// stays spent. A creation transaction keeps its creator's nonce bump, so it cannot be replayed. +#[test] +fn test_a_first_frame_revm_decides_is_held_for_its_upfront_charge() { + let account = one_account(); + let word = [7_u8; 32]; + let cases = [ + ("a value transfer to an account with no code", one_wei_to(EMPTY, &[]), EMPTY, 0), + ( + "a value transfer to a precompile that answers", + one_wei_to(IDENTITY, &word), + IDENTITY, + 32, + ), + ("a creation transaction", create(CALLER, Bytes::new(), BELOW_CAP), CALLER.create(0), 0), + ]; + for (name, tx, added, calldata) in cases { + let free = run_under(funded(), tx.clone(), u64::MAX); + assert!(free.result.is_success(), "{name}: {:?}", free.result); + assert_eq!(free.gas.state, account, "{name}: the account EIP-2780 charged"); + + let stopped = run_under(funded(), tx, account - 1); + assert_state_stopped(name, &stopped, account - 1, account); + assert_eq!(stopped.gas.state, 0, "{name}"); + let body = mega_evm::history_gas(TX_BODY_SIZE + calldata).expect("a body has a price"); + assert_eq!(stopped.gas.history, body, "{name}: the record's history came back"); + assert_eq!(stopped.gas.regular, free.gas.regular, "{name}: what ran is billed"); + assert_eq!( + stopped.usage, + LimitUsage { data_size: TX_BODY_SIZE + calldata, write_records: 0 }, + "{name}: the body alone" + ); + let account = stopped.state.get(&added); + assert!( + account.is_none_or(|account| account.info.balance.is_zero() && !account.is_created()), + "{name}: nothing moved, nothing added" + ); + assert_eq!(stopped.state[&CALLER].info.nonce, 1, "{name}: the sender's nonce"); + } +} + +/// The first frame's start is held as every frame start is: its record and transfer log before +/// revm builds the frame, its upfront state gas after revm has decided it. A value transfer whose +/// record and transfer log cross the data-size limit is stopped for them and adds no account, so +/// the state-gas limit its upfront charge would have crossed is not what stops it. +#[test] +fn test_a_first_frame_start_whose_records_cross_is_stopped_for_its_records() { + let account = one_account(); + let limit = TX_BODY_SIZE + WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; + let outcome = MegaEvm::new( + context(funded()).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_state_gas_limit(account - 1) + .with_tx_data_size_limit(limit), + ), + ) + .execute_transaction(one_wei_to(EMPTY, &[])) + .unwrap(); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + 1, + frame_local: false, + }), + "the recipient's record and the transfer log, over the limit by one byte", + ); + assert_eq!(outcome.gas.state, 0); + assert!(outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); +} + +/// Answers every call to [`EMPTY`] itself, with a success. +struct AnswersEmpty; + +impl Inspector, EthInterpreter> for AnswersEmpty { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + (inputs.target_address == EMPTY).then(|| { + CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// A first frame an inspector answers in place of running never started: it adds no account, and +/// its upfront charge comes back whatever the answer. So no limit holds that charge, and the +/// transaction keeps the inspector's answer. +#[test] +fn test_a_first_frame_an_inspector_answers_is_not_held_for_its_upfront_charge() { + let account = one_account(); + let mut evm = MegaEvm::new(context(funded()).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), + )) + .with_inspector(AnswersEmpty); + let outcome = evm.execute_transaction(one_wei_to(EMPTY, &[])).unwrap(); + assert_eq!(outcome.limit_exceeded, None); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0); + assert!(outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); +} + /* ---------- one limit for the whole call stack ---------- */ /// A child's crossing stops the whole transaction: there is no frame budget to revert it alone. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 47092d2d7..e7ef148f8 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -385,7 +385,7 @@ Three dimensions are limited per transaction; compute is not one of them (see [T A frame that crosses its budget MUST revert with `MegaLimitExceeded(kind, budget)` and its caller continues. - **State gas** is the net EIP-8037 state gas the transaction holds: what it was charged before the first frame, plus what every frame on the call stack holds, net of refills and of failed frames. It MUST be checked wherever state gas is charged, after the charge: a charge the frame cannot pay is an out-of-gas whatever the limit. - The sites are the applied authorities and the account a deposit-like transaction creates for its caller, before the first frame (the authorities are taken back on a crossing), the first frame's recipient or created account, a fresh slot, a `SELFDESTRUCT`'s new beneficiary, a new account a `CALL`, `CREATE` or `CREATE2` adds (held once the frame is decided: a frame refused on its caller's account gives the charge back and is not held for it), and deployed code (at the deposit, before the creation commits). + The sites are the applied authorities and the account a deposit-like transaction creates for its caller, before the first frame (the authorities are taken back on a crossing), a fresh slot, a `SELFDESTRUCT`'s new beneficiary, a new account a frame's start adds — the first frame's recipient or created account, and the account a `CALL`, `CREATE` or `CREATE2` adds — (held once the frame is decided: a frame refused on its caller's account, or answered with a failure, gives the charge back and is not held for it), and deployed code (at the deposit, before the creation commits). Because it is a limit on gas, a slot or an account in a bucket `m` times the minimum reaches it `m` times sooner. - **Order at one site.** Where the state gas and a count cross at the same site, the state gas is the dimension reported; between the counts, data size is checked before write records, and a transaction limit before a frame budget. From bfddf30fd4fed42b9f6ef4420f147a5fbd792c52 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:04:18 -0400 Subject: [PATCH 364/458] ci: run the test suite across a grid of byte prices scripts/price_grid.sh builds the suite with satin-price-override and runs it once per cost per state byte and cost per history byte. A pull request runs four points (0/0, 312.5/20, 5000/300, 10000/1000), which together failed every test the whole grid failed before the suite held at any price; nightly and on dispatch it runs the whole grid. --- .github/workflows/price-grid.yml | 62 +++++++++++++++++ AGENTS.md | 10 ++- REVIEW.md | 16 ++++- scripts/price_grid.sh | 113 +++++++++++++++++++++++++++++++ 4 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/price-grid.yml create mode 100755 scripts/price_grid.sh diff --git a/.github/workflows/price-grid.yml b/.github/workflows/price-grid.yml new file mode 100644 index 000000000..2ce32e7cd --- /dev/null +++ b/.github/workflows/price-grid.yml @@ -0,0 +1,62 @@ +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, four points: both bytes free, 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, 312.5, 700, 1530, 2000, +# 5000 and 10000 by a cost per history byte of 0, 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 57 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/AGENTS.md b/AGENTS.md index 64728967c..746690bec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,6 +30,9 @@ 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 # four 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 @@ -426,13 +429,15 @@ Every later mechanism plugs into these; a change to one comes back to this layer ## Test Gates -`REVIEW.md` lists every check a pull request meets; two of them are this repository's own execution gates. +`REVIEW.md` lists every check a pull request meets; two of them are this repository's own execution gates, and a third 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 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, four points on a pull request and the whole grid nightly. + The prices are provisional, so a test holds at any of them: 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`). ## Version Control @@ -498,6 +503,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. +- **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 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. - **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. diff --git a/REVIEW.md b/REVIEW.md index f1e2e07f9..c5e54b379 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -64,6 +64,9 @@ 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 any byte price, and the byte-price grid job checks it. + 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. @@ -104,6 +107,16 @@ These checks guard every change to the Satin engine. `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. +### 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 four points: both bytes free (0 / 0), the cheapest and the dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate (10000 / 1000). + Before the suite held at any price, these four failed every test the whole grid failed. +- Nightly and on dispatch it runs the whole grid: CPSB 0, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 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. +- 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), `factory` (EVM construction through `MegaEvmFactory`) and `block` (a block through `MegaBlockExecutor`), all in `crates/mega-evm/benches`. @@ -136,12 +149,13 @@ 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, weekly benchmark, replay-bench, 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). - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. - `doc-audit.yml`: the documentation audit of `satin`'s docs. + - `price-grid.yml`: the whole byte-price grid. - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the replay corpus, which is keyed by the legacy Rex5 spec, and a bench mode of the state-test tool exist for Satin. ## Dev tools and test infrastructure diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh new file mode 100755 index 000000000..303be2762 --- /dev/null +++ b/scripts/price_grid.sh @@ -0,0 +1,113 @@ +#!/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). A summary +# line per point 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), and a point past the +# dearest candidate on both axes. + +set -uo pipefail + +CPSB_AXIS="0 312.5 700 1530 2000 5000 10000" +CPHB_AXIS="0 20 50 88 100 200 300 1000" +EXTRA_POINTS="0.001/0.001" +# Both bytes free; the cheapest and the dearest pair under consideration; and a point past every +# candidate. Before the suite was made to hold at any price, these four failed every test the +# full grid failed. +PR_POINTS="0/0 312.5/20 5000/300 10000/1000" + +FEATURES="satin-price-override,test-utils" + +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,20p' "$0" | sed 's/^# \{0,1\}//' + exit 2 + ;; + *) + points="$*" + ;; +esac + +rm -rf "$OUT_DIR" +mkdir -p "$OUT_DIR" + +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 | 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" + log="$OUT_DIR/${cpsb//-/unset}_${cphb//-/unset}.log" + + 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") + if [ "$status" -eq 0 ]; then + result="ok" + else + result="FAILED" + failed_points="$failed_points $point" + fi + printf '%-12s %-7s %5s passed %4s failed %4ss %s\n' "$point" "$result" "$passed" "$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 | $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" From 38ab0badfdf36a7a2da5d11b359c2ca3baabe60f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:04:35 -0400 Subject: [PATCH 365/458] docs(spec): hold the first frame's EIP-2780 charge as a frame start's upfront charge --- docs/spec/upgrades/satin.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index e7ef148f8..e43d80301 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -389,7 +389,7 @@ Three dimensions are limited per transaction; compute is not one of them (see [T Because it is a limit on gas, a slot or an account in a bucket `m` times the minimum reaches it `m` times sooner. - **Order at one site.** Where the state gas and a count cross at the same site, the state gas is the dimension reported; between the counts, data size is checked before write records, and a transaction limit before a frame budget. - A frame start is the exception: its records and transfer log are held before the frame is built, and the state gas its opcode charged upfront for the account it adds only once the frame is decided; a start the records stop adds no account, so its upfront state gas is given back rather than held, and the data-size or KV stop is the one reported. + A frame start is the exception: its records and transfer log are held before the frame is built, and the state gas charged upfront for the account it adds — by its opcode, or, for the first frame, by EIP-2780 — only once the frame is decided; a start the records stop adds no account, so its upfront state gas is given back rather than held, and the data-size or KV stop is the one reported. - **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. @@ -423,7 +423,7 @@ What was applied before the first frame is not the frames' doing, and a later st 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. - The one exception is the state gas the calling opcode charges upfront for the account the frame adds: it is held once the frame is decided, so a frame built by then returns the stop before its first instruction, a frame answered without running is rewritten to the stop, and what the start moved is reverted with the frames the stop reverts. + The one exception is the state gas charged upfront for the account the frame adds — by the calling opcode, or, for the first frame, by EIP-2780: it is held once the frame is decided, so a frame built by then returns the stop before its first instruction, a frame answered without running is rewritten to the stop, and what the start moved is reverted with the frames the stop reverts — for the first frame, which no frame's revert follows, with its answer. - A body over the data-size limit MUST stop the transaction before it runs: no authorization is applied, no record made outside a frame is charged, the first frame's start is charged nothing, and the first frame is answered with the stop. - EIP-7702 authorities whose state gas or records would cross a limit MUST be taken back before the first frame, with their writes and the state gas applying them charged; the first frame is then answered with the stop. Authorities admitted there are kept through a later stop, as above. From b5dd5376adbbed778b6a71db87fe70c7fb7f3054 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:07:53 -0400 Subject: [PATCH 366/458] docs: state the first frame's upfront hold in the latch's exception --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 7505f4370..0cf8414c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -361,7 +361,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A frame budget reverts its frame alone, without a latch. The stop 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_gas_limit.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), and EIP-7702 authorities whose state gas or records would cross it are taken back before the first frame. - The one exception is the state gas an opcode charges upfront for the account the frame it starts adds: revm gives it back for a frame it refuses, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts. + The one exception is the state gas charged upfront for the account a frame's start adds — by the opcode that starts it, or by EIP-2780 for the transaction's own frame: revm gives it back for a frame it refuses or answers with a failure, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts; the transaction's own frame has no caller whose revert follows, so an answer of it that the stop rewrites has its journal taken back to where its start began. 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. From fde9386c94aecbfac2ee92386539261c2b3ff018 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:17:14 -0400 Subject: [PATCH 367/458] test(satin): port the parked CREATE and CREATE2 rows The 21 rows owed to the common execution layer run in create_opcodes.rs: missing operands halt with StackUnderflow, an empty init code reads no offset and touches no memory, an oversized one is refused before its offset is read or memory expanded, and a 32 KiB one pays exactly its words. The six static-callee rows already run in static_callee.rs under their names; what the rows compared with another legacy spec or read off the legacy compute ledger has no counterpart. --- crates/mega-evm/tests/_pending/README.md | 63 +- .../tests/_pending/rex4/create_safety.rs | 150 ----- crates/mega-evm/tests/_pending/rex4/main.rs | 6 - .../_pending/rex5/create2_empty_initcode.rs | 168 ------ .../rex5/create2_resize_gas_metering.rs | 192 ------ crates/mega-evm/tests/_pending/rex5/main.rs | 10 - crates/mega-evm/tests/_pending/rex6/common.rs | 69 --- .../_pending/rex6/create2_metering_order.rs | 568 ------------------ .../tests/_pending/rex6/error_paths.rs | 147 ----- crates/mega-evm/tests/_pending/rex6/main.rs | 10 - crates/mega-evm/tests/satin/create_opcodes.rs | 231 +++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/static_callee.rs | 4 +- 13 files changed, 250 insertions(+), 1369 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex4/create_safety.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/main.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/main.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/error_paths.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/main.rs create mode 100644 crates/mega-evm/tests/satin/create_opcodes.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 1d7ca9ea5..a7b7eac8e 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -27,9 +27,8 @@ 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 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **28** | **28** | **0** | **21** | **0** | **7** | +| **Total** | **7** | **7** | **0** | **0** | **0** | **7** | ## Tests ported in place @@ -66,36 +65,6 @@ 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 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. @@ -366,6 +335,21 @@ These 4 rows run in a real test target now, adapted to the Satin API: block exec | `rex4/intrinsic_limit_bypass.rs` | inspector support (1) | 1 | `tests/satin/inspector.rs` | | **Total** | | **4** | | +## Tests ported when the last rows were settled + +These 21 rows run in a real test target now, so the counts above are lower than the inventory's by exactly these rows. +The CREATE and CREATE2 rows owed to the common execution layer keep their transactions and what Satin keeps of their expectations: the halt reasons, and the order in which revm's own `CREATE2` checks its operands, at the Satin init-code limit; what they compared with another legacy spec or read off the legacy compute ledger has no counterpart. +Six of them are the static-callee rows, whose Satin assertions already ran in `tests/satin/static_callee.rs` under the same names; the rest of each compared with a legacy spec. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `rex4/create_safety.rs` | the common execution layer (1) | 1 | `tests/satin/create_opcodes.rs` | +| `rex5/create2_empty_initcode.rs` | the common execution layer (5) | 5 | `tests/satin/create_opcodes.rs` | +| `rex5/create2_resize_gas_metering.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | +| `rex6/create2_metering_order.rs` | the common execution layer (11) | 11 | `tests/satin/create_opcodes.rs`, `tests/satin/static_callee.rs` | +| `rex6/error_paths.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | +| **Total** | | **21** | | + ## Tests retired after the inventory These 21 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. @@ -384,16 +368,6 @@ They are not counted above. | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | | **Total** | | **21** | | -## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism - -| File | Test | Parked under | Reason | -|---|---|---|---| - -## Tests parked under a later mechanism than the inventory named - -| File | Test | Parked under | Reason | -|---|---|---|---| - ## Files Each cell lists `disposition count (mechanism · decision)`. @@ -402,8 +376,3 @@ Each cell lists `disposition count (mechanism · decision)`. |---|---:|---| | `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | | `mini_rex/gas.rs` | 2 | undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | -| `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `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) | -| `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | 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 deleted file mode 100644 index e62746d5f..000000000 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Tests for `Rex4` hardfork features. - -mod create_safety; -mod eip7702_delegation_cycle; -mod intrinsic_limit_bypass; -mod storage_call_stipend; 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 deleted file mode 100644 index 1136abb13..000000000 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ /dev/null @@ -1,10 +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 eip7702_metering; -mod pre_block_system_calls; -mod sstore_storage_gas_error; -mod stipend_accounting; 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/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/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs deleted file mode 100644 index 0e814f216..000000000 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Tests for `Rex6` hardfork features. - -mod common; -mod create2_metering_order; -mod create_frame_accounting; -mod error_paths; -mod fee_reward_accounting; -mod frame_local_accounting; -mod self_transfer_account_dedup; -mod sequencer_registry_rotation; 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/main.rs b/crates/mega-evm/tests/satin/main.rs index 8cbe4ffa4..48467bcfb 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -3,6 +3,7 @@ mod common; mod compute_gas; mod contract_size; +mod create_opcodes; mod data_size; mod data_size_counts; mod db_error; 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}; From 77c0da3f6325bc2799f995332f8740eacf59f405 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:17:37 -0400 Subject: [PATCH 368/458] test(satin): port the rows parked on preload-warm pricing and forwarding The seven rows that waited for their decisions take the answer the engine gives, Ethereum's: a precompile, the block beneficiary or an access-list address is charged warm on its first touch, against a control that sees the cold charge where nothing warmed the address, and a call or creation forwards all but a 64th of what it holds once its own charge is paid. No test is parked any more; the README records where each one went. --- AGENTS.md | 5 +- crates/mega-evm/tests/_pending/README.md | 82 +- .../_pending/block_executor/block_limits.rs | 112 --- .../tests/_pending/block_executor/main.rs | 5 - .../tests/_pending/compute_gas/claims.rs | 361 -------- .../tests/_pending/compute_gas/main.rs | 819 ------------------ .../mega-evm/tests/_pending/mini_rex/gas.rs | 536 ------------ .../mega-evm/tests/_pending/mini_rex/main.rs | 5 - crates/mega-evm/tests/_pending/rex/main.rs | 3 - crates/mega-evm/tests/_pending/rex3/main.rs | 3 - .../mega-evm/tests/satin/inherited_costs.rs | 234 +++++ crates/mega-evm/tests/satin/main.rs | 1 + 12 files changed, 263 insertions(+), 1903 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/block_executor/block_limits.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/main.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/gas.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/main.rs create mode 100644 crates/mega-evm/tests/satin/inherited_costs.rs diff --git a/AGENTS.md b/AGENTS.md index 746690bec..7c9fda607 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -422,9 +422,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer - `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. - `system/` — tests of the system contracts: the interceptor dispatch, what each contract answers, keyless deployment (`system/keyless/`) and the system-address transaction. -- `_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. +- `_pending/` — no test any more: its `README.md` records where each legacy test the test inventory kept went, ported into one of the targets above or retired, and why. + It has no `main.rs`, so Cargo builds nothing there. - Unit tests live next to the code in `#[cfg(test)] mod tests`. ## Test Gates diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index a7b7eac8e..ce52889e3 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -1,38 +1,15 @@ # 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. +The test inventory made for the engine rewrite kept a set of the legacy engine's tests; every one of them has since been ported into a real test target or retired, and none is parked here any more. +This file records where each one went: the sections below list them by the mechanism that ported or retired them. 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 | -|---|---:|---:|---:|---:|---:|---:| -| — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **7** | **7** | **0** | **0** | **0** | **7** | +The directory holds this record alone. +It has no `main.rs`, and Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`, so nothing here is built; do not add one. ## 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. +These rows came back with the code they test and run in `crates/mega-evm/src`. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -67,7 +44,7 @@ What the retired `tests/mutation/` rows cited, for the mechanisms that own them. ## 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. +These 45 rows run in a real test target now, adapted to the Satin API. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -87,7 +64,7 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## 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. +These 34 rows run in a real test target now, adapted to the Satin API and to the schedule the decision they cite fixes. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -102,7 +79,7 @@ These 34 rows run in a real test target now, adapted to the Satin API and to the ## 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. +These 53 rows run in a real test target now, adapted to the Satin API. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -124,7 +101,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 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. +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. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -144,7 +121,7 @@ These 67 rows run in a real test target now, adapted to the Satin API and to the ## 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. +These 61 rows run in a real test target now, adapted to the Satin API and to the dispatch the decision they cite fixes. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -163,7 +140,7 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by history gas -These 28 rows run in a real test target now, adapted to the Satin API and to the history ledger the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. +These 28 rows run in a real test target now, adapted to the Satin API and to the history ledger the decision they cite fixes. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -175,7 +152,7 @@ These 28 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by system contract deployment -These 29 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy, 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 and to the single-spec deploy. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -193,7 +170,7 @@ These 29 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by compute gas -These 24 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles, so the counts above are lower than the inventory's by exactly these rows. +These 24 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -204,7 +181,7 @@ These 24 rows run in a real test target now, adapted to the Satin API and to a c ## Tests ported by the data-size limit -These 47 rows run in a real test target now, adapted to the Satin API and to the byte table and budget rule the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. +These 47 rows run in a real test target now, adapted to the Satin API and to the byte table and budget rule the decision they cite fixes. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -221,7 +198,7 @@ These 47 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the state-growth and KV limits -These 54 rows run in a real test target now, adapted to the Satin API: the state growth they pin is held as EIP-8037 state gas by a per-transaction state-gas limit, and the KV updates they count are the write records the common execution layer keeps, held to a KV limit that follows the data-size limit's transaction and frame rules. The counts above are lower than the inventory's by exactly these rows. +These 54 rows run in a real test target now, adapted to the Satin API: the state growth they pin is held as EIP-8037 state gas by a per-transaction state-gas limit, and the KV updates they count are the write records the common execution layer keeps, held to a KV limit that follows the data-size limit's transaction and frame rules. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -239,7 +216,7 @@ These 54 rows run in a real test target now, adapted to the Satin API: the state ## Tests ported by detention -These 89 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix, so the counts above are lower than the inventory's by exactly these rows. +These 89 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -264,7 +241,7 @@ These 89 rows run in a real test target now, adapted to the Satin API and to the ## Tests ported by the oracle and control contracts -These 77 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. The counts above are lower than the inventory's by exactly these rows. +These 77 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -278,7 +255,7 @@ These 77 rows run in a real test target now, adapted to the Satin API: the Oracl ## Tests ported by native keyless deployment -These 69 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. The counts above are lower than the inventory's by exactly these rows. +These 69 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -296,7 +273,7 @@ These 69 rows run in a real test target now, adapted to the Satin API: a keyless ## Tests ported by the pre-block system calls -These 45 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. 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: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -310,7 +287,7 @@ These 45 rows run in a real test target now, adapted to the Satin API: a system ## Tests ported by revert-class aborts -These 17 rows run in a real test target now, adapted to the Satin API: a transaction-level limit — data size, KV updates, state gas or gas detention's compute limit — stops the transaction with a revert carrying `MegaLimitExceeded`, which settles like an EIP-8037 revert, where the legacy engine halted and rescued the remaining gas; a frame budget reverts its frame alone. The counts above are lower than the inventory's by exactly these rows. +These 17 rows run in a real test target now, adapted to the Satin API: a transaction-level limit — data size, KV updates, state gas or gas detention's compute limit — stops the transaction with a revert carrying `MegaLimitExceeded`, which settles like an EIP-8037 revert, where the legacy engine halted and rescued the remaining gas; a frame budget reverts its frame alone. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -327,7 +304,7 @@ These 17 rows run in a real test target now, adapted to the Satin API: a transac ## Tests ported by inspector support -These 4 rows run in a real test target now, adapted to the Satin API: block execution admits an inspector only when it is declared an observer, so an inspector that answers a frame has no route to a block and is exercised on the EVM, where a frame it answers, or a failed frame it rewrites into a success, settles as a frame that kept nothing; and a body over the data-size limit is stopped before any inspector's answer to its first frame. The counts above are lower than the inventory's by exactly these rows. +These 4 rows run in a real test target now, adapted to the Satin API: block execution admits an inspector only when it is declared an observer, so an inspector that answers a frame has no route to a block and is exercised on the EVM, where a frame it answers, or a failed frame it rewrites into a success, settles as a frame that kept nothing; and a body over the data-size limit is stopped before any inspector's answer to its first frame. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -337,23 +314,25 @@ These 4 rows run in a real test target now, adapted to the Satin API: block exec ## Tests ported when the last rows were settled -These 21 rows run in a real test target now, so the counts above are lower than the inventory's by exactly these rows. +These 28 rows were the last ones parked, and run in a real test target now. The CREATE and CREATE2 rows owed to the common execution layer keep their transactions and what Satin keeps of their expectations: the halt reasons, and the order in which revm's own `CREATE2` checks its operands, at the Satin init-code limit; what they compared with another legacy spec or read off the legacy compute ledger has no counterpart. Six of them are the static-callee rows, whose Satin assertions already ran in `tests/satin/static_callee.rs` under the same names; the rest of each compared with a legacy spec. +The rows that waited for D57 and D58 take the answer the engine gives, which is Ethereum's: a preload-warm address (a precompile, the block beneficiary, an access-list address) is charged warm on its first touch, and a call or creation forwards all but a 64th of its gas. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `compute_gas/claims.rs` | none (5) | 5 | `tests/satin/inherited_costs.rs` | +| `mini_rex/gas.rs` | none (2) | 2 | `tests/satin/inherited_costs.rs` | | `rex4/create_safety.rs` | the common execution layer (1) | 1 | `tests/satin/create_opcodes.rs` | | `rex5/create2_empty_initcode.rs` | the common execution layer (5) | 5 | `tests/satin/create_opcodes.rs` | | `rex5/create2_resize_gas_metering.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | | `rex6/create2_metering_order.rs` | the common execution layer (11) | 11 | `tests/satin/create_opcodes.rs`, `tests/satin/static_callee.rs` | | `rex6/error_paths.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | -| **Total** | | **21** | | +| **Total** | | **28** | | ## Tests retired after the inventory These 21 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 | |---|---|---:|---| @@ -367,12 +346,3 @@ They are not counted above. | `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | | `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | | **Total** | | **21** | | - -## Files - -Each cell lists `disposition count (mechanism · decision)`. - -| File | Tests | Owners | -|---|---:|---| -| `compute_gas/claims.rs` | 5 | undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold) | -| `mini_rex/gas.rs` | 2 | undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | 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 a58dcb8af..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs +++ /dev/null @@ -1,112 +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() -} - -const CALLER2: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); -const CALLER3: alloy_primitives::Address = address!("4000000000000000000000000000000000000004"); 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/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs deleted file mode 100644 index 81fa32411..000000000 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ /dev/null @@ -1,361 +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() -} - -/// 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" - ); - } -} 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 3843a4fc8..000000000 --- a/crates/mega-evm/tests/_pending/compute_gas/main.rs +++ /dev/null @@ -1,819 +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") -} 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 9033fa5b9..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! Tests for `MiniRex` hardfork features. - -mod block_env_access_tracking; -mod compute_gas_limit; -mod gas; 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/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs deleted file mode 100644 index edb4e4298..000000000 --- a/crates/mega-evm/tests/_pending/rex3/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Tests for Rex3 hardfork features. - -mod system_address; 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..897bb477f --- /dev/null +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -0,0 +1,234 @@ +//! 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, + }, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{block, call, context, execute}; + +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: EIP-2929's cold account access less +/// its warm read. +const COLD_OVER_WARM: u64 = 2_600 - 100; + +/* ---------- 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 - 2_600; + 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 - 32_000 - 2 - 3; + assert_eq!(forwarded, left - left / 64); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 48467bcfb..b4ceb2cf3 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,7 @@ mod history_bytes; mod history_exemption; mod history_gas; mod history_reservoir; +mod inherited_costs; mod inspector; mod inspector_cheatcodes; mod inspector_limits; From 8f7a39995061b45513fffc1751aa86ff02e29070 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:34:36 -0400 Subject: [PATCH 369/458] fix(evme): run a Satin counterfactual on the engine's fallback schedule The counterfactual schedule was a hand-built copy of the engine's unknown-chain fallback from before Satin required its protocol limits, so every Satin replay of a known chain's block was refused. It is now the engine's own fallback, which carries the placeholder registry and the protocol's default limits. A block a chain's own schedule runs on Satin takes that schedule, and is refused when it cannot run the block rather than filled in with defaults. --- bin/mega-evme/src/block/satin.rs | 19 +++--- bin/mega-evme/src/common/mod.rs | 2 + bin/mega-evme/src/common/schedule.rs | 95 ++++++++++++++++++++++++++++ bin/mega-evme/src/replay/cmd.rs | 34 ++-------- bin/mega-evme/src/replay/mod.rs | 1 - 5 files changed, 113 insertions(+), 38 deletions(-) create mode 100644 bin/mega-evme/src/common/schedule.rs diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 44c0dfa01..6846f47a0 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -21,19 +21,18 @@ use super::{ inputs::{HeaderFields, TxInput}, state::{BlockState, SatinDb}, }; -use crate::{ - common::{ - decode_revert_reason, format_halt_reason, EvmeError, EvmeExternalEnvs, Result, SatinReport, - }, - replay::satin_hardforks, +use crate::common::{ + decode_revert_reason, format_halt_reason, satin_schedule, EvmeError, EvmeExternalEnvs, Result, + SatinReport, }; /// Executes the block `header` describes, with `transactions`, on Satin over `state`. /// -/// The block runs as a node runs a Satin block it configures nothing else for: the chain's own -/// schedule when it activates Satin at the block, otherwise every fork active (a counterfactual), -/// the production data-size caps and gas detention's caps, the block's gas limit from its header. -/// A transaction the engine refuses is reported as refused and left out, and the block goes on. +/// 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 the protocol limits that schedule carries, with no building policy, and with the +/// block's gas limit from its header. 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, @@ -41,7 +40,7 @@ pub(super) fn execute( bucket_capacities: &[(u32, u64)], state: &mut BlockState, ) -> Result { - let hardforks = satin_hardforks(chain_id, header.timestamp); + let hardforks = satin_schedule(chain_id, header.timestamp)?; let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); cfg.chain_id = chain_id; let mut block_env = BlockEnv { diff --git a/bin/mega-evme/src/common/mod.rs b/bin/mega-evme/src/common/mod.rs index 2f43222f7..23cfa45b1 100644 --- a/bin/mega-evme/src/common/mod.rs +++ b/bin/mega-evme/src/common/mod.rs @@ -4,6 +4,7 @@ mod hex; mod logging; mod outcome; mod provider; +mod schedule; mod state; mod trace; mod tx; @@ -15,6 +16,7 @@ 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/schedule.rs b/bin/mega-evme/src/common/schedule.rs new file mode 100644 index 000000000..6d33a4b97 --- /dev/null +++ b/bin/mega-evme/src/common/schedule.rs @@ -0,0 +1,95 @@ +//! The hardfork schedule a Satin run executes under, and so the protocol limits it is held to. + +use mega_evm::{MegaHardforkConfig, MegaHardforks, MegaSpecId}; + +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, with the parameters +/// it carries: the chain's protocol limits among them. A schedule that cannot run the block — its +/// table schedules Satin without the parameters Satin requires — is refused rather than filled in: +/// the tool does not know the chain's limits, and a default in their place would report results +/// the chain does not produce. +/// +/// Any other run is a counterfactual and executes under the schedule the Satin engine gives a chain +/// it does not know ([`mega_evm::all_activated_hardforks`]): Satin from genesis, placeholder +/// registry parameters, which only a registry deployed from scratch reads (a chain whose registry +/// is already deployed keeps the roles in its storage), and +/// [`ProtocolLimits::DEFAULT`](mega_evm::ProtocolLimits::DEFAULT). +pub fn satin_schedule(chain_id: u64, timestamp: u64) -> Result { + schedule_for(mega_evm::hardfork_schedule(chain_id), timestamp) +} + +/// [`satin_schedule`] for a chain whose schedule is `chain`. +fn schedule_for(chain: MegaHardforkConfig, timestamp: u64) -> Result { + if chain.spec_id(timestamp) != Some(MegaSpecId::SATIN) { + return Ok(mega_evm::all_activated_hardforks()); + } + chain.validate_schedule().map_err(|e| { + EvmeError::InvalidInput(format!( + "the chain's schedule runs Satin at timestamp {timestamp} but cannot run it: {e}" + )) + })?; + Ok(chain) +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{ + system::SequencerRegistryConfig, ChainActivation, EvmTxRuntimeLimits, ProtocolLimits, + 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 engine's schedule for an unknown chain, whatever the chain: + /// Satin from genesis, the placeholder registry, the protocol's default limits. + #[test] + fn test_a_counterfactual_runs_on_the_engines_fallback_schedule() { + 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_eq!(schedule.protocol_limits(0), Some(ProtocolLimits::DEFAULT)); + assert_eq!( + schedule.fork_params::(), + Some(&SequencerRegistryConfig::placeholder()) + ); + assert_eq!(schedule.validate_schedule(), Ok(())); + } + } + + /// Before a chain's scheduled activation a Satin run is a counterfactual; from it on, the run + /// takes the chain's schedule, and its limits are the chain's, not the default. + #[test] + fn test_a_real_satin_block_runs_under_the_chains_own_limits() { + let own = ProtocolLimits::DEFAULT + .with_tx_runtime_limits(EvmTxRuntimeLimits::default().with_tx_data_size_limit(350)); + let chain = scheduled() + .with_params(SequencerRegistryConfig::placeholder()) + .with_params(own); + + let before = schedule_for(chain.clone(), ACTIVATION - 1).unwrap(); + assert_eq!(before.protocol_limits(ACTIVATION - 1), Some(ProtocolLimits::DEFAULT)); + let from = schedule_for(chain, ACTIVATION).unwrap(); + assert_eq!(from.protocol_limits(ACTIVATION), Some(own)); + assert_eq!(from.spec_id(ACTIVATION - 1), None, "the chain's own activation holds"); + } + + /// A chain whose table schedules Satin without the limits is refused, not run on a default. + #[test] + fn test_a_real_satin_block_without_the_chains_limits_is_refused() { + let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()); + let error = schedule_for(chain, ACTIVATION).unwrap_err().to_string(); + assert!(error.contains("ProtocolLimits params are not configured"), "{error}"); + assert!(error.contains(&ACTIVATION.to_string()), "{error}"); + + let error = schedule_for(scheduled(), ACTIVATION).unwrap_err().to_string(); + assert!(error.contains("cannot run it"), "{error}"); + } +} diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index a085b460b..d27235a21 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -14,9 +14,8 @@ use mega_evm::{ primitives::eip4844, DatabaseRef, }, - system::SequencerRegistryConfig, BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, - MegaHardforkConfig, MegaHardforks, MegaSpecId, + MegaSpecId, }; use tracing::{debug, info, trace, warn}; @@ -25,9 +24,9 @@ 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, print_satin_report, BuildProviderOutput, - EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, ExternalEnvSnapshot, OpTxReceipt, - RpcCacheStore, SatinReport, TxOverrideArgs, + print_execution_trace, print_receipt, print_satin_report, satin_schedule, + BuildProviderOutput, EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, ExternalEnvSnapshot, + OpTxReceipt, RpcCacheStore, SatinReport, TxOverrideArgs, }, engine::Engine, run, EvmeState, @@ -405,7 +404,7 @@ impl Cmd { P: Provider + Clone + std::fmt::Debug, { let timestamp = ctx.block.header.timestamp(); - let hardforks = satin_hardforks(ctx.chain_id, timestamp); + let hardforks = satin_schedule(ctx.chain_id, timestamp)?; debug!(chain_id = ctx.chain_id, spec = %MegaSpecId::SATIN, "Chain configuration"); info!(fork_block = ctx.parent_block.header.number(), "Forking state from parent block",); @@ -429,9 +428,8 @@ impl Cmd { &hardforks, evm_factory, ); - // The limits a Satin block runs under when its node configures nothing else: the - // production data-size caps and gas detention's caps; the block's gas limit comes from - // its header. + // The block is held to the protocol limits its schedule carries, with no building + // policy, as a validator holds it; the block's gas limit comes from its header. let block_ctx = MegaBlockExecutionCtx::new( ctx.parent_block.hash(), ctx.block.header.parent_beacon_block_root(), @@ -602,24 +600,6 @@ impl Cmd { } } -/// The hardfork schedule a Satin replay of a block of `chain_id` at `timestamp` runs under. -/// -/// A block the chain's own schedule runs on Satin runs under that schedule. Any other block is a -/// counterfactual: it runs as if Satin were active from genesis, with the placeholder registry -/// parameters, which only a registry deployed from scratch reads; a chain whose registry is -/// already deployed keeps the roles in its storage. -pub(crate) fn satin_hardforks(chain_id: u64, timestamp: u64) -> MegaHardforkConfig { - let schedule = mega_evm::hardfork_schedule(chain_id); - if schedule.spec_id(timestamp) == Some(MegaSpecId::SATIN) && - schedule.fork_params::().is_some() - { - return schedule; - } - MegaHardforkConfig::new() - .with_all_activated() - .with_params(SequencerRegistryConfig::placeholder()) -} - /// Build a [`BlockEnv`] from the RPC block header. /// /// Reads `excess_blob_gas` directly from the header rather than using a diff --git a/bin/mega-evme/src/replay/mod.rs b/bin/mega-evme/src/replay/mod.rs index 57640ef83..5afe64fbb 100644 --- a/bin/mega-evme/src/replay/mod.rs +++ b/bin/mega-evme/src/replay/mod.rs @@ -5,7 +5,6 @@ mod cmd; -pub(crate) use cmd::satin_hardforks; pub use cmd::Cmd; // Re-export EvmeError and Result from common module From 2aca15eef047c67ae96ce2fcf25bdaf00c48a344 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:37:31 -0400 Subject: [PATCH 370/458] feat(evme): hold every Satin run to the limits of its schedule run and tx built a bare context, held to gas detention's caps alone; they now install the per-transaction limits of the schedule a Satin run of the chain executes under, as a node's EVM factory does and as the released tool held a run to its spec's limits. The block paths' EVM factory is given the same schedule, so an EVM carries the chain's limits from creation, not only once the executor installs them. --- bin/mega-evme/src/block/satin.rs | 2 +- bin/mega-evme/src/common/env.rs | 44 +++++++++++++++++++++++++++++--- bin/mega-evme/src/replay/cmd.rs | 4 ++- 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 6846f47a0..ba0e543b3 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -65,7 +65,7 @@ pub(super) fn execute( let factory = MegaBlockExecutorFactory::new( OpAlloyReceiptBuilder::default(), &hardforks, - MegaEvmFactory::new().with_external_env_factory(envs), + MegaEvmFactory::new().with_schedule(hardforks.clone()).with_external_env_factory(envs), ); let block_ctx = MegaBlockExecutionCtx::new( header.parent_hash, diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 880daac9a..0d03e782c 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -12,14 +12,14 @@ use mega_evm::{ context::{block::BlockEnv, cfg::CfgEnv}, primitives::eip4844, }, - AHashBucketHasher, MegaContext, MegaSpecId, TestExternalEnvs, + AHashBucketHasher, MegaContext, MegaHardforks, 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::{satin_schedule, EvmeError, Result}; /// Chain configuration arguments (spec and chain ID) #[derive(Args, Debug, Clone)] @@ -53,6 +53,15 @@ impl ChainArgs { debug!(cfg = ?cfg, "Evm CfgEnv created"); Ok(cfg) } + + /// The protocol limits a Satin run of this chain at `timestamp` is held to: those of the + /// schedule [`satin_schedule`] gives, which for a chain that does not run Satin at `timestamp` + /// is a counterfactual on [`ProtocolLimits::DEFAULT`]. + pub fn protocol_limits(&self, timestamp: u64) -> Result { + satin_schedule(self.chain_id, timestamp)?.protocol_limits(timestamp).ok_or_else(|| { + EvmeError::Other(format!("the Satin schedule carries no limits at {timestamp}")) + }) + } } /// Block environment configuration arguments @@ -190,6 +199,10 @@ impl EnvArgs { /// Creates a [`MegaContext`] with all environment configurations. /// + /// The transaction is held to the per-transaction limits a block of the chain at the block's + /// timestamp would hold it to ([`ChainArgs::protocol_limits`]), as a node's EVM factory holds + /// an EVM it builds outside block execution. + /// /// 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, @@ -201,10 +214,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_with_external_envs(db, cfg.spec, external_envs.into()) .with_cfg(cfg) - .with_block(block)) + .with_block(block) + .with_tx_runtime_limits(limits.tx_runtime_limits)) } } @@ -230,3 +246,25 @@ 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 the chain's per-transaction limits: on the tool's + /// default chain, which does not run Satin, the protocol's defaults, where a bare context + /// would hold it to gas detention's caps alone. + #[test] + fn test_a_satin_run_is_held_to_the_protocol_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(), ProtocolLimits::DEFAULT.tx_runtime_limits); + assert_ne!( + *MegaEvm::new(MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN)) + .tx_runtime_limits(), + ProtocolLimits::DEFAULT.tx_runtime_limits, + "a bare context does not hold the transaction data-size limit" + ); + } +} diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index d27235a21..e0156fba1 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -422,7 +422,9 @@ impl Cmd { 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 evm_factory = MegaEvmFactory::new() + .with_schedule(hardforks.clone()) + .with_external_env_factory(external_envs); let block_executor_factory = MegaBlockExecutorFactory::new( OpAlloyReceiptBuilder::default(), &hardforks, From 36996250d22d3946815f3f221e20a644303f0044 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:37:32 -0400 Subject: [PATCH 371/458] style(evme): format the schedule tests --- bin/mega-evme/src/common/schedule.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/mega-evme/src/common/schedule.rs b/bin/mega-evme/src/common/schedule.rs index 6d33a4b97..4f9132369 100644 --- a/bin/mega-evme/src/common/schedule.rs +++ b/bin/mega-evme/src/common/schedule.rs @@ -70,9 +70,8 @@ mod tests { fn test_a_real_satin_block_runs_under_the_chains_own_limits() { let own = ProtocolLimits::DEFAULT .with_tx_runtime_limits(EvmTxRuntimeLimits::default().with_tx_data_size_limit(350)); - let chain = scheduled() - .with_params(SequencerRegistryConfig::placeholder()) - .with_params(own); + let chain = + scheduled().with_params(SequencerRegistryConfig::placeholder()).with_params(own); let before = schedule_for(chain.clone(), ACTIVATION - 1).unwrap(); assert_eq!(before.protocol_limits(ACTIVATION - 1), Some(ProtocolLimits::DEFAULT)); From 67b4964a684ab55592acf8ec55cb8b8841675cce Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:49:14 -0400 Subject: [PATCH 372/458] feat(evme): run Satin under overridden protocol limits --override.limits on run, tx and replay takes a JSON object in the shape a chain configuration carries ProtocolLimits in, inline or from a file, and replaces the fields it names of the limits the run's schedule carries: a counterfactual, held to the same checks a chain configuration is. A legacy command or block is refused with it, since the legacy engine's limits are its spec's. --- bin/mega-evme/src/block/cmd.rs | 23 +++- bin/mega-evme/src/block/satin.rs | 10 +- bin/mega-evme/src/cmd.rs | 24 +++- bin/mega-evme/src/common/env.rs | 20 ++- bin/mega-evme/src/common/schedule.rs | 176 ++++++++++++++++++++++++--- bin/mega-evme/src/replay/cmd.rs | 20 ++- bin/mega-evme/tests/block_replay.rs | 74 ++++++++++- bin/mega-evme/tests/limits.rs | 135 ++++++++++++++++++++ bin/mega-evme/tests/replay_paths.rs | 24 +++- 9 files changed, 465 insertions(+), 41 deletions(-) create mode 100644 bin/mega-evme/tests/limits.rs diff --git a/bin/mega-evme/src/block/cmd.rs b/bin/mega-evme/src/block/cmd.rs index 94cd1a288..f5da150b5 100644 --- a/bin/mega-evme/src/block/cmd.rs +++ b/bin/mega-evme/src/block/cmd.rs @@ -12,7 +12,7 @@ use super::{ state::{BlockState, ParentStateRpc}, }; use crate::{ - common::{EvmeError, Result, RpcArgs}, + common::{EvmeError, LimitsOverride, Result, RpcArgs}, engine::Engine, }; @@ -107,6 +107,7 @@ pub async fn replay_blocks( 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() { @@ -134,8 +135,14 @@ pub async fn replay_blocks( 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, &mut state); + 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 { @@ -188,11 +195,15 @@ pub async fn replay_blocks( /// 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. 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)> { match engine { @@ -202,10 +213,16 @@ pub fn execute_block( &inputs.header, &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 => run_legacy_block(inputs, bucket_capacities, spec_override, state), } } diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index ba0e543b3..4f4762410 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -22,15 +22,16 @@ use super::{ state::{BlockState, SatinDb}, }; use crate::common::{ - decode_revert_reason, format_halt_reason, satin_schedule, EvmeError, EvmeExternalEnvs, Result, - SatinReport, + decode_revert_reason, format_halt_reason, 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 the protocol limits that schedule carries, with no building policy, and with the +/// — held to the protocol limits that schedule carries, or `limits_override` over them, with no +/// building policy, and with the /// block's gas limit from its header. A transaction the engine refuses is reported as refused and /// left out, and the block goes on. pub(super) fn execute( @@ -38,9 +39,10 @@ pub(super) fn execute( header: &HeaderFields, transactions: &[TxInput], bucket_capacities: &[(u32, u64)], + limits_override: Option<&LimitsOverride>, state: &mut BlockState, ) -> Result { - let hardforks = satin_schedule(chain_id, header.timestamp)?; + let hardforks = satin_schedule(chain_id, header.timestamp, limits_override)?; let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); cfg.chain_id = chain_id; let mut block_env = BlockEnv { diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index c78c180e0..71aafba5b 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -4,7 +4,7 @@ use clap::{parser::ValueSource, ArgMatches, CommandFactory, FromArgMatches, Pars use tracing::error; use crate::{ - common::{EvmeError, LogArgs}, + common::{EvmeError, LimitsOverride, LogArgs}, engine::Engine, }; @@ -67,6 +67,19 @@ pub async fn run_cli(args: Vec) -> Result<(), Error> { } }; 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() => { + eprintln!( + "{}", + EvmeError::InvalidInput( + "--override.limits applies to Satin only: the legacy engine holds a \ + transaction to its spec's own limits" + .to_string() + ) + ); + std::process::exit(1); + } Engine::Legacy => { if let Err(e) = crate::engine::run_legacy(args, spec_is_default).await { eprintln!("{e}"); @@ -96,6 +109,15 @@ impl Commands { Self::Replay(cmd) => cmd.engine().await, } } + + /// 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 { diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 0d03e782c..5dad058f8 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -19,7 +19,7 @@ use mega_evm::{ pub type EvmeExternalEnvs = TestExternalEnvs; use tracing::{debug, trace}; -use super::{satin_schedule, EvmeError, Result}; +use super::{parse_limits_override, satin_schedule, EvmeError, LimitsOverride, Result}; /// Chain configuration arguments (spec and chain ID) #[derive(Args, Debug, Clone)] @@ -35,6 +35,14 @@ pub struct ChainArgs { /// `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 chain's, a counterfactual. A + /// JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, + /// per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names + /// replace the chain's, every other stays. Refused when it names an unknown field or a value + /// no chain may carry + #[arg(long = "override.limits", value_name = "JSON|FILE", value_parser = parse_limits_override)] + pub limits_override: Option, } impl ChainArgs { @@ -56,11 +64,13 @@ impl ChainArgs { /// The protocol limits a Satin run of this chain at `timestamp` is held to: those of the /// schedule [`satin_schedule`] gives, which for a chain that does not run Satin at `timestamp` - /// is a counterfactual on [`ProtocolLimits::DEFAULT`]. + /// is a counterfactual on [`ProtocolLimits::DEFAULT`], with `--override.limits` over them. pub fn protocol_limits(&self, timestamp: u64) -> Result { - satin_schedule(self.chain_id, timestamp)?.protocol_limits(timestamp).ok_or_else(|| { - EvmeError::Other(format!("the Satin schedule carries no limits at {timestamp}")) - }) + satin_schedule(self.chain_id, timestamp, self.limits_override.as_ref())? + .protocol_limits(timestamp) + .ok_or_else(|| { + EvmeError::Other(format!("the Satin schedule carries no limits at {timestamp}")) + }) } } diff --git a/bin/mega-evme/src/common/schedule.rs b/bin/mega-evme/src/common/schedule.rs index 4f9132369..41cbd2783 100644 --- a/bin/mega-evme/src/common/schedule.rs +++ b/bin/mega-evme/src/common/schedule.rs @@ -1,6 +1,7 @@ //! The hardfork schedule a Satin run executes under, and so the protocol limits it is held to. -use mega_evm::{MegaHardforkConfig, MegaHardforks, MegaSpecId}; +use mega_evm::{HardforkParams, MegaHardforkConfig, MegaHardforks, MegaSpecId, ProtocolLimits}; +use serde_json::{Map, Value}; use super::{EvmeError, Result}; @@ -15,31 +16,101 @@ use super::{EvmeError, Result}; /// Any other run is a counterfactual and executes under the schedule the Satin engine gives a chain /// it does not know ([`mega_evm::all_activated_hardforks`]): Satin from genesis, placeholder /// registry parameters, which only a registry deployed from scratch reads (a chain whose registry -/// is already deployed keeps the roles in its storage), and -/// [`ProtocolLimits::DEFAULT`](mega_evm::ProtocolLimits::DEFAULT). -pub fn satin_schedule(chain_id: u64, timestamp: u64) -> Result { - schedule_for(mega_evm::hardfork_schedule(chain_id), timestamp) +/// is already deployed keeps the roles in its storage), and [`ProtocolLimits::DEFAULT`]. +/// +/// `limits_override` replaces the fields it names of the limits that schedule carries, a +/// counterfactual either way. +pub fn satin_schedule( + chain_id: u64, + timestamp: u64, + limits_override: Option<&LimitsOverride>, +) -> Result { + schedule_for(mega_evm::hardfork_schedule(chain_id), timestamp, limits_override) } /// [`satin_schedule`] for a chain whose schedule is `chain`. -fn schedule_for(chain: MegaHardforkConfig, timestamp: u64) -> Result { - if chain.spec_id(timestamp) != Some(MegaSpecId::SATIN) { - return Ok(mega_evm::all_activated_hardforks()); - } - chain.validate_schedule().map_err(|e| { +fn schedule_for( + chain: MegaHardforkConfig, + timestamp: u64, + limits_override: Option<&LimitsOverride>, +) -> Result { + let runs_satin = chain.spec_id(timestamp) == Some(MegaSpecId::SATIN); + let schedule = if runs_satin { chain } else { mega_evm::all_activated_hardforks() }; + let schedule = match limits_override { + Some(limits) => { + let limits = limits.apply(schedule.protocol_limits(timestamp))?; + schedule.with_params(limits) + } + None => schedule, + }; + schedule.validate_schedule().map_err(|e| { EvmeError::InvalidInput(format!( "the chain's schedule runs Satin at timestamp {timestamp} but cannot run it: {e}" )) })?; - Ok(chain) + Ok(schedule) +} + +/// Protocol limits to run under in place of the chain's (`--override.limits`): a JSON object in +/// the shape a chain configuration carries [`ProtocolLimits`] in, 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. With no `base` + /// the override must name every field. + /// + /// The result is refused when it names a field [`ProtocolLimits`] does not have, lacks one, or + /// is a value no chain may carry ([`HardforkParams::validate`]). + pub fn apply(&self, base: Option) -> Result { + let invalid = + |message: String| EvmeError::InvalidInput(format!("--override.limits: {message}")); + let mut merged = match base { + Some(base) => serde_json::to_value(base).expect("limits serialize"), + None => Value::Object(Map::new()), + }; + merge(&mut merged, &self.0); + let limits: ProtocolLimits = + serde_json::from_value(merged).map_err(|e| invalid(e.to_string()))?; + limits.validate().map_err(|e| invalid(e.message))?; + Ok(limits) + } +} + +/// 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::{ - system::SequencerRegistryConfig, ChainActivation, EvmTxRuntimeLimits, ProtocolLimits, - MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, + system::SequencerRegistryConfig, ChainActivation, EvmTxRuntimeLimits, MAINNET_CHAIN_ID, + TESTNET_CHAIN_ID, }; const ACTIVATION: u64 = 1_800_000_000; @@ -53,7 +124,7 @@ mod tests { #[test] fn test_a_counterfactual_runs_on_the_engines_fallback_schedule() { for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, 6342, 1] { - let schedule = satin_schedule(chain_id, 1_700_000_000).unwrap(); + let schedule = satin_schedule(chain_id, 1_700_000_000, None).unwrap(); assert_eq!(schedule.spec_id(0), Some(MegaSpecId::SATIN), "chain {chain_id}"); assert_eq!(schedule.protocol_limits(0), Some(ProtocolLimits::DEFAULT)); assert_eq!( @@ -73,9 +144,9 @@ mod tests { let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()).with_params(own); - let before = schedule_for(chain.clone(), ACTIVATION - 1).unwrap(); + let before = schedule_for(chain.clone(), ACTIVATION - 1, None).unwrap(); assert_eq!(before.protocol_limits(ACTIVATION - 1), Some(ProtocolLimits::DEFAULT)); - let from = schedule_for(chain, ACTIVATION).unwrap(); + let from = schedule_for(chain, ACTIVATION, None).unwrap(); assert_eq!(from.protocol_limits(ACTIVATION), Some(own)); assert_eq!(from.spec_id(ACTIVATION - 1), None, "the chain's own activation holds"); } @@ -84,11 +155,80 @@ mod tests { #[test] fn test_a_real_satin_block_without_the_chains_limits_is_refused() { let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()); - let error = schedule_for(chain, ACTIVATION).unwrap_err().to_string(); + let error = schedule_for(chain, ACTIVATION, None).unwrap_err().to_string(); assert!(error.contains("ProtocolLimits params are not configured"), "{error}"); assert!(error.contains(&ACTIVATION.to_string()), "{error}"); - let error = schedule_for(scheduled(), ACTIVATION).unwrap_err().to_string(); + let error = schedule_for(scheduled(), ACTIVATION, None).unwrap_err().to_string(); assert!(error.contains("cannot run it"), "{error}"); } + + fn overriding(json: &str) -> LimitsOverride { + parse_limits_override(json).unwrap() + } + + /// An override replaces the fields it names and keeps every other one the schedule carries. + #[test] + fn test_an_override_replaces_only_the_fields_it_names() { + let schedule = satin_schedule( + MAINNET_CHAIN_ID, + 0, + Some(&overriding( + r#"{"txRuntimeLimits":{"txDataSizeLimit":350},"blockKvUpdateLimit":7}"#, + )), + ) + .unwrap(); + let expected = ProtocolLimits::DEFAULT + .with_tx_runtime_limits( + ProtocolLimits::DEFAULT.tx_runtime_limits.with_tx_data_size_limit(350), + ) + .with_block_kv_update_limit(7); + assert_eq!(schedule.protocol_limits(0), Some(expected)); + } + + /// An override applies to a chain's own Satin schedule too, and there it replaces the chain's + /// limits; a chain whose table carries none needs the override to name every field. + #[test] + fn test_an_override_supplies_limits_a_chain_does_not_carry() { + let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()); + let partial = overriding(r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#); + let error = schedule_for(chain.clone(), ACTIVATION, Some(&partial)).unwrap_err(); + assert!(error.to_string().contains("missing field"), "{error}"); + + let loosest = serde_json::to_string(&ProtocolLimits::loosest()).unwrap(); + let schedule = schedule_for(chain, ACTIVATION, Some(&overriding(&loosest))).unwrap(); + assert_eq!(schedule.protocol_limits(ACTIVATION), Some(ProtocolLimits::loosest())); + } + + /// An override is held to what a chain configuration is: no unknown field, no value the + /// limits' own check refuses. + #[test] + fn test_an_override_no_chain_may_carry_is_refused() { + let refused = |json: &str| { + satin_schedule(MAINNET_CHAIN_ID, 0, Some(&overriding(json))).unwrap_err().to_string() + }; + let unknown = refused(r#"{"txDataSizeLimit":350}"#); + assert!(unknown.contains("unknown field `txDataSizeLimit`"), "{unknown}"); + let zero = refused(r#"{"txRuntimeLimits":{"txKvUpdateLimit":0}}"#); + assert!(zero.contains("tx_kv_update_limit must not be zero"), "{zero}"); + let uncapped = + refused(r#"{"txRuntimeLimits":{"oracleAccessComputeGasLimit":18446744073709551615}}"#); + assert!(uncapped.contains("oracle_access_compute_gas_limit"), "{uncapped}"); + let not_a_number = refused(r#"{"blockTxsDataLimit":"1"}"#); + assert!(not_a_number.starts_with("Invalid input: --override.limits:"), "{not_a_number}"); + } + + /// 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#" {"blockKvUpdateLimit": 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/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index e0156fba1..bc91c5666 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -23,10 +23,11 @@ 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, print_satin_report, satin_schedule, - BuildProviderOutput, EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, ExternalEnvSnapshot, - OpTxReceipt, RpcCacheStore, SatinReport, TxOverrideArgs, + op_receipt_to_tx_receipt, parse_bucket_capacity, parse_limits_override, + print_execution_summary, print_execution_trace, print_receipt, print_satin_report, + satin_schedule, BuildProviderOutput, EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, + ExternalEnvSnapshot, LimitsOverride, OpTxReceipt, RpcCacheStore, SatinReport, + TxOverrideArgs, }, engine::Engine, run, EvmeState, @@ -66,6 +67,14 @@ pub struct Cmd { #[arg(long = "override.spec", value_name = "SPEC")] pub spec_override: Option, + /// Satin only: replay under these protocol limits instead of the chain's, a counterfactual. A + /// JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, + /// per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names + /// replace the chain's, every other stays. Refused when it names an unknown field or a value + /// no chain may carry, 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, @@ -175,6 +184,7 @@ impl Cmd { &self.rpc_args, &bucket_capacities, self.spec_override.as_deref(), + self.limits_override.as_ref(), self.output_args.json, ) .await?; @@ -404,7 +414,7 @@ impl Cmd { P: Provider + Clone + std::fmt::Debug, { let timestamp = ctx.block.header.timestamp(); - let hardforks = satin_schedule(ctx.chain_id, timestamp)?; + let hardforks = satin_schedule(ctx.chain_id, timestamp, self.limits_override.as_ref())?; debug!(chain_id = ctx.chain_id, spec = %MegaSpecId::SATIN, "Chain configuration"); info!(fork_block = ctx.parent_block.header.number(), "Forking state from parent block",); diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 0fde00db9..b43cac295 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -6,11 +6,12 @@ mod common; use std::path::Path; -use alloy_primitives::{B256, U256}; +use alloy_primitives::{Address, B256, U256}; use common::blocks::{ block_path, cache_copy, cache_copy_with_absent_factory, code_of, fixtures, read_block, run_evme, write_block, BLOCKS, FACTORY, }; +use mega_evm::{system::MEGA_SYSTEM_ADDRESS, ProtocolLimits}; use mega_evme::block::PreAccount; use serde_json::Value; @@ -218,3 +219,74 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 0); assert!(read_block(cache.path(), number).prestate.accounts.contains_key(&FACTORY)); } + +/// `--override.limits` replays a Satin block under other protocol limits: the fields it names +/// replace the chain's, and every other stays. At the protocol's defaults it changes nothing; a +/// transaction data-size limit of the body alone stops every transaction but the protocol's own, +/// which no per-transaction limit holds; 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_with_absent_factory(); + 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, _) = replay_under(None); + let defaults = serde_json::to_string(&ProtocolLimits::DEFAULT).unwrap(); + assert_eq!(replay_under(Some(&defaults)).0, counterfactual, "it runs on the defaults"); + 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 (stopped, _) = replay_under(Some(r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#)); + let (mut protocols, mut others) = (0, 0); + for (tx, sent) in stopped.iter().zip(sent) { + let stop = &tx["satin"]["limit_exceeded"]; + let from: Address = sent["from"].as_str().unwrap().parse().unwrap(); + if from == MEGA_SYSTEM_ADDRESS { + protocols += 1; + assert!( + stop.is_null(), + "the protocol's transaction {} is held to no limit", + tx["index"] + ); + assert!(tx["satin"]["data_size"].as_u64().unwrap() > 310); + } else { + others += 1; + assert_eq!(stop["kind"], "data_size", "{tx}"); + assert_eq!(stop["limit"], 310, "{tx}"); + assert_eq!(stop["used"], tx["satin"]["data_size"], "{tx}"); + } + } + assert!(protocols > 0 && others > 0, "{protocols} {others}"); + + let (packed, block) = replay_under(Some(r#"{"blockTxsDataLimit":1}"#)); + assert_eq!(block["refused"], block["transactions"].as_u64().unwrap() - 1); + assert_eq!(packed[0], counterfactual[0], "the transaction that reaches the budget is packed"); + for tx in &packed[1..] { + 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}"); +} diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs new file mode 100644 index 000000000..05b5c28a3 --- /dev/null +++ b/bin/mega-evme/tests/limits.rs @@ -0,0 +1,135 @@ +//! `--override.limits` on `run` and `tx`: a Satin transaction held to protocol limits other than +//! the chain's, the fields the override names replacing the chain's and every other staying. + +use std::process::Command; + +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"; + +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() +} + +/// Without an override the run keeps both writes; an override of the transaction data size or of +/// its write records stops it at the second write, and takes both back. +#[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); + + 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"); + + let records = run_two_writes(Some(r#"{"txRuntimeLimits":{"txKvUpdateLimit":1}}"#)); + assert_eq!( + records["satin"]["limit_exceeded"], + json!({ "kind": "kv_update", "limit": 1, "used": 2 }) + ); +} + +/// 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 stopped +/// before it runs. +#[test] +fn test_an_override_holds_a_satin_tx_to_other_limits() { + let args = ["tx", "--spec", "Satin", "--input", "0x00", "--json", "--override.limits"]; + let output = evme(&[&args[..], &[r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#]].concat()); + let stopped = output.json(); + assert_eq!(stopped["success"], false); + assert_eq!( + stopped["satin"]["limit_exceeded"], + json!({ "kind": "data_size", "limit": 310, "used": 311 }) + ); +} + +/// An override is held to what a chain configuration is: an unknown field, a value of the wrong +/// type or one the limits' own check refuses is an error, with nothing on stdout. +#[test] +fn test_an_override_no_chain_may_carry_is_refused() { + let refused = |limits: &str, code: i32, message: &str| { + let output = + evme(&["run", "0x00", "--spec", "Satin", "--json", "--override.limits", 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#"{"txRuntimeLimits":{"txKvUpdateLimit":0}}"#, + 1, + "tx_runtime_limits.tx_kv_update_limit must not be zero", + ); + refused(r#"{"blockTxsDataLimit":"1"}"#, 1, "--override.limits: invalid type"); + refused("[1]", 2, "must be a JSON object"); +} + +/// 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. +#[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", "{}"], + ] { + 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 + ); + } +} diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index 1c83462d2..a26ba3f04 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -141,14 +141,17 @@ impl Server { } } -/// The block replay's transaction records, on `spec`'s engine. -fn block_rows(spec: Option<&str>) -> Vec { +/// 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_with_absent_factory(); 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() @@ -170,8 +173,16 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { let server = Server::start(recorded).await; let uri = server.0.uri(); - for (spec, engine) in [(None, "legacy"), (Some("Satin"), "satin")] { - let rows = block_rows(spec); + // The last leg holds both paths to a transaction data-size limit of the body alone, which + // stops every transaction but the protocol's own. + let stopping = r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#; + let mut stops = 0; + for (spec, engine, limits) in [ + (None, "legacy", None), + (Some("Satin"), "satin", None), + (Some("Satin"), "satin", Some(stopping)), + ] { + let rows = block_rows(spec, limits); for index in checked(&rows) { let row = &rows[index]; let mut args = vec!["replay", row["hash"].as_str().unwrap(), "--rpc", &uri]; @@ -179,6 +190,10 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { if let Some(spec) = spec { args.extend(["--override.spec", spec]); } + if let Some(limits) = limits { + args.extend(["--override.limits", limits]); + stops += usize::from(!row["satin"]["limit_exceeded"].is_null()); + } let run = run_evme(&args); assert_eq!(run.code, 0, "{engine} tx {index}: {}{}", run.stderr, run.stdout); let single: Value = serde_json::from_str(&run.stdout).unwrap(); @@ -198,4 +213,5 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { } } } + assert!(stops > 0, "the limits leg checks a stopped transaction"); } From f23d8df07c7b24439208167ff3a1483071834cf2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:52:54 -0400 Subject: [PATCH 373/458] docs(evme): document the protocol limits a Satin run is held to The chain-and-spec page states where a Satin run's limits come from (the chain's schedule, or Satin's defaults for a counterfactual), the defaults, the refusal of a chain schedule that carries none, and the --override.limits object; the command pages, the crate README and the agent notes name the flag and the one place the schedule is chosen. --- AGENTS.md | 2 +- bin/mega-evme/AGENTS.md | 5 +- bin/mega-evme/README.md | 3 + docs/mega-evme/commands/replay.md | 14 ++++- docs/mega-evme/commands/run.md | 5 +- docs/mega-evme/commands/tx.md | 3 +- .../mega-evme/configuration/chain-and-spec.md | 58 +++++++++++++++++-- 7 files changed, 80 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0aa8439dc..1c177631d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -189,7 +189,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/protocol_limits.rs`). The executor checks the limits again (`validate()`) and refuses a block under limits the check refuses (`InvalidProtocolLimits`, internal), whatever the schedule's type: a node's own schedule type attaches its params without `with_params`, and `validate_schedule` runs only when the node calls it. Tests that run blocks without holding them to a limit attach `ProtocolLimits::loosest()`, the loosest limits a chain may carry (every limit unlimited, detention's caps at `MAX_TX_COMPUTE_GAS - 1`); `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`, builds a schedule carrying a value no chain may carry, to test what refuses it. - An EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) runs under the limits block execution would hold its block to without being told: the factory given the chain's schedule (`with_schedule`) resolves them at the block's timestamp, and without one, or where the schedule carries no valid limits there, installs `ProtocolLimits::DEFAULT`'s; `MegaEvmFactory::with_tx_runtime_limits` is the explicit opt-out for equivalence and tests, and a `MegaContext` built by hand (the state-test runner) gets its limits from its caller through `with_tx_runtime_limits`. + An EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) runs under the limits block execution would hold its block to without being told: the factory given the chain's schedule (`with_schedule`) resolves them at the block's timestamp, and without one, or where the schedule carries no valid limits there, installs `ProtocolLimits::DEFAULT`'s; `MegaEvmFactory::with_tx_runtime_limits` is the explicit opt-out for equivalence and tests, and a `MegaContext` built by hand gets its limits from its caller through `with_tx_runtime_limits`: the state-test runner's own, and `mega-evme`'s `run` and `tx`, those of the schedule the tool runs Satin under (the chain's, or for a counterfactual the engine's fallback, `all_activated_hardforks()`, on `ProtocolLimits::DEFAULT`). - 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 sticky `LimitCheck::Exempt` (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`): no data-size, KV or state-gas limit and no frame budget stops them, and they are never latched. 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. diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 5cb2c38b6..54b5e9d28 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -8,7 +8,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - `src/main.rs`: CLI bootstrap and panic hook. - `src/cmd.rs`: argument parsing, engine selection, and dispatch; a legacy spec's arguments are handed unchanged to the 1.7.1 CLI. - `src/engine.rs`: which engine a spec or a block runs on; the hand-off to the legacy CLI. -- `src/common/`: shared CLI args, state loading, tracing, tx parsing, output printers. +- `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 (Satin; a legacy spec is the 1.7.1 CLI's). @@ -27,6 +27,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` ## 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 use `cargo ... -p mega-evme`: the name also matches the linked 1.7.1 package. Use `--manifest-path bin/mega-evme/Cargo.toml`. +- Do not build a Satin hardfork schedule, or attach its params, in the CLI: a counterfactual takes the engine's own schedule for a chain it does not know (`mega_evm::all_activated_hardforks`), so it carries every params type Satin requires, and a chain's own Satin schedule is used as it is or refused. - 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. @@ -37,5 +38,5 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - Add a new top-level command: `src/cmd.rs` enum + module wiring in `src/main.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`. - Change receipt/summary formatting: `src/common/outcome.rs` and printer helpers. diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index ce40d5654..c44a2bcaa 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -33,6 +33,9 @@ Every command runs on the engine its spec names. 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`). `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 the protocol limits of the chain's schedule at the block's timestamp; a chain that does not run Satin there (mainnet and testnet today, the default chain, any chain the tool does not know) runs on Satin's default limits, a counterfactual. +`--override.limits ` on `run`, `tx` and `replay` replaces the fields it names of those limits; it is refused on a legacy spec. + The legacy leg is the default feature `legacy`; `--no-default-features` builds a Satin-only binary. ## Installation diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index d3b041a2e..665be5c36 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -175,6 +175,18 @@ mega-evme replay --override.spec Satin A Satin replay needs a state whose system contracts are at the versions Satin deploys, which MegaETH mainnet and testnet reach at `Rex6`. On an older block Satin's own deploy check refuses to overwrite them, and the replay fails with an error naming the contract. +### `--override.limits ` + +Replay on Satin under other protocol limits than the chain's, a counterfactual: the fields the JSON object names replace the chain's, and every other stays. +Without it, a Satin replay of a block its chain does not run on Satin runs on Satin's default limits. +The object's shape, the defaults 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. + +``` +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`. @@ -228,7 +240,7 @@ The exit code is 0, 1 when a block could not be replayed, or 2 when `--verify` i ### 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 the limits a Satin block runs under by default. +`--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 default 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. Satin's pre-block changes deploy the EIP-7997 factory at `0x4e59b44847b379578588920cA78FbF26c0B4956C`, which no legacy spec reads, so a block cached from a legacy replay does not hold it; the first Satin replay of the block reads it over RPC and adds it to the cache. diff --git a/docs/mega-evme/commands/run.md b/docs/mega-evme/commands/run.md index 0b2700a80..efe2be5ef 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) | @@ -335,6 +335,9 @@ Chain Options: --chain-id Chain ID [default: 6342] [aliases: --chainid] + --override.limits + Satin only: run under these protocol limits instead of the chain's, a counterfactual. A JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names replace the chain's, every other stays. Refused when it names an unknown field or a value no chain may carry + 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 3add30594..333dbb068 100644 --- a/docs/mega-evme/commands/tx.md +++ b/docs/mega-evme/commands/tx.md @@ -67,7 +67,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) | @@ -215,6 +215,7 @@ RPC Options: Chain Options: --spec Spec: `Satin`, or a legacy spec `Equivalence` to `Rex6` [default: Rex6] --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 d2a8308ed..7d46c6a64 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -10,10 +10,11 @@ The `replay` command auto-detects the spec from the chain ID and block timestamp ## Options -| Flag | Default | Aliases | Description | -| ----------------- | ------- | ----------- | ------------------- | -| `--spec ` | `Rex6` | — | MegaETH spec to use | -| `--chain-id ` | `6342` | `--chainid` | Chain ID | +| Flag | Default | Aliases | Description | +| -------------------------------- | ----------- | ----------- | ----------------------------------------------------------------------------------------- | +| `--spec ` | `Rex6` | — | MegaETH spec to use | +| `--chain-id ` | `6342` | `--chainid` | Chain ID | +| `--override.limits ` | the chain's | — | Satin only: protocol limits to run under instead, see [Protocol limits](#protocol-limits) | ## Available Specs @@ -66,6 +67,52 @@ On Satin, every output field keeps its legacy name and meaning, and one field is 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 the protocol limits of the chain it names, read from the chain's schedule at the block's timestamp, as a node holds a block of that chain. +On a chain whose schedule runs Satin at that timestamp, these are the chain's own limits. +Any other Satin run is a counterfactual: MegaETH mainnet and testnet, which do not schedule Satin yet, the default chain `6342`, and any chain the tool does not know run on Satin's default limits. + +| Limit | Default | +| ------------------------------------------------------------------------ | ---------- | +| 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 | +| Every other limit | unlimited | + +The defaults are provisional, as Satin is. +A chain whose schedule runs Satin but does not carry its limits is refused: the tool does not guess a chain's limits. +`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 shape a chain configuration carries the limits in, inline or as the path of a file. +The fields it names replace the chain's, and every other stays. +The whole shape, at the defaults: + +```json +{ + "txRuntimeLimits": { + "txDataSizeLimit": 13107200, + "frameDataSizeLimit": 18446744073709551615, + "txKvUpdateLimit": 18446744073709551615, + "frameKvUpdateLimit": 18446744073709551615, + "txStateGasLimit": 18446744073709551615, + "blockEnvAccessComputeGasLimit": 20000000, + "oracleAccessComputeGasLimit": 20000000 + }, + "blockExecutionGasLimit": 18446744073709551615, + "blockStateGasLimit": 18446744073709551615, + "blockTxsDataLimit": 13107200, + "blockKvUpdateLimit": 18446744073709551615 +} +``` + +`18446744073709551615` (`u64::MAX`) leaves a limit unlimited. +The limits an override leaves are held to what a chain configuration is: an unknown field, a zero limit, a transaction data-size limit below the 310 bytes every transaction's body counts, or a compute cap no transaction reaches is refused. +A transaction a limit stops reports it in `satin.limit_exceeded`. +A command on a legacy spec is refused with `--override.limits`: the legacy engine's limits are its spec's. + ## Examples ```bash @@ -80,4 +127,7 @@ 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 one write record +mega-evme run 0x600160005260... --spec Satin --override.limits '{"txRuntimeLimits":{"txKvUpdateLimit":1}}' ``` From 21b46c4b9a5189c53edfb2fcd9efa08cfe98a304 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:59:44 -0400 Subject: [PATCH 374/458] test(evme): refuse the limits override on a legacy transaction replay --- bin/mega-evme/tests/limits.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs index 05b5c28a3..5bd76aa58 100644 --- a/bin/mega-evme/tests/limits.rs +++ b/bin/mega-evme/tests/limits.rs @@ -115,13 +115,22 @@ fn test_an_override_no_chain_may_carry_is_refused() { } /// 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. +/// 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); From 6faeaa29f6ab0e81dfd3d45d5f0d997802101c20 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 03:59:54 -0400 Subject: [PATCH 375/458] style(evme): rewrap the Satin block executor's doc comment --- bin/mega-evme/src/block/satin.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 4f4762410..06ca1ea90 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -31,9 +31,8 @@ use crate::common::{ /// 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 the protocol limits that schedule carries, or `limits_override` over them, with no -/// building policy, and with the -/// block's gas limit from its header. A transaction the engine refuses is reported as refused and -/// left out, and the block goes on. +/// building policy, and with the block's gas limit from its header. 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, From c0bb351c3e063c649993f23522b5064cec392a32 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:20:57 -0400 Subject: [PATCH 376/458] test(block): size the refused-limits block's transaction at the byte prices in effect --- crates/mega-evm/tests/block/schedule.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index 2f52302fc..e34c1ddd5 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -188,8 +188,9 @@ fn test_limits_the_check_refuses_run_no_block() { let error = executor.apply_pre_execution_changes().expect_err("the block does not start"); assert_eq!(internal(&error), &refusal); assert!(executor.evm().db().bundle_state.state.is_empty(), "no pre-block step ran"); - let error = - executor.execute_transaction(&user_tx(0, 100_000)).expect_err("no transaction runs either"); + let error = executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("no transaction runs either"); assert_eq!(internal(&error), &refusal); assert!(executor.receipts().is_empty()); let Err(error) = executor.finish() else { panic!("nor is the block finished") }; @@ -208,5 +209,5 @@ fn test_limits_the_check_refuses_run_no_block() { ); assert_eq!(executor.protocol_limits(), Some(&ProtocolLimits::DEFAULT)); 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"); } From 90d3134b52942b9608cea2b239c72442453b8993 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:21:46 -0400 Subject: [PATCH 377/458] test(evm): size the factory's limit-stop call at the byte prices in effect --- crates/mega-evm/src/evm/factory.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index be9d62faa..ba3c51c0d 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -295,10 +295,15 @@ 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() })) } @@ -419,7 +424,15 @@ mod tests { #[test] fn test_an_evm_from_the_factory_stops_what_the_chain_stops() { 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( @@ -432,7 +445,8 @@ mod tests { ); let block_env = BlockEnv { timestamp: U256::from(SATIN_AT), ..evm_env().block_env }; let mut evm = factory.create_evm(db, EvmEnv { cfg_env: evm_env().cfg_env, block_env }); - evm.execute_transaction(call(WRITER)).expect("the call is valid") + evm.execute_transaction(call_with_gas_limit(WRITER, gas_limit)) + .expect("the call is valid") }; let stopped = run(&MegaEvmFactory::new().with_schedule(chain(chain_limits()))); From 45635ed328a0cdc2e38eee7ad363186363487d98 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:22:28 -0400 Subject: [PATCH 378/458] test(satin): skip the first frame's upfront-hold cases where a state byte is free --- .../mega-evm/tests/satin/state_gas_limit.rs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index 178bef875..c76c759dc 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -11,7 +11,8 @@ //! The figures are read off the engine rather than written out: each case first runs without a //! limit, and the state gas it reports is what the limit is set against. Where a state byte costs //! nothing, which only a measurement build arranges, no transaction adds state gas and the limit -//! has nothing to hold, so the cases that need a crossing return early. +//! has nothing to hold, so the cases that need a crossing, or an upfront charge to give back, +//! return early. use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ @@ -535,6 +536,11 @@ fn one_wei_to(to: Address, data: &[u8]) -> MegaTransaction { /// does without a limit, and nothing moves. #[test] fn test_a_first_frame_revm_answers_with_a_failure_is_not_held_for_its_upfront_charge() { + // Where a state byte is free the start is charged nothing for the account, and there is no + // charge to give back. + if state_is_free() { + return; + } let account = one_account(); let tx = one_wei_to(BN254_PAIRING, &[1]); let free = run_under(funded(), tx.clone(), u64::MAX); @@ -561,6 +567,11 @@ fn test_a_first_frame_revm_answers_with_a_failure_is_not_held_for_its_upfront_ch /// stays spent. A creation transaction keeps its creator's nonce bump, so it cannot be replayed. #[test] fn test_a_first_frame_revm_decides_is_held_for_its_upfront_charge() { + // Where a state byte is free the start is charged nothing for the account, and there is no + // charge to hold. + if state_is_free() { + return; + } let account = one_account(); let word = [7_u8; 32]; let cases = [ @@ -604,6 +615,11 @@ fn test_a_first_frame_revm_decides_is_held_for_its_upfront_charge() { /// the state-gas limit its upfront charge would have crossed is not what stops it. #[test] fn test_a_first_frame_start_whose_records_cross_is_stopped_for_its_records() { + // Where a state byte is free the start is charged nothing for the account, and there is no + // state-gas crossing for the records' stop to come before. + if state_is_free() { + return; + } let account = one_account(); let limit = TX_BODY_SIZE + WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; let outcome = MegaEvm::new( @@ -652,6 +668,11 @@ impl Inspector, EthInterpreter> for AnswersEmpty { /// transaction keeps the inspector's answer. #[test] fn test_a_first_frame_an_inspector_answers_is_not_held_for_its_upfront_charge() { + // Where a state byte is free the start is charged nothing for the account, and there is no + // charge to give back. + if state_is_free() { + return; + } let account = one_account(); let mut evm = MegaEvm::new(context(funded()).with_tx_runtime_limits( EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), From 7ef08707926a6cdea96fe93f833b71ccaaeea06f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:40:37 -0400 Subject: [PATCH 379/458] fix(evme): put a legacy command's default spec before its options separator --- bin/mega-evme/AGENTS.md | 2 +- bin/mega-evme/src/cmd.rs | 1 + bin/mega-evme/src/engine.rs | 45 ++++++++++++++++++++++++++---- bin/mega-evme/tests/integration.rs | 36 ++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 54b5e9d28..e7d01d82c 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -6,7 +6,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` ## STRUCTURE - `src/main.rs`: CLI bootstrap and panic hook. -- `src/cmd.rs`: argument parsing, engine selection, and dispatch; a legacy spec's arguments are handed unchanged to the 1.7.1 CLI. +- `src/cmd.rs`: argument parsing, engine selection, and dispatch; a legacy spec's arguments are handed unchanged to the 1.7.1 CLI, but for `--spec Rex6` added, before any `--`, to a `run` or `tx` that left `--spec` out (the 1.7.1 default is `Rex7`). - `src/engine.rs`: which engine a spec or a block runs on; the hand-off to the legacy CLI. - `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. diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index 71aafba5b..862f52625 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -49,6 +49,7 @@ pub enum Error { /// /// 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); diff --git a/bin/mega-evme/src/engine.rs b/bin/mega-evme/src/engine.rs index 6730368af..57c25572c 100644 --- a/bin/mega-evme/src/engine.rs +++ b/bin/mega-evme/src/engine.rs @@ -86,15 +86,14 @@ impl Engine { /// Runs `args` on the released 1.7.1 CLI. /// -/// `append_default_spec` appends `--spec Rex6` for a `run` or `tx` whose `--spec` was left out: +/// `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, append_default_spec: bool) -> Result<()> { +pub async fn run_legacy(mut args: Vec, add_default_spec: bool) -> Result<()> { use clap::Parser; - if append_default_spec { - args.push("--spec".into()); - args.push(DEFAULT_SPEC.into()); + if add_default_spec { + args = with_default_spec(args); } if let Err(e) = mega_evme_legacy::cmd::MainCmd::parse_from(args).run().await { // What the 1.7.1 binary's `main` does with an error its command returns: print it to @@ -106,9 +105,22 @@ pub async fn run_legacy(mut args: Vec, append_default_spec: bool) -> R 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, _append_default_spec: bool) -> Result<()> { +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" @@ -130,6 +142,27 @@ mod tests { 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(); diff --git a/bin/mega-evme/tests/integration.rs b/bin/mega-evme/tests/integration.rs index 0d98e4929..b02d5d770 100644 --- a/bin/mega-evme/tests/integration.rs +++ b/bin/mega-evme/tests/integration.rs @@ -165,3 +165,39 @@ fn test_errors_print_as_their_engine_prints_them() { ["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); +} From 98569b67156c371ff6ea429649c59e22ea0eb1e1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:42:21 -0400 Subject: [PATCH 380/458] docs: select the mega-evme tool by its manifest path --- README.md | 2 +- bench/replay/README.md | 3 ++- bin/mega-evme/tests/state.rs | 6 ++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 79226176b..39329cab0 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,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/bench/replay/README.md b/bench/replay/README.md index 739fbdc90..9f811d1a2 100644 --- a/bench/replay/README.md +++ b/bench/replay/README.md @@ -77,7 +77,8 @@ 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 +cargo build --release --manifest-path bin/mega-evme/Cargo.toml +cargo build --release -p state-test # Measure the current build: python3 bench/replay/run.py --bin pr=target/release diff --git a/bin/mega-evme/tests/state.rs b/bin/mega-evme/tests/state.rs index 76c2b3768..8fa5a2e55 100644 --- a/bin/mega-evme/tests/state.rs +++ b/bin/mega-evme/tests/state.rs @@ -176,7 +176,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 @@ -247,7 +248,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"] From 45e0be343855be724e037f5a63ee6a108d082a30 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 04:53:36 -0400 Subject: [PATCH 381/458] fix(evme): pin the legacy leg's precompile and encoding backends --- AGENTS.md | 2 +- Cargo.lock | 4 +- bin/mega-evme/AGENTS.md | 1 + bin/mega-evme/tests/legacy_line.rs | 87 +++++++++++++++++++++++++++--- 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index daebe41db..53735cd03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,7 +79,7 @@ Git submodules are required — clone with `--recursive` or run `git submodule u `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 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. `mega-t8n` still targets the legacy engine. It is outside `[workspace] members`, so no workspace command builds it; do not edit its sources until it is ported to Satin. diff --git a/Cargo.lock b/Cargo.lock index 3855e69de..966e63818 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1723,9 +1723,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", diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index e7d01d82c..33fa91221 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -26,6 +26,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` ## 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`. - Do not build a Satin hardfork schedule, or attach its params, in the CLI: a counterfactual takes the engine's own schedule for a chain it does not know (`mega_evm::all_activated_hardforks`), so it carries every params type Satin requires, and a chain's own Satin schedule is used as it is or refused. - Do not duplicate chain/spec parsing logic across commands. diff --git a/bin/mega-evme/tests/legacy_line.rs b/bin/mega-evme/tests/legacy_line.rs index 22ae71426..21304a80c 100644 --- a/bin/mega-evme/tests/legacy_line.rs +++ b/bin/mega-evme/tests/legacy_line.rs @@ -4,6 +4,12 @@ //! 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"); @@ -46,6 +52,56 @@ const LEGACY_LINE: &[(&str, &str)] = &[ ("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)`. alloy 2.4 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`. @@ -76,16 +132,21 @@ fn compatibility_line(version: &str) -> &str { } } +/// 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 line = compatibility_line(pinned); - let versions: Vec<&str> = locked - .iter() - .filter(|(n, v)| *n == name && compatibility_line(v) == line) - .map(|(_, v)| *v) - .collect(); + let versions = locked_on_the_line_of(&locked, name, pinned); assert_eq!( versions, [pinned], @@ -94,6 +155,20 @@ fn test_the_legacy_line_is_at_its_released_versions() { } } +#[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\ From 75fb7559f43bcd179518008de4d7d04348035268 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:13:14 -0400 Subject: [PATCH 382/458] test: derive the cannot-pay premises from the byte prices in effect --- crates/mega-evm/tests/satin/data_size.rs | 10 ++++--- crates/mega-evm/tests/satin/salt_refund.rs | 26 +++++++++++++++---- crates/mega-evm/tests/satin/system_call.rs | 18 ++++++++----- .../tests/system/keyless/precedence.rs | 7 +++-- crates/mega-evm/tests/system/keyless/rules.rs | 4 ++- crates/mega-evm/tests/system/system_tx.rs | 23 +++++++++++----- 6 files changed, 63 insertions(+), 25 deletions(-) diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 323812c68..2dd958a02 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -985,9 +985,14 @@ fn test_a_body_over_the_limit_is_the_stop_at_the_smallest_valid_gas_limit() { "{name}: the limit does not move validation" ); + let stopped = outcome_at(tx(valid), limit).unwrap(); // Where a state byte and a record's history are both free the start costs nothing past - // the intrinsic gas, and there is no out-of-gas for the stop to stand in for. - if !(state_is_free() && history(WRITE_RECORD_SIZE) == 0) { + // the intrinsic gas, and there is no out-of-gas for the stop to stand in for. Where a + // history byte is cheap enough, the calldata floor lifts the smallest valid gas limit past + // the intrinsic cost, which the stop spends alone, and what it covers past it may pay the + // start. + let free = state_is_free() && history(WRITE_RECORD_SIZE) == 0; + if !free && valid == stopped.result.gas().total_gas_spent() { let unlimited = outcome_at(tx(valid), u64::MAX).unwrap(); assert!( matches!( @@ -1002,7 +1007,6 @@ fn test_a_body_over_the_limit_is_the_stop_at_the_smallest_valid_gas_limit() { ); } - let stopped = outcome_at(tx(valid), limit).unwrap(); assert_stopped(&stopped, limit, body); assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); assert_eq!(stopped.result.gas().tx_gas_used(), valid, "{name}: the intrinsic cost only"); diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index d24bdf376..494b220d4 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -40,11 +40,11 @@ use revm::{ }; use crate::{ - common::state_is_free, + common::{history, state_is_free}, 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, + try_run, tx, tx_with_gas, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, }, }; @@ -613,8 +613,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. @@ -648,8 +648,24 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { 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))), diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index f607f0e45..e981e2a5a 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -235,16 +235,20 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { /// 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() { + 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| { @@ -252,8 +256,8 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { 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 (mega, op) = - run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), SYSTEM_CALL_GAS_LIMIT); + 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); @@ -262,14 +266,14 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { }; // The most slots the reservoir holds, and what the one after them spills. - let held = DEFAULT_RESERVOIR / slot(); - let spill = (held + 1) * slot() - DEFAULT_RESERVOIR; + 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, DEFAULT_RESERVOIR - (held - 1) * slot()); - assert_eq!(reservoir_at, DEFAULT_RESERVOIR - held * slot(), "empty at Satin's price"); + 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; diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 2f32bbbbf..4578bd339 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -182,6 +182,9 @@ fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { #[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); @@ -193,14 +196,14 @@ fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_bala 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), 1_000), + 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), 1_000), + gas_limit: leaving(&data(&carrying), short_of_the_account), answer: Answer::OutOfGas, }, Case { diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 7323dd554..43ddd429e 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -1046,7 +1046,9 @@ fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { 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_000; + // 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); diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 2d7366931..91030d477 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -631,6 +631,20 @@ fn test_a_deposit_that_creates_two_accounts_pays_for_both() { assert_eq!(two, one * 2, "two accounts created, two charges"); } +/// 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. +fn deposit_one_short_of_its_caller(sender: Address) -> MegaTransaction { + let deposit = || deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); + // A transaction without calldata has its intrinsic gas as its floor; run with its caller in + // place, the deposit creates no account. + let intrinsic = + run_outcome(chain_db().account_balance(sender, U256::from(1)), deposit()).gas.floor; + let mut tx = deposit(); + tx.0.base.gas_limit = intrinsic + account_state_gas() - 1; + tx +} + /// 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] @@ -640,10 +654,7 @@ fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { return; } 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); + let outcome = run_outcome(chain_db(), deposit_one_short_of_its_caller(sender)); assert!( matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?} is not a halt", @@ -661,13 +672,11 @@ fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_halts( return; } let sender = address!("0x00000000000000000000000000000000000f0008"); - let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); - tx.0.base.gas_limit = 30_000; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE - 1); let outcome = MegaEvm::new(chain_context(chain_db()).with_tx_runtime_limits(limits)) - .execute_transaction(tx) + .execute_transaction(deposit_one_short_of_its_caller(sender)) .expect("the deposit is included"); assert!( matches!(outcome.result, ExecutionResult::Halt { .. }), From 741fd875f2b3e45a511098a317349a5726f76cd4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:15:02 -0400 Subject: [PATCH 383/458] ci(grid): run the suite at one gas per byte, and claim the range it holds --- .github/workflows/price-grid.yml | 13 +++++++------ AGENTS.md | 8 +++++--- REVIEW.md | 9 +++++---- scripts/price_grid.sh | 20 +++++++++++--------- 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/.github/workflows/price-grid.yml b/.github/workflows/price-grid.yml index 2ce32e7cd..2abdcc19d 100644 --- a/.github/workflows/price-grid.yml +++ b/.github/workflows/price-grid.yml @@ -5,11 +5,12 @@ name: Byte-price grid # (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, four points: both bytes free, 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, 312.5, 700, 1530, 2000, -# 5000 and 10000 by a cost per history byte of 0, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on -# both. +# - 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. @@ -30,7 +31,7 @@ jobs: price-grid: name: byte-price grid runs-on: ubuntu-24.04 - # The pull-request points take minutes; the nightly grid runs the suite 57 times. + # The pull-request points take minutes; the nightly grid runs the suite 73 times. timeout-minutes: 90 steps: - uses: actions/checkout@v4 diff --git a/AGENTS.md b/AGENTS.md index 53735cd03..58aaa7e07 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,7 +32,7 @@ cargo test -p mega-evm --features satin-price-override,test-utils # 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 # four points; --full for the whole grid, or name points: 312.5/20 +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 @@ -443,8 +443,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer - 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 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, four points on a pull request and the whole grid nightly. - The prices are provisional, so a test holds at any of them: 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`). +- **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. ## Version Control @@ -512,6 +513,7 @@ When the agent is requested to implement a new feature or bug fix, it should con 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. - **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. diff --git a/REVIEW.md b/REVIEW.md index c5e54b379..407aa8858 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -64,7 +64,8 @@ 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 any byte price, and the byte-price grid job checks it. +- 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.** @@ -110,9 +111,9 @@ These checks guard every change to the Satin engine. ### 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 four points: both bytes free (0 / 0), the cheapest and the dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate (10000 / 1000). - Before the suite held at any price, these four failed every test the whole grid failed. -- Nightly and on dispatch it runs the whole grid: CPSB 0, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on both. +- 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. - 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/`. diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh index 303be2762..a783bc06c 100755 --- a/scripts/price_grid.sh +++ b/scripts/price_grid.sh @@ -17,18 +17,20 @@ # 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), and a point past the -# dearest candidate on both axes. +# 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 312.5 700 1530 2000 5000 10000" -CPHB_AXIS="0 20 50 88 100 200 300 1000" +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; the cheapest and the dearest pair under consideration; and a point past every -# candidate. Before the suite was made to hold at any price, these four failed every test the -# full grid failed. -PR_POINTS="0/0 312.5/20 5000/300 10000/1000" +# 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" @@ -49,7 +51,7 @@ case "${1:-}" in points="$points $EXTRA_POINTS" ;; "" | -h | --help) - sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//' + sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//' exit 2 ;; *) From a62c4bab6ac17c634be2a43137fc8fe0fc40f665 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:22:12 -0400 Subject: [PATCH 384/458] ci(grid): count the tests a price guard holds back at each point --- AGENTS.md | 3 +- REVIEW.md | 1 + crates/mega-evm/src/evm/prices.rs | 18 +++----- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/price_guard.rs | 34 +++++++++++++++ crates/mega-evm/tests/block/common.rs | 15 ++----- crates/mega-evm/tests/satin/common.rs | 43 ++++--------------- crates/mega-evm/tests/system/common.rs | 15 ++----- scripts/price_grid.sh | 25 +++++++---- 9 files changed, 75 insertions(+), 81 deletions(-) create mode 100644 crates/mega-evm/src/test_utils/price_guard.rs diff --git a/AGENTS.md b/AGENTS.md index 58aaa7e07..f7ae79dee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,7 +122,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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`, `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`) | — | +| `test_utils/` | `MemoryDatabase`, `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`) | — | ### How Satin executes today @@ -446,6 +446,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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. ## Version Control diff --git a/REVIEW.md b/REVIEW.md index 407aa8858..c20bb0df2 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -116,6 +116,7 @@ These checks guard every change to the Satin engine. - 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) diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index 2539f5768..a360f9dae 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -275,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 } diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 5b709397f..5f53f6ee0 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -7,6 +7,7 @@ mod inspectors; mod logs; mod neutral; mod opcode_gen; +mod price_guard; mod scenario; pub use bytes::*; @@ -16,4 +17,5 @@ pub use inspectors::*; pub use logs::*; pub use neutral::*; pub use opcode_gen::*; +pub use price_guard::*; pub use scenario::*; 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..3b3c9b250 --- /dev/null +++ b/crates/mega-evm/src/test_utils/price_guard.rs @@ -0,0 +1,34 @@ +//! The note a test leaves when the byte prices in effect leave it nothing to run. + +/// The variable naming the file [`note_price_guard`] appends its 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. +pub const PRICE_GUARD_LOG_ENV_VAR: &str = "MEGA_PRICE_GUARD_LOG"; + +/// 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) { + 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: some tests return early, because {reason}"); + } + 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/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 79df2f069..7148b4908 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -275,23 +275,14 @@ pub(crate) fn slot_state_gas() -> u64 { /// /// 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; the notice goes to stderr once, since the harness keeps a passing test's -/// output to itself. +/// 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 { - use std::io::Write; - let params = mega_evm::satin_gas_params(); if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { return false; } - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the cases that need state gas, because MEGA_SATIN_CPSB prices a state \ - byte at nothing" - ); - }); + mega_evm::test_utils::note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); true } diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 790ab4e0b..34137b6d7 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -5,7 +5,7 @@ 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}, + test_utils::{note_price_guard, op_transaction, zero_fee_l1_block_info}, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, }; @@ -125,22 +125,13 @@ pub(crate) fn execute( /// 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 } @@ -149,23 +140,14 @@ pub(crate) fn runs_at_measurement_prices() -> bool { /// /// 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; the notice goes -/// to stderr once, like [`runs_at_measurement_prices`]'s. +/// 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 { - use std::io::Write; - let params = mega_evm::satin_gas_params(); if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { return false; } - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the tests that need state gas, because MEGA_SATIN_CPSB prices a state \ - byte at nothing" - ); - }); + note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); true } @@ -175,19 +157,10 @@ pub(crate) fn state_is_free() -> bool { /// 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 { - use std::io::Write; - if active_satin_prices().cphb.milli_gas() != 0 { return false; } - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the tests that need history gas, because MEGA_SATIN_CPHB prices a \ - history byte at nothing" - ); - }); + note_price_guard("MEGA_SATIN_CPHB prices a history byte at nothing"); true } diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs index 2b35e2c07..fe87f75a5 100644 --- a/crates/mega-evm/tests/system/common.rs +++ b/crates/mega-evm/tests/system/common.rs @@ -140,23 +140,14 @@ pub(crate) fn revert_data(result: &ResultAndState) -> Bytes { /// /// 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; the notice -/// goes to stderr once, since the harness keeps a passing test's output to itself. +/// 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 { - use std::io::Write; - let params = mega_evm::satin_gas_params(); if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { return false; } - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the tests that need state gas, because MEGA_SATIN_CPSB prices a state \ - byte at nothing" - ); - }); + mega_evm::test_utils::note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); true } diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh index a783bc06c..4f6920a54 100755 --- a/scripts/price_grid.sh +++ b/scripts/price_grid.sh @@ -12,9 +12,10 @@ # 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). A summary -# line per point goes to stdout and, when $GITHUB_STEP_SUMMARY is set, a table to the step summary. -# Exits 1 if any point fails. +# Each point's output lands in $OUT_DIR/_.log (default target/price-grid), and the +# tests a price guard held back at it (`note_price_guard`) in _.guards, one per line. A +# summary line per point, with how many passed, were guarded 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 @@ -51,7 +52,7 @@ case "${1:-}" in points="$points $EXTRA_POINTS" ;; "" | -h | --help) - sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//' + sed -n '2,24p' "$0" | sed 's/^# \{0,1\}//' exit 2 ;; *) @@ -61,6 +62,8 @@ 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 @@ -68,7 +71,7 @@ if ! cargo test -p mega-evm --features "$FEATURES" --locked --no-run; then exit 1 fi -summary="| CPSB | CPHB | result | passed | failed |"$'\n'"|---|---|---|---:|---:|" +summary="| CPSB | CPHB | result | passed | guarded | failed |"$'\n'"|---|---|---|---:|---:|---:|" failed_points="" for point in $points; do cpsb="${point%/*}" @@ -76,7 +79,10 @@ for point in $points; do set -- env -u MEGA_SATIN_CPSB -u MEGA_SATIN_CPHB [ "$cpsb" != "-" ] && set -- "$@" "MEGA_SATIN_CPSB=$cpsb" [ "$cphb" != "-" ] && set -- "$@" "MEGA_SATIN_CPHB=$cphb" - log="$OUT_DIR/${cpsb//-/unset}_${cphb//-/unset}.log" + 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 @@ -85,19 +91,22 @@ for point in $points; do 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 + [ -f "$guards" ] && guarded=$(wc -l <"$guards" | tr -d ' ') if [ "$status" -eq 0 ]; then result="ok" else result="FAILED" failed_points="$failed_points $point" fi - printf '%-12s %-7s %5s passed %4s failed %4ss %s\n' "$point" "$result" "$passed" "$failed" "$seconds" "$log" + printf '%-12s %-7s %5s passed %4s guarded %4s failed %4ss %s\n' \ + "$point" "$result" "$passed" "$guarded" "$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 | $failed |" + summary="$summary"$'\n'"| $cpsb | $cphb | $result | $passed | $guarded | $failed |" done if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then From 5663ff1efc6ab2dfad95e1d3bf078f02d625e1b8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:23:31 -0400 Subject: [PATCH 385/458] docs(evm): hand the factory a schedule behind an Arc as it is --- crates/mega-evm/README.md | 1 + crates/mega-evm/src/evm/factory.rs | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 3980ff178..7bffa48a7 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -192,6 +192,7 @@ A node executes a block through the factory, which installs the block's limits o use alloy_evm::block::{BlockExecutor as _, BlockExecutorFactory as _}; use mega_evm::{BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory}; +// `chain_spec` is shared, an `Arc` of the node's schedule: `MegaHardforks` holds for an `Arc` of one. let evm_factory = MegaEvmFactory::new().with_schedule(chain_spec.clone()); let factory = MegaBlockExecutorFactory::new(receipt_builder, chain_spec, evm_factory); let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_block_root, extra_data, BlockLimits::no_limits()); diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index ba3c51c0d..8530a56bd 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -128,7 +128,9 @@ impl MegaEvmFactory { /// [`with_tx_runtime_limits`](Self::with_tx_runtime_limits). /// /// A node hands it the schedule it hands its block executor factory, so the EVMs it builds - /// outside block execution — an RPC call, a simulation — stop what the chain stops. + /// outside block execution — an RPC call, a simulation — stop what the chain stops. A schedule + /// held in an `Arc` is handed over as a clone of the `Arc`: [`MegaHardforks`] holds for an + /// `Arc` or a `Box` of a schedule. pub fn with_schedule(mut self, spec: Spec) -> Self where Spec: MegaHardforks + Send + Sync + 'static, @@ -372,6 +374,19 @@ mod tests { assert_ne!(*evm.tx_runtime_limits(), EvmTxRuntimeLimits::default()); } + /// A schedule shared behind an `Arc`, as a node holds its chain spec, is handed over as a + /// clone of the `Arc`, and resolves the limits the schedule it points to carries. + #[test] + fn test_a_schedule_behind_an_arc_is_a_schedule() { + let shared = Arc::new(chain(chain_limits())); + let factory = MegaEvmFactory::new().with_schedule(Arc::clone(&shared)); + assert_eq!(factory.tx_runtime_limits(SATIN_AT), chain_limits().tx_runtime_limits); + assert_eq!( + factory.tx_runtime_limits(SATIN_AT), + shared.protocol_limits(SATIN_AT).unwrap().tx_runtime_limits + ); + } + /// Given the chain's schedule, the factory's EVMs run under the limits it carries at the /// block's timestamp; where it carries none, or limits their own check refuses — both of which /// block execution refuses — under the protocol's defaults. From 0477b57e64d9bfa174fa0ef787f9a894b71c2f08 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:31:19 -0400 Subject: [PATCH 386/458] feat(evme): report the limits a run was held to under an override --- bin/mega-evme/README.md | 2 +- bin/mega-evme/src/block/cmd.rs | 5 +-- bin/mega-evme/src/block/exec.rs | 5 +++ bin/mega-evme/src/block/legacy.rs | 2 +- bin/mega-evme/src/block/record.rs | 10 ++++-- bin/mega-evme/src/block/satin.rs | 8 +++-- bin/mega-evme/src/common/env.rs | 9 +++++ bin/mega-evme/src/common/outcome.rs | 13 +++++-- bin/mega-evme/src/replay/cmd.rs | 9 +++-- bin/mega-evme/src/run/cmd.rs | 5 +-- bin/mega-evme/src/tx/cmd.rs | 5 +-- bin/mega-evme/tests/block_replay.rs | 25 ++++++++++++-- bin/mega-evme/tests/limits.rs | 34 ++++++++++++++++++- bin/mega-evme/tests/replay_paths.rs | 8 ++++- docs/mega-evme/commands/replay.md | 1 + .../mega-evme/configuration/chain-and-spec.md | 2 ++ 16 files changed, 119 insertions(+), 24 deletions(-) diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index c44a2bcaa..e228fa267 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -30,7 +30,7 @@ Every command runs on the engine its spec names. `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`). +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 the protocol limits of the chain's schedule at the block's timestamp; a chain that does not run Satin there (mainnet and testnet today, the default chain, any chain the tool does not know) runs on Satin's default limits, a counterfactual. diff --git a/bin/mega-evme/src/block/cmd.rs b/bin/mega-evme/src/block/cmd.rs index f5da150b5..407f2683b 100644 --- a/bin/mega-evme/src/block/cmd.rs +++ b/bin/mega-evme/src/block/cmd.rs @@ -280,9 +280,10 @@ fn print_block(txs: &[TxRecord], block: &BlockRecord, json: bool) { }; format!("{} of {} transactions differ{root}", block.differing, block.transactions) }; - let ledgers = block.satin.map_or_else(String::new, |satin| { + 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 {}]", + " [regular {} state {} history {}{overridden}]", satin.regular_gas, satin.state_gas, satin.history_gas ) }); diff --git a/bin/mega-evme/src/block/exec.rs b/bin/mega-evme/src/block/exec.rs index 344b8c8a8..7a2960ffc 100644 --- a/bin/mega-evme/src/block/exec.rs +++ b/bin/mega-evme/src/block/exec.rs @@ -6,6 +6,8 @@ use alloy_primitives::{Bytes, Log}; +use mega_evm::ProtocolLimits; + use crate::common::SatinReport; /// How an included transaction ended. @@ -69,6 +71,9 @@ pub enum TxResult { 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 { diff --git a/bin/mega-evme/src/block/legacy.rs b/bin/mega-evme/src/block/legacy.rs index d2235db7d..8cbdfbdb8 100644 --- a/bin/mega-evme/src/block/legacy.rs +++ b/bin/mega-evme/src/block/legacy.rs @@ -184,7 +184,7 @@ pub(super) fn execute( satin: None, }); } - Ok(ExecutedBlock { transactions: results }) + Ok(ExecutedBlock { transactions: results, limits_override: None }) }; run() }; diff --git a/bin/mega-evme/src/block/record.rs b/bin/mega-evme/src/block/record.rs index 1fb212668..7c1dde2bb 100644 --- a/bin/mega-evme/src/block/record.rs +++ b/bin/mega-evme/src/block/record.rs @@ -148,7 +148,7 @@ pub fn records( record.cumulative_gas_used = receipt.cumulative_gas_used; record.logs = receipt.logs.len(); record.reason.clone_from(reason); - record.satin = *satin; + record.satin = satin.clone(); previous = receipt.cumulative_gas_used; if receipt.success != chain.success() { record.differs.push("status"); @@ -170,7 +170,10 @@ pub fn records( 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(|| sum_satin(txs.iter().filter_map(|t| t.satin))); + 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, @@ -202,7 +205,7 @@ fn chain_view(chain: &ChainReceipt) -> ChainView { /// 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(reports: impl Iterator) -> SatinReport { +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, @@ -213,6 +216,7 @@ fn sum_satin(reports: impl Iterator) -> SatinReport { data_size: acc.data_size + r.data_size, write_records: acc.write_records + r.write_records, 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 06ca1ea90..5868b0f2b 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -12,8 +12,8 @@ use mega_evm::{ inspector::NoOpInspector, primitives::eip4844, }, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaSpecId, - MegaTxEnvelope, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaHardforks, + MegaSpecId, MegaTxEnvelope, }; use super::{ @@ -127,7 +127,9 @@ pub(super) fn execute( satin: Some(satin), }); } - Ok(ExecutedBlock { transactions: results }) + let limits_override = + limits_override.and_then(|_| hardforks.protocol_limits(header.timestamp)); + Ok(ExecutedBlock { transactions: results, limits_override }) }; run() }; diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 5dad058f8..0047e4bbf 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -207,6 +207,15 @@ impl EnvArgs { self.ext.create_external_envs() } + /// The protocol limits a Satin run is held to when `--override.limits` replaced the + /// schedule'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 transaction is held to the per-transaction limits a block of the chain at the block's diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index 1f4a9903a..a04e59229 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -12,7 +12,7 @@ use clap::Parser; use mega_evm::{ op_revm::OpHaltReason, revm::{context::result::ExecutionResult, state::EvmState}, - LimitCheck, LimitKind, MegaHaltReason, MegaTransactionOutcome, MegaTxType, + LimitCheck, LimitKind, MegaHaltReason, MegaTransactionOutcome, MegaTxType, ProtocolLimits, }; use op_alloy_consensus::{OpDepositReceipt, OpReceiptEnvelope}; use serde::Serialize; @@ -42,7 +42,7 @@ pub struct EvmeOutcome { /// /// 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, Copy, Default, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] pub struct SatinReport { /// Regular (compute) gas spent, before the refund. pub regular_gas: u64, @@ -62,6 +62,11 @@ pub struct SatinReport { pub write_records: u64, /// The transaction-level limit that stopped the transaction, if one did. 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 transaction-level limit that stopped a Satin transaction. @@ -94,6 +99,7 @@ impl SatinReport { } _ => None, }, + limits_override: None, } } } @@ -244,6 +250,9 @@ pub fn print_satin_report(report: &SatinReport) { 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. diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index bc91c5666..ad9215929 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -15,7 +15,7 @@ use mega_evm::{ DatabaseRef, }, BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, - MegaSpecId, + MegaHardforks, MegaSpecId, }; use tracing::{debug, info, trace, warn}; @@ -502,7 +502,10 @@ impl Cmd { .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 satin = SatinReport::of(&outcome.inner); + let mut satin = SatinReport::of(&outcome.inner); + if self.limits_override.is_some() { + satin.limits_override = hardforks.protocol_limits(timestamp).map(Box::new); + } let exec_result = outcome.inner.result.clone(); let evm_state = outcome.inner.state.clone(); @@ -587,7 +590,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); + summary.satin = Some(result.outcome.satin.clone()); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") diff --git a/bin/mega-evme/src/run/cmd.rs b/bin/mega-evme/src/run/cmd.rs index 68671f242..f7505cf72 100644 --- a/bin/mega-evme/src/run/cmd.rs +++ b/bin/mega-evme/src/run/cmd.rs @@ -107,8 +107,9 @@ 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, satin) = + let (exec_result, evm_state, trace_data, mut satin) = self.trace_args.execute_transaction(evm_context, tx)?; + satin.limits_override = self.env_args.limits_override_in_force()?; let exec_time = start.elapsed(); // Log execution result @@ -153,7 +154,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); + summary.satin = Some(outcome.satin.clone()); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") diff --git a/bin/mega-evme/src/tx/cmd.rs b/bin/mega-evme/src/tx/cmd.rs index dd50a1a3d..7215a9412 100644 --- a/bin/mega-evme/src/tx/cmd.rs +++ b/bin/mega-evme/src/tx/cmd.rs @@ -102,8 +102,9 @@ 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, satin) = + let (exec_result, evm_state, trace_data, mut satin) = self.trace_args.execute_transaction(evm_context, tx.clone())?; + satin.limits_override = self.env_args.limits_override_in_force()?; let exec_time = start.elapsed(); // Log execution result @@ -175,7 +176,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); + summary.satin = Some(outcome.satin.clone()); summary.receipt = Some(serde_json::to_value(&receipt).expect("failed to serialize receipt")); println!( diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index b43cac295..565e36313 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -241,14 +241,33 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { (records.into_iter().filter(|r| r["kind"] == "tx").collect(), block) }; - let (counterfactual, _) = replay_under(None); + let (counterfactual, plain) = replay_under(None); + assert!(plain["satin"].get("limits_override").is_none(), "{}", plain["satin"]); let defaults = serde_json::to_string(&ProtocolLimits::DEFAULT).unwrap(); - assert_eq!(replay_under(Some(&defaults)).0, counterfactual, "it runs on the defaults"); + let (on_the_defaults, overridden) = replay_under(Some(&defaults)); + assert_eq!(on_the_defaults, counterfactual, "it runs on the defaults"); + assert_eq!( + overridden["satin"]["limits_override"], + serde_json::to_value(ProtocolLimits::DEFAULT).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 (stopped, _) = replay_under(Some(r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#)); + let (stopped, stopped_block) = + replay_under(Some(r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#)); + assert_eq!( + stopped_block["satin"]["limits_override"]["txRuntimeLimits"]["txDataSizeLimit"], + 310 + ); let (mut protocols, mut others) = (0, 0); for (tx, sent) in stopped.iter().zip(sent) { let stop = &tx["satin"]["limit_exceeded"]; diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs index 5bd76aa58..d15571a68 100644 --- a/bin/mega-evme/tests/limits.rs +++ b/bin/mega-evme/tests/limits.rs @@ -3,6 +3,7 @@ use std::process::Command; +use mega_evm::ProtocolLimits; use serde_json::{json, Value}; /// Two fresh `SSTORE`s, keeping two write records: 310 bytes of body and 40 per record. @@ -39,8 +40,16 @@ fn run_two_writes(limits: Option<&str>) -> Value { evme(&args).json() } +/// The protocol's default 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::DEFAULT).unwrap(); + limits["txRuntimeLimits"]["txDataSizeLimit"] = json!(limit); + limits +} + /// Without an override the run keeps both writes; an override of the transaction data size or of -/// its write records stops it at the second write, and takes both back. +/// its write records 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 schedule's limits reports none. #[test] fn test_an_override_holds_a_satin_run_to_other_limits() { let kept = run_two_writes(None); @@ -48,6 +57,7 @@ fn test_an_override_holds_a_satin_run_to_other_limits() { 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); @@ -56,6 +66,7 @@ fn test_an_override_holds_a_satin_run_to_other_limits() { 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)); let records = run_two_writes(Some(r#"{"txRuntimeLimits":{"txKvUpdateLimit":1}}"#)); assert_eq!( @@ -91,6 +102,27 @@ fn test_an_override_holds_a_satin_tx_to_other_limits() { stopped["satin"]["limit_exceeded"], json!({ "kind": "data_size", "limit": 310, "used": 311 }) ); + assert_eq!(stopped["satin"]["limits_override"], defaults_with_tx_data_size(310)); +} + +/// 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 what a chain configuration is: an unknown field, a value of the wrong diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index a26ba3f04..da92a1b4b 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -196,7 +196,13 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { } let run = run_evme(&args); assert_eq!(run.code, 0, "{engine} tx {index}: {}{}", run.stderr, run.stdout); - let single: Value = serde_json::from_str(&run.stdout).unwrap(); + 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}"); diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index 665be5c36..bf7cc5774 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -181,6 +181,7 @@ Replay on Satin under other protocol limits than the chain's, a counterfactual: Without it, a Satin replay of a block its chain does not run on Satin runs on Satin's default limits. The object's shape, the defaults 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}}' diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index 7d46c6a64..96cf47d78 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -63,6 +63,7 @@ On Satin, every output field keeps its legacy name and meaning, and one field is | `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`, `kv_update`, `compute_gas`, `state_growth`), `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. @@ -111,6 +112,7 @@ The whole shape, at the defaults: `18446744073709551615` (`u64::MAX`) leaves a limit unlimited. The limits an override leaves are held to what a chain configuration is: an unknown field, a zero limit, a transaction data-size limit below the 310 bytes every transaction's body counts, or a compute cap no transaction reaches is refused. A transaction a limit stops reports it in `satin.limit_exceeded`. +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. ## Examples From fa086aa307f552d3046e00869185b371d76f69cf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:33:50 -0400 Subject: [PATCH 387/458] docs(limit): say what a state-growth stop reports as used, and pin it --- AGENTS.md | 1 + bin/mega-evme/src/common/outcome.rs | 4 ++- crates/mega-evm/src/limit/mod.rs | 7 ++++ .../mega-evm/tests/satin/state_gas_limit.rs | 36 +++++++++++++++++++ .../mega-evme/configuration/chain-and-spec.md | 1 + 5 files changed, 48 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index f7ae79dee..04f674c95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/frame_limit.rs`). It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. + The outcome's `limit_exceeded` reports as used the state gas held where the limit was crossed: before the first frame, what stands (a deposit's created caller, the authorities), not the first frame's upfront charge, so a deposit whose created caller alone crosses reports that account. It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a frame's start adds — EIP-2780's charge for the first frame's recipient or created account, and the account a `CALL`, `CREATE` or `CREATE2` is charged for upfront — once revm has decided the frame (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — or answered with a failure, such as a value transfer to a precompile that fails, gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded; the transaction's own frame has no caller whose revert takes an answer's writes back, so its answer is taken back to where its start began) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index a04e59229..e3d31c46f 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -76,7 +76,9 @@ pub struct LimitStop { pub kind: &'static str, /// The limit crossed, in the dimension's unit. pub limit: u64, - /// The usage that crossed it. + /// The usage that crossed it, where it crossed it: for `state_growth`, the state gas held + /// at that point, so a deposit whose created caller alone crosses the limit reports that + /// account, even where its first frame would add another. pub used: u64, } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 13a715c08..4aa7f25b1 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -532,6 +532,13 @@ pub enum LimitCheck { /// 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. + /// + /// For [`LimitKind::StateGrowth`] it is the state gas the transaction held where the limit + /// was crossed. Before the first frame that is what stands whatever the frame does — a + /// deposit's created caller, the applied authorities — and not the account EIP-2780 + /// charges the first frame's start for, which is held once revm has decided the frame: a + /// deposit whose created caller alone crosses the limit reports that account, even where + /// its first frame would add another. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, diff --git a/crates/mega-evm/tests/satin/state_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs index c76c759dc..300de8ab8 100644 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ b/crates/mega-evm/tests/satin/state_gas_limit.rs @@ -817,6 +817,42 @@ fn test_a_stopped_deposit_keeps_the_caller_it_created() { assert_eq!(stopped.gas.state, one_account()); } +/// A stop reports as used the state gas held where the limit was crossed. Before the first frame +/// that is what stands whatever the frame does, a deposit's created caller, and not the account +/// EIP-2780 charges the first frame's start for, which is held once revm has decided the frame. +/// So a deposit that creates its caller and sends value to an account that does not exist +/// reports the caller alone when the caller crosses the limit, and both accounts when only both +/// do. +#[test] +fn test_a_stop_reports_the_state_gas_held_where_it_crossed() { + if state_is_free() { + return; + } + let fresh = address!("00000000000000000000000000000000006000fe"); + let deposit = || { + let mut tx = call(fresh, EMPTY, U256::from(1), BELOW_CAP); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.deposit.mint = Some(5); + tx.0.base.gas_price = 0; + tx + }; + let account = one_account(); + let caller_alone = run_under(funded(), deposit(), account - 1); + assert_state_stopped("the created caller", &caller_alone, account - 1, account); + let both = run_under(funded(), deposit(), 2 * account - 1); + assert_state_stopped("the caller and the recipient", &both, 2 * account - 1, 2 * account); + for stopped in [&caller_alone, &both] { + assert!( + stopped.state.get(&EMPTY).is_none_or(|a| a.info.balance.is_zero()), + "no value moved" + ); + assert_eq!( + stopped.gas.state, account, + "the caller's account stays, the recipient's does not" + ); + } +} + /* ---------- refills give their room back ---------- */ /// The limit holds what the transaction holds net: a slot written back gives its room back, and diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index 96cf47d78..c77f6301a 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -112,6 +112,7 @@ The whole shape, at the defaults: `18446744073709551615` (`u64::MAX`) leaves a limit unlimited. The limits an override leaves are held to what a chain configuration is: an unknown field, a zero limit, a transaction data-size limit below the 310 bytes every transaction's body counts, or a compute cap no transaction reaches is refused. A transaction a limit stops reports it in `satin.limit_exceeded`. +Its `used` is the usage where the limit was crossed; for `state_growth`, the state gas held there, so a deposit whose created caller alone crosses the limit reports that account, even where its first frame would add another. 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. From 699d960ce2e8cba11271a998f1f9bb650a0bd0a7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:37:56 -0400 Subject: [PATCH 388/458] fix(evme): decide a pending transaction's engine at the block it replays in --- bin/mega-evme/AGENTS.md | 1 + bin/mega-evme/src/replay/cmd.rs | 27 +++++++++++++++------------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 33fa91221..cd92e227c 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -22,6 +22,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - 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 diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index ad9215929..3a337a560 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -129,8 +129,10 @@ impl Cmd { /// 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 block's timestamp, from the source the replay itself reads, - /// through a provider that persists nothing. + /// 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. pub async fn engine(&self) -> Result { let tx_hash = self.tx_hash(); if let Some(spec) = &self.spec_override { @@ -145,17 +147,18 @@ impl Cmd { .await .map_err(|e| ReplayError::RpcError(format!("Failed to fetch transaction: {e}")))? .ok_or(ReplayError::TransactionNotFound(tx_hash))?; - let timestamp = match tx.block_number { - Some(number) => provider - .get_block_by_number(number.into()) - .await - .map_err(|e| ReplayError::RpcError(format!("RPC transport error: {e}")))? - .ok_or(ReplayError::BlockNotFound(number))? - .header - .timestamp(), - // A pending transaction executes on top of the latest block, at a later timestamp. - None => u64::MAX, + 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(); Ok(Engine::of_block(chain_id, timestamp)) } From c1c12431f533698f5530ba73f2a623b2d4a6230e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 29 Sep 2026 05:39:13 -0400 Subject: [PATCH 389/458] docs(evme): say what a block replay does not compare, and what picking the engine reads --- bin/mega-evme/README.md | 2 +- docs/mega-evme/commands/replay.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index e228fa267..ed45f13e8 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -267,7 +267,7 @@ 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. +`--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 | | --------------------- | ------------------------------------------------------------------------------------------------------- | diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index bf7cc5774..f78c870c5 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -156,6 +156,7 @@ Hardcoded hardfork configs exist for: 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 runs Satin from genesis, the rung the Satin engine pins for an unrecognized chain. The 1.7.1 tool ran such a chain through `Rex7`, the legacy line's unstable spec, which Satin supersedes. @@ -193,6 +194,7 @@ mega-evme replay --block 26400001 --rpc --block-cache ./blocks --override. `--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. 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. From 4912ae7eb267de4a10b0ad316f35af5fe83ddc3a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 14:32:21 +0800 Subject: [PATCH 390/458] feat(satin): node integration API, the stateless witness, randomized tests and four engine fixes (#400) Co-authored-by: mega-putin --- .cargo/config.toml | 5 + .claude/skills/satin-review/SKILL.md | 255 +++ .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 | 188 ++- .github/workflows/exec-spec.yml | 3 + .github/workflows/fuzz.yml | 126 ++ .github/workflows/mutation.yml | 147 +- .github/workflows/replay-bench.yml | 270 ---- .gitignore | 5 + AGENTS.md | 370 +++-- Cargo.lock | 345 ++-- Cargo.toml | 18 +- README.md | 1 - REVIEW.md | 98 +- bench/replay/README.md | 133 -- 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 | 17 +- bin/mega-evme/README.md | 43 +- bin/mega-evme/src/block/cmd.rs | 30 +- bin/mega-evme/src/block/inputs.rs | 61 +- bin/mega-evme/src/block/satin.rs | 121 +- bin/mega-evme/src/cmd.rs | 141 +- bin/mega-evme/src/common/env.rs | 71 +- bin/mega-evme/src/common/error.rs | 114 +- bin/mega-evme/src/common/hex.rs | 63 +- bin/mega-evme/src/common/mod.rs | 1 + bin/mega-evme/src/common/outcome.rs | 87 +- .../src/common/provider/cache_store.rs | 88 +- bin/mega-evme/src/common/provider/mod.rs | 196 ++- bin/mega-evme/src/common/schedule.rs | 446 ++++-- bin/mega-evme/src/common/state.rs | 538 +++++-- bin/mega-evme/src/common/trace.rs | 86 +- bin/mega-evme/src/common/tx.rs | 254 ++- bin/mega-evme/src/common/tx_override.rs | 102 +- bin/mega-evme/src/engine.rs | 85 +- bin/mega-evme/src/lib.rs | 15 +- bin/mega-evme/src/main.rs | 8 +- bin/mega-evme/src/replay/cmd.rs | 408 ++++- bin/mega-evme/src/run/README.md | 492 ------ bin/mega-evme/src/run/cmd.rs | 36 +- bin/mega-evme/src/tx/cmd.rs | 34 +- bin/mega-evme/tests/block_replay.rs | 564 +++++-- bin/mega-evme/tests/common/blocks.rs | 105 +- bin/mega-evme/tests/common/mod.rs | 14 + bin/mega-evme/tests/differences.rs | 17 +- bin/mega-evme/tests/dump_code.rs | 168 ++ .../fixtures/test_satin_run_dump_inline.json | 13 +- bin/mega-evme/tests/integration.rs | 267 +++- bin/mega-evme/tests/legacy_line.rs | 5 +- bin/mega-evme/tests/limits.rs | 178 ++- bin/mega-evme/tests/provider.rs | 70 +- bin/mega-evme/tests/replay_dump.rs | 3 +- bin/mega-evme/tests/replay_paths.rs | 491 +++++- bin/mega-evme/tests/satin-differences.md | 36 +- bin/mega-evme/tests/state.rs | 525 +++++- 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 | 87 +- crates/mega-evm/benches/block.rs | 165 +- crates/mega-evm/benches/corpus.rs | 35 +- 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 | 109 +- crates/mega-evm/src/access/detention.rs | 99 +- crates/mega-evm/src/access/mod.rs | 48 +- crates/mega-evm/src/access/volatile.rs | 78 +- crates/mega-evm/src/block/chain.rs | 160 +- crates/mega-evm/src/block/eips.rs | 133 +- crates/mega-evm/src/block/executor.rs | 853 +++++----- crates/mega-evm/src/block/factory.rs | 17 +- crates/mega-evm/src/block/genesis.rs | 621 ++++++++ crates/mega-evm/src/block/hardfork.rs | 554 ++----- crates/mega-evm/src/block/l1_block_info.rs | 183 +++ crates/mega-evm/src/block/limit.rs | 1016 +++--------- crates/mega-evm/src/block/mod.rs | 4 + crates/mega-evm/src/block/result.rs | 86 +- crates/mega-evm/src/constants.rs | 33 +- crates/mega-evm/src/evm/context.rs | 341 +++- crates/mega-evm/src/evm/execution.rs | 650 +++----- crates/mega-evm/src/evm/factory.rs | 309 ++-- crates/mega-evm/src/evm/history.rs | 51 +- crates/mega-evm/src/evm/host.rs | 529 +----- crates/mega-evm/src/evm/inspector.rs | 118 +- crates/mega-evm/src/evm/instructions.rs | 149 +- crates/mega-evm/src/evm/mod.rs | 98 +- crates/mega-evm/src/evm/precompiles.rs | 44 +- crates/mega-evm/src/evm/result.rs | 61 +- crates/mega-evm/src/evm/schedule.rs | 225 ++- crates/mega-evm/src/evm/state.rs | 178 ++- crates/mega-evm/src/evm/validation.rs | 154 ++ crates/mega-evm/src/external/gas.rs | 140 +- crates/mega-evm/src/external/hasher/mod.rs | 19 + crates/mega-evm/src/external/oracle.rs | 2 +- crates/mega-evm/src/external/salt.rs | 8 +- crates/mega-evm/src/external/test_utils.rs | 18 - crates/mega-evm/src/lib.rs | 82 +- crates/mega-evm/src/limit/frame_limit.rs | 202 +-- crates/mega-evm/src/limit/limit.rs | 786 ++++----- crates/mega-evm/src/limit/mod.rs | 491 +++--- crates/mega-evm/src/limit/record.rs | 19 +- crates/mega-evm/src/system/AGENTS.md | 41 +- crates/mega-evm/src/system/control.rs | 6 +- crates/mega-evm/src/system/deploy.rs | 318 ---- .../mega-evm/src/system/keyless/dispatch.rs | 61 +- crates/mega-evm/src/system/keyless/error.rs | 96 +- crates/mega-evm/src/system/keyless/mod.rs | 47 +- crates/mega-evm/src/system/keyless/settle.rs | 35 +- crates/mega-evm/src/system/mod.rs | 14 +- crates/mega-evm/src/system/oracle.rs | 115 +- crates/mega-evm/src/system/predeploys.rs | 206 +++ .../mega-evm/src/system/sequencer_registry.rs | 297 ++-- crates/mega-evm/src/system/tx.rs | 183 ++- crates/mega-evm/src/test_utils/bytes.rs | 22 + crates/mega-evm/src/test_utils/database.rs | 170 +- crates/mega-evm/src/test_utils/inspectors.rs | 200 ++- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/neutral.rs | 69 +- crates/mega-evm/src/test_utils/opcode_gen.rs | 13 + crates/mega-evm/src/test_utils/price_guard.rs | 37 +- crates/mega-evm/src/test_utils/witness.rs | 702 ++++++++ crates/mega-evm/src/types.rs | 6 +- crates/mega-evm/tests/_pending/README.md | 348 ---- crates/mega-evm/tests/block/activation.rs | 229 +++ crates/mega-evm/tests/block/bucket_ids.rs | 295 ++++ ...{protocol_limits.rs => building_policy.rs} | 141 +- crates/mega-evm/tests/block/common.rs | 214 ++- crates/mega-evm/tests/block/counters.rs | 166 +- crates/mega-evm/tests/block/deploy.rs | 315 ---- crates/mega-evm/tests/block/deposits.rs | 255 ++- crates/mega-evm/tests/block/detention.rs | 11 +- crates/mega-evm/tests/block/eips.rs | 258 +-- crates/mega-evm/tests/block/external_envs.rs | 14 +- crates/mega-evm/tests/block/factory.rs | 154 +- crates/mega-evm/tests/block/inspector.rs | 139 +- crates/mega-evm/tests/block/l1_attributes.rs | 144 ++ crates/mega-evm/tests/block/limits.rs | 291 +--- crates/mega-evm/tests/block/main.rs | 14 +- crates/mega-evm/tests/block/predeploys.rs | 274 ++++ .../mega-evm/tests/block/receipt_goldens.rs | 321 ++++ crates/mega-evm/tests/block/receipts.rs | 48 +- crates/mega-evm/tests/block/rules.rs | 50 +- crates/mega-evm/tests/block/schedule.rs | 280 ++-- .../tests/block/sequencer_registry.rs | 535 ++++--- crates/mega-evm/tests/block/sequences.rs | 139 ++ crates/mega-evm/tests/block/stale.rs | 186 +++ crates/mega-evm/tests/block/state_gas.rs | 399 +---- .../mega-evm/tests/block/system_tx_budgets.rs | 189 +++ crates/mega-evm/tests/block/transfer_logs.rs | 118 +- 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 | 89 +- crates/mega-evm/tests/satin/compute_gas.rs | 76 +- crates/mega-evm/tests/satin/contract_size.rs | 40 - crates/mega-evm/tests/satin/corpus.rs | 59 + crates/mega-evm/tests/satin/count_order.rs | 83 + crates/mega-evm/tests/satin/data_size.rs | 843 ++++++---- .../mega-evm/tests/satin/data_size_counts.rs | 26 +- crates/mega-evm/tests/satin/deposit_charge.rs | 726 ++++++--- .../tests/satin/detained_transfers.rs | 69 +- crates/mega-evm/tests/satin/detention.rs | 310 ++-- crates/mega-evm/tests/satin/equivalence.rs | 162 +- 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 | 481 ++---- .../mega-evm/tests/satin/history_exemption.rs | 108 +- crates/mega-evm/tests/satin/history_gas.rs | 118 +- .../mega-evm/tests/satin/history_reservoir.rs | 84 +- .../mega-evm/tests/satin/inherited_costs.rs | 20 +- crates/mega-evm/tests/satin/inspector.rs | 200 ++- .../tests/satin/inspector_settlement.rs | 176 +- crates/mega-evm/tests/satin/intrinsic.rs | 172 +- crates/mega-evm/tests/satin/kv_limit.rs | 523 ------ .../mega-evm/tests/satin/limit_exemption.rs | 114 +- crates/mega-evm/tests/satin/limit_stop.rs | 187 +++ crates/mega-evm/tests/satin/main.rs | 12 +- crates/mega-evm/tests/satin/neutral.rs | 38 +- crates/mega-evm/tests/satin/outcome.rs | 6 +- .../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 | 50 +- crates/mega-evm/tests/satin/pricing_table.rs | 66 +- crates/mega-evm/tests/satin/salt.rs | 229 ++- .../mega-evm/tests/satin/salt_delegation.rs | 18 - crates/mega-evm/tests/satin/salt_refund.rs | 136 +- crates/mega-evm/tests/satin/schedule.rs | 78 +- ...atin__corpus__corpus_outcomes_and_gas.snap | 96 ++ crates/mega-evm/tests/satin/spec_numbers.rs | 499 ++++++ .../mega-evm/tests/satin/state_gas_limit.rs | 1416 ----------------- crates/mega-evm/tests/satin/state_growth.rs | 638 ++++++++ crates/mega-evm/tests/satin/stops.rs | 1182 ++++++-------- .../tests/satin/storage_call_stipend.rs | 266 +++- crates/mega-evm/tests/satin/strategic_stop.rs | 285 ++-- .../tests/satin/synthetic_frame_gas.rs | 27 +- crates/mega-evm/tests/satin/system_call.rs | 3 - crates/mega-evm/tests/satin/transfer_logs.rs | 412 +++-- .../mega-evm/tests/satin/volatile_access.rs | 327 ++-- crates/mega-evm/tests/satin/withheld_gas.rs | 567 ++++--- crates/mega-evm/tests/satin/write_records.rs | 282 ++-- crates/mega-evm/tests/shared/snapshot.rs | 50 + .../mega-evm/tests/system/access_control.rs | 239 +-- crates/mega-evm/tests/system/common.rs | 123 +- crates/mega-evm/tests/system/control.rs | 11 +- crates/mega-evm/tests/system/deploy.rs | 338 ---- .../mega-evm/tests/system/keyless/charges.rs | 75 +- .../mega-evm/tests/system/keyless/deploy.rs | 228 +-- .../tests/system/keyless/detention.rs | 161 +- .../tests/system/keyless/differential.rs | 97 +- .../tests/system/keyless/inspector.rs | 150 +- .../tests/system/keyless/interface.rs | 31 + .../mega-evm/tests/system/keyless/limits.rs | 441 ++--- crates/mega-evm/tests/system/keyless/mod.rs | 31 +- .../tests/system/keyless/precedence.rs | 40 + crates/mega-evm/tests/system/keyless/rules.rs | 116 +- ...erential__keyless_differential_record.snap | 153 ++ crates/mega-evm/tests/system/limit_control.rs | 64 +- crates/mega-evm/tests/system/main.rs | 4 +- crates/mega-evm/tests/system/oracle.rs | 159 +- .../mega-evm/tests/system/oracle_storage.rs | 145 +- crates/mega-evm/tests/system/predeploys.rs | 182 +++ .../tests/system/remaining_compute_gas.rs | 44 +- crates/mega-evm/tests/system/system_tx.rs | 366 +++-- 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 | 10 +- crates/mega-state-test/Cargo.toml | 6 +- crates/mega-state-test/DEVIATIONS.md | 51 + crates/mega-state-test/README.md | 80 +- .../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 | 867 +++++++++- crates/mega-state-test/src/exceptions.rs | 2 +- crates/mega-state-test/src/lib.rs | 11 +- crates/mega-state-test/src/mode.rs | 37 +- crates/mega-state-test/src/roots.rs | 89 +- crates/mega-state-test/src/runner.rs | 71 +- crates/mega-state-test/src/witness.rs | 251 +++ crates/mega-state-test/tests/blockchain.rs | 668 ++++++++ crates/mega-state-test/tests/runner.rs | 1 + crates/mega-state-test/tests/witness.rs | 184 +++ crates/state-test/AGENTS.md | 3 +- crates/state-test/Cargo.toml | 6 + crates/state-test/README.md | 12 +- crates/state-test/src/btest.rs | 199 +++ crates/state-test/src/main.rs | 17 +- crates/state-test/tests/cli.rs | 173 +- 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 | 75 +- docs/mega-evme/commands/run.md | 6 +- docs/mega-evme/commands/tx.md | 17 +- .../mega-evme/configuration/chain-and-spec.md | 76 +- .../configuration/state-management.md | 53 +- docs/mega-evme/cookbook.md | 2 +- docs/mega-evme/overview.md | 15 + docs/spec/glossary.md | 8 + docs/spec/hardfork-spec.md | 10 +- docs/spec/overview.md | 2 +- docs/spec/system-contracts/keyless-deploy.md | 48 + docs/spec/upgrades/overview.md | 2 +- docs/spec/upgrades/satin.md | 673 +++++--- mutants/README.md | 8 +- mutants/suppressions.toml | 151 +- scripts/fuzz_price_monotonic.py | 74 + scripts/keyless_deploy.sh | 236 --- scripts/mutation_gate.py | 57 +- scripts/mutation_test.sh | 3 +- scripts/price_grid.sh | 27 +- scripts/test_mutation_gate.py | 44 + 353 files changed, 41519 insertions(+), 21290 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/fuzz.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 delete mode 100644 bin/mega-evme/src/run/README.md create mode 100644 bin/mega-evme/tests/dump_code.rs 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/block/genesis.rs create mode 100644 crates/mega-evm/src/block/l1_block_info.rs create mode 100644 crates/mega-evm/src/evm/validation.rs delete mode 100644 crates/mega-evm/src/system/deploy.rs create mode 100644 crates/mega-evm/src/system/predeploys.rs create mode 100644 crates/mega-evm/src/test_utils/witness.rs delete mode 100644 crates/mega-evm/tests/_pending/README.md create mode 100644 crates/mega-evm/tests/block/activation.rs create mode 100644 crates/mega-evm/tests/block/bucket_ids.rs rename crates/mega-evm/tests/block/{protocol_limits.rs => building_policy.rs} (68%) delete mode 100644 crates/mega-evm/tests/block/deploy.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/sequences.rs create mode 100644 crates/mega-evm/tests/block/stale.rs create mode 100644 crates/mega-evm/tests/block/system_tx_budgets.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/corpus.rs create mode 100644 crates/mega-evm/tests/satin/count_order.rs create mode 100644 crates/mega-evm/tests/satin/failed_deposit.rs create mode 100644 crates/mega-evm/tests/satin/floor_exempt.rs delete mode 100644 crates/mega-evm/tests/satin/kv_limit.rs create mode 100644 crates/mega-evm/tests/satin/limit_stop.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 delete mode 100644 crates/mega-evm/tests/satin/state_gas_limit.rs create mode 100644 crates/mega-evm/tests/satin/state_growth.rs create mode 100644 crates/mega-evm/tests/shared/snapshot.rs delete mode 100644 crates/mega-evm/tests/system/deploy.rs create mode 100644 crates/mega-evm/tests/system/keyless/interface.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/predeploys.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/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/witness.rs create mode 100644 crates/mega-state-test/tests/blockchain.rs create mode 100644 crates/mega-state-test/tests/witness.rs create mode 100644 crates/state-test/src/btest.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 create mode 100755 scripts/fuzz_price_monotonic.py delete mode 100755 scripts/keyless_deploy.sh 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/.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/scripts/bench_compare.py b/.github/scripts/bench_compare.py deleted file mode 100644 index 393a2fa27..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", -] -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 index 4329a20e5..104068d6c 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -11,6 +11,21 @@ name: Execution-spec tests on Satin # 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. @@ -74,13 +89,27 @@ jobs: echo "run=true" >> "$GITHUB_OUTPUT" exit 0 fi - # The paths the push trigger filters on; the two lists stay equal. A rename lists both of - # its paths, so a file moved out of a covered path counts. - covered='^(Cargo\.lock|Cargo\.toml|rust-toolchain\.toml|\.github/workflows/exec-spec-satin\.yml)$|^crates/(mega-evm|mega-state-test|state-test|system-contracts)/' - if git diff --name-only --no-renames 'HEAD^1' HEAD | grep -qE "$covered"; then - run=true - else + # 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" @@ -100,6 +129,12 @@ jobs: 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: @@ -160,13 +195,21 @@ jobs: 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 cache is keyed on the archives themselves: another name or host at the same - # version is another download. - archives=$(printf '%s\n%s\n' "$main" "$devnet" | sha256sum | cut -c1-16) + # 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 "key=eest-state-tests-$main_version-$devnet_version-$archives" + 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 @@ -181,18 +224,23 @@ jobs: 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" - # Only the state tests: the archive's top-level `fixtures/` directory is stripped, as - # the fork's runner strips it. - tar -xzf "fixtures/$1.tar.gz" --strip-components=1 -C "fixtures/$1" fixtures/state_tests + tar -xzf "fixtures/$1.tar.gz" --strip-components=1 -C "fixtures/$1" "${members[@]}" rm "fixtures/$1.tar.gz" } - fetch main "$MAIN_URL" - fetch devnet "$DEVNET_URL" + fetch main "$MAIN_URL" "$MAIN_DIRS" + fetch devnet "$DEVNET_URL" "$DEVNET_DIRS" - uses: actions-rust-lang/setup-rust-toolchain@v1 @@ -252,6 +300,116 @@ jobs: 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] diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index f027dcc6f..227f3c190 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -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 7255c0e54..520a81851 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -1,22 +1,24 @@ name: Mutation Testing -# All mutation-testing CI lives here. Five 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 # * gate self-test — the scorer's and the driver's own tests -# All four gates share the scorer scripts/mutation_gate.py. See mutants/README.md. +# 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: @@ -197,139 +199,6 @@ jobs: target/mutants-infra/recheck.log 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 - 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' - runs-on: ubuntu-24.04 - timeout-minutes: 330 - strategy: - fail-fast: false - matrix: - subsystem: [evm, limit, block, access, external, system, sandbox] - 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 - # ── 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 diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml deleted file mode 100644 index e66f158da..000000000 --- a/.github/workflows/replay-bench.yml +++ /dev/null @@ -1,270 +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: the corpus under bench/replay/fixtures is - # keyed by the legacy Rex5 spec, and the Satin `state-test` has no `--bench` - # mode; the job returns with a corpus and a bench mode for Satin. (`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 04f674c95..eb470a8c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,22 +6,25 @@ 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. +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) @@ -41,6 +44,12 @@ UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin 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 @@ -60,38 +69,38 @@ 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` | yes | Execution-spec state-test runner on Satin: the equivalence gate, the report | -| `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 | -| `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 | `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. -`mega-t8n` still targets the legacy engine. -It is outside `[workspace] members`, so no workspace command builds it; do not edit its sources until it is ported to Satin. - ### 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: the engine's graph (the default member) never reaches another. - The workspace also locks revm 27.1.0, linked only by `mega-evme`'s legacy leg (`cargo tree --workspace -i revm@27.1.0`). + 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. @@ -101,37 +110,46 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### 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` … `Rex6`) 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. +- 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 (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 record, the Oracle's storage read through the oracle service, the volatile-read marks and refusals and the non-warming journal reads (`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 creation-revival refusal, 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`) | — | -| `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`, the Satin params type carrying the limits every node shares (the per-transaction runtime limits and the four block budgets, today's values as its default), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the execution-gas, state-gas, data-size and KV block limits (`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 system-contract deploy, the `SequencerRegistry`'s due changes and the pre-block state observer in `apply_pre_execution_changes`; `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.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, the log and code bytes of the history byte count and the state gas held outside each frame, which is what the state-gas limit counts (`frame_limit.rs`), staging, the latch, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; `EvmTxRuntimeLimits` (the data-size and KV limits: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap, each in its own unit; the per-transaction state-gas limit; gas detention's two caps, the spec's by default; in block execution the chain's, from `ProtocolLimits`) | — | -| `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 deploy helper, the EIP-7997 factory and `SequencerRegistryConfig` (`deploy.rs`, `sequencer_registry.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address a transaction of the system shape makes when it is validated (`sequencer_registry.rs`, `tx.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`, `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`) | — | +| 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 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 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. @@ -140,7 +158,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. @@ -153,7 +171,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 and binds nothing: history charges the same bytes at a higher rate. + 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. @@ -167,53 +186,54 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. - A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped through the latch (the contracts below). - A bare `MegaContext` sets no limit but detention's caps; a block executor installs the chain's (see the protocol limits below), whose default 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 like the block's execution gas (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 162,306 gas, and keeping its record costs its 3,520 history on top. -- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0) and KV updates (1), counted on the lanes with a transaction limit and frame budgets; compute gas (2), gas detention's stop; and state growth (3), held as EIP-8037 state gas by a per-transaction limit. -- The KV 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 — by the data-size limit's rules in its own unit: `EvmTxRuntimeLimits::tx_kv_update_limit` stops the transaction, and every frame gets a record budget, what the transaction has left for its own frame and 98% of what its parent has left for a child, under `frame_kv_update_limit`. + 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 data size is checked before the records wherever both cross. - At the production data-size caps a transaction or a block keeps at most 327,680 records, so the KV limits bind only below that; both are unlimited unless the chain sets them, and `ProtocolLimits::block_kv_update_limit` is the block's, a packing budget like its data size. -- The state-gas limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, so nothing counts new accounts and slots beside it. - `EvmTxRuntimeLimits::tx_state_gas_limit` holds what the transaction holds, net of refills and of failed frames, so a write taken back gives its room back: the state gas charged before its first frame plus what every frame on the call stack holds, read off revm's own per-frame counters (`limit/frame_limit.rs`). - It is per transaction, with no frame budget: a child's crossing stops the whole transaction, with `MegaLimitExceeded(3, limit)` where the limit is in gas. - The outcome's `limit_exceeded` reports as used the state gas held where the limit was crossed: before the first frame, what stands (a deposit's created caller, the authorities), not the first frame's upfront charge, so a deposit whose created caller alone crosses reports that account. - It is held where state gas is charged, after the charge — a charge the frame cannot pay is an out-of-gas whatever the limit: the authorities before the first frame (taken back on a crossing), the `SSTORE` and `SELFDESTRUCT` wrappers, the new account a frame's start adds — EIP-2780's charge for the first frame's recipient or created account, and the account a `CALL`, `CREATE` or `CREATE2` is charged for upfront — once revm has decided the frame (`MegaEvm::frame_init`: a frame refused — a value call its caller cannot fund, one past the call-stack limit — or answered with a failure, such as a value transfer to a precompile that fails, gives the charge back and is never held for it; a built frame returns the stop before its first instruction and an answered one is rewritten to it, which gives back the gas they forwarded; the transaction's own frame has no caller whose revert takes an answer's writes back, so its answer is taken back to where its start began) — and, for deployed code, at the code-deposit admission (`MegaContext::admit_code_deposit`), once `return_create` has made every charge of the deposit, its state gas priced through the same hook, and before it commits the creation, as the data-size limit counts the same bytes there: a crossing refuses the deposit, which reverts the creation on the gas it had before the deposit and leaves no code behind, and a creation that cannot pay a part of its deposit — the regular costs, the state gas, the history — runs out of gas whatever the limit. - The state gas is checked before the data size and the records wherever both cross at one site; at a frame start the records are held before revm builds the frame, and a frame they stop adds no account, so its upfront state gas is given back rather than held. - It is a limit on gas, so it counts state at the price SALT sets for it: a slot or an account in a bucket `m` times the minimum costs `m` times the entry, and a crowded bucket reaches the limit sooner. - It is unlimited unless the chain sets it; the per-block one is `ProtocolLimits::block_state_gas_limit`. -- The limits that change a result are protocol values, carried by the Satin fork's parameters: `ProtocolLimits` (`block/limit.rs`), attached to the schedule with `MegaHardforkConfig::with_params` and read at the block's timestamp with `MegaHardforks::protocol_limits`. - It holds the seven per-transaction limits (`tx_runtime_limits`: data size, KV and state gas per transaction, the two frame caps, detention's two caps) and the block's execution-gas, state-gas, data-size and KV budgets; `ProtocolLimits::DEFAULT` is today's values, provisional with the constants. - `validate()` refuses a zero limit (what a field left out of a configuration reads as), a transaction data-size limit below `TX_BODY_SIZE`, and a detention cap no transaction's compute reaches — at or above `MAX_TX_COMPUTE_GAS`, 199,987,900: the execution cap less EIP-2780's base cost of 12,000 and the warm access a frame that runs code pays at least; `validate_schedule` requires the params and runs `validate()` on them, because a node's own schedule type attaches them without `with_params`; it is serde-ready (camelCase, every field required, unknown fields refused). - The block executor installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to the four budgets; a schedule with no limits at the block's timestamp refuses the block before it starts (`MissingProtocolLimits`), as an internal error: a gap in the node's configuration, like a missing `SequencerRegistryConfig`, is not a verdict on the block. - 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 four 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/protocol_limits.rs`). - The executor checks the limits again (`validate()`) and refuses a block under limits the check refuses (`InvalidProtocolLimits`, internal), whatever the schedule's type: a node's own schedule type attaches its params without `with_params`, and `validate_schedule` runs only when the node calls it. - Tests that run blocks without holding them to a limit attach `ProtocolLimits::loosest()`, the loosest limits a chain may carry (every limit unlimited, detention's caps at `MAX_TX_COMPUTE_GAS - 1`); `MegaHardforkConfig::with_params_unchecked`, which exists only under `cfg(test)` or `test-utils`, builds a schedule carrying a value no chain may carry, to test what refuses it. - An EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) runs under the limits block execution would hold its block to without being told: the factory given the chain's schedule (`with_schedule`) resolves them at the block's timestamp, and without one, or where the schedule carries no valid limits there, installs `ProtocolLimits::DEFAULT`'s; `MegaEvmFactory::with_tx_runtime_limits` is the explicit opt-out for equivalence and tests, and a `MegaContext` built by hand gets its limits from its caller through `with_tx_runtime_limits`: the state-test runner's own, and `mega-evme`'s `run` and `tx`, those of the schedule the tool runs Satin under (the chain's, or for a counterfactual the engine's fallback, `all_activated_hardforks()`, on `ProtocolLimits::DEFAULT`). -- 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, KV or state-gas limit and no frame budget stops them, and they are never latched. + 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 transaction through the latch, with `MegaLimitExceeded` of kind compute; every other out-of-gas halts as it would without the read. + 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 the chain's `ProtocolLimits` and the builder's `BlockLimits`, and fills `BlockGasCounters`. - A block limit known only after execution packs the transaction that reaches it: the execution-gas and data-size limits then refuse every later transaction before it runs, and the state-gas limit refuses a later transaction after it runs, only if it adds state gas — one that adds none still fits. - The KV limit refuses like the data-size one. - None of the four refuses a deposit: they are packing budgets for the transactions the builder chooses, and a deposit is not chosen; it still counts towards all four, so the transactions after it find the room it used. - A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which the block decides on before the engine promotes it to a deposit, so it is held to the four budgets and to the data-availability limits like any non-deposit transaction, as in the legacy engine, and an activation block refuses it. + 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`. - Neither commit checks the state a candidate executed against: a candidate executed before another commit changed that state is the builder's to execute again. - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` deploys the six MegaETH system contracts and the EIP-7997 factory every block (idempotent), handing each pre-block state to an optional observer before it is committed — that sequence is the witness a stateless client needs; after the deploy it applies a role change the `SequencerRegistry` has due in the block (see the system calls below). - It does not read the live system address: a system-address transaction reads it itself (see below). -- The six MegaETH system contracts and the EIP-7997 factory are deployed at Satin activation, idempotently, at the start of every block. - Three of the six system contracts answer calls through their interceptors (`system/`), and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless dispatch before interception. + 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` 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`). @@ -223,8 +243,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 the transaction at the compute limit. + 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. @@ -237,21 +259,24 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 the call is left with — the latch, or its own budget crossed by the creator's nonce record — 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 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` stay in the ABI with no producer: 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. -- 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, 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::is_live_system_transaction`, called first thing in `MegaHandler::validate_env`): only a transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — reads `_currentSystemAddress` from the journal, cold and without the registry's code, and compares it with its caller. - A transaction of any other shape reads nothing and is never a system-address transaction, whoever sent it: one from the system address is an ordinary transaction, validated and charged as a user's is, where the legacy engine refused it. - That is the engine's view, not the contracts': the Oracle's `onlySystemAddress` tests the sender alone, so a non-legacy transaction signed by the system key to the Oracle is accepted by the Oracle and its writes land, executed as a user's transaction — it pays fees, is held to every per-transaction limit, is detained, is priced by bucket, and pays history; both engines refused it at validation before. + `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 deploys and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution the pre-block deploy guarantees the code. - It is a read of the transaction's own, so the slot is in the system-address transaction's state and witness, not in the pre-block witness. + 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`). @@ -268,7 +293,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 reaches the observer. + 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`). @@ -295,7 +320,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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::DEFAULT` detain, and `ProtocolLimits::validate` refuses a cap at or above `MAX_TX_COMPUTE_GAS`, which never binds, so no chain 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. @@ -305,7 +330,8 @@ Detention caps how much a transaction may still compute once it read such data ( - **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 latch'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 the sender, and the transaction is billed its compute at the crossing, less than one charge short of the limit. + 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. @@ -324,7 +350,7 @@ Detention caps how much a transaction may still compute once it read such data ( - **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 transaction through the latch, and the call returns the stop on its resume, which takes the deployment back. + 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.** @@ -332,7 +358,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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, 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. + `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. @@ -346,7 +372,7 @@ 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, 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. @@ -354,49 +380,51 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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, and the KV limit holds it. + 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. + `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. - What the state-gas limit holds outside each frame is on its lane: a lane pushed holds what its caller's holds plus what its caller held when it suspended on it. -- **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. - The rewrite takes every result, whatever produced it — revm, an interceptor, or an inspector that turned it into a success or a halt (`AdditionalLimit::apply_latch`): no frame runs an instruction under the latch, so a halt there can only be an inspector's. - A stopped creation an inspector revived is one of them: the creation-revival refusal puts it back and leaves a latched transaction to the latch rather than failing 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. 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 frame budget reverts its frame alone, without a latch. - The stop 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_gas_limit.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), and EIP-7702 authorities whose state gas or records would cross it are taken back before the first frame. - The one exception is the state gas charged upfront for the account a frame's start adds — by the opcode that starts it, or by EIP-2780 for the transaction's own frame: revm gives it back for a frame it refuses or answers with a failure, so it is held once revm has decided the frame, and what the frame's start wrote goes with the frames the stop reverts; the transaction's own frame has no caller whose revert follows, so an answer of it that the stop rewrites has its journal taken back to where its start began. + 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 body over the limit latches the transaction before it runs: pre-execution applies no authorization and charges no record made outside a frame, the first frame's input is built with nothing charged for its start, and the first frame is answered with the stop. - 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 — only the account a deposit-like transaction creates for its caller can still run a latched transaction out of gas there, and then the halt clears the latch. + 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. - `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result, and a column of stopped creations that inspector revives. + 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. + 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. - The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`), unless the transaction is latched: the creation is put back, and the latch reports the stop. - A creation stopped by its own frame budget latches nothing, and its revival is refused. + 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, as does, for the transaction's own frame, the history of its write record. + 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`. @@ -429,25 +457,79 @@ 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. +- `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. -- `_pending/` — no test any more: its `README.md` records where each legacy test the test inventory kept went, ported into one of the targets above or retired, and why. - It has no `main.rs`, so Cargo builds nothing there. +- `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 every check a pull request meets; two of them are this repository's own execution gates, and a third holds the suite at other byte prices. +`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 @@ -502,12 +584,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. +- **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. @@ -517,6 +604,18 @@ When the agent is requested to implement a new feature or bug fix, it should con 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. @@ -533,18 +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, or with params their `validate()` refuses, is rejected at load time. - A fork may carry several params types (Satin carries `SequencerRegistryConfig` and `ProtocolLimits`): a schedule keeps one value per type, and `MegaHardforks::fork_params_any` answers by fork and `TypeId`. -- **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 EIP-2935 and EIP-4788 calls and the post-block balance increments, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, 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, ...};`. @@ -565,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/Cargo.lock b/Cargo.lock index 966e63818..b50a95875 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -79,16 +79,16 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b836b372d3b742b7c083d2617d6e68563cd5dadbd8752c461a935a756551e69" +checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" dependencies = [ - "alloy-eips 2.4.2", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "alloy-trie", - "alloy-tx-macros 2.4.2", + "alloy-tx-macros 2.1.1", "auto_impl", "borsh", "c-kzg", @@ -120,15 +120,15 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1befb37485ea71e8599e32ffd76c98af7c3720a34741d30abd87f41c3148407" +checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "serde", ] @@ -224,9 +224,9 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3e76d47e8de277cb55e7e77fa38adde835162fc01cddbe1b258b5e0a86035b" +checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" dependencies = [ "alloy-eip2124", "alloy-eip2930", @@ -234,7 +234,7 @@ dependencies = [ "alloy-eip7928 0.4.11", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "auto_impl", "borsh", "c-kzg", @@ -272,12 +272,12 @@ version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6e494529570a4d25eb4d1a7456d8f969c3202aceaf703e4006cec5f730aee96" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "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 2.4.2", + "alloy-rpc-types-eth 2.1.1", "alloy-sol-types", "auto_impl", "derive_more", @@ -288,13 +288,13 @@ dependencies = [ [[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 2.4.2", + "alloy-eips 2.1.1", "alloy-primitives", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "alloy-trie", "borsh", "serde", @@ -356,9 +356,9 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a523ca087dda941e53f6ecde5bf5df78b9dbe760f3f77488e13dbf355de4a84" +checksum = "c4691c60de5d628533752cd07e102d17c47874c06c04c91af33960fd94c484f4" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -397,20 +397,20 @@ dependencies = [ [[package]] name = "alloy-network" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f263c8d752b15e19b7c2d3cbad00338ec2d7cc923a46cd1ff98aea2fa333166b" +checksum = "9d912bb639bf4ac31e83095afe9e907c8b9774ce0c405966228368309fcfc45f" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-consensus-any 2.4.2", - "alloy-eips 2.4.2", - "alloy-json-rpc 2.4.2", - "alloy-network-primitives 2.4.2", + "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 2.4.2", - "alloy-rpc-types-eth 2.4.2", - "alloy-serde 2.4.2", - "alloy-signer 2.4.2", + "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", @@ -436,14 +436,14 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8795eecf50374a0dd942caff57922c59333c9991ead9eccbbc1709f55d73c7c2" +checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "serde", ] @@ -469,8 +469,8 @@ name = "alloy-op-evm" version = "0.32.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-evm 0.36.0", "alloy-op-hardforks 0.5.0", "alloy-primitives", @@ -572,25 +572,25 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef487e44dfae9c87cb732989d3f43682f65aefb11a0f56045b26be357f671fcf" +checksum = "0e7d526d184d392a8fbcf4293e457789b307bb70646e4f8b902989a246529450" dependencies = [ "alloy-chains", - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", - "alloy-json-rpc 2.4.2", - "alloy-network 2.4.2", - "alloy-network-primitives 2.4.2", + "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 2.4.2", + "alloy-rpc-client 2.1.1", "alloy-rpc-types-debug", - "alloy-rpc-types-eth 2.4.2", - "alloy-rpc-types-trace 2.4.2", - "alloy-signer 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-trace 2.1.1", + "alloy-signer 2.1.1", "alloy-sol-types", - "alloy-transport 2.4.2", - "alloy-transport-http 2.4.2", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", "async-stream", "async-trait", "auto_impl", @@ -598,8 +598,7 @@ dependencies = [ "either", "futures", "futures-utils-wasm", - "http", - "lru 0.18.4", + "lru 0.16.4", "parking_lot", "pin-project", "reqwest 0.13.5", @@ -659,14 +658,14 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98267c2d47f9c185b575bac3f772a8ca66bcbd712693535e50980c12eab80a42" +checksum = "755447dc13a04c6fa6db8dedb5d32ab5edfa4dd7aa34487ff192a3d873e0e8cf" dependencies = [ - "alloy-json-rpc 2.4.2", + "alloy-json-rpc 2.1.1", "alloy-primitives", - "alloy-transport 2.4.2", - "alloy-transport-http 2.4.2", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", "futures", "pin-project", "reqwest 0.13.5", @@ -693,24 +692,24 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1176430031ba27abfb51b95516cf71e8ce3ff4172c72f3136627f0f89813a739" +checksum = "911a513723ef0b90c3b072f65eebf54d6ebc8b651d06734e252d024bd89b88ac" dependencies = [ - "alloy-consensus-any 2.4.2", - "alloy-network-primitives 2.4.2", + "alloy-consensus-any 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", - "alloy-rpc-types-eth 2.4.2", - "alloy-serde 2.4.2", + "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", @@ -721,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 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "derive_more", "ethereum_ssz", "ethereum_ssz_derive", @@ -761,17 +760,17 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "756eb5803e70985be4066b636194ccb5f6629e5d141817c1f0c50cea8350bf5c" +checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-consensus-any 2.4.2", - "alloy-eips 2.4.2", - "alloy-network-primitives 2.4.2", + "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 2.4.2", + "alloy-serde 2.1.1", "alloy-sol-types", "itertools 0.14.0", "serde", @@ -796,13 +795,13 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "2.4.2" +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 2.4.2", - "alloy-serde 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "serde", "serde_json", "thiserror", @@ -821,9 +820,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc142e40df0c3eb5983b1637a68ab33471d8d22b8f402c9ed8260411a4e89d86" +checksum = "c1e97b3e0b9f816b25083045dcfa69431bd059a078e828e4d82d296d1949b96c" dependencies = [ "alloy-primitives", "serde", @@ -847,9 +846,9 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c84f88f8a29d2607f98993687ed55a5943ba06819bc2126bb078dca54be943" +checksum = "6913d06ccc0d9c6ab67e2f82e2fbe292706da1f91442f30cded2d04b56bf0d58" dependencies = [ "alloy-primitives", "async-trait", @@ -955,11 +954,11 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" +checksum = "999adfe5c91035c6bf4c4210e0eb8d0caed79d76fbf5e1b70d78721f6097ac04" dependencies = [ - "alloy-json-rpc 2.4.2", + "alloy-json-rpc 2.1.1", "auto_impl", "base64 0.22.1", "derive_more", @@ -993,12 +992,12 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" +checksum = "0e79a2c1793afc61eed9ca0963da370a988b27d2bbfa67c78013e262d47424c4" dependencies = [ - "alloy-json-rpc 2.4.2", - "alloy-transport 2.4.2", + "alloy-json-rpc 2.1.1", + "alloy-transport 2.1.1", "itertools 0.14.0", "reqwest 0.13.5", "serde_json", @@ -1037,9 +1036,9 @@ dependencies = [ [[package]] name = "alloy-tx-macros" -version = "2.4.2" +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", @@ -1915,7 +1914,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -2515,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -2911,13 +2910,22 @@ dependencies = [ [[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 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", ] @@ -3282,6 +3290,18 @@ dependencies = [ "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" @@ -3296,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3580,11 +3600,11 @@ dependencies = [ [[package]] name = "lru" -version = "0.18.4" +version = "0.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" dependencies = [ - "hashbrown 0.17.1", + "hashbrown 0.16.1", ] [[package]] @@ -3640,22 +3660,26 @@ dependencies = [ name = "mega-evm" version = "2.0.0-alpha.1" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "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", + "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", @@ -3704,19 +3728,19 @@ dependencies = [ name = "mega-evme" version = "2.0.0-alpha.1" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", - "alloy-json-rpc 2.4.2", - "alloy-network 2.4.2", + "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.4.2", - "alloy-rpc-client 2.4.2", - "alloy-rpc-types-eth 2.4.2", - "alloy-rpc-types-trace 2.4.2", - "alloy-serde 2.4.2", + "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.4.2", - "alloy-transport-http 2.4.2", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", "alloy-trie", "clap", "dirs", @@ -3769,6 +3793,7 @@ dependencies = [ 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", @@ -4095,13 +4120,13 @@ name = "op-alloy-consensus" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", - "alloy-network 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-network 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.4.2", - "alloy-serde 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "bytes", "derive_more", "reth-codecs", @@ -4138,10 +4163,10 @@ name = "op-alloy-network" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-network 2.4.2", - "alloy-provider 2.4.2", - "alloy-rpc-types-eth 2.4.2", + "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", ] @@ -4151,11 +4176,11 @@ name = "op-alloy-provider" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-network 2.4.2", + "alloy-network 2.1.1", "alloy-primitives", - "alloy-provider 2.4.2", + "alloy-provider 2.1.1", "alloy-rpc-types-engine", - "alloy-transport 2.4.2", + "alloy-transport 2.1.1", "async-trait", "op-alloy-rpc-types-engine", ] @@ -4184,13 +4209,13 @@ name = "op-alloy-rpc-types" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", - "alloy-network 2.4.2", - "alloy-network-primitives 2.4.2", + "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 2.4.2", - "alloy-serde 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "derive_more", "op-alloy-consensus 2.0.0", "reth-rpc-traits", @@ -4204,12 +4229,12 @@ name = "op-alloy-rpc-types-engine" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-serde 2.4.2", + "alloy-serde 2.1.1", "ethereum_ssz", "ethereum_ssz_derive", "op-alloy-consensus 2.0.0", @@ -5077,8 +5102,8 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9c37bb4d1bac98661bf9128e1141b969034640d68697b22f70377e492fd332c" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -5107,12 +5132,12 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9102518f0bbf99bc8f0e656a56fb2a7513248630275b608d3706076a82fde42b" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-eips 2.4.2", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-genesis", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.4.2", + "alloy-rpc-types-eth 2.1.1", "alloy-trie", "bytes", "derive_more", @@ -5131,11 +5156,11 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa03a2c9681c385ae1c72b169ac9c3525163b71db0b3362f16e8929e19e45fd" dependencies = [ - "alloy-consensus 2.4.2", - "alloy-network 2.4.2", + "alloy-consensus 2.1.1", + "alloy-network 2.1.1", "alloy-primitives", - "alloy-rpc-types-eth 2.4.2", - "alloy-signer 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-signer 2.1.1", "reth-primitives-traits", "thiserror", ] @@ -5295,9 +5320,9 @@ name = "revm-database" version = "15.0.2" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ - "alloy-eips 2.4.2", - "alloy-provider 2.4.2", - "alloy-transport 2.4.2", + "alloy-eips 2.1.1", + "alloy-provider 2.1.1", + "alloy-transport 2.1.1", "derive_more", "revm-bytecode 11.0.1", "revm-database-interface 12.1.1", @@ -5432,8 +5457,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e93b96ddc470322a7294b8aecad862480625a9f1346d42fea51b1cce54afdb05" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 2.4.2", - "alloy-rpc-types-trace 2.4.2", + "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-trace 2.1.1", "alloy-sol-types", "anstyle", "colorchoice", @@ -5739,7 +5764,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6130,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" @@ -6239,7 +6270,9 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" 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", @@ -6396,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6952,7 +6985,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ca9d94180..ae3ba2ae5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,5 @@ [workspace] -# `bin/mega-t8n` still targets the legacy engine; its sources are kept untouched and it -# rejoins the workspace when it is ported to Satin, as `bin/mega-evme` has. members = [ "bin/mega-evme", "crates/mega-evm", @@ -18,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" @@ -163,37 +161,27 @@ 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 } diff --git a/README.md b/README.md index 39329cab0..b976a9e72 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,6 @@ A specialized Ethereum Virtual Machine (EVM) implementation tailored for MegaETH | [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-t8n](bin/mega-t8n) | Standalone state transition (t8n) tool | | [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 | diff --git a/REVIEW.md b/REVIEW.md index c20bb0df2..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 @@ -71,9 +82,6 @@ This is the single most important correctness concern in mega-evm. - **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.** @@ -89,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. @@ -104,10 +118,26 @@ These checks guard every change to the Satin engine. 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`. @@ -122,7 +152,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` (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 that already holds the predeploys, under `BlockLimits::default()`; the one-off deployment of the first block after activation is its own arm, `block/activation_pre_block`. +- `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. @@ -142,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. @@ -151,18 +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, the nightly byte-price grid) 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. - `price-grid.yml`: the whole byte-price grid. - - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the replay corpus, which is keyed by the legacy Rex5 spec, and a bench mode of the state-test tool exist for Satin. ## 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 9f811d1a2..000000000 --- a/bench/replay/README.md +++ /dev/null @@ -1,133 +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 --manifest-path bin/mega-evme/Cargo.toml -cargo build --release -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 cd92e227c..780505a48 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -5,18 +5,19 @@ CLI toolbox for direct MegaEVM execution (`run`, `tx`, `replay`) with optional f 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`: argument parsing, engine selection, and dispatch; a legacy spec's arguments are handed unchanged to the 1.7.1 CLI, but for `--spec Rex6` added, before any `--`, to a `run` or `tx` that left `--spec` out (the 1.7.1 default is `Rex7`). -- `src/engine.rs`: which engine a spec or a block runs on; the hand-off to the legacy CLI. +- `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 (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`), records and the comparison (`record.rs`), the driver (`cmd.rs`). +- `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. @@ -29,7 +30,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - 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`. -- Do not build a Satin hardfork schedule, or attach its params, in the CLI: a counterfactual takes the engine's own schedule for a chain it does not know (`mega_evm::all_activated_hardforks`), so it carries every params type Satin requires, and a chain's own Satin schedule is used as it is or refused. +- 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. @@ -37,8 +38,8 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - 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 which engine a spec or block runs on: `src/engine.rs`; which Satin schedule and limits it runs under: `src/common/schedule.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/README.md b/bin/mega-evme/README.md index ed45f13e8..a8510ddf7 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -33,8 +33,10 @@ Every command runs on the engine its spec names. 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 the protocol limits of the chain's schedule at the block's timestamp; a chain that does not run Satin there (mainnet and testnet today, the default chain, any chain the tool does not know) runs on Satin's default limits, a counterfactual. -`--override.limits ` on `run`, `tx` and `replay` replaces the fields it names of those limits; it is refused on a legacy spec. +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. @@ -118,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). --- @@ -131,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 @@ -207,11 +209,11 @@ 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 | --- @@ -222,13 +224,10 @@ The spec, and so the engine, comes from the chain's schedule at the block's time ```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 @@ -239,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 @@ -280,7 +279,7 @@ mega-evme replay 0x1234...txhash --override.input-file calldata.hex # 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 EIP-7997 factory over RPC; +# 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 ``` @@ -306,7 +305,7 @@ These options are available across all commands. | Option | Default | Description | | ---------------------- | ------- | ----------------------------------------- | -| `--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) | +| `--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 @@ -391,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... ``` @@ -449,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 index 407f2683b..3c78654d9 100644 --- a/bin/mega-evme/src/block/cmd.rs +++ b/bin/mega-evme/src/block/cmd.rs @@ -128,9 +128,19 @@ pub async fn replay_blocks( for number in range.from..=range.to { summary.blocks += 1; let outcome = async { - let inputs = source.load(number, &mut codes).await?; - let engine = forced_engine - .unwrap_or_else(|| Engine::of_block(inputs.chain_id, inputs.header.timestamp)); + 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 = @@ -173,7 +183,7 @@ pub async fn replay_blocks( serde_json::json!({ "kind": "block", "block": number, "error": message }) ); } else { - println!("block {number} error: {message}"); + println!("block {number} error: {}", crate::sanitize_terminal_text(&message)); } summary.failed.push((number, message)); } @@ -197,7 +207,10 @@ pub async fn replay_blocks( /// 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. +/// 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, @@ -206,11 +219,13 @@ pub fn execute_block( 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, @@ -223,6 +238,11 @@ pub fn execute_block( 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), } } diff --git a/bin/mega-evme/src/block/inputs.rs b/bin/mega-evme/src/block/inputs.rs index 9b307bab3..dd34de4f6 100644 --- a/bin/mega-evme/src/block/inputs.rs +++ b/bin/mega-evme/src/block/inputs.rs @@ -25,8 +25,8 @@ 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, and the -/// pre-state built from its trace. +/// 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. @@ -39,6 +39,12 @@ pub struct CachedBlock { 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. @@ -142,7 +148,11 @@ pub struct BlockInputs { pub receipts: Vec, /// The part of the parent block's state the block reads. pub prestate: BlockPrestate, - /// Whether the inputs came from the block cache. + /// 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), @@ -155,6 +165,7 @@ impl BlockInputs { block: Value, receipts: Value, prestate: BlockPrestate, + parent_timestamp: Option, from_cache: bool, ) -> Result { let parsed: Block = serde_json::from_value(block.clone()) @@ -215,6 +226,7 @@ impl BlockInputs { transactions, receipts: chain_receipts, prestate, + parent_timestamp, from_cache, raw: (block, receipts), }) @@ -228,6 +240,7 @@ impl BlockInputs { block: self.raw.0.clone(), receipts: self.raw.1.clone(), prestate: prestate.clone(), + parent_timestamp: self.parent_timestamp, } } } @@ -313,6 +326,7 @@ impl BlockSource { cached.block, cached.receipts, cached.prestate, + cached.parent_timestamp, true, ); } @@ -338,7 +352,46 @@ impl BlockSource { request("debug_traceBlockByNumber", json!([tag, { "tracer": "prestateTracer" }])) .await?; let prestate = BlockPrestate::from_block_trace(trace, codes)?; - BlockInputs::from_responses(chain_id, block, receipts, prestate, false) + 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. diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 5868b0f2b..3e2eb3159 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -12,8 +12,8 @@ use mega_evm::{ inspector::NoOpInspector, primitives::eip4844, }, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaHardforks, - MegaSpecId, MegaTxEnvelope, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, + MegaHardforkConfig, MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits, }; use super::{ @@ -22,26 +22,31 @@ use super::{ state::{BlockState, SatinDb}, }; use crate::common::{ - decode_revert_reason, format_halt_reason, satin_schedule, EvmeError, EvmeExternalEnvs, - LimitsOverride, Result, SatinReport, + 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 the protocol limits that schedule carries, or `limits_override` over them, with no -/// building policy, and with the block's gas limit from its header. A transaction the engine -/// refuses is reported as refused and left out, and the block goes on. +/// — 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, limits_override)?; + 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 { @@ -66,14 +71,22 @@ pub(super) fn execute( let factory = MegaBlockExecutorFactory::new( OpAlloyReceiptBuilder::default(), &hardforks, - MegaEvmFactory::new().with_schedule(hardforks.clone()).with_external_env_factory(envs), + 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(); @@ -83,6 +96,9 @@ pub(super) fn execute( block_ctx, NoOpInspector, ); + if let Some(limits) = limits_override { + executor = executor.with_protocol_limits(limits); + } let mut run = || -> Result { executor .apply_pre_execution_changes() @@ -127,8 +143,6 @@ pub(super) fn execute( satin: Some(satin), }); } - let limits_override = - limits_override.and_then(|_| hardforks.protocol_limits(header.timestamp)); Ok(ExecutedBlock { transactions: results, limits_override }) }; run() @@ -139,3 +153,86 @@ pub(super) fn execute( } 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/cmd.rs b/bin/mega-evme/src/cmd.rs index 862f52625..065cfa99b 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -3,8 +3,13 @@ use std::ffi::OsString; use clap::{parser::ValueSource, ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand}; use tracing::error; +use mega_evm::MegaSpecId; + use crate::{ - common::{EvmeError, LimitsOverride, LogArgs}, + common::{ + check_genesis_chain, parse_genesis, sanitize_terminal_text, use_genesis, EvmeError, + GenesisChain, LimitsOverride, LogArgs, + }, engine::Engine, }; @@ -16,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, @@ -53,45 +66,61 @@ pub enum Error { 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 cmd = MainCmd::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); + 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, - }; - let engine = match engine { - Ok(engine) => engine, - Err(e) => { - eprintln!("{e}"); - std::process::exit(1); - } - }; + }?; 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() => { - eprintln!( - "{}", - EvmeError::InvalidInput( - "--override.limits applies to Satin only: the legacy engine holds a \ - transaction to its spec's own limits" - .to_string() - ) - ); - std::process::exit(1); - } + 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 => { - if let Err(e) = crate::engine::run_legacy(args, spec_is_default).await { - eprintln!("{e}"); - std::process::exit(1); - } - Ok(()) + 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 { @@ -111,6 +140,25 @@ impl Commands { } } + /// 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 { @@ -136,8 +184,45 @@ impl MainCmd { }; 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 0047e4bbf..8d0999d48 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -12,14 +12,16 @@ use mega_evm::{ context::{block::BlockEnv, cfg::CfgEnv}, primitives::eip4844, }, - AHashBucketHasher, MegaContext, MegaHardforks, MegaSpecId, ProtocolLimits, 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::{parse_limits_override, satin_schedule, EvmeError, LimitsOverride, Result}; +use super::{ + parse_limits_override, satin_limits, satin_schedule, EvmeError, LimitsOverride, Result, +}; /// Chain configuration arguments (spec and chain ID) #[derive(Args, Debug, Clone)] @@ -28,7 +30,7 @@ pub struct ChainArgs { /// 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) + /// `Equivalence`/`MiniRex` behavior). Under `--genesis` the default is `Satin` #[arg(long = "spec", default_value = "Rex6")] pub spec: String, @@ -36,11 +38,10 @@ pub struct ChainArgs { #[arg(long = "chain-id", visible_aliases = ["chainid"], default_value = "6342")] pub chain_id: u64, - /// Satin only: run under these protocol limits instead of the chain's, a counterfactual. A - /// JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, - /// per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names - /// replace the chain's, every other stays. Refused when it names an unknown field or a value - /// no chain may carry + /// 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, } @@ -62,15 +63,13 @@ impl ChainArgs { Ok(cfg) } - /// The protocol limits a Satin run of this chain at `timestamp` is held to: those of the - /// schedule [`satin_schedule`] gives, which for a chain that does not run Satin at `timestamp` - /// is a counterfactual on [`ProtocolLimits::DEFAULT`], with `--override.limits` over them. + /// 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, self.limits_override.as_ref())? - .protocol_limits(timestamp) - .ok_or_else(|| { - EvmeError::Other(format!("the Satin schedule carries no limits at {timestamp}")) - }) + satin_schedule(self.chain_id, timestamp)?; + satin_limits(self.limits_override.as_ref()) } } @@ -207,8 +206,8 @@ impl EnvArgs { self.ext.create_external_envs() } - /// The protocol limits a Satin run is held to when `--override.limits` replaced the - /// schedule's, for its report; `None` without an override. + /// 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); @@ -218,14 +217,12 @@ impl EnvArgs { /// Creates a [`MegaContext`] with all environment configurations. /// - /// The transaction is held to the per-transaction limits a block of the chain at the block's - /// timestamp would hold it to ([`ChainArgs::protocol_limits`]), as a node's EVM factory holds - /// an EVM it builds outside block execution. + /// 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. /// - /// 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. + /// 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, @@ -271,19 +268,29 @@ mod tests { use super::*; use mega_evm::{revm::database::EmptyDB, MegaEvm}; - /// A `run` or `tx` on Satin is held to the chain's per-transaction limits: on the tool's - /// default chain, which does not run Satin, the protocol's defaults, where a bare context - /// would hold it to gas detention's caps alone. + /// 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(), ProtocolLimits::DEFAULT.tx_runtime_limits); - assert_ne!( + assert_eq!(*evm.tx_runtime_limits(), satin); + assert_eq!( *MegaEvm::new(MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN)) .tx_runtime_limits(), - ProtocolLimits::DEFAULT.tx_runtime_limits, - "a bare context does not hold the transaction data-size limit" + 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 69ca5bc05..4207f679c 100644 --- a/bin/mega-evme/src/common/error.rs +++ b/bin/mega-evme/src/common/error.rs @@ -1,17 +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, database_interface::bal::EvmDatabaseError}, -}; +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), @@ -20,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), @@ -68,6 +56,10 @@ 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 @@ -84,3 +76,99 @@ impl From> for EvmeError { /// 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/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 23cfa45b1..f4bbef346 100644 --- a/bin/mega-evme/src/common/mod.rs +++ b/bin/mega-evme/src/common/mod.rs @@ -11,6 +11,7 @@ mod tx; mod tx_override; pub use env::*; +pub(crate) use error::sanitize_terminal_text; pub use error::*; pub use hex::*; pub use logging::*; diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index e3d31c46f..942cbfe83 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -5,7 +5,7 @@ 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; @@ -60,7 +60,8 @@ pub struct SatinReport { pub data_size: u64, /// Account and storage write records the transaction kept: its KV count. pub write_records: u64, - /// The transaction-level limit that stopped the transaction, if one did. + /// 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 @@ -69,16 +70,14 @@ pub struct SatinReport { pub limits_override: Option>, } -/// A transaction-level limit that stopped a Satin transaction. +/// A limit that stopped a Satin transaction. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct LimitStop { - /// The dimension: `data_size`, `kv_update`, `compute_gas` or `state_growth`. + /// 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: for `state_growth`, the state gas held - /// at that point, so a deposit whose created caller alone crosses the limit reports that - /// account, even where its first frame would add another. + /// The usage that crossed it, where it crossed it. pub used: u64, } @@ -110,9 +109,7 @@ impl SatinReport { pub const fn limit_kind_name(kind: LimitKind) -> &'static str { match kind { LimitKind::DataSize => "data_size", - LimitKind::KVUpdate => "kv_update", LimitKind::ComputeGas => "compute_gas", - LimitKind::StateGrowth => "state_growth", } } @@ -159,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, }; @@ -182,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), @@ -226,7 +227,10 @@ pub fn print_execution_summary( 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 { reason, .. } => { println!("Status: Halted"); @@ -263,6 +267,9 @@ pub fn print_satin_report(report: &SatinReport) { /// - `Error(string)` via `alloy_sol_types::Revert` /// - `Panic(uint256)` via `alloy_sol_types::Panic` /// - Raw hex fallback +/// +/// 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(); @@ -475,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 1b1d0c13d..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: alloy_transport_http::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, @@ -262,9 +257,7 @@ impl RpcArgs { .to_string(), ) })?; - let url: alloy_transport_http::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)?; let chain_id = self.resolve_chain_id(url.clone()).await?; Ok((build_bare_op_provider(self.build_retry_client(url)), chain_id)) } @@ -323,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: alloy_transport_http::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() { @@ -357,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. @@ -378,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)", @@ -428,10 +422,10 @@ 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: alloy_transport_http::reqwest::Url) -> Result { - let url_str = url.as_str().to_string(); + 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)) }) } } @@ -467,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 @@ -474,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() @@ -488,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 index 41cbd2783..ca93f4ea0 100644 --- a/bin/mega-evme/src/common/schedule.rs +++ b/bin/mega-evme/src/common/schedule.rs @@ -1,47 +1,173 @@ -//! The hardfork schedule a Satin run executes under, and so the protocol limits it is held to. +//! The hardfork schedule a Satin run executes under, and the protocol limits it is held to. -use mega_evm::{HardforkParams, MegaHardforkConfig, MegaHardforks, MegaSpecId, ProtocolLimits}; +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, with the parameters -/// it carries: the chain's protocol limits among them. A schedule that cannot run the block — its -/// table schedules Satin without the parameters Satin requires — is refused rather than filled in: -/// the tool does not know the chain's limits, and a default in their place would report results -/// the chain does not produce. +/// 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 /// -/// Any other run is a counterfactual and executes under the schedule the Satin engine gives a chain -/// it does not know ([`mega_evm::all_activated_hardforks`]): Satin from genesis, placeholder -/// registry parameters, which only a registry deployed from scratch reads (a chain whose registry -/// is already deployed keeps the roles in its storage), and [`ProtocolLimits::DEFAULT`]. +/// 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. /// -/// `limits_override` replaces the fields it names of the limits that schedule carries, a -/// counterfactual either way. -pub fn satin_schedule( +/// 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, - limits_override: Option<&LimitsOverride>, ) -> Result { - schedule_for(mega_evm::hardfork_schedule(chain_id), timestamp, limits_override) + 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}")) + }) } -/// [`satin_schedule`] for a chain whose schedule is `chain`. -fn schedule_for( - chain: MegaHardforkConfig, - timestamp: u64, - limits_override: Option<&LimitsOverride>, -) -> Result { - let runs_satin = chain.spec_id(timestamp) == Some(MegaSpecId::SATIN); - let schedule = if runs_satin { chain } else { mega_evm::all_activated_hardforks() }; - let schedule = match limits_override { - Some(limits) => { - let limits = limits.apply(schedule.protocol_limits(timestamp))?; - schedule.with_params(limits) - } - None => schedule, +/// 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!( @@ -51,30 +177,24 @@ fn schedule_for( Ok(schedule) } -/// Protocol limits to run under in place of the chain's (`--override.limits`): a JSON object in -/// the shape a chain configuration carries [`ProtocolLimits`] in, naming only the fields it -/// replaces. +/// 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. With no `base` - /// the override must name every field. + /// The limits `base` becomes with the fields this names replaced, recursively. /// - /// The result is refused when it names a field [`ProtocolLimits`] does not have, lacks one, or - /// is a value no chain may carry ([`HardforkParams::validate`]). - pub fn apply(&self, base: Option) -> Result { + /// 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 = match base { - Some(base) => serde_json::to_value(base).expect("limits serialize"), - None => Value::Object(Map::new()), - }; + let mut merged = serde_json::to_value(base).expect("limits serialize"); merge(&mut merged, &self.0); - let limits: ProtocolLimits = - serde_json::from_value(merged).map_err(|e| invalid(e.to_string()))?; - limits.validate().map_err(|e| invalid(e.message))?; - Ok(limits) + serde_json::from_value(merged).map_err(|e| invalid(e.to_string())) } } @@ -108,10 +228,7 @@ pub fn parse_limits_override(arg: &str) -> std::result::Result(), - Some(&SequencerRegistryConfig::placeholder()) - ); + 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; from it on, the run - /// takes the chain's schedule, and its limits are the chain's, not the default. + /// 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_under_the_chains_own_limits() { - let own = ProtocolLimits::DEFAULT - .with_tx_runtime_limits(EvmTxRuntimeLimits::default().with_tx_data_size_limit(350)); - let chain = - scheduled().with_params(SequencerRegistryConfig::placeholder()).with_params(own); - - let before = schedule_for(chain.clone(), ACTIVATION - 1, None).unwrap(); - assert_eq!(before.protocol_limits(ACTIVATION - 1), Some(ProtocolLimits::DEFAULT)); - let from = schedule_for(chain, ACTIVATION, None).unwrap(); - assert_eq!(from.protocol_limits(ACTIVATION), Some(own)); + 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 table schedules Satin without the limits is refused, not run on a default. + /// 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_without_the_chains_limits_is_refused() { - let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()); - let error = schedule_for(chain, ACTIVATION, None).unwrap_err().to_string(); - assert!(error.contains("ProtocolLimits params are not configured"), "{error}"); + 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}"); - - let error = schedule_for(scheduled(), ACTIVATION, None).unwrap_err().to_string(); 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 the schedule carries. + /// 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 schedule = satin_schedule( - MAINNET_CHAIN_ID, - 0, - Some(&overriding( - r#"{"txRuntimeLimits":{"txDataSizeLimit":350},"blockKvUpdateLimit":7}"#, - )), - ) + let limits = satin_limits(Some(&overriding( + r#"{"txRuntimeLimits":{"txDataSizeLimit":350},"blockTxsDataLimit":7}"#, + ))) .unwrap(); - let expected = ProtocolLimits::DEFAULT - .with_tx_runtime_limits( - ProtocolLimits::DEFAULT.tx_runtime_limits.with_tx_data_size_limit(350), - ) - .with_block_kv_update_limit(7); - assert_eq!(schedule.protocol_limits(0), Some(expected)); + 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}" + ); + } } - /// An override applies to a chain's own Satin schedule too, and there it replaces the chain's - /// limits; a chain whose table carries none needs the override to name every field. + /// 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_an_override_supplies_limits_a_chain_does_not_carry() { - let chain = scheduled().with_params(SequencerRegistryConfig::placeholder()); - let partial = overriding(r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#); - let error = schedule_for(chain.clone(), ACTIVATION, Some(&partial)).unwrap_err(); - assert!(error.to_string().contains("missing field"), "{error}"); + 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 loosest = serde_json::to_string(&ProtocolLimits::loosest()).unwrap(); - let schedule = schedule_for(chain, ACTIVATION, Some(&overriding(&loosest))).unwrap(); - assert_eq!(schedule.protocol_limits(ACTIVATION), Some(ProtocolLimits::loosest())); + 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}"); } - /// An override is held to what a chain configuration is: no unknown field, no value the - /// limits' own check refuses. + /// 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_an_override_no_chain_may_carry_is_refused() { - let refused = |json: &str| { - satin_schedule(MAINNET_CHAIN_ID, 0, Some(&overriding(json))).unwrap_err().to_string() + 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 unknown = refused(r#"{"txDataSizeLimit":350}"#); - assert!(unknown.contains("unknown field `txDataSizeLimit`"), "{unknown}"); - let zero = refused(r#"{"txRuntimeLimits":{"txKvUpdateLimit":0}}"#); - assert!(zero.contains("tx_kv_update_limit must not be zero"), "{zero}"); - let uncapped = - refused(r#"{"txRuntimeLimits":{"oracleAccessComputeGasLimit":18446744073709551615}}"#); - assert!(uncapped.contains("oracle_access_compute_gas_limit"), "{uncapped}"); - let not_a_number = refused(r#"{"blockTxsDataLimit":"1"}"#); - assert!(not_a_number.starts_with("Invalid input: --override.limits:"), "{not_a_number}"); + 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#" {"blockKvUpdateLimit": 7}"#; + let inline = r#" {"blockTxsDataLimit": 7}"#; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("limits.json"); std::fs::write(&path, inline).unwrap(); diff --git a/bin/mega-evme/src/common/state.rs b/bin/mega-evme/src/common/state.rs index 56c2f4d79..cf2f88035 100644 --- a/bin/mega-evme/src/common/state.rs +++ b/bin/mega-evme/src/common/state.rs @@ -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)?; @@ -236,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, TransactionId::ZERO)); + 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. @@ -280,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 { @@ -297,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")] @@ -409,29 +520,43 @@ 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() @@ -441,6 +566,42 @@ impl AccountState { } } +/// 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 @@ -476,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) @@ -497,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. @@ -547,30 +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, TransactionId::ZERO))), - ); + /// 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(()) } - /// Installs the code of Satin's predeploys: the six system contracts and the EIP-7997 factory. - /// - /// `run` and `tx` execute no block, so nothing deploys them; the code is applied as a raw - /// state patch, over whatever a forked state holds at those addresses. The factory gets the - /// nonce its deployment gives it. The `SequencerRegistry`'s storage is not seeded: a local run - /// has no chain configuration to seed it from, and a forked run reads the chain's. - pub fn deploy_system_contracts(&mut self) { - use mega_evm::system::{system_contract_specs, SequencerRegistryConfig}; - - for contract in system_contract_specs(&SequencerRegistryConfig::placeholder()) { - self.set_account_code(contract.address, Bytecode::new_raw(contract.code)); - if contract.nonce != 0 { - self.set_account_nonce(contract.address, contract.nonce); + /// 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)) } + }) + } + + /// 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 + }) } } @@ -611,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, + }) } } @@ -630,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.filter(|info| !rpc_reads_as_absent(info))) - } - } + // 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( @@ -684,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) { @@ -751,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.filter(|info| !rpc_reads_as_absent(info))) + account.filter(|info| !rpc_reads_as_absent(info)) } - } + }; + self.apply_account_overlay(address, account) } fn code_by_hash_ref( @@ -805,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) { @@ -863,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 b093b57f4..f0ac83825 100644 --- a/bin/mega-evme/src/common/trace.rs +++ b/bin/mega-evme/src/common/trace.rs @@ -93,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 @@ -257,3 +279,61 @@ impl TraceArgs { } } } + +#[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 e52d677d3..cec0ea01e 100644 --- a/bin/mega-evme/src/common/tx.rs +++ b/bin/mega-evme/src/common/tx.rs @@ -351,7 +351,8 @@ 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 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())); @@ -366,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. @@ -378,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 { @@ -433,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`]. @@ -441,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; @@ -490,9 +507,101 @@ 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). @@ -510,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) @@ -598,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, @@ -612,3 +727,132 @@ fn create_fake_envelope(tx_env: &TxEnv) -> Result { 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 fa42a42db..979af4ce8 100644 --- a/bin/mega-evme/src/common/tx_override.rs +++ b/bin/mega-evme/src/common/tx_override.rs @@ -3,19 +3,12 @@ //! This module provides the ability to override transaction fields when replaying //! transactions from RPC. -use std::cell::RefCell; - use alloy_primitives::{Bytes, TxHash, U256}; use clap::Args; 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")] @@ -49,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, }, }) } @@ -73,31 +57,28 @@ impl TxOverrideArgs { /// Parsed transaction overrides. /// -/// All fields are `Copy`, as `OverriddenTx` is. 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; } } } @@ -106,13 +87,13 @@ impl TxOverrides { /// /// 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, Copy)] -pub struct OverriddenTx { +#[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 @@ -123,7 +104,7 @@ impl OverriddenTx { // apply. impl ExecutableTxParts for OverriddenTx where - T: ExecutableTxParts + Copy, + T: ExecutableTxParts, { type Recovered = T::Recovered; @@ -136,7 +117,7 @@ where // 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 { +impl MegaTransactionExt for OverriddenTx { fn tx_hash(&self) -> TxHash { self.inner.tx_hash() } @@ -149,3 +130,56 @@ impl MegaTransactionExt for OverriddenTx { self.inner.estimated_da_size() } } + +#[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) + } + } + + impl RecoveredTx<()> for NoRecovered { + fn tx(&self) -> &() { + &() + } + + fn signer(&self) -> &Address { + &Address::ZERO + } + } + + fn blank() -> EnvOnly { + let tx_env = TxEnvBuilder::new().tx_type(Some(0)).build().expect("legacy transaction"); + EnvOnly(OpTx(OpTransaction::new(tx_env))) + } + + #[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 index 57c25572c..6c3e58415 100644 --- a/bin/mega-evme/src/engine.rs +++ b/bin/mega-evme/src/engine.rs @@ -7,9 +7,9 @@ use std::ffi::OsString; -use mega_evm::{chain_activation, ChainActivation, MegaSpecId, ParseMegaSpecError}; +use mega_evm::{ChainActivation, MegaSpecId, ParseMegaSpecError}; -use crate::common::{EvmeError, Result}; +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"; @@ -49,29 +49,36 @@ impl Engine { /// 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. An unknown chain runs the - /// Satin engine's fallback rung, Satin, from genesis. - pub fn of_block(chain_id: u64, timestamp: u64) -> Self { - Self::under(chain_activation(chain_id), timestamp) + /// 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 an unknown chain). - fn under(activation: Option, timestamp: u64) -> Self { - match activation { - None => Self::Satin, - Some(ChainActivation { satin: Some(satin), .. }) if timestamp >= satin => Self::Satin, - Some(_) => Self::Legacy, + /// 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. - pub fn of_chain(chain_id: u64) -> Option { + /// + /// # Errors + /// + /// For a chain that is not known ([`unknown_chain`]). + pub fn of_chain(chain_id: u64) -> Result> { match chain_activation(chain_id) { - None => Some(Self::Satin), - Some(ChainActivation { satin: None, .. }) => Some(Self::Legacy), - Some(ChainActivation { satin: Some(_), .. }) => None, + None => Err(unknown_chain(chain_id)), + Some(ChainActivation { satin: None, .. }) => Ok(Some(Self::Legacy)), + Some(ChainActivation { satin: Some(_), .. }) => Ok(None), } } @@ -84,6 +91,17 @@ impl Engine { } } +/// 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: @@ -96,11 +114,10 @@ pub async fn run_legacy(mut args: Vec, add_default_spec: bool) -> Resu args = with_default_spec(args); } if let Err(e) = mega_evme_legacy::cmd::MainCmd::parse_from(args).run().await { - // What the 1.7.1 binary's `main` does with an error its command returns: print it to - // stdout, then return it from `main`, which prints it to stderr and exits with code 1. - println!("{e:?}"); - eprintln!("Error: {e:?}"); - std::process::exit(1); + // 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(()) } @@ -174,25 +191,31 @@ mod tests { } /// Mainnet and testnet have no Satin timestamp yet: every block of theirs is legacy, and the - /// schedule says so without a timestamp. An unknown chain runs Satin from genesis. + /// 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), Some(Engine::Legacy)); - assert_eq!(Engine::of_block(chain_id, 0), Engine::Legacy); - assert_eq!(Engine::of_block(chain_id, u64::MAX), Engine::Legacy); + 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}"); } - assert_eq!(Engine::of_chain(1_337), Some(Engine::Satin)); - assert_eq!(Engine::of_block(1_337, 0), Engine::Satin); } /// Once a known chain schedules Satin, its blocks before the timestamp stay legacy and the - /// block at the timestamp is the first Satin one. + /// 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), Engine::Legacy); - assert_eq!(Engine::under(Some(scheduled), 1_800_000_000), Engine::Satin); - assert_eq!(Engine::under(None, 0), Engine::Satin); + 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 b7a7911af..2574bb20b 100644 --- a/bin/mega-evme/src/lib.rs +++ b/bin/mega-evme/src/lib.rs @@ -29,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, @@ -38,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 24b395198..f62445cd6 100644 --- a/bin/mega-evme/src/main.rs +++ b/bin/mega-evme/src/main.rs @@ -4,10 +4,12 @@ //! This binary is intentionally minimal: parse CLI arguments, install the panic //! hook, hand the arguments to the engine the spec names, and exit. -use mega_evme::{cmd::Error, set_thread_panic_hook}; +use mega_evme::set_thread_panic_hook; #[tokio::main(flavor = "multi_thread")] -async fn main() -> std::result::Result<(), Error> { +async fn main() { set_thread_panic_hook(); - mega_evme::cmd::run_cli(std::env::args_os().collect()).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 3a337a560..032b47bff 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -6,13 +6,18 @@ 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, CfgEnv}, + 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, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaHardforks, MegaSpecId, @@ -23,11 +28,11 @@ use op_alloy_rpc_types::Transaction; use crate::{ common::{ - op_receipt_to_tx_receipt, parse_bucket_capacity, parse_limits_override, - print_execution_summary, print_execution_trace, print_receipt, print_satin_report, - satin_schedule, BuildProviderOutput, EvmeExternalEnvs, EvmeOutcome, ExecutionSummary, - ExternalEnvSnapshot, LimitsOverride, OpTxReceipt, RpcCacheStore, SatinReport, - 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, }, engine::Engine, run, EvmeState, @@ -67,11 +72,11 @@ pub struct Cmd { #[arg(long = "override.spec", value_name = "SPEC")] pub spec_override: Option, - /// Satin only: replay under these protocol limits instead of the chain's, a counterfactual. A - /// JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, - /// per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names - /// replace the chain's, every other stays. Refused when it names an unknown field or a value - /// no chain may carry, and for a block that runs on the legacy engine + /// 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, @@ -89,11 +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`. Legacy specs - /// only: no state-test runner prices a transaction as Satin does. + /// 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, } @@ -132,14 +136,16 @@ impl Cmd { /// 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. + /// 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?; - if let Some(engine) = Engine::of_chain(chain_id) { + check_genesis_chain(chain_id)?; + if let Some(engine) = Engine::of_chain(chain_id)? { return Ok(engine); } let tx = provider @@ -159,7 +165,7 @@ impl Cmd { .ok_or(ReplayError::BlockNotFound(number))? .header .timestamp(); - Ok(Engine::of_block(chain_id, timestamp)) + Engine::of_block(chain_id, timestamp) } /// Whether this replays whole blocks (`--block`), which runs here for both engines. @@ -274,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( @@ -299,7 +305,7 @@ impl Cmd { .get_transaction_by_hash(tx_hash) .await .map_err(|e| ReplayError::RpcError(format!("Failed to fetch transaction: {e}")))? - .ok_or_else(|| ReplayError::TransactionNotFound(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 { @@ -329,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 == 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"); @@ -417,7 +422,9 @@ impl Cmd { P: Provider + Clone + std::fmt::Debug, { let timestamp = ctx.block.header.timestamp(); - let hardforks = satin_schedule(ctx.chain_id, timestamp, self.limits_override.as_ref())?; + 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",); @@ -435,26 +442,33 @@ impl Cmd { cfg_env.chain_id = ctx.chain_id; let evm_env = EvmEnv::new(cfg_env, block_env); - let evm_factory = MegaEvmFactory::new() - .with_schedule(hardforks.clone()) - .with_external_env_factory(external_envs); + 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 the protocol limits its schedule carries, with no building - // policy, as a validator holds it; the block's gas limit comes from its header. + // 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(), BlockLimits::default(), - ); + ) + .with_no_user_tx_activation_block(only_deposits) + .with_satin_activation_block(activates_satin); let start = Instant::now(); // The tracer reads and writes nothing back, so block execution admits it declared. - let mut inspector = DeclaredObserver::new(self.trace_args.create_inspector()); + // 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_trusted_inspector( @@ -463,13 +477,21 @@ impl Cmd { 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 @@ -477,13 +499,32 @@ 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); } // Execute target transaction. @@ -500,15 +541,15 @@ impl Cmd { .unwrap_or(0); // The trace covers the target transaction only. - block_executor.evm_mut().inspector_mut().0.fuse(); + 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); - if self.limits_override.is_some() { - satin.limits_override = hardforks.protocol_limits(timestamp).map(Box::new); - } + satin.limits_override = limits_override.map(Box::new); let exec_result = outcome.inner.result.clone(); let evm_state = outcome.inner.state.clone(); @@ -529,13 +570,14 @@ impl Cmd { state: evm_state.clone(), }; - let trace_data = self.trace_args.is_tracing_enabled().then(|| { - self.trace_args.generate_trace( - &block_executor.inspector().0, + 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(), - ) - }); + )), + ReplayTracer::Off => None, + }; let gas_output = block_executor .commit_transaction_outcome(outcome) @@ -566,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 { @@ -618,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 @@ -651,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::*; @@ -701,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/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 f7505cf72..9784de44e 100644 --- a/bin/mega-evme/src/run/cmd.rs +++ b/bin/mega-evme/src/run/cmd.rs @@ -74,7 +74,7 @@ impl Cmd { debug!(sender = %sender, "State initialized"); // Install Satin's predeploys - state.deploy_system_contracts(); + state.deploy_system_contracts()?; debug!("System contracts deployed"); let pre_execution_nonce = state.basic_ref(sender)?.map(|acc| acc.nonce).unwrap_or(0); @@ -82,8 +82,7 @@ impl Cmd { // 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,8 +106,11 @@ 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, mut satin) = + 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(); @@ -177,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 7215a9412..ce54b28a9 100644 --- a/bin/mega-evme/src/tx/cmd.rs +++ b/bin/mega-evme/src/tx/cmd.rs @@ -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(); + 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,8 +105,11 @@ 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, mut satin) = + 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(); @@ -132,7 +138,7 @@ impl Cmd { // 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()?; @@ -141,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; @@ -168,8 +179,9 @@ impl Cmd { contract_address, effective_gas_price, outcome.exec_result.tx_gas_used(), + tx_hash, None, - None, + 0, 0, ); diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 565e36313..1fd09502f 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -8,11 +8,11 @@ use std::path::Path; use alloy_primitives::{Address, B256, U256}; use common::blocks::{ - block_path, cache_copy, cache_copy_with_absent_factory, code_of, fixtures, read_block, - run_evme, write_block, BLOCKS, FACTORY, + 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, ProtocolLimits}; -use mega_evme::block::PreAccount; +use mega_evm::{system::MEGA_SYSTEM_ADDRESS, MegaSpecId, ProtocolLimits}; use serde_json::Value; fn blocks_of(records: &[Value]) -> Vec<&Value> { @@ -63,25 +63,44 @@ fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { assert_eq!(std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(), before); } -/// A Satin replay of a recorded block reads the EIP-7997 factory, which the recording lacks: -/// offline, the block fails and names the account, and the exit code is 1. +/// 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 run = replay(BLOCKS[0], cache.path(), &["--override.spec", "Satin"]); - assert_eq!(run.code, 1); - let records = run.records(); - let error = records[0]["error"].as_str().unwrap(); - assert!(error.contains("no RPC to read it"), "{error}"); - assert!(error.to_lowercase().contains(&format!("{FACTORY:#x}")), "{error}"); + 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, nothing is refused, every -/// record carries the legacy columns and adds `satin`, and `--verify` reports the difference +/// 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_with_absent_factory(); + 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); @@ -89,7 +108,7 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { let block = blocks_of(&records)[0]; assert_eq!(block["engine"], "satin"); assert_eq!(block["spec"], "Satin"); - assert_eq!(block["refused"], 0); + assert_eq!(block["refused"], refused_for_block_gas(&records)); assert_eq!(block["matches_chain"], false); assert!(block["satin"]["history_gas"].as_u64().unwrap() > 0); } @@ -104,96 +123,47 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { for key in l.keys() { assert!(s.contains_key(key), "the Satin record lacks the legacy column {key}"); } - assert!(s.contains_key("satin"), "{satin}"); + // A refused transaction ran nothing and has no ledgers. + if satin["status"] != "refused" { + assert!(s.contains_key("satin"), "{satin}"); + } } } -/// Whichever state the factory had on chain, the Satin rows of the recorded blocks are the -/// same: no transaction reads the factory, and the pre-block deploy that reads it is no -/// transaction. +/// 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_factory_state_does_not_change_the_satin_rows() { - let absent = cache_copy_with_absent_factory(); - let present = cache_copy(); +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(present.path(), number); - block.prestate.accounts.insert( - FACTORY, - PreAccount { - balance: U256::ZERO, - nonce: 1, - code_hash: Some(mega_evm::system::CREATE2_FACTORY_CODE_HASH), - storage: Default::default(), - }, - ); - write_block(present.path(), number, &block); + let mut block = read_block(set.path(), number); + set_overhead(&mut block, U256::from(188)); + write_block(set.path(), number, &block); } - let hash = mega_evm::system::CREATE2_FACTORY_CODE_HASH.to_string(); - let code_dir = present.path().join("codes").join(&hash[2..4]); - std::fs::create_dir_all(&code_dir).unwrap(); - std::fs::write( - code_dir.join(format!("{}.bin", &hash[2..])), - mega_evm::system::CREATE2_FACTORY_CODE, - ) - .unwrap(); - 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(absent.path()), rows(present.path()), "block {number}"); + assert_eq!(rows(zero.path()), rows(set.path()), "block {number}"); } } -/// 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. +/// [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() { - use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; - let number = BLOCKS[2]; - 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 }), - ) - }) - }; - 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: only the factory, which does not exist. - respond("eth_getBalance", serde_json::json!("0x0")).mount(&server).await; - respond("eth_getTransactionCount", serde_json::json!("0x0")).mount(&server).await; - respond("eth_getCode", serde_json::json!("0x")).mount(&server).await; - + let server = recorded_chain(number, Parent::Block).await; let cache = tempfile::tempdir().unwrap(); let uri = server.uri(); @@ -204,12 +174,9 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { let run = replay(number, cache.path(), &["--rpc", &uri, "--override.spec", "Satin"]); assert_eq!(run.code, 0, "{}", run.stderr); - assert!( - blocks_of(&run.records())[0]["rpc_reads"].as_u64().unwrap() > 0, - "the factory came over RPC" - ); + 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 factory the Satin replay read. + // 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); @@ -217,17 +184,21 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { 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); - assert!(read_block(cache.path(), number).prestate.accounts.contains_key(&FACTORY)); + 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 chain's, and every other stays. At the protocol's defaults it changes nothing; a -/// transaction data-size limit of the body alone stops every transaction but the protocol's own, -/// which no per-transaction limit holds; a block data budget of one byte packs the first -/// transaction and refuses every later one. +/// 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_with_absent_factory(); + 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"]; @@ -243,12 +214,13 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { let (counterfactual, plain) = replay_under(None); assert!(plain["satin"].get("limits_override").is_none(), "{}", plain["satin"]); - let defaults = serde_json::to_string(&ProtocolLimits::DEFAULT).unwrap(); + 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 defaults"); + assert_eq!(on_the_defaults, counterfactual, "it runs on the spec's limits"); assert_eq!( overridden["satin"]["limits_override"], - serde_json::to_value(ProtocolLimits::DEFAULT).unwrap(), + serde_json::to_value(satin).unwrap(), "the block's record says what it ran under" ); let dir = cache.path().to_str().unwrap(); @@ -262,37 +234,64 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { 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(r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#)); + replay_under(Some(&format!(r#"{{"txRuntimeLimits":{{"txDataSizeLimit":{limit}}}}}"#))); assert_eq!( stopped_block["satin"]["limits_override"]["txRuntimeLimits"]["txDataSizeLimit"], - 310 + limit ); let (mut protocols, mut others) = (0, 0); - for (tx, sent) in stopped.iter().zip(sent) { - let stop = &tx["satin"]["limit_exceeded"]; + 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 { - protocols += 1; + // 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!( - stop.is_null(), + tx["satin"]["limit_exceeded"].is_null(), "the protocol's transaction {} is held to no limit", tx["index"] ); - assert!(tx["satin"]["data_size"].as_u64().unwrap() > 310); - } else { + 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"], 310, "{tx}"); - assert_eq!(stop["used"], tx["satin"]["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}"#)); - assert_eq!(block["refused"], block["transactions"].as_u64().unwrap() - 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 tx in &packed[1..] { + 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}"); @@ -309,3 +308,340 @@ fn test_an_override_refuses_a_legacy_block() { 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 index 10a21c81e..6c4e012df 100644 --- a/bin/mega-evme/tests/common/blocks.rs +++ b/bin/mega-evme/tests/common/blocks.rs @@ -11,17 +11,36 @@ use std::{ process::Command, }; -use alloy_primitives::{address, Address, B256}; +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 pre-block changes deploy and the legacy engine never -/// reads: the one account a Satin replay reads that the recording does not hold. +/// 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")) @@ -44,11 +63,19 @@ pub(crate) fn write_block(dir: &Path, number: u64, block: &CachedBlock) { 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. +/// 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(); - std::fs::read(fixtures().join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..]))) - .unwrap() + 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. @@ -58,19 +85,32 @@ pub(crate) fn cache_copy() -> tempfile::TempDir { dir } -/// A copy of the recorded block cache in which every block's pre-state holds the factory, absent: -/// what a Satin replay needs offline. `block_replay.rs` shows the factory's state changes no -/// transaction row. -pub(crate) fn cache_copy_with_absent_factory() -> tempfile::TempDir { +/// 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, PreAccount::default()); + 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() { @@ -101,6 +141,27 @@ impl Run { } } +/// 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(); @@ -115,3 +176,25 @@ pub(crate) fn run_evme>(args: &[S]) -> Run { .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 fc71cf425..1ebbaa75e 100644 --- a/bin/mega-evme/tests/common/mod.rs +++ b/bin/mega-evme/tests/common/mod.rs @@ -104,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 index 08fde4345..8dfa53f59 100644 --- a/bin/mega-evme/tests/differences.rs +++ b/bin/mega-evme/tests/differences.rs @@ -16,7 +16,7 @@ mod common; use std::{collections::BTreeMap, fmt::Write as _, path::Path}; -use common::blocks::{cache_copy_with_absent_factory, read_block, run_evme, BLOCKS}; +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; @@ -150,7 +150,7 @@ fn is_success(record: &Value) -> bool { } fn render_blocks(out: &mut String) { - let cache = cache_copy_with_absent_factory(); + let cache = cache_copy_for_satin(); let mut pairs = Vec::new(); writeln!(out, "## Recorded mainnet blocks\n").unwrap(); writeln!( @@ -253,7 +253,14 @@ fn render_blocks(out: &mut String) { 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"])); - let state_gas = sum(&|p| u64_of(&p.satin["satin"]["state_gas"])); + // 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"])); @@ -289,8 +296,8 @@ fn render() -> String { .unwrap(); writeln!(out, "What the Satin columns show:\n").unwrap(); for line in [ - "- **Regular**: execution, at the Satin schedule (Amsterdam's, with the entries EIP-8038 \ - repriced back at Osaka's) and EIP-2780's intrinsic cost.", + "- **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 \ 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/test_satin_run_dump_inline.json b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json index ccb9d1fd1..547aa97a5 100644 --- a/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json +++ b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json @@ -9,7 +9,7 @@ ], "expected": { "success": true, - "gas_used": 165826, + "gas_used": 155826, "logs_count": 0, "state": { "0x0000000000000000000000000000000000000000": { @@ -42,6 +42,15 @@ "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "storage": {} }, + "0x6342000000000000000000000000000000000006": { + "balance": "0x0", + "nonce": "0x0", + "code": "0x608060405234801561000f575f5ffd5b50600436106100e5575f3560e01c806354fd4d5011610088578063de7a36af11610063578063de7a36af146101f7578063e3093f5014610214578063e812903014610227578063f851a44014610245575f5ffd5b806354fd4d501461019d57806375829def146101dc578063c7455c42146101ef575f5ffd5b80632b659fd8116100c35780632b659fd81461014e5780633411f3c31461016157806344d744591461017457806348a2cf6d1461017c575f5ffd5b80630e18b681146100e9578063129c8240146100f35780632678224714610130575b5f5ffd5b6100f1610263565b005b610106610101366004611274565b610336565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020015b60405180910390f35b60035473ffffffffffffffffffffffffffffffffffffffff16610106565b6100f161015c3660046112b3565b61045c565b6100f161016f366004611336565b6107e1565b6100f1610a91565b61018f61018a366004611336565b610aa3565b604051908152602001610127565b604080518082018252600581527f322e302e3000000000000000000000000000000000000000000000000000000060208201529051610127919061135e565b6100f16101ea3660046113b1565b610c5b565b600d5461018f565b5f5473ffffffffffffffffffffffffffffffffffffffff16610106565b610106610222366004611274565b610d0b565b60015473ffffffffffffffffffffffffffffffffffffffff16610106565b60025473ffffffffffffffffffffffffffffffffffffffff16610106565b60035473ffffffffffffffffffffffffffffffffffffffff163381146102b5576040517f058d9a1b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff00000000000000000000000000000000000000008084168217909455600380549094169093556040519116919082907ff8ccb027dfcd135e000e9d45e6cc2d662578a8825d4c45b5e32e0adf67e79ec6905f90a35050565b5f43821115610371576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6006548210156103ad576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c54805b801561043b575f600c6103c66001846113fe565b815481106103d6576103d6611411565b5f91825260209091200180549091506bffffffffffffffffffffffff16851061042857546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b50806104338161143e565b9150506103b2565b505060055473ffffffffffffffffffffffffffffffffffffffff1692915050565b610464610e31565b43831161049d576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036105cd5773ffffffffffffffffffffffffffffffffffffffff841615610512576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f600a81905560015473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf97fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6040516105c091815260200190565b60405180910390a36107db565b6bffffffffffffffffffffffff831115610613576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8416610660576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600d5461066d9043611472565b8310156106a6576040517f11ede46e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f6106bb6106b48686610aa3565b8484610e82565b90508473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610722576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6009805473ffffffffffffffffffffffffffffffffffffffff87167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155600a85905561078a60015473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf9866040516107d191815260200190565b60405180910390a3505b50505050565b6107e9610e31565b438111610822576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81036109505773ffffffffffffffffffffffffffffffffffffffff821615610897576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f6008819055805473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9157fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60405161094491815260200190565b60405180910390a35050565b6bffffffffffffffffffffffff811115610996576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff82166109e3576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff84167fffffffffffffffffffffffff000000000000000000000000000000000000000090911681179091556008829055610a4a5f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9158360405161094491815260200190565b610a9961108c565b610aa1611181565b565b604080518082018252601981527f4d6567614554482053657175656e63657252656769737472790000000000000060209182015281518083018352600181527f31000000000000000000000000000000000000000000000000000000000000009082015281517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f818301527f85da835bd1cf371efdb3f9056e5a3a6245af1400fa0ce2e878a198765a4eb9c2818401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a0808301919091528351808303909101815260c0820184528051908301207faebf84f20bcc14afc14200ed16cfb9314ef205d4d1d8fbcc0a256c39a3e79aa960e083015273ffffffffffffffffffffffffffffffffffffffff861661010083015261012080830186905284518084039091018152610140830185528051908401207f190100000000000000000000000000000000000000000000000000000000000061016084015261016283019190915261018280830191909152835180830390910181526101a290910190925281519101205b92915050565b610c63610e31565b6003805473ffffffffffffffffffffffffffffffffffffffff83167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155610cc660025473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fe5cd1c804f1c9cc6d7009e4c0fb532f0e2d8863524c3323a6b3790c3f80bf25c60405160405180910390a350565b5f43821115610d46576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600654821015610d82576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b54805b8015610e10575f600b610d9b6001846113fe565b81548110610dab57610dab611411565b5f91825260209091200180549091506bffffffffffffffffffffffff168510610dfd57546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b5080610e088161143e565b915050610d87565b505060045473ffffffffffffffffffffffffffffffffffffffff1692915050565b60025473ffffffffffffffffffffffffffffffffffffffff163314610aa1576040517f7bfa4b9f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f60418214610ebd576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610ecb6020828587611485565b610ed4916114ac565b90505f610ee5604060208688611485565b610eee916114ac565b90505f85856040818110610f0457610f04611411565b919091013560f81c9150507f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0821115610f69576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8060ff16601b14158015610f8157508060ff16601c14155b15610fb8576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604080515f808252602082018084528a905260ff841692820192909252606081018590526080810184905260019060a0016020604051602081039080840390855afa158015611009573d5f5f3e3d5ffd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff8116611081576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b979650505050505050565b60075473ffffffffffffffffffffffffffffffffffffffff16806110ad5750565b600854438111156110bc575050565b5f805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600b8054600181018255908552905191519095166c01000000000000000000000000029316929092177f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db990930192909255600780549091169055600855565b60095473ffffffffffffffffffffffffffffffffffffffff16806111a25750565b600a54438111156111b1575050565b6001805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600c805494850181555f908152905191519095166c01000000000000000000000000029316929092177fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c790910155600980549091169055600a55565b5f60208284031215611284575f5ffd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff811681146112ae575f5ffd5b919050565b5f5f5f5f606085870312156112c6575f5ffd5b6112cf8561128b565b935060208501359250604085013567ffffffffffffffff8111156112f1575f5ffd5b8501601f81018713611301575f5ffd5b803567ffffffffffffffff811115611317575f5ffd5b876020828401011115611328575f5ffd5b949793965060200194505050565b5f5f60408385031215611347575f5ffd5b6113508361128b565b946020939093013593505050565b602081525f82518060208401528060208501604085015e5f6040828501015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011684010191505092915050565b5f602082840312156113c1575f5ffd5b6113ca8261128b565b9392505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81810381811115610c5557610c556113d1565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f8161144c5761144c6113d1565b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b80820180821115610c5557610c556113d1565b5f5f85851115611493575f5ffd5b8386111561149f575f5ffd5b5050820193919092039150565b80356020831015610c55577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b169291505056fea164736f6c634300081e000a", + "codeHash": "0xabd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43", + "storage": { + "0x0": "0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d" + } + }, "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": { "balance": "0x0", "nonce": "0x1", @@ -51,7 +60,7 @@ } }, "satin": { - "regular_gas": 37106, + "regular_gas": 27106, "state_gas": 97920, "history_gas": 30800, "history_bytes": 350, diff --git a/bin/mega-evme/tests/integration.rs b/bin/mega-evme/tests/integration.rs index b02d5d770..6a07f0416 100644 --- a/bin/mega-evme/tests/integration.rs +++ b/bin/mega-evme/tests/integration.rs @@ -139,9 +139,9 @@ fn assert_superset(satin: &serde_json::Value, legacy: &serde_json::Value, name: } } -/// An error prints as the engine that ran the command prints it: on a legacy spec exactly as the -/// 1.7.1 binary did (its `Debug` form to stdout, then `Error: ...` to stderr), on Satin once, to -/// stderr, as a message. Both exit with code 1. +/// 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() { @@ -153,8 +153,9 @@ fn test_errors_print_as_their_engine_prints_them() { let (code, stdout, stderr) = run(&["run", "--codefile", "/nonexistent/code.hex"]); assert_eq!(code, Some(1)); - assert!(stdout.starts_with("Evme(FileRead(Os {"), "{stdout}"); + 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"]); @@ -201,3 +202,261 @@ fn test_a_legacy_command_ending_its_options_runs_on_the_default_spec() { 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 index 21304a80c..4167cd1d4 100644 --- a/bin/mega-evme/tests/legacy_line.rs +++ b/bin/mega-evme/tests/legacy_line.rs @@ -91,8 +91,9 @@ const LEGACY_LINE: &[(&str, &str)] = &[ ]; /// The packages of the legacy leg's encodings that the Satin engine's alloy 2 line holds above -/// the released version: `(name, locked, released)`. alloy 2.4 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`. +/// 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"), diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs index d15571a68..a8fe8c507 100644 --- a/bin/mega-evme/tests/limits.rs +++ b/bin/mega-evme/tests/limits.rs @@ -1,14 +1,21 @@ //! `--override.limits` on `run` and `tx`: a Satin transaction held to protocol limits other than -//! the chain's, the fields the override names replacing the chain's and every other staying. +//! the spec's, the fields the override names replacing the spec's and every other staying. use std::process::Command; -use mega_evm::ProtocolLimits; +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, @@ -40,16 +47,16 @@ fn run_two_writes(limits: Option<&str>) -> Value { evme(&args).json() } -/// The protocol's default limits with `txDataSizeLimit` at `limit`, as a report carries them. +/// 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::DEFAULT).unwrap(); + 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 or of -/// its write records 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 schedule's limits reports none. +/// 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); @@ -67,12 +74,6 @@ fn test_an_override_holds_a_satin_run_to_other_limits() { ); 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)); - - let records = run_two_writes(Some(r#"{"txRuntimeLimits":{"txKvUpdateLimit":1}}"#)); - assert_eq!( - records["satin"]["limit_exceeded"], - json!({ "kind": "kv_update", "limit": 1, "used": 2 }) - ); } /// The override is read from a file as it is given inline. @@ -90,19 +91,24 @@ fn test_an_override_is_read_from_a_file() { assert_eq!(from_file, inline); } -/// `tx` takes the override too: a body one byte over the transaction data-size limit is stopped -/// before it runs. +/// `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 output = evme(&[&args[..], &[r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#]].concat()); - let stopped = output.json(); - assert_eq!(stopped["success"], false); - assert_eq!( - stopped["satin"]["limit_exceeded"], - json!({ "kind": "data_size", "limit": 310, "used": 311 }) + 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 ); - assert_eq!(stopped["satin"]["limits_override"], defaults_with_tx_data_size(310)); + + 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 @@ -125,25 +131,26 @@ fn test_the_report_names_an_override() { assert!(!plain.stdout.contains("Limits Override"), "{}", plain.stdout); } -/// An override is held to what a chain configuration is: an unknown field, a value of the wrong -/// type or one the limits' own check refuses is an error, with nothing on 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_no_chain_may_carry_is_refused() { +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 = - evme(&["run", "0x00", "--spec", "Satin", "--json", "--override.limits", limits]); + 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#"{"txRuntimeLimits":{"txKvUpdateLimit":0}}"#, - 1, - "tx_runtime_limits.tx_kv_update_limit must not be zero", - ); 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 @@ -174,3 +181,110 @@ fn test_an_override_is_refused_on_a_legacy_spec() { ); } } + +/// 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 3783dddf7..85d96ffc1 100644 --- a/bin/mega-evme/tests/replay_dump.rs +++ b/bin/mega-evme/tests/replay_dump.rs @@ -5,8 +5,7 @@ //! (`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. diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index da92a1b4b..4762cf033 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -7,18 +7,23 @@ //! 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 one exception is the EIP-7997 factory, which Satin's -//! pre-block changes read and no recording holds; it is served as absent, which -//! `block_replay.rs` shows changes no transaction row. +//! 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::sync::Arc; +use std::{ + collections::{BTreeMap, HashMap}, + sync::Arc, +}; -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{address, Address, B256, U256}; use common::blocks::{ - cache_copy_with_absent_factory, code_of, fixtures, read_block, run_evme, FACTORY, + 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}; @@ -29,13 +34,22 @@ 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(PreAccount::default()), + None if address == FACTORY => Some(factory_account()), None => None, } } @@ -45,6 +59,9 @@ impl Recording { 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 } @@ -93,7 +110,11 @@ impl Recording { "eth_getTransactionCount" => json!(format!("0x{:x}", account.nonce)), _ => json!(account .code_hash - .map(|hash| alloy_primitives::hex::encode_prefixed(code_of(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())), }) } @@ -132,9 +153,23 @@ 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 }) + .respond_with(Recording { block, parent_timestamp, codes }) .mount(&server) .await; Self(Arc::new(server)) @@ -143,7 +178,7 @@ impl 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_with_absent_factory(); + 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 { @@ -158,10 +193,22 @@ fn block_rows(spec: Option<&str>, limits: Option<&str>) -> Vec { } /// The transactions checked: the first user transaction, the plain value transfer, one in the -/// middle and the last. -fn checked(rows: &[Value]) -> Vec { +/// 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 @@ -173,17 +220,24 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { let server = Server::start(recorded).await; let uri = server.0.uri(); - // The last leg holds both paths to a transaction data-size limit of the body alone, which - // stops every transaction but the protocol's own. - let stopping = r#"{"txRuntimeLimits":{"txDataSizeLimit":310}}"#; - let mut stops = 0; + // 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(stopping)), + (Some("Satin"), "satin", Some(holding.as_str())), ] { let rows = block_rows(spec, limits); - for index in checked(&rows) { + 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"]); @@ -192,7 +246,10 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { } if let Some(limits) = limits { args.extend(["--override.limits", limits]); - stops += usize::from(!row["satin"]["limit_exceeded"].is_null()); + 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); @@ -219,5 +276,399 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { } } } - assert!(stops > 0, "the limits leg checks a stopped transaction"); + 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 index d449c9a30..3f133ef8d 100644 --- a/bin/mega-evme/tests/satin-differences.md +++ b/bin/mega-evme/tests/satin-differences.md @@ -6,7 +6,7 @@ Legacy is `Rex6` on the released `mega-evm` 1.7.1. Satin is the in-tree engine a What the Satin columns show: -- **Regular**: execution, at the Satin schedule (Amsterdam's, with the entries EIP-8038 repriced back at Osaka's) and EIP-2780's intrinsic cost. +- **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. @@ -21,7 +21,7 @@ Each fixture's command run on both engines: `tests/fixtures/test_.json` an | 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 165826 | +83720 | 37106 | 97920 | 30800 | 350 | 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 | @@ -39,9 +39,9 @@ The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. | Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused | |---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:| -| 26400001 | 39 | 10592072 | 12252942 | 1.15 | 7185347 | 0 | 5065016 | 13 | 138 -> 121 | 0 | -| 26400007 | 25 | 8428932 | 8956346 | 1.06 | 4457736 | 0 | 4493720 | 0 | 119 -> 119 | 0 | -| 26400110 | 27 | 8051381 | 8678731 | 1.07 | 4182321 | 0 | 4491520 | 0 | 121 -> 121 | 0 | +| 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 @@ -49,30 +49,30 @@ The transactions of the three blocks grouped by the contract they call and the s | Call target | Selector | Transactions | Legacy gas | Satin gas | Satin / legacy | State gas | Status differs | Logs | |---|---|---:|---:|---:|---:|---:|---:|---| -| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 853864 | 0.33 | 0 | 0 | 0 -> 0 | -| 0x897a33a0af45b3ba097bd6045187d622252e6acd | 0x9aec351f | 30 | 18019164 | 21657264 | 1.20 | 0 | 0 | 330 -> 330 | -| deposit | - | 3 | 304908 | 120588 | 0.39 | 0 | 0 | 0 -> 0 | -| 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x21d5c9bb | 2 | 601407 | 643335 | 1.06 | 0 | 0 | 6 -> 6 | -| 0x57677bdc4f24d5c08ddce87e06670c26a00cac0b | 0xb7a16251 | 2 | 1559890 | 1509424 | 0.96 | 0 | 0 | 19 -> 19 | -| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fad7 | 2 | 151028 | 121524 | 0.80 | 0 | 0 | 0 -> 0 | +| 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 | 340081 | 1.07 | 0 | 0 | 5 -> 5 | +| 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 | 593610 | 0.91 | 0 | 0 | 0 -> 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 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | -| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fadd | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | -| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb42 | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 0 | -| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb43 | 1 | 75514 | 60762 | 0.80 | 0 | 0 | 0 -> 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 | 186001 | 0.98 | 0 | 0 | 1 -> 1 | +| 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 8fa5a2e55..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 @@ -226,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"); @@ -290,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"); @@ -369,3 +602,255 @@ async fn test_forked_state_reads_an_all_zero_account_as_absent() { 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 c2db5c431..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` (`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 7bffa48a7..9bb86423e 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -27,7 +27,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. -The gas schedule is Amsterdam's with three changes: the entries EIP-8038 repriced go back to their Osaka values, 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 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. @@ -38,7 +38,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 abort protocol that stops a transaction crossing a limit with a revert, 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 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. @@ -47,21 +47,20 @@ 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. -`EvmTxRuntimeLimits` sets the limits on a bare EVM, where they default to none but gas detention's caps; a block executor installs the chain's, whose default holds each transaction and the block to 12.5 MiB of data size. +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 chain'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: `ProtocolLimits`, the Satin fork's parameters, which a chain configuration carries beside `SequencerRegistryConfig` and block execution reads at the block's timestamp. -They are the per-transaction runtime limits and the block's execution-gas, state-gas, data-size and KV budgets; their default is today's values, and `validate_schedule` refuses a schedule that activates Satin without them or with a value no chain can run on. -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 a block budget and never raise it, so a validator that leaves it at its default computes the block a builder packed under any policy. +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. -A block's state gas can be capped: the transaction that reaches the cap is packed, and after it only a transaction that adds no state gas is. -No block cap on execution gas, state gas, data size or write records refuses a deposit, which the block must include; a deposit still counts towards all four. +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, deploys the six MegaETH system contracts and the EIP-7997 `CREATE2` factory every block, idempotently, and applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call. -It hands each pre-block state — the two EIP calls, the seven deploys, the read of the registry's pending changes and its call — to an optional observer before it commits; that sequence is the witness a stateless client needs. +`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. @@ -78,7 +77,7 @@ 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 are deployed at Satin activation, together with the EIP-7997 factory at `0x4e59…`. +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()`. @@ -99,7 +98,7 @@ The call pays a fixed 100,000 gas for decoding the transaction and recovering it 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 transaction limit the deployment crosses stops the transaction and takes the deployment back whole. +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()`). @@ -108,11 +107,11 @@ The exception is a signer whose own code spends a nonce in the constructor that 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 the transaction reads it itself: a transaction of that shape reads the registry's `_currentSystemAddress` from the journal when it is validated, without warming it, and compares it with its caller. -Every other transaction reads nothing, and one of another shape from the system address is an ordinary transaction. +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 the system-address transaction's own state and witness; the pre-block steps no longer carry it. +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 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. @@ -122,7 +121,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, KV or state-gas 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 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. @@ -134,13 +133,11 @@ 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. -The KV and state-gas limits are in place too. -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 the KV limit holds it by the data-size limit's rules: a transaction limit that stops the transaction, and a record budget per frame, 98% of what the 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 whatever its KV limit. -The transaction's KV count is in its outcome's usage and the block's in its result; a block can be held to a KV limit, a packing budget like its data size. -A transaction's state growth is the EIP-8037 state gas it spends, so the state-gas limit is what holds it: `EvmTxRuntimeLimits::tx_state_gas_limit` holds the state gas a transaction holds, net of what it refilled and of what its failed frames rolled back, at every site state gas is charged, and a crossing anywhere on the call stack stops the transaction with `MegaLimitExceeded(3, limit)`. -It is a limit on gas, so a slot or an account in a crowded SALT bucket reaches it sooner. -Every one of these limits is unlimited unless the chain sets it in its `ProtocolLimits`. +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. @@ -148,8 +145,9 @@ The one exception is what a frame has left when an opcode's static gas fails, wh 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 transaction is stopped with a revert carrying `MegaLimitExceeded` of kind compute, billed its compute before that charge, less than one charge short of the limit, and the sender gets back everything the frame had, the part withheld included. -The stop reports that compute as what the transaction used. +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. @@ -161,12 +159,15 @@ 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 transaction-level limit — data size, KV updates, state gas, gas detention's compute limit — stops a transaction the same way. -The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, and every frame above returns the same revert without running another instruction, whatever produced its result: revm, an interceptor, or an inspector that rewrites it into a success or a halt. -The transaction settles like any EIP-8037 revert: it 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. +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. -A frame budget reverts its frame alone, and its caller runs on; 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 at the transaction's own frame and three calls down, below and above the execution cap, with and without an inspector that rewrites every result. +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 @@ -186,15 +187,13 @@ 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; given the same schedule, the EVM factory runs the EVMs it creates outside block execution — an RPC call, a simulation — under the chain's limits too: +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 _}; use mega_evm::{BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory}; -// `chain_spec` is shared, an `Arc` of the node's schedule: `MegaHardforks` holds for an `Arc` of one. -let evm_factory = MegaEvmFactory::new().with_schedule(chain_spec.clone()); -let factory = MegaBlockExecutorFactory::new(receipt_builder, chain_spec, evm_factory); +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); @@ -223,7 +222,23 @@ A success an inspector rewrites into a failure has its journal taken back as a f 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 486788071..35e6b8396 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -3,10 +3,13 @@ //! //! Every block runs as a node runs one: //! -//! - on a state that already holds the seven predeploys, which a chain deploys once, in its first -//! block after activation: the state the previous block's pre-block changes left; -//! - under the chain's default limits, `ProtocolLimits::DEFAULT`: the production data-size limits -//! and gas detention's caps, with no building policy on top (`BlockLimits::default()`); +//! - 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 @@ -20,26 +23,27 @@ //! counters, with a log-free receipt. //! //! 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. Two more -//! arms measure `apply_pre_execution_changes` alone: -//! -//! - `steady_pre_block`: on the steady state, the per-block cost of the idempotent check of the -//! predeploys and of the pre-block system calls; -//! - `activation_pre_block`: on a state without the predeploys, the first block after activation, -//! which deploys all seven. A chain pays it once; it is the one arm that runs the deploys. +//! 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::{ - system::{SequencerRegistryConfig, SYSTEM_CONTRACT_DEPLOY_COUNT}, - test_utils::{BytecodeBuilder, MemoryDatabase}, + system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + test_utils::{BytecodeBuilder, CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, PreBlockStateSource, ProtocolLimits, + MegaSpecId, MegaTxEnvelope, }; +use op_revm::constants::L1_BLOCK_CONTRACT; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, context::{BlockEnv, CfgEnv}, @@ -47,10 +51,7 @@ use revm::{ state::EvmState, DatabaseCommit, }; -use std::{ - hint::black_box, - sync::{Arc, Mutex}, -}; +use std::hint::black_box; /// Transactions in the block. const N: u64 = 64; @@ -64,14 +65,15 @@ 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"); -/// What the pre-block changes of a block handed their observer, in the order the executor -/// commits them. -type PreBlockStates = Arc>>; - /// 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 { @@ -90,12 +92,15 @@ fn slot_calldata(nonce: u64) -> Bytes { Bytes::from(U256::from(nonce + 1).to_be_bytes::<32>()) } -/// The accounts the workloads use, and nothing the chain deploys. +/// 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 } @@ -122,7 +127,12 @@ fn evm_env() -> EvmEnv { /// 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::default()) + 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. @@ -151,75 +161,70 @@ fn transactions( } fn chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated() - .with_params(SequencerRegistryConfig::placeholder()) - .with_params(ProtocolLimits::DEFAULT) + MegaHardforkConfig::default().with_all_activated() } -/// Runs the pre-block changes of block `number` on `db` and returns what they handed their -/// observer, without committing anything to `db`. -fn pre_block_states(db: MemoryDatabase, number: u64) -> Vec<(PreBlockStateSource, EvmState)> { +/// 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()); - let log = PreBlockStates::default(); - let captured = Arc::clone(&log); - executor.set_pre_block_observer(Some(Box::new( - move |source: PreBlockStateSource, state: &EvmState| { - captured.lock().expect("pre-block observer").push((source, state.clone())); - }, - ))); executor.apply_pre_execution_changes().expect("the pre-block changes apply"); drop(executor); - let states = std::mem::take(&mut *log.lock().expect("pre-block observer")); - states + 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, the seven predeploys among them, committed in -/// the order the executor commits them. +/// 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(); - let states = pre_block_states(db.clone(), BLOCK_NUMBER - 1); - let deployed = states - .iter() - .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) - .filter(|(_, state)| state.values().any(|account| account.is_created())) - .count(); - assert_eq!(deployed, SYSTEM_CONTRACT_DEPLOY_COUNT, "the previous block deploys all seven"); - for (_, state) in states { + 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` find every predeploy in place: -/// each is a read-only witness entry, neither created nor touched. -fn assert_predeploys_in_place(db: &MemoryDatabase) { +/// 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 deploys: Vec<_> = states + let named: Vec<_> = states .iter() - .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) + .map(|state| { + assert_eq!(state.len(), 1, "a pre-block step names one account: {state:?}"); + *state.keys().next().expect("one account") + }) .collect(); - assert_eq!(deploys.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); - for (source, state) in &deploys { - assert_eq!(state.len(), 1, "{source:?} is one witness account"); - let account = state.values().next().expect("the account is present"); - assert!(!account.is_touched(), "{source:?} is not touched"); - assert!(!account.is_created(), "{source:?} is not created"); + 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"); } - assert_eq!(states[0].0, PreBlockStateSource::Eip2935); - assert_eq!(states[1].0, PreBlockStateSource::Eip4788); } fn bench_block(c: &mut Criterion) { let spec = chain_spec(); let steady = steady_database(); - // Checked once before measurement, so a block that would deploy is not measured as steady. - assert_predeploys_in_place(&steady); + // 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 @@ -301,34 +306,6 @@ fn bench_block(c: &mut Criterion) { ); }); - // The first block after activation deploys all seven, checked once before measurement. - let deployed = pre_block_states(database(), BLOCK_NUMBER) - .iter() - .filter(|(source, _)| matches!(source, PreBlockStateSource::SystemContract(_))) - .filter(|(_, state)| state.values().any(|account| account.is_created())) - .count(); - assert_eq!(deployed, SYSTEM_CONTRACT_DEPLOY_COUNT, "the first block deploys all seven"); - - group.bench_function("activation_pre_block", |b| { - b.iter_batched( - || State::builder().with_database(database()).build(), - |mut state| { - let used = { - 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(); - 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 eb440126d..b3b16d962 100644 --- a/crates/mega-evm/benches/corpus.rs +++ b/crates/mega-evm/benches/corpus.rs @@ -1,9 +1,9 @@ //! 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. +//! 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 @@ -37,25 +37,10 @@ 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.evm(scenario.database()), @@ -67,5 +52,15 @@ fn bench_corpus(c: &mut Criterion) { 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 42e9a1b61..1acddffa6 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -41,10 +41,6 @@ //! 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`). -//! - `state_limits`: the same transaction under a state-gas limit and a KV limit equal to exactly -//! the state gas and the write records it keeps, so every fresh slot is held to both as it is -//! written (`satin`); and under a state-gas limit one gas short, so the last slot crosses and the -//! transaction is stopped (`stopped`). Its op-revm baseline is `data_size_limit/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: @@ -65,9 +61,7 @@ //! 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; the state-limit one -//! keeps exactly the state gas and records its limits allow, and stops at its last slot one gas -//! short of them. A workload that +//! 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)] @@ -97,7 +91,7 @@ use mega_evm::{ use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, BALANCE, CALL, CALLDATACOPY, CALLDATALOAD, CODECOPY, DUP1, EXP, GAS, ISZERO, + 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, }, @@ -121,6 +115,11 @@ 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; @@ -324,7 +323,19 @@ fn salt_context( /// `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 @@ -334,9 +345,13 @@ fn system_caller_code(target: Address, selector: [u8; 4]) -> Bytes { .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 { @@ -385,6 +400,18 @@ fn bench_transact(c: &mut Criterion) { .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()) @@ -473,6 +500,25 @@ fn bench_transact(c: &mut Criterion) { "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| { @@ -546,49 +592,6 @@ fn bench_transact(c: &mut Criterion) { ); }); - // The state-limit arms: the same transaction under a state-gas and a KV limit it exactly - // reaches, and under a state-gas limit one gas short of it. - let state_gas = MegaEvm::new(mega_context(db.clone())) - .execute_transaction(OpTx(limited_tx.clone())) - .unwrap() - .gas - .state; - let state_limited = |limit| { - mega_context(db.clone()).with_tx_runtime_limits( - EvmTxRuntimeLimits::default() - .with_tx_state_gas_limit(limit) - .with_tx_kv_update_limit(REPEAT), - ) - }; - let at_limit = MegaEvm::new(state_limited(state_gas)) - .execute_transaction(OpTx(limited_tx.clone())) - .unwrap(); - assert!(at_limit.result.is_success(), "state_limits: {:?}", at_limit.result); - assert_eq!(at_limit.gas.state, state_gas, "state_limits: the arm must reach its state gas"); - assert_eq!(at_limit.usage.write_records, REPEAT, "state_limits: and its records"); - let stopped = MegaEvm::new(state_limited(state_gas - 1)) - .execute_transaction(OpTx(limited_tx.clone())) - .unwrap(); - assert_eq!( - stopped.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::StateGrowth, - limit: state_gas - 1, - used: state_gas, - frame_local: false, - }), - "state_limits/stopped: the last slot must be the gas that crosses", - ); - for (arm, limit) in [("satin", state_gas), ("stopped", state_gas - 1)] { - group.bench_function(format!("state_limits/{arm}"), |b| { - b.iter_batched( - || MegaEvm::new(state_limited(limit)), - |mut evm| evm.transact(OpTx(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| { diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 236aea862..c013d8c30 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -11,8 +11,8 @@ use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, Interpret use super::VolatileDataAccess; use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; -/// A transaction gas detention stops: the compute limit it crossed, and its compute at the -/// crossing. +/// 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. @@ -146,9 +146,11 @@ impl FrameFigures { /// /// 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, and each value call costs its caller at least 9,100 of compute — the -/// 9,000 of the value transfer and a warm access of 100 — so the gas run after a read is at most -/// about 25% (2,300 / 9,100) more than the cap. +/// 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 @@ -209,6 +211,10 @@ pub struct Detention { /// 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. @@ -242,6 +248,7 @@ impl Detention { 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; @@ -535,8 +542,8 @@ impl Detention { /// 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 stop the - /// transaction rather than halt. The stop's compute is the transaction's with the frame's 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( @@ -597,12 +604,34 @@ impl Detention { /// /// 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; @@ -723,6 +752,15 @@ impl Detention { 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 { @@ -1206,6 +1244,45 @@ mod tests { } } + /// 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. @@ -1269,14 +1346,14 @@ mod tests { detention.on_frame_run(&mut call, 0); assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert!(call.record_regular_cost(132_000)); + 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), 132_000, "the charges, not the forward"); - assert_eq!(creation.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 132_000); - assert_eq!(detention.allowance(2, 0), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS - 132_000)); + 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 diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 10daee3de..d02593039 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -15,12 +15,12 @@ //! | 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)): the spec's, +//! 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), by default. In block -//! execution they are the chain's ([`ProtocolLimits`](crate::ProtocolLimits)), which must be -//! below [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a -//! transaction can spend; a standalone EVM's caller may set either. A cap of `u64::MAX` caps +//! [`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 @@ -50,8 +50,9 @@ //! `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 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. +//! 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 @@ -87,16 +88,20 @@ //! # 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 stops the transaction the way every -//! transaction-level limit does — it reverts with `MegaLimitExceeded` (kind: compute), the -//! transaction is latched, no caller resumes, and the transaction settles like an EIP-8037 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, the spendable -//! part the frame had and the withheld part go back to the sender, and the transaction is billed -//! its compute at the crossing, less than one charge short of the limit. The stop reports that -//! compute as what was used, the same figure at every site a crossing is made: a frame that ran, +//! 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. //! @@ -109,15 +114,15 @@ //! 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 -//! stops the transaction; +//! 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, where without the read the check fails the call, -//! which burns its forward and which its caller survives. Running it to find out would compute -//! past the limit. +//! 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 @@ -125,13 +130,12 @@ //! 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 its caller survives. It also sees the +//! 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 stops the -//! transaction. +//! 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 diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs index df8d0b9b9..a91cd4cea 100644 --- a/crates/mega-evm/src/access/volatile.rs +++ b/crates/mega-evm/src/access/volatile.rs @@ -11,6 +11,11 @@ use crate::system::{VolatileDataAccessType, SLOT_NUM_ACCESS_TYPE}; /// 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); @@ -21,9 +26,6 @@ impl VolatileDataAccess { pub const TIMESTAMP: Self = Self(1 << 1); /// The block beneficiary's address (`COINBASE`). pub const COINBASE: Self = Self(1 << 2); - /// The block difficulty. Satin's base spec answers `DIFFICULTY` with the randomness instead, - /// so no read sets it; the bit keeps its position. - pub const DIFFICULTY: Self = Self(1 << 3); /// The block gas limit (`GASLIMIT`). pub const GAS_LIMIT: Self = Self(1 << 4); /// The base fee (`BASEFEE`). @@ -34,9 +36,6 @@ impl VolatileDataAccess { pub const BLOCK_HASH: Self = Self(1 << 7); /// The blob base fee (`BLOBBASEFEE`). pub const BLOB_BASE_FEE: Self = Self(1 << 8); - /// A blob hash. `BLOBHASH` reads the transaction's own blob hashes, which nothing but the - /// transaction decides, so no read sets it; the bit keeps its position. - pub const BLOB_HASH: Self = Self(1 << 9); /// The block beneficiary's account: its balance, code or code hash. pub const BENEFICIARY_BALANCE: Self = Self(1 << 10); /// The Oracle contract's storage. @@ -62,11 +61,6 @@ impl VolatileDataAccess { self.0 } - /// The bits of the set. An alias of [`bits`](Self::bits). - pub const fn raw(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 @@ -97,17 +91,6 @@ impl VolatileDataAccess { (self.0 & Self::BLOCK_ENV_MASK).count_ones() as usize } - /// How many block-environment kinds the set holds. An alias of - /// [`count_block_env_accessed`](Self::count_block_env_accessed). - pub const fn count_accessed(self) -> usize { - self.count_block_env_accessed() - } - - /// The block-environment kinds of the set. - pub const fn block_env_only(self) -> Self { - Self(self.0 & Self::BLOCK_ENV_MASK) - } - /// 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 { @@ -162,15 +145,13 @@ mod tests { 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); + assert_eq!(access.bits(), 0); } #[test] fn test_block_env_helpers_ignore_non_block_flags() { let access = VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::BLOB_HASH | + VolatileDataAccess::BLOCK_HASH | VolatileDataAccess::BENEFICIARY_BALANCE | VolatileDataAccess::ORACLE; @@ -179,12 +160,6 @@ mod tests { 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()); let beneficiary_and_oracle = VolatileDataAccess::BENEFICIARY_BALANCE | VolatileDataAccess::ORACLE; @@ -193,28 +168,32 @@ mod tests { 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, 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), + 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, expected_flag); + assert_eq!(converted.bits(), 1 << (access_type as u8)); assert_eq!(converted.as_u8(), access_type as u8); - assert_eq!(converted.as_u8(), expected_flag.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); @@ -246,20 +225,17 @@ mod tests { 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 | VolatileDataAccess::SLOT_NUM; - assert_eq!(all_block_env.count_block_env_accessed(), 11); + 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()); - assert_eq!(all_block_env.block_env_only(), all_block_env); } /// A union keeps a kind both sides hold: it is a union, not a difference. diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index fba9a2570..0aac49600 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -2,15 +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::{ - system::SequencerRegistryConfig, MegaHardfork, MegaHardforkConfig, MegaSpecId, ProtocolLimits, -}; +use crate::{MegaHardfork, MegaHardforkConfig}; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -18,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 { @@ -78,41 +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. -/// -/// Satin requires a [`SequencerRegistryConfig`]. An unknown chain has no published roles, so -/// every role is seeded with [`MEGA_SYSTEM_ADDRESS`], `_initialFromBlock` is zero, and -/// `_minRotationDelay` is [`crate::system::PLACEHOLDER_MIN_ROTATION_DELAY`]. The placeholder -/// only matters when bootstrapping a fresh registry: on a chain whose registry is already -/// deployed, the live roles are read from storage. -/// -/// Satin also requires its [`ProtocolLimits`]; an unknown chain runs on -/// [`ProtocolLimits::DEFAULT`]. -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.with_params(SequencerRegistryConfig::placeholder()).with_params(ProtocolLimits::DEFAULT) -} - -/// 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::{ - system::{MEGA_SYSTEM_ADDRESS, PLACEHOLDER_MIN_ROTATION_DELAY}, - MegaHardforks, - }; + use crate::{MegaHardforks, MegaSpecId}; #[test] fn test_known_chains_have_satin_unscheduled() { @@ -147,115 +112,26 @@ mod tests { /// 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() - .with_params(SequencerRegistryConfig::placeholder()) - .with_params(ProtocolLimits::DEFAULT); + 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(())); } + /// 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 carries placeholder registry params, 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(())); - let params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryConfig"); - assert_eq!(params.initial_system_address, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.initial_sequencer, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.initial_admin, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.initial_from_block, 0); - assert_eq!(params.min_rotation_delay, PLACEHOLDER_MIN_ROTATION_DELAY); - assert_ne!(params.min_rotation_delay, 0); - assert_eq!( - hf.protocol_limits(0), - Some(ProtocolLimits::DEFAULT), - "an unknown chain runs on Satin's default limits" - ); - } - - /// [`SequencerRegistryConfig::placeholder`] is attached only by the unknown-chain fallback. - /// - /// [`hardfork_schedule`] returns it exactly when the chain ID is absent from the activation - /// table. A known chain ID resolves to that chain's own table, which never carries the - /// placeholder. - #[test] - fn test_the_placeholder_is_only_the_unknown_chain_fallback() { - let placeholder = SequencerRegistryConfig::placeholder(); - let fallback = all_activated_hardforks(); - assert_eq!( - fallback.fork_params::(), - Some(&placeholder), - "the unknown-chain fallback is what attaches the placeholder" - ); - - for chain_id in [0_u64, 1, 999_999] { - assert_eq!(chain_activation(chain_id), None, "{chain_id} is not a known chain"); - assert_eq!( - hardfork_schedule(chain_id).fork_params::(), - Some(&placeholder), - "chain {chain_id} reaches the placeholder only by taking the fallback" - ); - } - for activation in CHAIN_ACTIVATIONS { - let schedule = hardfork_schedule(activation.chain_id); - assert_eq!( - schedule.fork_params::(), - activation.hardforks().fork_params::(), - "chain {} resolves to its own table", - activation.chain_id - ); - assert_ne!( - schedule.fork_params::(), - Some(&placeholder), - "chain {} must not return the placeholder", - activation.chain_id - ); + 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))); + } } - } - - /// 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 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 f895346ca..54531548f 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -1,8 +1,9 @@ -//! 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 @@ -10,6 +11,11 @@ //! 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; @@ -22,17 +28,14 @@ use std::{ use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use alloy_hardforks::EthereumHardforks; -use alloy_primitives::{Address, Bytes, B256, U256}; +use alloy_primitives::{Address, Bytes, B256}; use op_revm::OpHaltReason; use revm::{ context::{ result::{EVMError, ResultAndState}, Block, ContextTr, DBErrorMarker, }, - database::State, handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, - state::{Account, EvmState}, - Database, }; use crate::{ExternalEnvTypes, MegaEvm}; @@ -179,32 +182,6 @@ where 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; - } - 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::*; @@ -212,96 +189,12 @@ mod tests { test_utils::{ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, MegaContext, MegaSpecId, }; - use alloy_primitives::address; + use alloy_primitives::{address, U256}; use revm::{ context::BlockEnv, - database::InMemoryDB, state::{AccountInfo, Bytecode}, - DatabaseCommit, + Database, }; - 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()); - } /// A database error that says it is not fatal, as a block access list that does not cover a /// read does. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 8059ad0d4..39ae6ab14 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -6,15 +6,11 @@ //! //! # Where the limits come from //! -//! The limits every node must agree on are the chain's: the executor reads the -//! [`ProtocolLimits`] the fork active at the block's timestamp carries -//! ([`MegaHardforks::protocol_limits`]), installs their per-transaction half on the EVM before -//! every transaction, and holds the block to their four budgets. The node's context adds only the -//! builder's policy ([`BlockLimits`]), which can tighten a budget and never loosen one; a validator -//! leaves it at its default. A block whose schedule carries no limits at its timestamp, or limits -//! their own check refuses ([`HardforkParams::validate`](crate::HardforkParams::validate)), is -//! refused before anything runs, as an internal error: the schedule is the node's configuration, -//! and a node's own schedule type may hand the executor values nothing checked at load. +//! 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 //! @@ -57,33 +53,52 @@ //! cannot refuse, and must not accept such an outcome silently either: a debug build makes the //! same check there and panics. //! -//! Neither path checks the state a candidate executed against. A candidate executed before -//! another commit changed that state is stale whatever the counters say, and executing it again -//! is the builder's responsibility. +//! 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 pre-block observer +//! # The witness is what the block commits //! -//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, every system-contract deploy, the -//! read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` call — -//! produces an [`EvmState`] that this executor commits. alloy-evm 0.36 -//! re-exports revm's `OnStateHook` (`on_state(&EvmState)`) but has no `set_state_hook` on -//! [`BlockExecutor`] and no source tag, so this crate names the step ([`PreBlockStateSource`]) and -//! carries an optional [`PreBlockStateObserver`]. Every pre-block state is handed to the observer -//! **before** it is committed, in execution order. The sequence is the witness a stateless client -//! needs: revm drops untouched accounts from the committed transition, so a caller that only saw -//! the database after the commit would miss the read-only deploy entries of a later block. +//! 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, deploys the system contracts and the EIP-7997 factory (idempotent), then -//! applies a role change the `SequencerRegistry` has due in this block. Every call is a system call +//! 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. //! -//! The executor does not read the live system address: a transaction of the system shape reads it -//! out of the registry itself when it is validated, and the pre-block step is what leaves the -//! registry naming this block's address. +//! 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; @@ -101,7 +116,7 @@ use alloy_evm::{ Database, Evm, FromRecoveredTx, FromTxWithEncoded, RecoveredTx, }; use alloy_op_evm::block::{receipt_builder::OpReceiptBuilder, OpTxEnv}; -use alloy_primitives::{Address, 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, @@ -109,7 +124,7 @@ use op_revm::{ use revm::{ context::{result::ResultAndState, Block, ContextTr}, database::DatabaseCommitExt, - state::EvmState, + state::{AccountInfo, EvmState}, DatabaseCommit, Inspector, }; @@ -119,13 +134,14 @@ pub type MegaFinishedBlock = (MegaEvm, MegaBlockExecutionResult<::Receipt>); use crate::{ - block::eips, + block::{eips, read_l1_block_info}, estimated_da_size, system::{ - is_apply_pending_changes_due, system_contract_specs, transact_apply_pending_changes, - transact_deploy, SequencerRegistryConfig, SystemContractDeployError, + 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, ExternalEnvTypes, HardforkParams, + BlockGasCounters, BlockLimiter, BlockLimits, BucketId, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, MegaTransaction, MegaTransactionExt, ProtocolLimits, }; @@ -133,9 +149,8 @@ use crate::{ /// 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 builder's -/// packing policy. The limits the protocol holds the block to are not here: they are the chain's -/// ([`ProtocolLimits`]), read from the schedule. +/// 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. @@ -150,8 +165,17 @@ 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 builder's packing policy: the limits only a builder applies, and caps on the block's - /// budgets below the protocol's ([`BlockLimits`]). + /// 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. @@ -171,6 +195,7 @@ impl MegaBlockExecutionCtx { parent_beacon_block_root, extra_data, no_user_tx_activation_block: false, + satin_activation_block: false, block_limits, } } @@ -180,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. @@ -196,58 +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, - /// A system-contract address already holds bytecode that is not the contract this engine - /// deploys. - ForeignSystemContractCode { - /// The system-contract address that already has code. + /// 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 hash this engine deploys. + /// The code hash Satin expects there. expected: B256, - /// The hash already in state. + /// The code hash the address holds: the empty code's for no code or no account. found: B256, }, - /// Satin is scheduled but the schedule does not carry a [`SequencerRegistryConfig`]. - /// - /// A gap in the node's configuration, not a verdict on the block: an internal error. - MissingSequencerRegistryConfig, - /// The schedule carries no [`ProtocolLimits`] for the block's timestamp: no `MegaETH` fork is - /// active there, or the fork active there carries none. - /// - /// A gap in the node's configuration, not a verdict on the block: an internal error. - MissingProtocolLimits { - /// The block's timestamp. - timestamp: u64, - }, - /// The schedule carries [`ProtocolLimits`] for the block's timestamp that their own check - /// refuses ([`HardforkParams::validate`](crate::HardforkParams::validate)): limits no chain - /// may carry, which a schedule checked at load cannot hold. - /// - /// A gap in the node's configuration, not a verdict on the block: an internal error. - InvalidProtocolLimits { - /// The block's timestamp. - timestamp: u64, - /// What the check reported. - message: String, - }, - /// The EIP-7997 factory holds the right runtime but nonce 0. - ZeroFactoryNonce { - /// The factory address. - address: Address, - }, - /// A system-contract address has empty code but a used nonce. - UsedEmptyAccount { - /// The system-contract address. - address: Address, - /// The nonce already on the account. - nonce: u64, - }, /// 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 { @@ -268,33 +280,17 @@ impl fmt::Display for MegaBlockExecutionError { Self::RewritingInspector => f.write_str( "block execution does not admit an inspector that may rewrite execution", ), - Self::ForeignSystemContractCode { address, expected, found } => write!( - f, - "system contract at {address} has unexpected code hash {found}, expected {expected}; refusing to overwrite" - ), - Self::MissingSequencerRegistryConfig => { - f.write_str("Satin is scheduled but SequencerRegistryConfig is not configured") + Self::UnexpectedSystemContractCode { address, expected, found } => { + write_unexpected_code(f, *address, *expected, *found) } - Self::MissingProtocolLimits { timestamp } => write!( - f, - "the schedule carries no ProtocolLimits for the block at timestamp {timestamp}" - ), - Self::InvalidProtocolLimits { timestamp, message } => write!( - f, - "the schedule's ProtocolLimits for the block at timestamp {timestamp} are \ - invalid: {message}" - ), - Self::ZeroFactoryNonce { address } => write!( - f, - "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" - ), - Self::UsedEmptyAccount { address, nonce } => write!( - f, - "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" - ), 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" + ), } } } @@ -302,21 +298,17 @@ impl fmt::Display for MegaBlockExecutionError { impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { - /// A block refused for what the node's configuration lacks is an internal error: a schedule - /// without a parameter the block needs says nothing about the block, and a node must not mark - /// a block invalid because its own configuration is incomplete. Every other refusal is a - /// verdict on the block, a validation error. + /// 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 { match error { - MegaBlockExecutionError::MissingSequencerRegistryConfig | - MegaBlockExecutionError::MissingProtocolLimits { .. } | - MegaBlockExecutionError::InvalidProtocolLimits { .. } => Self::other(error), + MegaBlockExecutionError::RewritingInspector | + MegaBlockExecutionError::StaleOutcome { .. } => Self::other(error), MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | - MegaBlockExecutionError::RewritingInspector | - MegaBlockExecutionError::ForeignSystemContractCode { .. } | - MegaBlockExecutionError::ZeroFactoryNonce { .. } | - MegaBlockExecutionError::UsedEmptyAccount { .. } | + MegaBlockExecutionError::UnexpectedSystemContractCode { .. } | MegaBlockExecutionError::ApplyPendingChangesFailed { .. } => { Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) } @@ -324,57 +316,6 @@ impl From for BlockExecutionError { } } -/// Where a pre-block state change came from. -/// -/// alloy-evm 0.36 re-exports revm's `OnStateHook` (`on_state(&EvmState)`) but has no -/// `set_state_hook` on [`BlockExecutor`] and no source tag, so this crate names the step. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PreBlockStateSource { - /// The EIP-2935 history-storage system call. - Eip2935, - /// The EIP-4788 beacon-root system call. - Eip4788, - /// A system-contract or factory deploy at this address. - SystemContract(Address), - /// The reads of the `SequencerRegistry`'s pending role changes that decide whether the - /// block makes the `applyPendingChanges()` call. - PendingChanges, - /// The `SequencerRegistry.applyPendingChanges()` system call. - ApplyPendingChanges, -} - -/// Receives each pre-block [`EvmState`] before the executor commits it. -/// -/// The sequence is the witness a stateless client needs: every read and write a pre-block step -/// made, tagged with its source, in execution order. Install one with -/// [`MegaBlockExecutor::set_pre_block_observer`]. -pub trait PreBlockStateObserver: Send + 'static { - /// `state` is the witness of this step, not yet committed. - fn on_pre_block_state(&mut self, source: PreBlockStateSource, state: &EvmState); -} - -impl PreBlockStateObserver for F -where - F: FnMut(PreBlockStateSource, &EvmState) + Send + 'static, -{ - fn on_pre_block_state(&mut self, source: PreBlockStateSource, state: &EvmState) { - self(source, state) - } -} - -/// [`Debug`] skip for the optional observer: a trait object is not [`Debug`]. -struct OptionalPreBlockObserver(Option>); - -impl fmt::Debug for OptionalPreBlockObserver { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.0.is_some() { - f.write_str("Some(_)") - } else { - f.write_str("None") - } - } -} - /// Executes the transactions of one block on a Satin EVM. #[derive(Debug)] pub struct MegaBlockExecutor { @@ -391,15 +332,8 @@ pub struct MegaBlockExecutor { /// 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 schedule holds this block to, read at the block's timestamp and checked; - /// the refusal of the block when the schedule carries none there, or limits the check refuses. - protocol_limits: Result, - /// 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, - /// Optional observer of each pre-block state, invoked before the state is committed. - pre_block_observer: OptionalPreBlockObserver, + /// The limits the protocol holds this block to: the spec's. + protocol_limits: ProtocolLimits, } impl MegaBlockExecutor { @@ -427,13 +361,6 @@ impl MegaBlockExecutor { pub const fn gas(&self) -> &BlockGasCounters { &self.limiter.gas } - - /// Installs the observer that receives every pre-block state before it is committed. - /// - /// The sequence is the witness a stateless client needs. `None` turns observation off. - pub fn set_pre_block_observer(&mut self, observer: Option>) { - self.pre_block_observer = OptionalPreBlockObserver(observer); - } } impl MegaBlockExecutor, R, Spec> @@ -445,75 +372,49 @@ where { /// Creates an executor that runs `ctx`'s block on `evm`. /// - /// The limits come from `spec`, at the block environment's timestamp - /// ([`MegaHardforks::protocol_limits`]): 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 the chain's limits, - /// whatever the caller did or did not apply to the EVM. The block is held to the protocol's - /// budgets, each 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 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. /// - /// A schedule with no limits at the block's timestamp, or with limits their own check refuses - /// ([`HardforkParams::validate`](crate::HardforkParams::validate)), builds an executor all - /// the same, which installs nothing on the EVM; the block is refused at its first entry point - /// ([`MegaBlockExecutionError::MissingProtocolLimits`], - /// [`MegaBlockExecutionError::InvalidProtocolLimits`]). The check is made here, whatever the - /// schedule's type: a node's own implementation of [`MegaHardforks`] attaches its parameters - /// without [`MegaHardforkConfig::with_params`](crate::MegaHardforkConfig::with_params), and - /// [`validate_schedule`](MegaHardforks::validate_schedule) checks them only when a node calls - /// it. + /// 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 { - let (timestamp, block_gas_limit) = { - let block = evm.ctx().block(); - (block.timestamp().saturating_to(), block.gas_limit()) - }; - let protocol_limits = match spec.protocol_limits(timestamp) { - None => Err(MegaBlockExecutionError::MissingProtocolLimits { timestamp }), - Some(limits) => match limits.validate() { - Ok(()) => Ok(limits), - Err(error) => Err(MegaBlockExecutionError::InvalidProtocolLimits { - timestamp, - message: error.message, - }), - }, - }; - let policy = match &protocol_limits { - Ok(protocol) => { - evm.set_tx_runtime_limits(protocol.tx_runtime_limits); - ctx.block_limits.within(protocol) - } - Err(_) => ctx.block_limits, - }; - let limits = policy.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(), - protocol_limits, - pre_block_observer: OptionalPreBlockObserver(None), - } + 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 schedule holds this block to, read at the block's timestamp; `None` when it - /// carries none there, or limits their own check refuses, either of which refuses the block. - pub const fn protocol_limits(&self) -> Option<&ProtocolLimits> { - match &self.protocol_limits { - Ok(limits) => Some(limits), - Err(_) => None, - } + /// 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 } } @@ -533,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. @@ -549,14 +454,6 @@ where self.evm.ctx_mut().db_mut().commit(state); } - /// Hands `state` to the pre-block observer, then commits it. - fn deliver_pre_block(&mut self, source: PreBlockStateSource, state: EvmState) { - if let Some(observer) = self.pre_block_observer.0.as_mut() { - observer.on_pre_block_state(source, &state); - } - self.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. @@ -586,19 +483,54 @@ where output.gas_limit, output.tx_size, output.da_size, - output.is_deposit, + output.is_deposit || output.is_system_transaction, )?; - self.check_da_footprint(output.da_footprint)?; - self.limiter.post_execution_check(output.tx_hash, &output.block_usage()) + self.check_da_footprint(output.da_footprint) } - /// The limits the schedule holds this block to, or the refusal of a block whose schedule - /// carries none at its timestamp, or limits their own check refuses. - fn require_protocol_limits(&self) -> Result { - match &self.protocol_limits { - Ok(limits) => Ok(*limits), - Err(refusal) => Err(refusal.clone().into()), + /// 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. @@ -637,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 @@ -656,39 +625,48 @@ where /// Runs what a block does before its transactions. /// - /// In order: the admission gate, the reset of the block-hash record, the EIP-2935 and - /// EIP-4788 pre-block calls, the system-contract deploys and the `SequencerRegistry`'s due - /// role changes. Each step's state is handed to the - /// pre-block observer and then committed here rather than inside its helper, so a witness - /// generator sees every step's read and write set. The sequence the observer receives is - /// the witness a stateless client needs. + /// 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 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 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 EIP-2935 and EIP-4788 calls run before the deploy. 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 deploy that follows. Each runs on the pre-block budget + /// 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 reaches the observer. + /// 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 + /// 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 the deploy, which is what puts the registry in - /// state on the chain's first block. Its pending slots are read and handed on 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. + /// 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()?; - self.require_protocol_limits()?; - // 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, @@ -696,7 +674,7 @@ where &mut self.evm, )?; if let Some(ResultAndState { state, .. }) = state { - self.deliver_pre_block(PreBlockStateSource::Eip2935, state); + self.commit(state); } let state = eips::transact_beacon_root_contract_call( @@ -705,42 +683,54 @@ where &mut self.evm, )?; if let Some(ResultAndState { state, .. }) = state { - self.deliver_pre_block(PreBlockStateSource::Eip4788, state); + self.commit(state); } // 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. - let config = self - .spec - .fork_params::() - .copied() - .ok_or(MegaBlockExecutionError::MissingSequencerRegistryConfig)?; - for spec in system_contract_specs(&config) { - let state = transact_deploy(self.evm.db_mut(), &spec).map_err(|error| match error { - SystemContractDeployError::Database(error) => BlockExecutionError::other(error), - SystemContractDeployError::ForeignCode { address, expected, found } => { - MegaBlockExecutionError::ForeignSystemContractCode { address, expected, found } - .into() - } - SystemContractDeployError::ZeroFactoryNonce { address } => { - MegaBlockExecutionError::ZeroFactoryNonce { address }.into() - } - SystemContractDeployError::UsedEmptyAccount { address, nonce } => { - MegaBlockExecutionError::UsedEmptyAccount { address, nonce }.into() - } - })?; - self.deliver_pre_block(PreBlockStateSource::SystemContract(spec.address), state); + 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.deliver_pre_block(PreBlockStateSource::PendingChanges, reads); + self.commit(reads); if due { let ResultAndState { state, .. } = transact_apply_pending_changes(&mut self.evm)?; - self.deliver_pre_block(PreBlockStateSource::ApplyPendingChanges, state); + 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(()) } @@ -780,13 +770,15 @@ where /// [`commit_transaction_outcome`](MegaBlockExecutor::commit_transaction_outcome), which /// refuses an outcome the block no longer has room for. /// - /// Neither commit checks the state `output` executed against: an outcome executed before - /// another commit changed that state is the caller's to execute again. + /// [`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` — a caller that broke the - /// contract, which would otherwise pack the block past a limit. + /// 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(), @@ -794,6 +786,13 @@ where 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; @@ -818,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), }) } }, @@ -891,37 +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`. /// /// 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 and the state gas it adds included — and nothing changes before the check - /// passes. + /// footprint included — and nothing changes before the check passes. /// - /// The check covers the block's counters, not the state `output` executed against. A - /// candidate executed before another commit changed that state is stale whatever the counters - /// say, and executing it again is the builder's responsibility. + /// 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.check_room(&output)?; + self.check_sender_unchanged(&output)?; Ok(self.commit_transaction(output)) } @@ -936,7 +928,6 @@ where BlockExecutionError, > { self.check_admission()?; - let limits = self.require_protocol_limits()?; let (tx_env, tx) = tx.into_parts(); let inner = tx.tx(); @@ -976,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. @@ -988,25 +991,18 @@ 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 chain's limits, whatever was set on the EVM since the + // The transaction runs under the block's limits, whatever was set on the EVM since the // last one. - self.evm.set_tx_runtime_limits(limits.tx_runtime_limits); + self.evm.set_tx_runtime_limits(self.protocol_limits.tx_runtime_limits); let outcome = self .evm .execute_transaction(tx_env) @@ -1020,13 +1016,13 @@ 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, }; - // A block that has reached its state gas refuses a transaction that adds some, and only - // its execution tells whether it does. Nothing is committed yet, so the refusal leaves the - // block as it was. - self.limiter.post_execution_check(tx_hash, &result.block_usage())?; Ok(result) } @@ -1036,15 +1032,10 @@ where /// 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. - /// - /// A block whose schedule carries no limits at its timestamp, or limits their own check - /// refuses, is refused here too, before the post-block balance increments: a caller that never - /// started the block cannot finish it either. pub fn finish_with_counters( mut self, ) -> Result, BlockExecutionError> { self.check_admission()?; - self.require_protocol_limits()?; let balance_increments = post_block_balance_increments::
(&self.spec, self.evm.block(), &[], None); @@ -1085,17 +1076,17 @@ mod tests { let mut executor = MegaBlockExecutor::new( MegaEvm::new(ctx), MegaBlockExecutionCtx::default(), - MegaHardforkConfig::default().with_all_activated().with_params(ProtocolLimits::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); - assert_eq!(executor.protocol_limits(), Some(&ProtocolLimits::DEFAULT)); + 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, - "a default chain installs the production per-transaction data-size cap" + "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!( @@ -1106,44 +1097,45 @@ mod tests { assert!(executor.into_evm().is_inspecting()); } - /// A schedule that carries no limits at the block's timestamp refuses the block before any - /// pre-block step runs, and refuses to finish it: the block is not executed under limits - /// nobody chose. + /// 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_without_protocol_limits_is_refused_before_it_starts() { - let ctx = - MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN).with_block(BlockEnv { - timestamp: alloy_primitives::U256::from(7), - ..Default::default() - }); - let mut executor = MegaBlockExecutor::new( + 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::default(), - MegaHardforkConfig::default() - .with_all_activated() - .with_params(crate::system::SequencerRegistryConfig::placeholder()), + 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(), None); - let error = executor.apply_pre_execution_changes().expect_err("no limits, no block"); - assert_eq!( - internal(&error), - &MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 }, - "a gap in the node's configuration is not a verdict on the block" - ); - assert_eq!( - error.to_string(), - "the schedule carries no ProtocolLimits for the block at timestamp 7" - ); - assert!(executor.receipts().is_empty()); - - // Nor can it be finished: the post-block balance increments do not run on it. - let Err(error) = executor.finish() else { panic!("no limits, no finished block") }; - assert_eq!( - internal(&error), - &MegaBlockExecutionError::MissingProtocolLimits { timestamp: 7 } - ); + 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. @@ -1154,30 +1146,9 @@ mod tests { .unwrap_or_else(|| panic!("not an internal refusal of this engine: {error:?}")) } - /// A schedule that activates Satin without a `SequencerRegistryConfig` refuses the block at - /// the deploy, as an internal error: the registry cannot be seeded, and that is the node's - /// configuration, not the block. - #[test] - fn test_a_block_without_the_registry_config_is_an_internal_error() { - 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), - MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::default(), - ), - MegaHardforkConfig::default().with_all_activated().with_params(ProtocolLimits::DEFAULT), - alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), - ); - - let error = executor.apply_pre_execution_changes().expect_err("no registry, no block"); - assert_eq!(internal(&error), &MegaBlockExecutionError::MissingSequencerRegistryConfig); - } - - /// Every refusal but a configuration gap is a verdict on the block: a validation 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); @@ -1187,14 +1158,11 @@ mod tests { transaction_da_footprint: 2, available_block_da_footprint: 1, }, - MegaBlockExecutionError::RewritingInspector, - MegaBlockExecutionError::ForeignSystemContractCode { + MegaBlockExecutionError::UnexpectedSystemContractCode { address, expected: B256::ZERO, found: B256::repeat_byte(1), }, - MegaBlockExecutionError::ZeroFactoryNonce { address }, - MegaBlockExecutionError::UsedEmptyAccount { address, nonce: 1 }, MegaBlockExecutionError::ApplyPendingChangesFailed { message: String::new() }, ] { let error = BlockExecutionError::from(refusal.clone()); @@ -1204,34 +1172,7 @@ mod tests { }; assert_eq!(inner.downcast_ref::(), Some(&refusal)); } - for gap in [ - MegaBlockExecutionError::MissingSequencerRegistryConfig, - MegaBlockExecutionError::MissingProtocolLimits { timestamp: 1 }, - MegaBlockExecutionError::InvalidProtocolLimits { timestamp: 1, message: String::new() }, - ] { - assert_eq!(internal(&BlockExecutionError::from(gap.clone())), &gap); - } - } - - /// The executor prints whether a pre-block observer is installed. A trait object has no - /// `Debug`, so the observer is reported as a flag rather than dropped: a reader of a node's - /// log can tell a block whose pre-block states were witnessed from one whose were not. - #[test] - fn test_debug_reports_whether_a_pre_block_observer_is_installed() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - 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!(format!("{:?}", executor.pre_block_observer), "None"); - - executor.set_pre_block_observer(Some(Box::new(|_: PreBlockStateSource, _: &EvmState| {}))); - assert_eq!(format!("{:?}", executor.pre_block_observer), "Some(_)"); - - executor.set_pre_block_observer(None); - assert_eq!(format!("{:?}", executor.pre_block_observer), "None"); + 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 7db565920..3e4e7bc55 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -16,9 +16,8 @@ use crate::{ /// Creates the block executors a node drives. /// -/// It holds what every block of the chain shares — the hardfork schedule, with the limits the -/// protocol holds a block to, 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, @@ -29,10 +28,9 @@ 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 the limits `spec` carries, whatever the EVM they run on - /// was created with. A node gives the EVM factory the same schedule - /// ([`MegaEvmFactory::with_schedule`]), so the EVMs it creates outside block execution run - /// under the same limits. + /// 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 } } @@ -107,9 +105,8 @@ where /// Creates an executor over an EVM the caller built. /// - /// The chain's limits at the block's timestamp are installed by [`MegaBlockExecutor::new`], - /// from the factory's schedule, so an EVM the caller built without them, or with others, - /// 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 dc977015e..13dc8cfb7 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -8,18 +8,38 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::{ - any::{Any, TypeId}, - 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}; use alloy_primitives::{BlockTimestamp, U256}; use auto_impl::auto_impl; -use crate::{MegaSpecId, ProtocolLimits}; +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 @@ -43,44 +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. A fork may require several params types; a schedule carries one value of each. -/// [`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 @@ -93,24 +75,6 @@ pub trait MegaHardforks: OpHardforks { /// carry it. fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; - /// The parameters of the type `params` names that are attached to `fork`, type-erased; `None` - /// when the schedule carries no value of that type for the fork. - /// - /// A fork may carry several params types, so the value is looked up by fork and type: an - /// implementation answers each `(fork, TypeId::of::

())` it holds a `P` for with that `P`. - fn fork_params_any( - &self, - _fork: MegaHardfork, - _params: TypeId, - ) -> Option<&(dyn Any + Send + Sync)> { - None - } - - /// The `P` attached to the fork `P` belongs to, or `None` when the schedule carries none. - fn fork_params(&self) -> Option<&P> { - self.fork_params_any(P::FORK, TypeId::of::

())?.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, @@ -129,24 +93,22 @@ pub trait MegaHardforks: OpHardforks { self.hardfork(timestamp).map(|fork| fork.spec_id()) } - /// The limits the protocol holds a block at `timestamp` to: the [`ProtocolLimits`] the fork - /// active there carries, or `None` when no `MegaETH` fork is active there or the fork carries - /// none. - /// - /// This is where block execution reads them; a later fork that changes a limit answers here, - /// with a params type of its own, since a params type belongs to one fork - /// ([`HardforkParams::FORK`]). - fn protocol_limits(&self, timestamp: BlockTimestamp) -> Option { - match self.hardfork(timestamp)? { - MegaHardfork::Satin => self.fork_params::().copied(), - } - } - /// 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) } + /// 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. /// @@ -162,28 +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`, or with a `P` its - /// [`validate`](HardforkParams::validate) refuses. - /// - /// 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. The value - /// is checked here as well as in [`MegaHardforkConfig::with_params`], because a node's own - /// implementation of this trait attaches its parameters without going through that method. - /// A fork the schedule does not activate requires nothing. - fn require_params(&self) -> Result<(), ScheduleError> { - if self.mega_fork_activation(P::FORK) == ForkCondition::Never { - return Ok(()); - } - let params = self - .fork_params::

() - .ok_or(ScheduleError::MissingParams { fork: P::FORK, params: P::NAME })?; - params.validate().map_err(|error| ScheduleError::InvalidParams { - fork: P::FORK, - params: P::NAME, - message: error.message, - }) - } - /// 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. /// @@ -192,11 +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, and their values pass their - /// type's own checks ([`require_params`](Self::require_params)). Satin requires - /// [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) so the registry can be - /// seeded at the first block, and [`ProtocolLimits`], the limits every node of the chain - /// holds its blocks and transactions to. + /// - 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. @@ -208,12 +149,42 @@ pub trait MegaHardforks: OpHardforks { } } - // Required parameters, one `self.require_params::

()?` per params type. - self.require_params::()?; - self.require_params::()?; + 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. @@ -225,21 +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, - }, - /// A scheduled fork carries parameters whose own checks refuse them. - InvalidParams { - /// The scheduled fork. - fork: MegaHardfork, - /// The params type, as [`HardforkParams::NAME`] names it. - params: &'static str, - /// What [`HardforkParams::validate`] reported. - message: String, + /// 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, }, } @@ -249,41 +213,37 @@ 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" ) } - Self::InvalidParams { fork, params, message } => { - write!(f, "hardfork {fork:?} is scheduled with invalid {params} params: {message}") - } } } } impl core::error::Error for ScheduleError {} -/// One fork of a schedule: which fork, when it activates, and the parameters it carries, one -/// value per params type. +/// One fork of a schedule: which fork, and when it activates. #[derive(Debug)] struct ForkEntry { fork: Box, condition: ForkCondition, - params: Vec<(TypeId, Arc)>, } 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, @@ -306,7 +266,6 @@ where .map(|(fork, condition)| ForkEntry { fork: Box::new(fork) as Box, condition, - params: Vec::new(), }) .collect(), } @@ -314,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)), @@ -359,7 +319,7 @@ impl MegaHardforkConfig { Self { entries: forks .into_iter() - .map(|(fork, condition)| ForkEntry { fork, condition, params: Vec::new() }) + .map(|(fork, condition)| ForkEntry { fork, condition }) .collect(), } } @@ -372,61 +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(self, params: P) -> Self { - if let Err(e) = params.validate() { - panic!("Invalid params for fork {:?}: {}", P::FORK, e.message); - } - self.attach(params) - } - - /// Attaches `params` to the fork they belong to without checking them. - /// - /// Test tooling, behind the `test-utils` feature: it lets a test build a schedule that carries - /// a value no chain may carry, such as limits that leave gas detention off, to test what - /// refuses it. It is not the only way such a value reaches block execution: a node's own - /// implementation of [`MegaHardforks`] attaches its parameters without - /// [`with_params`](Self::with_params) and hands the block executor whatever it holds. What - /// stands in the way is [`validate_schedule`](MegaHardforks::validate_schedule), which a node - /// runs when it loads its chain configuration, and the block executor, which refuses a block - /// whose [`ProtocolLimits`] their own check refuses. - /// - /// # Panics - /// - /// If the fork is not registered in this schedule. - #[cfg(any(test, feature = "test-utils"))] - pub fn with_params_unchecked(self, params: P) -> Self { - self.attach(params) - } - - /// Attaches `params` to their fork's entry, replacing a value of the same type and keeping - /// the values of every other type. - fn attach(mut self, params: P) -> Self { - 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, - ) - }); - let value: Arc = Arc::new(params); - match entry.params.iter_mut().find(|(type_id, _)| *type_id == TypeId::of::

()) { - Some((_, slot)) => *slot = value, - None => entry.params.push((TypeId::of::

(), value)), - } - 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()); @@ -439,18 +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: Vec::new(), - }); + self.entries.push(ForkEntry { fork: Box::new(hardfork), condition }); } } @@ -479,47 +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, - params: TypeId, - ) -> Option<&(dyn Any + Send + Sync)> { - let entry = self.entries.iter().find(|entry| entry.fork.name() == fork.name())?; - entry.params.iter().find(|(type_id, _)| *type_id == params).map(|(_, value)| value.as_ref()) - } } #[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, independent of the [`SequencerRegistryConfig`](crate::system::SequencerRegistryConfig) - /// Satin actually requires. - #[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]); @@ -555,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] @@ -600,81 +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()); - } - - /// A fork carries one value per params type: attaching a second type keeps the first, and - /// attaching a type again replaces that type's value alone. - #[test] - fn test_a_fork_carries_one_value_per_params_type() { - #[derive(Clone, Debug, PartialEq, Eq)] - struct OtherParams(u64); - - impl HardforkParams for OtherParams { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "OtherParams"; - } - - let config = MegaHardforkConfig::default() - .with_all_activated() - .with_params(params()) - .with_params(OtherParams(1)); - assert_eq!(config.fork_params::(), Some(¶ms())); - assert_eq!(config.fork_params::(), Some(&OtherParams(1))); - - let replaced = config.with_params(OtherParams(2)); - assert_eq!(replaced.fork_params::(), Some(¶ms()), "untouched"); - assert_eq!(replaced.fork_params::(), Some(&OtherParams(2))); - - // The type-erased lookup answers by fork and type. - assert!(replaced - .fork_params_any(MegaHardfork::Satin, TypeId::of::()) - .is_some_and(|value| value.downcast_ref::() == Some(&OtherParams(2)))); - assert!(replaced.fork_params_any(MegaHardfork::Satin, TypeId::of::()).is_none()); - } - - #[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. @@ -694,128 +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(())); - // TestParams is not SequencerRegistryConfig, so the schedule still cannot run. - assert_eq!( - with_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Satin, - params: "SequencerRegistryConfig", - }) - ); - - // Satin requires both of its params types: the registry's alone does not load. - let with_registry = MegaHardforkConfig::default() - .with_all_activated() - .with_params(crate::system::SequencerRegistryConfig::placeholder()); - assert_eq!( - with_registry.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Satin, - params: "ProtocolLimits", - }) - ); - assert_eq!( - with_registry.validate_schedule().unwrap_err().to_string(), - "hardfork Satin is scheduled but its ProtocolLimits params are not configured" - ); - let with_limits = MegaHardforkConfig::default() - .with_all_activated() - .with_params(ProtocolLimits::default()); - assert_eq!( - with_limits.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Satin, - params: "SequencerRegistryConfig", - }) - ); - let with_both = with_registry.with_params(ProtocolLimits::default()); - assert_eq!(with_both.validate_schedule(), Ok(())); - - // Limits no chain may carry are refused at load, however they were attached. - let unlimited = MegaHardforkConfig::default() - .with_all_activated() - .with_params(crate::system::SequencerRegistryConfig::placeholder()) - .with_params_unchecked(ProtocolLimits::no_limits()); - assert!( - matches!( - unlimited.validate_schedule(), - Err(ScheduleError::InvalidParams { - fork: MegaHardfork::Satin, - params: "ProtocolLimits", - .. - }) - ), - "{:?}", - unlimited.validate_schedule() - ); - } - - /// A block reads the limits of the fork active at its timestamp: Satin's from its activation - /// on, and none before it or on a schedule that carries none. - #[test] - fn test_protocol_limits_are_the_active_forks_params() { - let limits = ProtocolLimits::default().with_block_kv_update_limit(7); - let config = MegaHardforkConfig::default() - .with(MegaHardfork::Satin, ForkCondition::Timestamp(100)) - .with_params(limits); - - assert_eq!(config.protocol_limits(99), None, "no MegaETH fork is active yet"); - assert_eq!(config.protocol_limits(100), Some(limits)); - assert_eq!(config.protocol_limits(u64::MAX), Some(limits)); - - let without = MegaHardforkConfig::default().with_all_activated(); - assert_eq!(without.protocol_limits(0), None, "Satin carries no limits here"); - } - - /// A scheduled fork's params are checked at load even when they were attached without - /// [`MegaHardforkConfig::with_params`], as a node's own schedule type attaches them; an - /// unscheduled fork's are not read at all. - #[test] - fn test_require_params_refuses_a_value_its_type_refuses() { - let invalid = TestParams { sequencer: alloy_primitives::Address::ZERO }; - - let scheduled = - MegaHardforkConfig::default().with_all_activated().with_params_unchecked(invalid); - let error = scheduled.require_params::().unwrap_err(); - assert_eq!( - error, - ScheduleError::InvalidParams { - fork: MegaHardfork::Satin, - params: "TestParams", - message: "sequencer must be set".into(), - } - ); - assert_eq!( - error.to_string(), - "hardfork Satin is scheduled with invalid TestParams params: sequencer must be set" - ); - - // The same value on a schedule that never activates the fork requires nothing. - let unscheduled = MegaHardforkConfig::default() - .with(MegaHardfork::Satin, ForkCondition::Never) - .with_params_unchecked(TestParams { sequencer: alloy_primitives::Address::ZERO }); - assert_eq!(unscheduled.require_params::(), 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] @@ -829,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 44726c7af..52a91f768 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -2,17 +2,12 @@ //! //! The limits come from two places, by who must agree on them: //! -//! - [`ProtocolLimits`] are the limits every node of a chain holds its blocks and transactions to, -//! because a different value is a different result: the per-transaction limits the EVM enforces -//! and the block's four budgets. They are the Satin fork's parameters, read from the schedule at -//! the block's timestamp, and their default is [`ProtocolLimits::DEFAULT`]: data size capped at -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) per transaction and -//! [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) per block, gas detention's caps at -//! the spec's, and every other limit unlimited. +//! - [`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 caps a builder may put on the block's budgets below the -//! protocol's. It never loosens a protocol limit ([`BlockLimits::within`]), and a validator +//! 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. @@ -23,156 +18,127 @@ //! 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, the state ledger, and the data-size -//! bytes and write records a transaction kept — is accumulated when the transaction commits. 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 reached its limit refuses what comes after it, so the overshoot is bounded by -//! one transaction per dimension, besides what deposits add: -//! -//! - the execution ledger, the data-size bytes and the write records are checked before the *next* -//! transaction starts, and a block that has reached any of them refuses every later transaction — -//! a deposit excepted; -//! - the state ledger is checked once the next transaction has executed, and a block that has -//! reached its limit refuses a later transaction only if it adds state gas — a deposit excepted. -//! One that adds none still fits, and only its own execution can tell which it is. +//! 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 execution-gas, -//! state-gas, data-size and KV limits are packing budgets for the transactions the builder -//! chooses, so none of them refuses a deposit either. A deposit still counts towards all four, 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 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 — data size, write records, state gas -//! — 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. +//! 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`]), execution and state have a -//! block limit. History has none by design; the history bytes beside it are reported, not -//! limited. The write-record count, which is the block's KV count, has one too: -//! [`ProtocolLimits::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 whatever its KV limit; the KV limit binds only below that, and is unlimited unless the -//! chain sets it. +//! 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; #[cfg(not(feature = "std"))] use alloc as std; -use std::{boxed::Box, format}; +use std::boxed::Box; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ - constants::MAX_TX_COMPUTE_GAS, BlockGasCounters, EvmTxRuntimeLimits, HardforkParams, - HardforkParamsError, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, MegaHardfork, - MegaTxLimitExceededError, TX_BODY_SIZE, + constants::{ + BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, + }, + BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, + MegaSpecId, MegaTxLimitExceededError, }; -/// The limits the protocol holds every block and every transaction to: the Satin fork's -/// parameters. +/// The limits the protocol holds every block and every transaction to, fixed per spec. /// -/// Each of them changes what a validator computes when it re-executes a block, so every node of -/// a chain holds the same values, and they travel with the chain configuration, attached to the -/// fork ([`HardforkParams`]). Block execution reads them from the schedule at the block's -/// timestamp ([`MegaHardforks::protocol_limits`](crate::MegaHardforks::protocol_limits)); a node -/// does not pass them with a block. +/// 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 four block budgets hold what a block's transactions spend and keep together. A validator -/// refuses a block that packs a transaction after the block reached one; a builder may pack +/// - 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. /// -/// [`Default`] is [`DEFAULT`](Self::DEFAULT): the values of [`crate::constants`], provisional -/// until the economics sign-off fixes them. +/// 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, write records and state gas, per transaction and per frame, and gas - /// detention's two caps. + /// data size, per transaction and per frame, and gas detention's two caps. pub tx_runtime_limits: EvmTxRuntimeLimits, - /// The most execution gas a block's transactions may spend together. The transaction that - /// reaches it is packed; after it, only a deposit is. - pub block_execution_gas_limit: u64, - /// The most state gas a block's transactions may spend together. The transaction that reaches - /// it is packed; after it, only a transaction that adds no state gas is, or a deposit. - pub block_state_gas_limit: u64, /// 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, - /// The most write records a block's transactions may keep together: the block's KV count. The - /// transaction that reaches it is packed; after it, only a deposit is. - pub block_kv_update_limit: u64, -} - -impl Default for ProtocolLimits { - fn default() -> Self { - Self::DEFAULT - } } impl ProtocolLimits { - /// Satin's limits: each transaction holds [`TX_DATA_LIMIT`] bytes of data size and a block - /// [`BLOCK_DATA_LIMIT`], a read of volatile data caps the transaction's compute at - /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] or [`ORACLE_ACCESS_COMPUTE_GAS`], and every other limit is - /// unlimited. Provisional, as the constants are. + /// The limits a block of `spec`, and every transaction in it, is held to. /// - /// [`TX_DATA_LIMIT`]: crate::constants::TX_DATA_LIMIT - /// [`BLOCK_DATA_LIMIT`]: crate::constants::BLOCK_DATA_LIMIT - /// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS - /// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS - pub const DEFAULT: Self = Self { - tx_runtime_limits: EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(crate::constants::TX_DATA_LIMIT) - .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) - .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS), - block_execution_gas_limit: u64::MAX, - block_state_gas_limit: u64::MAX, - block_txs_data_limit: crate::constants::BLOCK_DATA_LIMIT, - block_kv_update_limit: u64::MAX, - }; - - /// No limit at all, gas detention's caps included, so no transaction is detained - /// ([`EvmTxRuntimeLimits::no_limits`]). + /// [`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. /// - /// For tests of what refuses it: [`validate`](HardforkParams::validate) refuses it, so no - /// chain configuration carries it, and the block executor refuses a block under it. A test - /// that runs blocks without holding them to a limit uses [`loosest`](Self::loosest). - pub const fn no_limits() -> Self { - Self { - tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), - block_execution_gas_limit: u64::MAX, - block_state_gas_limit: u64::MAX, - block_txs_data_limit: u64::MAX, - block_kv_update_limit: u64::MAX, + /// 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, + }, } } - /// The loosest limits a chain may carry: every limit unlimited, and gas detention's caps at - /// the largest [`validate`](HardforkParams::validate) accepts, one below - /// [`MAX_TX_COMPUTE_GAS`]. + /// No limit at all, gas detention's caps included, so no transaction is detained + /// ([`EvmTxRuntimeLimits::no_limits`]). /// - /// A read of volatile data still detains the transaction, but a cap that high stops only a - /// transaction that spends the most compute any can. For tests and test chains that run blocks - /// without holding them to a limit. - pub const fn loosest() -> Self { - let cap = MAX_TX_COMPUTE_GAS - 1; - Self::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_block_env_access_compute_gas_limit(cap) - .with_oracle_access_compute_gas_limit(cap), - ) + /// 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. @@ -181,108 +147,19 @@ impl ProtocolLimits { 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 state-gas limit. - pub const fn with_block_state_gas_limit(mut self, limit: u64) -> Self { - self.block_state_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 block's KV limit: the most write records its transactions may keep together. - pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { - self.block_kv_update_limit = limit; - self - } } -impl HardforkParams for ProtocolLimits { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "ProtocolLimits"; - - /// Refuses a value no chain can run on: - /// - /// - a limit of zero, which is what a field left out of a configuration reads as, and which - /// stops or refuses every transaction that uses the dimension; - /// - a transaction data-size limit below [`TX_BODY_SIZE`], the bytes every transaction's body - /// counts, which stops every transaction before it runs; - /// - a gas-detention cap at or above [`MAX_TX_COMPUTE_GAS`], the most compute a transaction can - /// spend: such a cap never stops a read of volatile data, `u64::MAX` among them, and a - /// chain's caps must be able to. - /// - /// `u64::MAX` is a valid value for every other limit: it leaves the dimension unlimited. - fn validate(&self) -> Result<(), HardforkParamsError> { - let EvmTxRuntimeLimits { - tx_data_size_limit, - frame_data_size_limit, - tx_kv_update_limit, - frame_kv_update_limit, - tx_state_gas_limit, - block_env_access_compute_gas_limit, - oracle_access_compute_gas_limit, - } = self.tx_runtime_limits; - let detention_caps = [ - ( - "tx_runtime_limits.block_env_access_compute_gas_limit", - block_env_access_compute_gas_limit, - ), - ("tx_runtime_limits.oracle_access_compute_gas_limit", oracle_access_compute_gas_limit), - ]; - let limits = [ - ("tx_runtime_limits.tx_data_size_limit", tx_data_size_limit), - ("tx_runtime_limits.frame_data_size_limit", frame_data_size_limit), - ("tx_runtime_limits.tx_kv_update_limit", tx_kv_update_limit), - ("tx_runtime_limits.frame_kv_update_limit", frame_kv_update_limit), - ("tx_runtime_limits.tx_state_gas_limit", tx_state_gas_limit), - detention_caps[0], - detention_caps[1], - ("block_execution_gas_limit", self.block_execution_gas_limit), - ("block_state_gas_limit", self.block_state_gas_limit), - ("block_txs_data_limit", self.block_txs_data_limit), - ("block_kv_update_limit", self.block_kv_update_limit), - ]; - - let invalid = |message| Err(HardforkParamsError { message }); - for (name, limit) in limits { - if limit == 0 { - return invalid(format!("ProtocolLimits.{name} must not be zero")); - } - } - if tx_data_size_limit < TX_BODY_SIZE { - return invalid(format!( - "ProtocolLimits.tx_runtime_limits.tx_data_size_limit must be at least \ - {TX_BODY_SIZE}, the bytes every transaction's body counts" - )); - } - for (name, cap) in detention_caps { - if cap >= MAX_TX_COMPUTE_GAS { - return invalid(format!( - "ProtocolLimits.{name} must be below {MAX_TX_COMPUTE_GAS}, the most compute \ - a transaction can spend: a cap there leaves a read of volatile data \ - undetained" - )); - } - } - Ok(()) - } -} - -/// The building policy one block is packed under: the limits only a builder applies, and the -/// caps it may put on the block's budgets below the protocol's. +/// 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 chain's -/// schedule, and this can only make a block tighter than they do ([`within`](Self::within)). So a +/// 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 @@ -292,18 +169,15 @@ impl HardforkParams for 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. -/// - The four block budgets are the builder's caps on the protocol's: the block executor holds a -/// block to the smaller of the two. -/// - [`block_gas_limit`](Self::block_gas_limit) is the header's: the block executor always sets it -/// from the block environment. +/// - [`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. 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. Deposits are exempt. pub tx_encode_size_limit: u64, /// The most bytes the block's transaction bodies may take together, uncompressed. Deposits are @@ -314,20 +188,6 @@ pub struct BlockLimits { /// 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. 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_execution_gas_limit`]. - pub block_execution_gas_limit: u64, - /// The most state gas the block's transactions may spend together. The transaction that - /// reaches it is packed; after it, only a transaction that adds no state gas is, or a deposit, - /// 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_state_gas_limit`]. - pub block_state_gas_limit: u64, /// 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. @@ -335,13 +195,6 @@ 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: the block's KV count. - /// 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_kv_update_limit`]. - pub block_kv_update_limit: u64, } impl Default for BlockLimits { @@ -357,32 +210,23 @@ impl BlockLimits { 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_state_gas_limit: u64::MAX, block_txs_data_limit: u64::MAX, - block_kv_update_limit: u64::MAX, } } - /// These limits held within `protocol`: each of the block's four budgets 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 one. The limits only a builder applies are kept as they are. + /// 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_execution_gas_limit: self - .block_execution_gas_limit - .min(protocol.block_execution_gas_limit), - block_state_gas_limit: self.block_state_gas_limit.min(protocol.block_state_gas_limit), 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), ..self } } @@ -393,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; @@ -426,42 +261,17 @@ impl BlockLimits { self } - /// Caps the block's execution gas. - pub const fn with_block_execution_gas_limit(mut self, limit: u64) -> Self { - self.block_execution_gas_limit = limit; - self - } - - /// Caps the block's state gas. - pub const fn with_block_state_gas_limit(mut self, limit: u64) -> Self { - self.block_state_gas_limit = limit; - self - } - /// 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 } - - /// Caps the block's KV count: the write records its transactions may keep together. - pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { - self.block_kv_update_limit = limit; - self - } - - /// 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, @@ -484,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. @@ -500,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, history_bytes: 0 }, - usage: LimitUsage { data_size: 0, write_records: 0 }, + usage: LimitUsage::ZERO, block_tx_size_used: 0, block_da_size_used: 0, block_da_footprint_used: 0, @@ -515,24 +332,23 @@ 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; a - /// deposit is held to the block's gas limit alone — to no limit only a builder applies, and to - /// neither the execution-gas, the data-size nor the KV limit. It reads the counters and changes - /// nothing; - /// [`post_execution_check`](Self::post_execution_check) checks what only the transaction's - /// execution reveals, and [`post_execution_update`](Self::post_execution_update) advances the - /// counters once the transaction commits. + /// 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 /// @@ -546,14 +362,11 @@ impl BlockLimiter { gas_limit: u64, tx_size: u64, da_size: u64, - is_deposit: bool, + packing_exempt: bool, ) -> Result<(), BlockExecutionError> { - // 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 it — its declared gas, its encoded size and its data-availability size, and what - // those add to the block — and it does not count towards the block's data-availability - // size. The block's gas limit, the header's, holds it as it holds every transaction. - if !is_deposit && 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 { @@ -563,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(), @@ -571,11 +384,9 @@ impl BlockLimiter { .into()); } - // The packing budgets below are the dimensions a transaction's own execution reveals. The - // transaction that crossed one is already packed, so what they refuse is the next one — - // never a deposit, which is not the builder's to refuse either. Every committed - // transaction counts towards them, a deposit included, in `post_execution_update`. - if is_deposit { + // Nothing below refuses a packing-exempt transaction; `post_execution_update` still counts + // it. + if packing_exempt { return Ok(()); } @@ -622,16 +433,6 @@ impl BlockLimiter { )); } - 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, @@ -642,70 +443,20 @@ impl BlockLimiter { )); } - // The block's KV count. - 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, - }, - )); - } - - // `self.gas.state` is checked after execution, in `post_execution_check`: a block that has - // reached its state gas still admits a transaction that adds none. `self.gas.history` is - // accumulated and not checked: history has no block limit. + // `self.gas` and `self.usage.write_records` are accumulated and not checked: none of them + // has a block limit. Ok(()) } - /// Whether the executed transaction whose block usage is `usage` may be packed in this block. - /// - /// A block that has reached its state-gas limit refuses a transaction that adds state gas, and - /// only such a transaction: whether one does is known only once it has run. The transaction - /// that reaches the limit is itself packed — the block had not reached it when that - /// transaction came — so the block overshoots its limit by at most one transaction's state - /// gas, besides what deposits add: a deposit is never refused. Like - /// [`pre_execution_check`](Self::pre_execution_check) it changes nothing. - /// - /// # Errors - /// - /// A [`MegaBlockLimitExceededError::StateGasLimit`] when the block has no state gas left and - /// the transaction, not a deposit, adds some, which a builder answers by trying the next - /// transaction. - pub fn post_execution_check( - &self, - tx_hash: TxHash, - usage: &BlockUsage, - ) -> Result<(), BlockExecutionError> { - // A deposit is not the builder's to refuse; it still counts, in `post_execution_update`. - if !usage.is_deposit && - usage.gas.state > 0 && - self.gas.state >= self.limits.block_state_gas_limit - { - return Err(invalid_tx( - tx_hash, - MegaBlockLimitExceededError::StateGasLimit { - block_used: self.gas.state, - tx_used: usage.gas.state, - limit: self.limits.block_state_gas_limit, - }, - )); - } - 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.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); @@ -726,205 +477,86 @@ fn invalid_tx( #[cfg(test)] mod tests { use super::*; - use crate::{MegaHardforkConfig, MegaHardforks}; + use crate::{constants::MAX_TX_COMPUTE_GAS, TX_BODY_SIZE}; use alloy_primitives::B256; - /// The protocol's default limits, written out so a change to one is a visible diff: today's - /// provisional constants, and unlimited everywhere else. + /// 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_default_protocol_limits_are_the_provisional_constants() { - use crate::constants::{ - BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, - TX_DATA_LIMIT, - }; - assert_eq!(ProtocolLimits::default(), ProtocolLimits::DEFAULT); + fn test_the_satin_limits_are_written_out() { + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); assert_eq!( - ProtocolLimits::DEFAULT, + limits, ProtocolLimits { tx_runtime_limits: EvmTxRuntimeLimits { - tx_data_size_limit: TX_DATA_LIMIT, + tx_data_size_limit: 13_107_200, frame_data_size_limit: u64::MAX, - tx_kv_update_limit: u64::MAX, - frame_kv_update_limit: u64::MAX, - tx_state_gas_limit: u64::MAX, - block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, - oracle_access_compute_gas_limit: ORACLE_ACCESS_COMPUTE_GAS, + block_env_access_compute_gas_limit: 20_000_000, + oracle_access_compute_gas_limit: 20_000_000, }, - block_execution_gas_limit: u64::MAX, - block_state_gas_limit: u64::MAX, - block_txs_data_limit: BLOCK_DATA_LIMIT, - block_kv_update_limit: u64::MAX, + block_txs_data_limit: 13_107_200, } ); - assert_eq!( - ProtocolLimits::DEFAULT.tx_runtime_limits, - EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_DATA_LIMIT), - "a transaction's defaults are a bare context's, with the data-size limit" - ); - assert_eq!(ProtocolLimits::DEFAULT.validate(), Ok(())); + + 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 travel with a chain configuration: they survive a round trip through its JSON, - /// whose shape is written out here, and through a schedule, which hands back what was - /// attached. + /// 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 limits = ProtocolLimits::DEFAULT - .with_tx_runtime_limits( - ProtocolLimits::DEFAULT - .tx_runtime_limits - .with_frame_data_size_limit(1) - .with_tx_kv_update_limit(2) - .with_frame_kv_update_limit(3) - .with_tx_state_gas_limit(4), - ) - .with_block_execution_gas_limit(5) - .with_block_state_gas_limit(6) - .with_block_txs_data_limit(7) - .with_block_kv_update_limit(8); + 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,"txKvUpdateLimit":2,"frameKvUpdateLimit":3,"txStateGasLimit":4,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockExecutionGasLimit":5,"blockStateGasLimit":6,"blockTxsDataLimit":7,"blockKvUpdateLimit":8}"# + r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7}"# ); assert_eq!(serde_json::from_str::(&json).expect("deserializes"), limits); - // A field left out is an error, not a zero; so is one the type does not have. - let missing = json.replace(r#","blockKvUpdateLimit":8"#, ""); + let missing = json.replace(r#","blockTxsDataLimit":7"#, ""); assert!(serde_json::from_str::(&missing).is_err(), "{missing}"); - let missing_tx = json.replace(r#""txStateGasLimit":4,"#, ""); + let missing_tx = json.replace(r#""frameDataSizeLimit":1,"#, ""); assert!(serde_json::from_str::(&missing_tx).is_err(), "{missing_tx}"); - let unknown = json.replace(r#""blockKvUpdateLimit":8"#, r#""blockKvUpdateLimit":8,"x":1"#); + let unknown = json.replace(r#""blockTxsDataLimit":7"#, r#""blockTxsDataLimit":7,"x":1"#); assert!(serde_json::from_str::(&unknown).is_err(), "{unknown}"); - - let schedule = MegaHardforkConfig::default().with_all_activated().with_params(limits); - assert_eq!(schedule.fork_params::(), Some(&limits)); - assert_eq!(schedule.protocol_limits(0), Some(limits)); - } - - /// Every limit refuses zero, the value a field left out of a configuration reads as; the - /// transaction's data size refuses less than a body; the detention caps refuse a value no - /// transaction's compute reaches, and every other limit accepts `u64::MAX`. - #[test] - fn test_validate_refuses_what_no_chain_can_run_on() { - let base = ProtocolLimits::DEFAULT; - let tx = |f: fn(EvmTxRuntimeLimits, u64) -> EvmTxRuntimeLimits, value| { - base.with_tx_runtime_limits(f(base.tx_runtime_limits, value)) - }; - type Set = fn(ProtocolLimits, u64) -> ProtocolLimits; - let fields: [(&str, Set); 11] = [ - ("tx_runtime_limits.tx_data_size_limit", |l, v| { - l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_data_size_limit(v)) - }), - ("tx_runtime_limits.frame_data_size_limit", |l, v| { - l.with_tx_runtime_limits(l.tx_runtime_limits.with_frame_data_size_limit(v)) - }), - ("tx_runtime_limits.tx_kv_update_limit", |l, v| { - l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_kv_update_limit(v)) - }), - ("tx_runtime_limits.frame_kv_update_limit", |l, v| { - l.with_tx_runtime_limits(l.tx_runtime_limits.with_frame_kv_update_limit(v)) - }), - ("tx_runtime_limits.tx_state_gas_limit", |l, v| { - l.with_tx_runtime_limits(l.tx_runtime_limits.with_tx_state_gas_limit(v)) - }), - ("tx_runtime_limits.block_env_access_compute_gas_limit", |l, v| { - l.with_tx_runtime_limits( - l.tx_runtime_limits.with_block_env_access_compute_gas_limit(v), - ) - }), - ("tx_runtime_limits.oracle_access_compute_gas_limit", |l, v| { - l.with_tx_runtime_limits( - l.tx_runtime_limits.with_oracle_access_compute_gas_limit(v), - ) - }), - ("block_execution_gas_limit", ProtocolLimits::with_block_execution_gas_limit), - ("block_state_gas_limit", ProtocolLimits::with_block_state_gas_limit), - ("block_txs_data_limit", ProtocolLimits::with_block_txs_data_limit), - ("block_kv_update_limit", ProtocolLimits::with_block_kv_update_limit), - ]; - - for (name, set) in fields { - assert_eq!( - set(base, 0).validate(), - Err(HardforkParamsError { - message: std::format!("ProtocolLimits.{name} must not be zero") - }), - "{name}" - ); - assert_eq!( - set(base, 1).validate().is_ok(), - name != "tx_runtime_limits.tx_data_size_limit", - "{name} at one" - ); - if name.ends_with("compute_gas_limit") { - // A cap no transaction's compute reaches is refused, the execution cap and - // `u64::MAX` among them; one below the most compute is accepted. - for cap in - [MAX_TX_COMPUTE_GAS, crate::constants::TX_GAS_LIMIT_CAP, u64::MAX - 1, u64::MAX] - { - assert_eq!( - set(base, cap).validate(), - Err(HardforkParamsError { - message: std::format!( - "ProtocolLimits.{name} must be below {MAX_TX_COMPUTE_GAS}, the \ - most compute a transaction can spend: a cap there leaves a read \ - of volatile data undetained" - ) - }), - "{name} at {cap}" - ); - } - assert_eq!( - set(base, MAX_TX_COMPUTE_GAS - 1).validate(), - Ok(()), - "{name} just below" - ); - } else { - assert_eq!(set(base, u64::MAX).validate(), Ok(()), "{name} may be unlimited"); - } - } - - // The transaction's data size holds at least a body, and exactly a body is enough. - assert_eq!( - tx(EvmTxRuntimeLimits::with_tx_data_size_limit, TX_BODY_SIZE - 1).validate(), - Err(HardforkParamsError { - message: std::format!( - "ProtocolLimits.tx_runtime_limits.tx_data_size_limit must be at least \ - {TX_BODY_SIZE}, the bytes every transaction's body counts" - ) - }) - ); - assert_eq!( - tx(EvmTxRuntimeLimits::with_tx_data_size_limit, TX_BODY_SIZE).validate(), - Ok(()) - ); - - // The unlimited set is refused; the loosest a chain may carry is unlimited but for - // detention's caps, one below the most compute a transaction can spend. - assert!(ProtocolLimits::no_limits().validate().is_err()); - assert_eq!(ProtocolLimits::loosest().validate(), Ok(())); - let cap = MAX_TX_COMPUTE_GAS - 1; - assert_eq!( - ProtocolLimits::loosest(), - ProtocolLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_block_env_access_compute_gas_limit(cap) - .with_oracle_access_compute_gas_limit(cap) - ) - ); } - /// A schedule refuses to carry the unlimited set, so no validated chain configuration does. + /// `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] - #[should_panic(expected = "Invalid params for fork Satin: \ - ProtocolLimits.tx_runtime_limits.block_env_access_compute_gas_limit must be \ - below 199987900")] - fn test_a_schedule_refuses_the_unlimited_protocol_limits() { - let _ = MegaHardforkConfig::default() - .with_all_activated() - .with_params(ProtocolLimits::no_limits()); + 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 @@ -935,76 +567,50 @@ mod tests { assert_eq!(BlockLimits::default(), BlockLimits::no_limits()); let BlockLimits { tx_gas_limit, - block_gas_limit, tx_encode_size_limit, block_txs_encode_size_limit, tx_da_size_limit, block_da_size_limit, - block_execution_gas_limit, - block_state_gas_limit, block_txs_data_limit, - block_kv_update_limit, } = BlockLimits::default(); for limit in [ tx_gas_limit, - block_gas_limit, tx_encode_size_limit, block_txs_encode_size_limit, tx_da_size_limit, block_da_size_limit, - block_execution_gas_limit, - block_state_gas_limit, block_txs_data_limit, - block_kv_update_limit, ] { assert_eq!(limit, u64::MAX); } assert_eq!( - BlockLimits::default().within(&ProtocolLimits::DEFAULT).block_txs_data_limit, + 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 a block 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 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::DEFAULT - .with_block_execution_gas_limit(100) - .with_block_state_gas_limit(200) - .with_block_txs_data_limit(300) - .with_block_kv_update_limit(400); + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_txs_data_limit(300); let tighter = BlockLimits::no_limits() - .with_block_execution_gas_limit(10) - .with_block_state_gas_limit(20) .with_block_txs_data_limit(30) - .with_block_kv_update_limit(40) .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) - .with_block_gas_limit(6); + .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_execution_gas_limit(1_000) - .with_block_state_gas_limit(2_000) - .with_block_txs_data_limit(3_000) - .with_block_kv_update_limit(4_000); + let looser = BlockLimits::no_limits().with_block_txs_data_limit(3_000); let held = looser.within(&protocol); - assert_eq!( - ( - held.block_execution_gas_limit, - held.block_state_gas_limit, - held.block_txs_data_limit, - held.block_kv_update_limit, - ), - (100, 200, 300, 400), - "a cap above the protocol's gives way to it" - ); + 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) }, @@ -1012,14 +618,15 @@ mod tests { ); } - 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) + /// 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, @@ -1038,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"); @@ -1046,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()); @@ -1055,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()); @@ -1064,7 +675,7 @@ 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, @@ -1099,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; @@ -1114,62 +725,13 @@ 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. - #[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}"); - } - - /// A deposit is never refused by the execution-gas 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_never_refuses_a_deposit_and_counts_it() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_execution_gas_limit(1_000)); - let deposit = BlockUsage { - gas: MegaGasUsage { regular: 600, ..Default::default() }, - is_deposit: true, - ..Default::default() - }; - - // 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.gas.execution, 1_800, "every deposit counts"); - - let err = limiter - .pre_execution_check(B256::ZERO, 0, 0, 0, false) - .expect_err("the deposits used the room an ordinary transaction would need"); - assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); - } - /// 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_data_size_limit_never_refuses_a_deposit_and_counts_it() { let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_txs_data_limit(1_000)); + 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, @@ -1203,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) @@ -1211,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) @@ -1222,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), ), @@ -1232,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, @@ -1239,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), ), @@ -1247,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), @@ -1287,7 +853,7 @@ mod tests { ), ]; for (name, limits, gas_limit, size) in cases { - let limiter = BlockLimiter::new(limits); + 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) @@ -1296,7 +862,7 @@ mod tests { assert!(check(false).is_err(), "{name} over the policy: a transaction is refused"); } - let limiter = BlockLimiter::new(limits_with_block_gas(100)); + 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"); @@ -1307,8 +873,10 @@ mod tests { /// 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)); + 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 { @@ -1329,10 +897,13 @@ mod tests { /// 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 @@ -1344,16 +915,18 @@ 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 history ledger and the history bytes are accumulated, and no check refuses a - /// transaction on them; nor on the state ledger or the write records, whose limits are - /// unlimited unless the chain sets 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_history_is_counted_but_not_enforced() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + 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, @@ -1372,132 +945,5 @@ mod tests { 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()); - assert!(limiter.post_execution_check(B256::ZERO, &usage).is_ok()); - } - - /// What one committed transaction kept of write records, and nothing else. - fn keeps_records(write_records: u64) -> BlockUsage { - BlockUsage { usage: LimitUsage { data_size: 0, write_records }, ..Default::default() } - } - - /// The block's KV limit is a packing budget like its data size: the transaction that reaches - /// it is packed, the next one is refused before it runs, and the limit is an inclusive bound. - #[test] - fn test_kv_limit_refuses_the_transaction_after_the_crossing() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); - - limiter.post_execution_update(&keeps_records(999)); - assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); - - // The crossing transaction had been admitted, and it is packed: the block overshoots. - limiter.post_execution_update(&keeps_records(5)); - assert_eq!(limiter.usage.write_records, 1_004); - let err = limiter - .pre_execution_check(B256::ZERO, 0, 0, 0, false) - .expect_err("the block's write records have reached their limit"); - assert!(std::format!("{err}").contains("Block KV update limit reached"), "{err}"); - assert!(std::format!("{err}").contains("block_used=1004"), "{err}"); - - // A block that kept exactly its limit is full. - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); - limiter.post_execution_update(&keeps_records(1_000)); - assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_err()); - } - - /// A deposit is never refused by the block's KV 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_kv_limit_never_refuses_a_deposit_and_counts_it() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_kv_update_limit(1_000)); - let deposit = BlockUsage { is_deposit: true, ..keeps_records(600) }; - - 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.write_records, 1_800, "every deposit counts"); - - let err = limiter - .pre_execution_check(B256::ZERO, 0, 0, 0, false) - .expect_err("the deposits used the room an ordinary transaction would need"); - assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); - } - - /// What one committed transaction spent on the state ledger, and nothing else. - fn adds_state(state: u64) -> BlockUsage { - BlockUsage { gas: MegaGasUsage { state, ..Default::default() }, ..Default::default() } - } - - /// The state ledger's block limit: the transaction that reaches it is packed, and after it a - /// transaction is refused only if it adds state gas. - #[test] - fn test_state_gas_limit_packs_the_crossing_transaction_and_skips_the_next_that_adds_state() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); - - // The n-th transaction finds the block below its limit and crosses it: it is packed. - limiter.post_execution_update(&adds_state(900)); - assert!(limiter.post_execution_check(B256::ZERO, &adds_state(300)).is_ok()); - limiter.post_execution_update(&adds_state(300)); - assert_eq!(limiter.gas.state, 1_200, "the block overshoots by that one transaction"); - - // The (n+1)-th adds state gas: refused, with the state dimension's own error. - let err = limiter - .post_execution_check(B256::ZERO, &adds_state(1)) - .expect_err("the block has no state gas left"); - assert!(std::format!("{err}").contains("Block state gas limit reached"), "{err}"); - assert!(std::format!("{err}").contains("block_used=1200"), "{err}"); - assert!(std::format!("{err}").contains("tx_used=1"), "{err}"); - - // One that adds none still fits, before execution and after it. - assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); - assert!(limiter.post_execution_check(B256::ZERO, &adds_state(0)).is_ok()); - } - - /// A deposit is never refused by the state-gas 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_state_gas_limit_never_refuses_a_deposit_and_counts_it() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); - let deposit = |state| BlockUsage { is_deposit: true, ..adds_state(state) }; - - // Two deposits cross the limit between them. - for _ in 0..2 { - assert!(limiter.post_execution_check(B256::ZERO, &deposit(600)).is_ok()); - limiter.post_execution_update(&deposit(600)); - } - assert_eq!(limiter.gas.state, 1_200); - - // A third finds the block past its limit and is still admitted. - assert!(limiter.post_execution_check(B256::ZERO, &deposit(600)).is_ok()); - limiter.post_execution_update(&deposit(600)); - assert_eq!(limiter.gas.state, 1_800, "every deposit counts"); - - let err = limiter - .post_execution_check(B256::ZERO, &adds_state(1)) - .expect_err("the deposits used the room an ordinary transaction would need"); - assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); - } - - /// The state-gas limit is an inclusive bound like every other: a block may spend exactly its - /// limit, and the block that has is full. - #[test] - fn test_state_gas_limit_admits_what_exactly_fills_it() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_state_gas_limit(1_000)); - limiter.post_execution_update(&adds_state(999)); - assert!(limiter.post_execution_check(B256::ZERO, &adds_state(1)).is_ok()); - - limiter.post_execution_update(&adds_state(1)); - assert!( - limiter.post_execution_check(B256::ZERO, &adds_state(1)).is_err(), - "a block that spent exactly its limit is full" - ); } } 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 ad64f8986..83243b51c 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -9,7 +9,7 @@ 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}; @@ -17,8 +17,9 @@ use crate::{BlockUsage, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactio /// 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, where it has one. +/// 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. @@ -27,15 +28,8 @@ pub struct BlockGasCounters { pub state: u64, /// History gas. pub history: u64, - /// The history bytes the block's transactions appended, whoever paid for them. At the cost per - /// history byte they are worth [`history`](Self::history) plus what the history allowances of - /// value transfers paid, which no gas ledger carries. - /// - /// They are the history bytes the schedule prices, not the chain's physical growth: the - /// block's exempt transactions (its deposits, the transactions the protocol sent) add none, - /// each body counts its five fixed write records even when fewer fee accounts are written, - /// and the EIP-7708 transfer logs in the block's receipts, which nothing prices, are not in - /// them. + /// 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, } @@ -144,27 +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. A deposit is never refused this - /// way. - ExecutionGasLimit { - /// The execution gas the block has spent. - block_used: u64, - /// The block's execution-gas limit. - limit: u64, - }, - /// The block's transactions have reached their state gas, and this transaction adds more. - /// - /// Only a transaction's own execution tells whether it adds state gas, so this one was - /// executed before it was refused; a transaction that adds none still fits the block, and a - /// deposit is never refused this way. - StateGasLimit { - /// The state gas the block has spent. - block_used: u64, - /// The state gas this transaction would add. - tx_used: u64, - /// The block's state-gas limit. - limit: u64, - }, /// The block's transactions have kept their data-size bytes. TransactionDataLimit { /// The data-size bytes the block has kept. @@ -172,14 +145,6 @@ pub enum MegaBlockLimitExceededError { /// The block's data-size limit. limit: u64, }, - /// The block's transactions have kept their write records, the block's KV count. A deposit is - /// never refused this way. - KVUpdateLimit { - /// The write records the block has kept. - block_used: u64, - /// The block's KV 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. @@ -204,10 +169,7 @@ impl MegaBlockLimitExceededError { /// What the block used of the resource. pub const fn block_used(&self) -> u64 { match self { - Self::ExecutionGasLimit { block_used, .. } | - Self::StateGasLimit { block_used, .. } | Self::TransactionDataLimit { block_used, .. } | - Self::KVUpdateLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, } @@ -216,10 +178,7 @@ impl MegaBlockLimitExceededError { /// The limit of the resource. pub const fn limit(&self) -> u64 { match self { - Self::ExecutionGasLimit { limit, .. } | - Self::StateGasLimit { limit, .. } | Self::TransactionDataLimit { limit, .. } | - Self::KVUpdateLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, } @@ -229,19 +188,9 @@ 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::StateGasLimit { block_used, tx_used, limit } => write!( - f, - "Block state gas limit reached: block_used={block_used} >= limit={limit}, tx_used={tx_used}" - ), 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::TransactionEncodeSizeLimit { block_used, tx_used, limit } => write!( f, "Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" @@ -294,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, @@ -306,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, @@ -440,14 +403,7 @@ 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::StateGasLimit { block_used: 6, tx_used: 2, limit: 15 }, - 6, - 15, - ), (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), - (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 7, limit: 16 }, 7, 16), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { block_used: 4, diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 8f2e5d469..d11367e6f 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -13,25 +13,20 @@ //! | [`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 default protocol limits | -//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the default 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) | the default detention cap of the runtime limits and of the protocol limits | -//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | the default detention cap of the runtime limits and of the 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 | the protocol limits, whose detention caps must be below it | +//! | [`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. -//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`] and the two detention caps are the defaults of the -//! Satin fork's parameters, [`ProtocolLimits::DEFAULT`](crate::ProtocolLimits::DEFAULT): a chain -//! carries its own in its configuration, and block execution reads them from there. The state-gas -//! limits have no constant at all: the per-transaction one is -//! [`EvmTxRuntimeLimits::tx_state_gas_limit`](crate::EvmTxRuntimeLimits::tx_state_gas_limit) and -//! the per-block one -//! [`ProtocolLimits::block_state_gas_limit`](crate::ProtocolLimits::block_state_gas_limit). A chain -//! sets both, and both are unlimited by default. +//! [`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::{ context_interface::cfg::gas::WARM_STORAGE_READ_COST, @@ -93,9 +88,9 @@ pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; /// 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 (Satin -/// keeps Osaka's). A gas-detention cap at or above this never stops a transaction, however early -/// it read, so a chain's caps must be below it. +/// 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; @@ -113,10 +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); - assert_eq!(BLOCK_ENV_ACCESS_COMPUTE_GAS, 20_000_000); - assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, 20_000_000); + // 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 6dd747e05..03d3fe786 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,5 +1,9 @@ //! 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::{ @@ -16,12 +20,16 @@ use crate::{ constants, evm::{ history::transaction_body_bytes, + inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{self, keyless::KeylessFrame}, - AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, Detention, EmptyExternalEnv, - EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, - SaltEnv, VolatileDataAccess, + 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` @@ -41,8 +49,9 @@ pub(crate) type MegaInnerContext = /// [`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 /// common execution layer's state for the running transaction ([`AdditionalLimit`]), gas -/// detention's ([`Detention`]) and the SALT bucket multipliers that transaction has priced state -/// gas with ([`BucketMultipliers`]). +/// 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, @@ -51,12 +60,23 @@ pub struct MegaContext>, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, + /// 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 @@ -69,13 +89,17 @@ pub struct MegaContext 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, @@ -87,11 +111,17 @@ 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"))] @@ -103,8 +133,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 and the two code-size limits. Every other - /// field (chain id, disabled checks, blob schedule) is taken from `cfg`. + /// 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 { @@ -207,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 @@ -226,18 +258,36 @@ 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. - #[cfg(any(test, feature = "test-utils"))] - pub const fn additional_limit_mut(&mut self) -> &mut AdditionalLimit { - &mut self.additional_limit - } - /// 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 { @@ -265,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 @@ -280,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. @@ -319,10 +394,11 @@ impl MegaContext { /// 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 for a transaction of the system shape, so the - /// layer is prepared before anything else of the transaction runs. + /// 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 @@ -333,23 +409,37 @@ impl MegaContext { /// not a transaction anybody sent. pub(crate) fn on_new_system_call(&mut self) { 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 go with it: they are what one transaction read, so the next - /// one reads its own. + /// 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, - /// the KV count, the state gas, and the frame budgets of the first two — 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. + /// 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; @@ -437,7 +527,18 @@ 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 @@ -456,7 +557,11 @@ impl MegaContext { /// 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. -fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { +/// +/// 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; @@ -464,6 +569,7 @@ fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { 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 @@ -520,12 +626,23 @@ 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) { + return Err(Bytes::new()); + } self.additional_limit.on_code_deposit(deposit) } } @@ -559,6 +676,7 @@ mod tests { 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"); @@ -573,6 +691,7 @@ mod tests { eip7708: bool, eip7708_disabled: bool, margin: bool, + chain_id_check: bool, code_size: Option, initcode_size: Option, gas_params: &'a GasParams, @@ -587,6 +706,7 @@ mod tests { 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, @@ -608,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] @@ -620,6 +757,7 @@ mod tests { 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); @@ -630,58 +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_on() { - assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip7708 = false)); - } - - #[test] - fn test_eip7708_cannot_be_disabled() { - assert_satin_cfg(&context_with(|cfg| cfg.amsterdam_eip7708_disabled = true)); - } - - #[test] - fn test_the_system_call_reservoir_margin_stays_on() { - assert_satin_cfg(&context_with(|cfg| { - cfg.system_call_state_gas_margin_in_reservoir = false; - })); - } - - #[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() { @@ -732,6 +818,91 @@ mod tests { 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] diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index b93199e46..0db00ef6f 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -13,7 +13,7 @@ use op_revm::{ transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; -use std::{boxed::Box, vec::Vec}; +use std::vec::Vec; use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ @@ -29,6 +29,7 @@ use revm::{ }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, + execution::runtime_oog_unwind, instructions::InstructionProvider, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, @@ -38,9 +39,8 @@ use revm::{ InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallInput, CallInputs, - CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, InitialAndFloorGas, - InstructionResult, InterpreterAction, InterpreterResult, SharedMemory, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, + InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, Inspector, Journal, @@ -48,16 +48,15 @@ use revm::{ use crate::{ access::ComputeStop, - evm::{ - history::transaction_body_bytes, - inspector::{ - frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, - }, + charge_write_records_history, + evm::inspector::{ + frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, + UpfrontRecord, }, history_gas, synthetic_frame_result, system::keyless, - write_record_history_gas, Detention, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitKind, - MegaContext, MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, + Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, + PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; /// The Satin handler. @@ -87,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, @@ -107,10 +144,6 @@ 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 @@ -118,12 +151,9 @@ where /// 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. /// - /// A transaction whose body crossed the data-size limit is latched before it runs, and its - /// first frame will be answered with the stop. Nothing after the caller's account is applied - /// or charged for it: the authorizations would be taken back, and the records made outside a - /// frame are records the limit rejects. So no charge made for them can run the transaction - /// out of gas, and the stop that bound first is what it reports. The caller's account is - /// charged all the same, because it exists whatever the transaction 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, @@ -131,51 +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); } - if evm.ctx_ref().additional_limit.latched().is_some() { - return Ok(Some(PreExecutionOutput { eip7702_refund: 0, checkpoint })); - } - 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); }; - let authorities = - record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i, gas.state_gas_spent()); - if authorities.check.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 })); - } - if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, authorities.applied) { - evm.ctx().journal_mut().checkpoint_revert(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 })) } - /// 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. + /// 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. Only a transaction of the - /// system shape reads the live system address, from the journal and without warming it; every - /// other transaction pays the shape test, a comparison or two on its own fields. + /// 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> { - let ctx = evm.ctx_mut(); - let system_transaction = crate::system::is_live_system_transaction(ctx)?; - ctx.on_new_tx(system_transaction); - if system_transaction { - crate::system::validate_and_promote::<_, _, Self::Error>(ctx)?; - } - 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 @@ -212,15 +231,27 @@ where /// 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 = transaction_body_bytes(evm.ctx_ref().tx()); + 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); @@ -238,43 +269,35 @@ where Ok(gas) } - /// revm's first frame, unless the transaction is already latched: then a frame input built on - /// what the transaction has left, with nothing charged for the frame's start. - /// - /// A latched transaction's first frame is answered with the stop before revm builds it, so it - /// makes none of the writes revm's EIP-2780 runtime charges price for its start — a value - /// recipient's new account, a created account — and reaches no delegation target. Charging - /// them would only matter to a gas limit that cannot pay them, which would then report an - /// out-of-gas in place of the stop that bound first. The input carries no charged flag, so - /// the stop's settlement gives nothing back that was not charged. - /// - /// Once revm has prepared the first frame, the state gas the transaction has been charged is - /// all it holds outside its frames: the account a deposit-like transaction creates for its - /// caller, the applied authorities, and the new account EIP-2780 charges the first frame's - /// start for. The first two stand whatever the first frame does, and are held to the - /// state-gas limit here: a crossing latches the transaction, and the frame is answered with the - /// stop before it is built. The third is the first frame's upfront charge, held as every - /// frame's is, once revm has decided the frame ([`hold_upfront_state_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> { - if evm.ctx_ref().additional_limit.latched().is_some() { - return Ok(Some(unbuilt_first_frame(evm.ctx_ref(), gas))); - } - let stands = gas.state_gas_spent(); - let frame = self.op.first_frame_input(evm, gas)?; - let spent = gas.state_gas_spent(); - evm.ctx_mut().additional_limit.on_state_gas_before_frames(stands, spent); + 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(frame) + Ok(Some(frame)) } - /// 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. + /// 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. @@ -357,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, @@ -416,53 +444,46 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = self.answered_before_building(&frame_init)? { + if let Some(result) = self.answered_before_building(&frame_init) { return Ok(ItemOrResult::Result(result)); } let keyless = keyless::is_dispatched(&self.inner.ctx, &frame_init); @@ -475,7 +496,6 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm { ctx.additional_limit.set_frame_address(address); - hold_upfront_state_gas(ctx, None); if keyless { ctx.keyless_frame = Some(keyless::KeylessFrame::Built); } @@ -532,18 +553,21 @@ impl EvmTr for MegaEvm 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 it has a stop to return: the latched one, or - /// its own when a failed creation put it over its budget. Then the frame returns the stop - /// without running another instruction (see [`before_frame_run`]). A `keylessDeploy` call's + /// 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 @@ -566,16 +590,6 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - let refund = self.inner.ctx.additional_limit.on_frame_return(&mut 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 @@ -658,11 +671,11 @@ 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, and its - /// answer settles as a frame that never started ([`answered_without_running`]). + /// answer settles as a frame that never started ([`answered_by_inspector`]). /// - /// A frame nothing may start — a latched transaction's, 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 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 @@ -676,9 +689,12 @@ where // 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) { - return answered_by_inspector(ctx, inspector, &frame_init, output) - .map(ItemOrResult::Result); + 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 @@ -702,10 +718,12 @@ where } } let source = ResultSource::Engine(start); - frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source); + 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); } @@ -741,7 +759,8 @@ where after_frame_run(ctx, frame, &mut next); if let Ok(ItemOrResult::Result(result)) = &mut next { let source = ResultSource::Engine(frame.checkpoint); - frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source); + 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 @@ -753,9 +772,9 @@ where /// 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. Under a latch, the child that crossed the limit reverted, and its caller must not -/// resume. Without one, the child was a failed creation whose nonce record put its creator over -/// its budget, and the creator reverts alone. +/// 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. /// /// 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 @@ -770,14 +789,13 @@ fn before_frame_run( let stop = ctx.additional_limit.stop_before_run()?; Some(InterpreterAction::new_return( InstructionResult::Revert, - stop.revert_data(), + ctx.additional_limit.note_frame_stop(&stop), frame.interpreter.gas, )) } /// 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, and its state gas on its lane for the -/// child's to hold outside it; a frame that returns is classified. +/// 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 @@ -786,8 +804,9 @@ fn before_frame_run( /// 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 transaction-level stop -/// ([`stop_at_the_compute_limit`]). Every other out-of-gas halts, as it would without the read. +/// 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, @@ -797,7 +816,6 @@ fn after_frame_run( match next { Ok(ItemOrResult::Item(_)) => { ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); - ctx.additional_limit.on_frame_suspend(frame.interpreter.gas.state_gas_spent()); } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); @@ -949,10 +967,11 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { } } -/// Turns a frame that crossed gas detention's compute limit into the transaction-level stop: a -/// revert carrying `MegaLimitExceeded` (kind: compute), with the transaction latched, so no caller -/// resumes. The frame's gas is what it had before the charge that crossed, which goes back with -/// the revert, to the caller and in the end to the sender. +/// 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. @@ -961,16 +980,9 @@ fn stop_at_the_compute_limit( result: &mut InterpreterResult, stop: ComputeStop, ) { - let stop = ctx.additional_limit.latch(LimitKind::ComputeGas, stop.limit, stop.used); + let stop = ctx.additional_limit.crossed(LimitKind::ComputeGas, stop.limit, stop.used, false); result.result = InstructionResult::Revert; - result.output = stop.revert_data(); -} - -/// 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()) + result.output = ctx.additional_limit.note_frame_stop(&stop); } impl MegaEvm { @@ -999,69 +1011,28 @@ impl MegaEvm { crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth, caller_remaining) } - /// Steps 1 and 2 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may - /// start ([`answer_before_building`]), with the empty lane that stands in for it. It comes - /// before the keyless dispatch, so the dispatch never sees a latched transaction; on the - /// inspected path it comes after the inspector's `frame_start`. + /// 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, - ) -> Result, ContextDbError>> { - let answer = answer_before_building(&mut self.inner.ctx, 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(); } - Ok(answer) + answer } } -/// Holds the state gas the caller was charged upfront for the frame that is starting — the new -/// account a value `CALL` adds, a creation's account, or, for the transaction's own frame, the -/// recipient or created account EIP-2780 charges the transaction for — to the state-gas limit, -/// once revm has decided the frame. `answer` is the frame's result when it was answered without -/// running; a frame revm built has none yet. -/// -/// revm's `CALL`, `CREATE` and `CREATE2`, and its EIP-2780 phase for the first frame, make that -/// charge before anything knows whether the frame can start, and a frame that adds no account -/// gives it back when its answer returns ([`FrameResult::refundable_state_gas_charge`]): a value -/// call its caller cannot fund, a call past the call-stack limit, an answer that fails. Such a -/// charge is never held. A charge that stands — the frame is built, or answered with a success, as -/// a value call to an account with no code is — is held, and a crossing latches the transaction: a -/// built frame returns the stop before its first instruction, and an answer is rewritten to it -/// here, so an inspector sees the answer the caller gets. The writes the frame's start made go with -/// the frames the stop reverts; an answer of the transaction's own frame, which no frame's revert -/// follows, is taken back by its start ([`take_back_a_stopped_answer`]). A built frame that later -/// fails gives the charge back too, but by then it has started, and a crossing inside a frame that -/// later fails is a crossing. -/// -/// The frame's own lane is on top by now, and holds outside it what its caller held, the charge -/// included; the frame itself holds nothing yet. Every other charge was held where it was made, so -/// only the upfront one can cross here. -fn hold_upfront_state_gas( - ctx: &mut MegaContext, - answer: Option<&mut FrameResult>, -) { - let Some(answer) = answer else { - ctx.additional_limit.check_state_gas(0); - return; - }; - if answer.refundable_state_gas_charge().is_none() && - ctx.additional_limit.check_state_gas(0).exceeded_limit() - { - ctx.additional_limit.apply_latch(answer); - } -} - -/// Takes the journal back to `start`, where the transaction's own frame began, when revm answered -/// that frame with a success (`succeeded`) that the engine then rewrote into `result`, the stop. +/// 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. Below the transaction's own frame the stop -/// reverts every caller, and the caller's checkpoint takes the answer's writes back with its own; -/// the transaction's own frame has no caller, so its answer's writes are taken back here, as revm -/// takes back a frame that fails. The journal's depth is left as it is. +/// 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, start: JournalCheckpoint, @@ -1073,65 +1044,39 @@ fn take_back_a_stopped_answer( } } -/// Settles `output`, the answer the inspector gave the frame `frame_init` starts in its place. -/// 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. -fn answered_by_inspector( - ctx: &mut MegaContext, - inspector: &mut INSP, - frame_init: &FrameInit, - mut output: FrameResult, -) -> Result>> -where - INSP: Inspector, EthInterpreter>, -{ - if let Some(answer) = answer_before_building(ctx, frame_init)? { - output = answer; - } - Ok(answered_without_running(ctx, inspector, frame_init, output)) -} - /// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as -/// [`EvmTr::frame_init`] settles an answer: 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`]). That charge never stands, so it is not held to the -/// state-gas limit. -fn answered_without_running( +/// [`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, - mut output: FrameResult, + 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); + frame_end_checked(ctx, inspector, input, &mut output, depth, ResultSource::Inspector, upfront); 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)) -} - -/// Answers a frame a limit stops before it is built with the stop. +/// 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, @@ -1140,7 +1085,8 @@ 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 frame past the call-stack limit, of any call scheme or a creation, answered @@ -1236,42 +1182,6 @@ fn inspect_logs( } } -/// The first frame of a latched transaction: the transaction's call or creation on the gas it -/// has left, for the frame the latch answers with the stop. -/// -/// Nothing is loaded and nothing is charged. The frame is never built, so its code is never read. -fn unbuilt_first_frame( - ctx: &MegaContext, - gas: &GasTracker, -) -> FrameInit { - let tx = ctx.tx(); - let frame_input = match tx.kind() { - TxKind::Call(target_address) => FrameInput::Call(Box::new(CallInputs { - input: CallInput::Bytes(tx.input().clone()), - return_memory_offset: 0..0, - gas_limit: gas.remaining(), - reservoir: gas.reservoir(), - bytecode_address: target_address, - known_bytecode: Default::default(), - target_address, - caller: tx.caller(), - value: CallValue::Transfer(tx.value()), - scheme: CallScheme::Call, - is_static: false, - charged_new_account_state_gas: false, - })), - TxKind::Create => FrameInput::Create(Box::new(CreateInputs::new( - tx.caller(), - CreateScheme::Create, - tx.value(), - tx.input().clone(), - gas.remaining(), - gas.reservoir(), - ))), - }; - FrameInit { depth: 0, memory: SharedMemory::new(), frame_input } -} - /// 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. @@ -1281,8 +1191,8 @@ fn unbuilt_first_frame( /// 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 { @@ -1290,7 +1200,7 @@ fn deposit_creates_caller( 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 @@ -1383,20 +1293,15 @@ fn caller_refuses( } /// 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. -/// -/// `state_gas` is what the transaction has been charged before its first frame, the authorities' -/// new accounts and delegations included, which the state-gas limit holds before the records are -/// counted. +/// `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, - state_gas: i64, -) -> AppliedAuthorities { +) -> u64 { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return AppliedAuthorities { check: LimitCheck::WithinLimit, applied: 0 }; + return 0; } let caller = ctx.tx().caller(); let target = ctx.tx().kind().to().copied(); @@ -1412,27 +1317,12 @@ fn record_applied_authorities( let target_is_authority = target.is_some_and(|target| authorities.binary_search(&target).is_ok()); let applied = authorities.len() as u64; - let check = ctx.additional_limit.record_applied_authorities( - caller, - applied, - target_is_authority, - state_gas, - ); - if check.exceeded_limit() { - return AppliedAuthorities { check, applied: 0 }; - } + 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); } - AppliedAuthorities { check, applied } -} - -/// What [`record_applied_authorities`] found: the verdict of the limit check, and how many -/// authorities were applied — none, when the check stopped them. -struct AppliedAuthorities { - check: LimitCheck, - applied: u64, + applied } /// Charges the history of the write records a transaction makes outside any frame: one per @@ -1440,7 +1330,8 @@ struct AppliedAuthorities { /// 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. A first +/// 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 @@ -1470,56 +1361,49 @@ fn charge_records_made_outside_a_frame( ctx.additional_limit.stage_start_refused(refused); !refused }; - let Some(top_level) = write_record_history_gas(u64::from(top_level_record)) else { - return false; - }; - let Some(authorities) = write_record_history_gas(applied_authorities) else { return false }; - let Some(cost) = top_level.checked_add(authorities) else { return false }; - if !gas.record_history_cost(cost) { - 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)); true } #[cfg(test)] mod tests { use super::*; - use crate::{ - test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaLimitExceeded, MegaSpecId, - }; + use crate::{test_utils::MemoryDatabase, MegaSpecId}; use alloy_primitives::{address, U256}; - use alloy_sol_types::SolError; - use revm::interpreter::gas::WithheldCrossing; + 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` from `caller` to `target` of `value` wei, which its opcode charged a new account - /// for when `charged`. - fn call(caller: Address, target: Address, value: u64, charged: bool) -> FrameInput { + /// 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, + bytecode_address: TARGET, known_bytecode: Default::default(), - target_address: target, - caller, - value: CallValue::Transfer(U256::from(value)), + target_address: TARGET, + caller: CALLER, + value: CallValue::Transfer(U256::from(1)), scheme: CallScheme::Call, is_static: false, - charged_new_account_state_gas: charged, + charged_new_account_state_gas: true, })) } - /// A `CALL` of one wei to `TARGET`, which its opcode charged a new account for. - fn value_call() -> FrameInput { - call(CALLER, TARGET, 1, 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); @@ -1528,18 +1412,6 @@ mod tests { FrameInput::Create(Box::new(inputs)) } - /// A context under a state-gas limit of 99, with the transaction's own frame on the call stack - /// holding 100 — the upfront charge of the frame it starts — and the lane of that frame - /// pushed. - fn starting_a_frame_charged_100() -> MegaContext { - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(99)); - let _ = ctx.additional_limit.on_frame_init(&call(CALLER, CALLER, 0, false), 0); - ctx.additional_limit.on_frame_suspend(100); - ctx.additional_limit.push_empty_frame(); - ctx - } - /// 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 { @@ -1746,19 +1618,25 @@ mod tests { } } - /// A frame revm refuses — past the call-stack limit, which no transaction reaches under the - /// execution cap — gives its caller's upfront charge back, so the charge is not held, for a - /// call and a creation alike; the answer stays what it was. + /// 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_refused_frame_is_not_held_for_its_upfront_charge() { - for input in [value_call(), creation()] { - let mut ctx = starting_a_frame_charged_100(); - let mut refused = - synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); - assert!(refused.refundable_state_gas_charge().is_some(), "{input:?}"); - hold_upfront_state_gas(&mut ctx, Some(&mut refused)); - assert_eq!(ctx.additional_limit.latched(), None, "{input:?}"); - assert_eq!(refused.instruction_result(), InstructionResult::CallTooDeep); + 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}"); } } @@ -1832,30 +1710,4 @@ mod tests { let answered = synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); assert_start_as_counted(&ctx, (false, false, 0), Some(&answered)); } - - /// A charge that stands is held: a frame revm built latches the transaction, and a success - /// answer carrying the charge latches it and is rewritten to the stop. - #[test] - fn test_a_charge_that_stands_is_held() { - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::StateGrowth, - limit: 99, - used: 100, - frame_local: false, - }; - let mut ctx = starting_a_frame_charged_100(); - hold_upfront_state_gas(&mut ctx, None); - assert_eq!(ctx.additional_limit.latched(), Some(&stop), "a built frame"); - - let mut ctx = starting_a_frame_charged_100(); - let mut answered = - synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); - hold_upfront_state_gas(&mut ctx, Some(&mut answered)); - assert_eq!(ctx.additional_limit.latched(), Some(&stop), "a success answer"); - assert_eq!(answered.instruction_result(), InstructionResult::Revert); - assert_eq!( - answered.interpreter_result().output, - Bytes::from(MegaLimitExceeded { kind: 3, limit: 99 }.abi_encode()), - ); - } } diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 8530a56bd..32b7a45d9 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -1,11 +1,6 @@ //! Factory of Satin EVMs for alloy-evm consumers. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::sync::Arc; - use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; -use alloy_primitives::BlockTimestamp; use core::fmt; use op_revm::OpHaltReason; use revm::{ @@ -15,64 +10,31 @@ use revm::{ }; use crate::{ - DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, - HardforkParams, MegaContext, MegaEvm, MegaHardforks, MegaSpecId, MegaTransaction, - MegaTransactionError, ProtocolLimits, + DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, MegaContext, + MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionError, ProtocolLimits, }; -/// Reads the limits a chain's schedule carries at a block's timestamp. -type ProtocolLimitsResolver = Arc Option + Send + Sync>; - -/// Where the EVMs a factory creates take their per-transaction limits from. -#[derive(Clone, Default)] -enum TxRuntimeLimitsSource { - /// The protocol's defaults, [`ProtocolLimits::DEFAULT`]: the factory holds no schedule. - #[default] - ProtocolDefault, - /// The chain's, read from its schedule at the block's timestamp. - Schedule(ProtocolLimitsResolver), - /// The caller's, whatever the block. - Fixed(EvmTxRuntimeLimits), -} - -impl fmt::Debug for TxRuntimeLimitsSource { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ProtocolDefault => f.write_str("ProtocolDefault"), - Self::Schedule(_) => f.write_str("Schedule"), - Self::Fixed(limits) => f.debug_tuple("Fixed").field(limits).finish(), - } - } -} - /// 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, the optional builder of the dynamic precompiles a node -/// adds on top of the Satin set, and where the EVMs take their per-transaction limits from. +/// 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 the limits block execution would hold its block's -/// transactions to, so an RPC call, a simulation or a tool built on the factory stops what the -/// chain stops without having to be told: -/// -/// - given the chain's schedule ([`with_schedule`](Self::with_schedule)), the limits the schedule -/// carries at the block's timestamp ([`MegaHardforks::protocol_limits`]); -/// - without one, the protocol's defaults ([`ProtocolLimits::DEFAULT`]), which is what block -/// execution runs on a chain that keeps them; -/// - where the schedule carries no limits at the timestamp, or limits their own check refuses -/// ([`HardforkParams::validate`]), the protocol's defaults too: block execution refuses such a -/// block, and an EVM cannot refuse to be built. +/// 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 chain's limits on the EVM whatever it was created with. +/// 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, - tx_runtime_limits: TxRuntimeLimitsSource, + /// 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 { @@ -86,13 +48,13 @@ impl fmt::Debug for MegaEvmFactory { } impl MegaEvmFactory { - /// Creates a factory whose EVMs have no external environments and run under the protocol's - /// default limits. + /// 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, - tx_runtime_limits: TxRuntimeLimitsSource::ProtocolDefault, + tx_runtime_limits: None, } } } @@ -122,44 +84,18 @@ impl MegaEvmFactory { self } - /// Gives the factory the chain's schedule: every EVM it creates runs under the limits the - /// schedule carries at the block's timestamp, as block execution holds that block's - /// transactions to them. It replaces limits set with - /// [`with_tx_runtime_limits`](Self::with_tx_runtime_limits). - /// - /// A node hands it the schedule it hands its block executor factory, so the EVMs it builds - /// outside block execution — an RPC call, a simulation — stop what the chain stops. A schedule - /// held in an `Arc` is handed over as a clone of the `Arc`: [`MegaHardforks`] holds for an - /// `Arc` or a `Box` of a schedule. - pub fn with_schedule(mut self, spec: Spec) -> Self - where - Spec: MegaHardforks + Send + Sync + 'static, - { - self.tx_runtime_limits = TxRuntimeLimitsSource::Schedule(Arc::new(move |timestamp| { - spec.protocol_limits(timestamp) - })); - self - } - - /// Runs every EVM the factory creates under exactly `limits`, whatever the block and whatever - /// the chain's schedule says: the explicit opt-out, for the execution-spec gate's equivalence - /// mode ([`EvmTxRuntimeLimits::no_limits`]) and for tests. It replaces a schedule given with - /// [`with_schedule`](Self::with_schedule). + /// 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 = TxRuntimeLimitsSource::Fixed(limits); + self.tx_runtime_limits = Some(limits); self } - /// The limits an EVM the factory creates for a block at `timestamp` runs under. - pub fn tx_runtime_limits(&self, timestamp: BlockTimestamp) -> EvmTxRuntimeLimits { - let protocol_default = ProtocolLimits::DEFAULT.tx_runtime_limits; - match &self.tx_runtime_limits { - TxRuntimeLimitsSource::ProtocolDefault => protocol_default, - TxRuntimeLimitsSource::Schedule(resolve) => resolve(timestamp) - .filter(|limits| limits.validate().is_ok()) - .map_or(protocol_default, |limits| limits.tx_runtime_limits), - TxRuntimeLimitsSource::Fixed(limits) => *limits, - } + /// 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) } } @@ -176,7 +112,7 @@ impl alloy_evm::EvmFactory for MegaEvmFactory type Precompiles = PrecompilesMap; /// Creates an EVM for the block in `evm_env`, with the external environments of that block, - /// running under the limits the factory resolves for the block's timestamp + /// 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 @@ -189,8 +125,8 @@ 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 limits = self.tx_runtime_limits(block_env.timestamp.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) @@ -222,7 +158,7 @@ mod tests { use crate::{ satin_precompiles, test_utils::{op_transaction, MemoryDatabase}, - ExternalEnvs, MegaHardforkConfig, SaltEnv, TestExternalEnvs, + ExternalEnvs, SaltEnv, TestExternalEnvs, }; use alloy_evm::{precompiles::DynPrecompile, Evm, EvmFactory}; use alloy_op_evm::OpTx; @@ -232,7 +168,7 @@ mod tests { sync::atomic::{AtomicUsize, Ordering}, }; use revm::{ - context::{CfgEnv, TxEnv}, + context::{CfgEnv, ContextTr, TxEnv}, precompile::{PrecompileId, PrecompileOutput}, primitives::HashMap, }; @@ -247,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 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 + }; - let evm = MegaEvmFactory::new() - .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env, block_env }); + evm.transact_raw(on_chain(call(CUSTOM))).unwrap(); + assert_eq!(runs_with(&evm), (exported.clone(), op_view.clone())); - 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)); + 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", + ); + + 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. @@ -311,133 +287,55 @@ mod tests { } /// The factory prints its external environment factory, whether a precompile builder is - /// installed and where its EVMs take their limits from. A closure has no `Debug`, so the - /// builder and the schedule are reported by name rather than dropped: a reader of a node's log - /// can tell the configurations apart. + /// 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_the_factorys_configuration() { let factory = MegaEvmFactory::new(); assert_eq!( format!("{factory:?}"), "MegaEvmFactory { external_env_factory: EmptyExternalEnv, \ - dyn_precompiles_builder: false, tx_runtime_limits: ProtocolDefault }" + 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, tx_runtime_limits: ProtocolDefault }" + dyn_precompiles_builder: true, tx_runtime_limits: None }" ); - let on_schedule = with_builder.with_schedule(MegaHardforkConfig::default()); - assert!(format!("{on_schedule:?}").ends_with("tx_runtime_limits: Schedule }")); - let fixed = on_schedule.with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - assert!(format!("{fixed:?}").contains("tx_runtime_limits: Fixed(EvmTxRuntimeLimits {")); + let fixed = with_builder.with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + assert!(format!("{fixed:?}").contains("tx_runtime_limits: Some(EvmTxRuntimeLimits {")); } - /// A timestamp from which a chain's schedule activates Satin in these tests. - const SATIN_AT: u64 = 1_000; - - /// A chain that activates Satin at [`SATIN_AT`] and holds its transactions to `limits`, - /// attached unchecked so a test may hand it limits no chain may carry. - fn chain(limits: ProtocolLimits) -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(crate::MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(SATIN_AT)) - .with_params_unchecked(limits) - } - - /// A chain's own limits, which no default carries. - fn chain_limits() -> ProtocolLimits { - ProtocolLimits::DEFAULT.with_tx_runtime_limits( - ProtocolLimits::DEFAULT - .tx_runtime_limits - .with_tx_data_size_limit(crate::TX_BODY_SIZE + 40) - .with_tx_kv_update_limit(7), - ) - } - - /// An EVM the factory creates for a block at `timestamp`. - fn evm_at(factory: &MegaEvmFactory, timestamp: u64) -> MegaEvm { - let block_env = BlockEnv { timestamp: U256::from(timestamp), ..evm_env().block_env }; - factory - .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env: evm_env().cfg_env, block_env }) - } - - /// Without a schedule the factory's EVMs run under the protocol's default limits, which is - /// what block execution runs on a chain that keeps them — not a bare context's, which leave - /// the data size unlimited. - #[test] - fn test_without_a_schedule_an_evm_runs_under_the_protocols_defaults() { - let evm = evm_at(&MegaEvmFactory::new(), SATIN_AT); - assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); - assert_ne!(*evm.tx_runtime_limits(), EvmTxRuntimeLimits::default()); - } - - /// A schedule shared behind an `Arc`, as a node holds its chain spec, is handed over as a - /// clone of the `Arc`, and resolves the limits the schedule it points to carries. - #[test] - fn test_a_schedule_behind_an_arc_is_a_schedule() { - let shared = Arc::new(chain(chain_limits())); - let factory = MegaEvmFactory::new().with_schedule(Arc::clone(&shared)); - assert_eq!(factory.tx_runtime_limits(SATIN_AT), chain_limits().tx_runtime_limits); - assert_eq!( - factory.tx_runtime_limits(SATIN_AT), - shared.protocol_limits(SATIN_AT).unwrap().tx_runtime_limits - ); - } - - /// Given the chain's schedule, the factory's EVMs run under the limits it carries at the - /// block's timestamp; where it carries none, or limits their own check refuses — both of which - /// block execution refuses — under the protocol's defaults. + /// 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_the_limits_the_schedule_carries_at_its_block() { - let factory = MegaEvmFactory::new().with_schedule(chain(chain_limits())); - assert_eq!( - *evm_at(&factory, SATIN_AT).tx_runtime_limits(), - chain_limits().tx_runtime_limits - ); - assert_eq!(factory.tx_runtime_limits(SATIN_AT + 1), chain_limits().tx_runtime_limits); - assert_eq!( - factory.tx_runtime_limits(SATIN_AT - 1), - ProtocolLimits::DEFAULT.tx_runtime_limits, - "before Satin the schedule carries no limits" - ); - - let refused = MegaEvmFactory::new().with_schedule(chain(ProtocolLimits::no_limits())); - assert_eq!( - *evm_at(&refused, SATIN_AT).tx_runtime_limits(), - ProtocolLimits::DEFAULT.tx_runtime_limits, - "limits their own check refuses run no EVM" - ); + 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, whatever the - /// schedule says; the last of the two settings made is the one that holds. + /// 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_schedules() { - let factory = MegaEvmFactory::new() - .with_schedule(chain(chain_limits())) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - for timestamp in [SATIN_AT - 1, SATIN_AT] { - assert_eq!( - *evm_at(&factory, timestamp).tx_runtime_limits(), - EvmTxRuntimeLimits::no_limits() - ); - } - - let factory = factory.with_schedule(chain(chain_limits())); - assert_eq!( - *evm_at(&factory, SATIN_AT).tx_runtime_limits(), - chain_limits().tx_runtime_limits - ); + 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 - /// chain allows one is stopped on an EVM from a factory given the schedule, and keeps both on - /// one from a factory without it. + /// 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_stops_what_the_chain_stops() { + 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"); @@ -458,13 +356,15 @@ mod tests { .stop() .build(), ); - let block_env = BlockEnv { timestamp: U256::from(SATIN_AT), ..evm_env().block_env }; - let mut evm = factory.create_evm(db, EvmEnv { cfg_env: evm_env().cfg_env, block_env }); + 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 stopped = run(&MegaEvmFactory::new().with_schedule(chain(chain_limits()))); + 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 { @@ -548,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/history.rs b/crates/mega-evm/src/evm/history.rs index 16730b2c7..fbf3be94a 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -16,7 +16,10 @@ //! 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}; +use revm::{ + context::{transaction::AccessListItemTr, Transaction}, + context_interface::cfg::gas::GasTracker, +}; use crate::{ evm::prices::active_satin_prices, @@ -41,11 +44,19 @@ pub fn write_record_history_gas(records: u64) -> Option { history_gas(WRITE_RECORD_SIZE.checked_mul(records)?) } -/// The history bytes a `LOG` with `topics` topics and `data_len` bytes of data appends: its own -/// record for the address that emitted it, one per topic, and the data. +/// 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 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) +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 @@ -113,7 +124,10 @@ pub const fn tx_body_history_bytes( #[cfg(test)] mod tests { use super::*; - use crate::{constants::COST_PER_HISTORY_BYTE, evm::prices::runs_at_measurement_prices}; + 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] @@ -323,4 +337,29 @@ mod tests { ); 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 9650ac6be..cade09497 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -1,4 +1,4 @@ -//! The Host of the Satin engine, and the journal reads that observe without warming. +//! The Host of the Satin engine. //! //! # The Host only observes //! @@ -59,7 +59,6 @@ use alloc as std; use std::format; -use alloy_primitives::map::Entry; use delegate::delegate; use revm::{ context::ContextTr, @@ -69,9 +68,8 @@ use revm::{ host::LoadError, journaled_state::AccountInfoLoad, }, - primitives::{Address, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256}, - state::{Account, EvmStorageSlot}, - Database, Journal, + primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, + Database, }; use crate::{ @@ -309,7 +307,6 @@ impl revm::context_interface::Host } 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, }); @@ -348,6 +345,10 @@ impl MegaContext { /// 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 @@ -355,6 +356,10 @@ impl MegaContext { /// /// 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, key: StorageKey, @@ -370,512 +375,25 @@ impl MegaContext { false, )? .data; - let value = self.external_envs().oracle_env.get_oracle_storage(key).unwrap_or(loaded); + // 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(value, true)) - } -} - -/// 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. Never loads the account's code: a slot read needs only - /// the account and the slot in a witness, not its bytecode. - 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; - self.inspect_account_code_hash(address)?; - let account = self.inner.state.get_mut(&address).expect("inspected above"); - let is_newly_created = account.is_created(); - 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)) - } - } + Ok(StateLoad::new(answer.unwrap_or(loaded), true)) } } #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{address, keccak256, Bytes}; - 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" - ); - } - - /// `inspect_storage` reads the slot without hydrating the account's code, on either branch, - /// so a slot read leaves no bytecode in a stateless witness. - #[test] - fn test_inspect_storage_never_hydrates_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000ee"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - let code_is_loaded = - |journal: &Journal| journal.inner.state[&ADDR].info.code.is_some(); - - journal.inspect_storage(ADDR, U256::from(1)).expect("vacant read must succeed"); - assert!(!code_is_loaded(&journal), "the vacant branch must not hydrate info.code"); - - journal.inspect_storage(ADDR, U256::from(2)).expect("occupied read must succeed"); - assert!(!code_is_loaded(&journal), "the occupied branch must not hydrate info.code"); - assert!(journal.inner.state[&ADDR].is_cold_transaction_id(journal.transaction_id)); - } + 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. @@ -917,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 ad18731c2..88d30da55 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -19,8 +19,8 @@ //! 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 latch -//! writes the stop over its results. +//! 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 @@ -52,20 +52,16 @@ //! //! # What a rewrite does not change //! -//! - **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. A transaction a limit stopped is the exception: -//! once it is latched, every frame's result is the stop whatever produced it, so a revived -//! creation is put back and reports the stop, and the transaction does not fail. A creation -//! stopped by its own frame budget latches nothing, and its revival is refused. //! - **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. +//! 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, @@ -77,10 +73,11 @@ //! 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. -//! - **The latch.** Once a limit stopped the transaction, every frame's result is the stop, -//! whatever produced it: an inspector turns it into neither a success nor a halt. //! -//! Every other rewrite is the tool's business. +//! 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 //! @@ -107,12 +104,8 @@ //! carries. The gas of a result a frame ran to produce is the inspector's to rewrite, reservoir //! included. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{format, string::String}; - 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}, @@ -126,12 +119,6 @@ use revm::{ use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; -/// 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 @@ -461,6 +448,43 @@ fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callbac } } +/// 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 { @@ -475,9 +499,6 @@ pub(crate) enum ResultSource { /// Hands a frame's end to the inspector, then settles what its rewrite does not change. /// -/// - **The refusal.** A creation that failed, rewritten into a success, is put back and fails the -/// transaction with [`FORBIDDEN_CREATE_REVIVAL`] — unless the transaction is latched, where the -/// creation is put back and reports the stop, which the latch writes over every result. /// - **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 @@ -487,12 +508,8 @@ pub(crate) enum ResultSource { /// 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 all three cover 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. The latch is read after the hooks that can set -/// it — the frame's run, detention's classification of its end, the hold on a start's upfront state -/// gas, and the answer before building — have run, so a creation the latch stopped is never -/// refused. +/// 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, @@ -501,6 +518,7 @@ pub(crate) fn frame_end_checked( frame_result: &mut FrameResult, depth: usize, source: ResultSource, + upfront: Option, ) where DB: Database, ExtEnvs: ExternalEnvTypes, @@ -509,7 +527,15 @@ pub(crate) fn frame_end_checked( { 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) => { @@ -554,9 +580,6 @@ pub(crate) fn frame_end_checked( /// 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. -/// -/// A latched transaction is left to the latch, which writes the stop over every result, and the -/// stop settles as a revert. fn settle_kept_nothing( context: &mut MegaContext, input: &FrameInput, @@ -565,8 +588,7 @@ fn settle_kept_nothing( answered: bool, ) { carry_upfront_flags(input, result); - let success = - result.instruction_result().is_ok() && context.additional_limit.latched().is_none(); + let success = result.instruction_result().is_ok(); let gas = result.gas_mut(); if answered || success { gas.rollback_state_gas(); @@ -646,21 +668,3 @@ fn upfront_charge(input: &FrameInput) -> Option { synthetic_frame_result(input, InstructionResult::Revert, Bytes::new()) .refundable_state_gas_charge() } - -/// Puts a revived creation back to `before` and, unless the transaction is latched, records the -/// refusal as the context's error. -fn refuse_create_revival( - context: &mut MegaContext, - 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.additional_limit.latched().is_none() && 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 70ef77887..7494f5e2c 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -10,8 +10,7 @@ //! 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, hold the state gas it charged to -//! the state-gas limit, then commit the record; +//! 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. //! @@ -19,9 +18,9 @@ //! 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 state charge or 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 history charge the frame +//! 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 @@ -31,10 +30,7 @@ //! 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 state gas revm's -//! instruction charged for the account the frame would add is held to the state-gas limit later, -//! once revm has decided the frame: revm refuses some frames after the charge — a value call its -//! caller cannot fund, one past the call-stack limit — and gives the charge back. +//! 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 @@ -57,8 +53,8 @@ //! 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 revm's table charges for its opcode, so the gas schedule is -//! unchanged. +//! 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. @@ -77,22 +73,22 @@ use revm::{ handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{arithmetic, block_info, contract, gas_table_spec, host, memory, system}, + instructions::{arithmetic, block_info, contract, host, memory, system}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, InterpreterAction, }, - primitives::hardfork::SpecId, + primitives::{hardfork::SpecId, Bytes}, Database, }; use crate::{ - history_gas, limit::HistoryBytes, volatile_data_access_disabled_revert_data, - write_record_history_gas, ExternalEnvTypes, LimitCheck, MegaContext, VolatileDataAccess, + charge_write_records_history, history_gas, limit::HistoryBytes, + volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -use super::{caller_refuses_start, 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>; @@ -102,13 +98,13 @@ type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecRes /// 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. +/// 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 mut instructions = EthInstructions::new(table, satin_gas_table(), spec); let wrappers: [(u8, InstructionFn); 34] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), @@ -159,19 +155,17 @@ pub(crate) fn mega_instructions( /// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the /// staged write back with it. /// -/// The state gas the opcode charged is held to the state-gas limit first — `SSTORE` charges a -/// fresh slot's and `SELFDESTRUCT` a new beneficiary's inside revm's instruction — and a crossing -/// stops the frame and discards the record with the write. Then the record is held to the -/// data-size and KV limits, and only then is its history charged. A record a limit rejects is not -/// kept, so its history is not a charge and the stop is what the frame reports. A record the -/// limits accept is charged, and a charge the frame cannot pay is an out-of-gas. +/// 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_stale_record(); + host.additional_limit.discard_staged_record(); let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); let completed = match result { Ok(()) => true, @@ -181,14 +175,9 @@ fn commit_after(interpreter, host, history); @@ -236,25 +225,18 @@ fn settle_history, - 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 } @@ -304,9 +286,7 @@ fn selfdestruct( /// 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. That charge is held to the state-gas -/// limit when revm has decided the frame, not here: a frame revm refuses gives it back, and a -/// limit that held it would stop the transaction for an account nobody adds. +/// 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`]). @@ -334,16 +314,12 @@ fn charge_frame_start( if !host.prices_history() { return result; } - let (Some(on_lane), Some(caller)) = ( - write_record_history_gas(records.on_lane), - write_record_history_gas(u64::from(records.caller)), - ) else { - return abandon_frame(interpreter, host); - }; - let Some(cost) = on_lane.checked_add(caller) else { return abandon_frame(interpreter, host) }; - if !interpreter.gas.record_history_cost(cost) { - return abandon_frame(interpreter, host); - } + 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 @@ -534,11 +510,11 @@ fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { } } -/// Defines an opcode that reads a block-environment field, as revm's instruction in -/// [`read_volatile`]. -macro_rules! block_env_read { - ($($name:ident => $inner:path, $opcode:literal;)*) => {$( - #[doc = concat!("`", $opcode, "`, committing the read of the field.")] +/// 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 { @@ -547,15 +523,21 @@ macro_rules! block_env_read { )*}; } -block_env_read! { - coinbase => block_info::coinbase, "COINBASE"; - timestamp => block_info::timestamp, "TIMESTAMP"; - number => block_info::block_number, "NUMBER"; - difficulty => block_info::difficulty, "PREVRANDAO"; - gaslimit => block_info::gaslimit, "GASLIMIT"; - basefee => block_info::basefee, "BASEFEE"; - blobbasefee => block_info::blob_basefee, "BLOBBASEFEE"; - slotnum => block_info::slot_num_enabled, "SLOTNUM"; +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. @@ -572,28 +554,6 @@ fn blockhash( }) } -/// Defines an opcode that loads an account or a slot, as revm's instruction in -/// [`read_volatile`]. -macro_rules! state_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) - } - )*}; -} - -state_read! { - 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"; -} - /// 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. @@ -625,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 2259f5265..8893e7efc 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -19,13 +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 history::*; -pub use host::*; pub use inspector::*; pub use precompiles::*; pub use prices::*; @@ -33,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}, @@ -62,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 = @@ -207,12 +208,11 @@ impl MegaEvm { /// Enforces `limits` on every transaction this EVM runs from now on. /// - /// Block execution installs the chain's limits this way before every transaction - /// ([`ProtocolLimits`](crate::ProtocolLimits)), so a block's transaction runs under them - /// whatever the caller configured on the EVM. An EVM from - /// [`MegaEvmFactory`](crate::MegaEvmFactory) already runs under the limits the factory - /// resolved for its block; outside block execution — an RPC call, a tool, a test — this is how - /// a caller chooses others. + /// 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); @@ -254,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 @@ -263,8 +290,9 @@ 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, @@ -280,17 +308,11 @@ where 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, @@ -370,30 +392,18 @@ where { } -/// The transaction a system call runs, on the gas limit its caller names. -trait SystemCallTxWithGasLimit: SystemCallTx { - /// 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 new_system_tx_with_gas_limit( - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, - ) -> Self; -} - -impl SystemCallTxWithGasLimit for MegaTransaction { - fn new_system_tx_with_gas_limit( - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, - ) -> Self { - let mut tx = Self::new_system_tx_with_caller(caller, contract, data); - tx.0.base.gas_limit = gas_limit; - tx - } +/// 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 { @@ -430,7 +440,7 @@ impl MegaEvm { data: Bytes, gas_limit: u64, ) -> Result, EVMError> { - let tx = MegaTransaction::new_system_tx_with_gas_limit(caller, contract, data, gas_limit); + 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))) } diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index cc263a133..1ebe4fddb 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -392,29 +392,55 @@ 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, Bytes::from(std::vec![0u8; KARST_MAX_INPUT_SIZE + 1]), 50_000_000); - assert_eq!(over.result, InstructionResult::PrecompileError); + let over = run(address, pairs(301), 50_000_000); + assert_eq!(over.result, InstructionResult::PrecompileError, "a whole pair past the bound"); } /// 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() { - assert!(precompile.required_gas(&[]).is_some(), "{:?} is priced", precompile.id()); + 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() + ); + } + } } } diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index cfdac2d5c..b3873f90d 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -24,9 +24,13 @@ //! 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. @@ -41,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 { @@ -126,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() @@ -176,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)); @@ -189,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 2e894a781..793908eac 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -1,83 +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. //! -//! The one entry outside Amsterdam's table is the history price of deposited code -//! ([`HISTORY_GAS_PRICED`]): 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. -//! -//! 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 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); @@ -132,14 +93,18 @@ pub fn satin_gas_params_history_exempt() -> GasParams { .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))), ); @@ -167,89 +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. - #[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 + /// 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_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), @@ -261,7 +162,59 @@ 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"); + } + } + + /// 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_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"); } } 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/gas.rs b/crates/mega-evm/src/external/gas.rs index 9c85e62ff..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}; @@ -94,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. @@ -147,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"); @@ -163,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. @@ -196,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 @@ -224,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 @@ -243,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 @@ -274,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 feebdf38e..f1c7505e0 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -34,7 +34,7 @@ pub trait OracleEnv: Debug + Unpin { /// 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 the transaction at the compute limit. + /// 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 f2c63c0e7..28f859579 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -27,12 +27,60 @@ pub mod system; pub mod test_utils; mod types; -pub use access::*; -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; @@ -44,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 d7545c673..6c6d19214 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -10,19 +10,6 @@ //! 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. //! -//! The lanes also carry what the state-gas limit counts: the state gas the transaction holds. -//! EIP-8037 charges state gas for exactly the state a transaction adds — a fresh slot, a new -//! account, the bytes of deployed code, a delegation — at the state's own price, scaled by the -//! SALT bucket it lands in. So the state a transaction grows is the state gas it spends, and a -//! limit on that gas is the limit on its growth; nothing counts new accounts and slots beside it. -//! revm keeps state gas on each frame's own gas, net of what the frame refilled, and merges a -//! frame's into its caller's when the frame succeeds; a frame that fails rolls its own back. What -//! the transaction holds at any point is therefore what it was charged before its first frame, -//! plus what every frame on the call stack holds. The first part is fixed once the first frame -//! starts, and every frame below the running one is suspended, so each frame's share of the rest -//! is fixed while it runs: each lane keeps what the transaction holds outside its frame, and the -//! running frame adds what it holds itself ([`FrameLimitTracker::state_gas_held`]). -//! //! Every operation is O(1): the totals are cached and kept in step with each change. #[cfg(not(feature = "std"))] @@ -31,7 +18,7 @@ use std::vec::Vec; use alloy_primitives::Address; -use super::{LimitUsage, UNLIMITED, WRITE_RECORD}; +use super::{LimitUsage, WRITE_RECORD}; /// One frame's lane. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -64,9 +51,8 @@ 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 the frame may keep: data-size bytes and write records, each `u64::MAX` where the - /// frame has no budget. - pub(crate) budget: LimitUsage, + /// 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, @@ -74,13 +60,6 @@ pub(crate) struct Lane { /// 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, - /// The state gas the transaction holds outside the frame: what was charged before the first - /// frame, and what each frame below it held when the frame above it started. Set when the - /// lane is pushed ([`FrameLimitTracker::push`]). - pub(crate) state_gas_outside: i64, - /// The state gas the frame held when it last suspended on a child, which that child's lane - /// holds outside it beyond this lane's own. - pub(crate) state_gas_at_suspension: i64, } impl Lane { @@ -89,7 +68,7 @@ impl Lane { pub(crate) const fn new( address: Option
, account_recorded: bool, - budget: LimitUsage, + budget: u64, history_charge: u64, ) -> Self { Self { @@ -105,15 +84,13 @@ impl Lane { budget, stipend_remaining: 0, log_and_code_bytes: 0, - state_gas_outside: 0, - state_gas_at_suspension: 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, UNLIMITED, history_charge) } + Self { records_made: false, ..Self::new(None, false, u64::MAX, history_charge) } } /// The history gas the caller gets back when this frame returns. @@ -146,7 +123,9 @@ impl Lane { /// is at most the share of what the caller had left. pub(crate) const fn hands_caller_unchecked(&self, success: bool) -> bool { if success { - self.net().crossing(self.budget).is_some() + // 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 } @@ -157,9 +136,9 @@ impl Lane { self.used.saturating_sub(self.refund) } - /// What the frame may still keep: the data-size bytes and the write records. - pub(crate) const fn remaining_budget(&self) -> LimitUsage { - self.budget.saturating_sub(self.net()) + /// 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) } } @@ -178,9 +157,6 @@ pub(crate) struct FrameLimitTracker { total_refund: LimitUsage, /// The log and code bytes the outermost frame kept, plus every lane's. log_and_code_bytes: u64, - /// The state gas the transaction was charged before its first frame, which the first frame's - /// lane holds outside it. - state_gas_before_frames: i64, } impl FrameLimitTracker { @@ -192,7 +168,6 @@ impl FrameLimitTracker { self.total_used = LimitUsage::ZERO; self.total_refund = LimitUsage::ZERO; self.log_and_code_bytes = 0; - self.state_gas_before_frames = 0; } /// The number of lanes, which is the number of frames on the call stack. @@ -240,41 +215,13 @@ impl FrameLimitTracker { drawn } - /// Pushes the lane of a frame that starts. It holds outside its frame what its caller's lane - /// holds outside the caller, plus what the caller held when it suspended on this frame; the - /// transaction's own frame holds what was charged before any frame. - pub(crate) fn push(&mut self, mut lane: Lane) { - lane.state_gas_outside = match self.lanes.last() { - Some(caller) => caller.state_gas_outside.saturating_add(caller.state_gas_at_suspension), - None => self.state_gas_before_frames, - }; + /// 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); } - /// Records the state gas the transaction was charged before its first frame. - pub(crate) const fn set_state_gas_before_frames(&mut self, spent: i64) { - self.state_gas_before_frames = spent; - } - - /// Records the state gas `held` by the running frame as it suspends on a child. - pub(crate) fn set_state_gas_at_suspension(&mut self, held: i64) { - if let Some(lane) = self.lanes.last_mut() { - lane.state_gas_at_suspension = held; - } - } - - /// The state gas the transaction holds while the running frame holds `running`; outside any - /// frame, `running` is all of it. - /// - /// A frame can hold less than nothing — it refilled a slot a caller of its filled — but never - /// by more than its callers hold, so the sum is never below zero. - pub(crate) fn state_gas_held(&self, running: i64) -> u64 { - let outside = self.lanes.last().map_or(0, |lane| lane.state_gas_outside); - u64::try_from(outside.saturating_add(running)).unwrap_or_default() - } - /// 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() { @@ -333,12 +280,15 @@ impl FrameLimitTracker { /// /// 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 }; - self.lanes.push(Lane { - state_gas_outside: lane.state_gas_outside, - ..Lane::empty(lane.history_refund(false)) - }); + 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 @@ -437,13 +387,13 @@ mod tests { 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, bytes(7), 0)); + 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, bytes(7)); + assert_eq!(t.current().unwrap().budget, 7); assert!(t.pop(true).is_some()); assert_eq!(t.depth(), 0); assert!(t.current().is_none()); @@ -456,7 +406,7 @@ mod tests { let mut t = FrameLimitTracker::default(); t.record_caller(true, 0); assert_eq!(t.net(), LimitUsage::ZERO); - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + 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); @@ -466,11 +416,11 @@ mod tests { #[test] fn test_record_caller_records_a_caller_once() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); - t.push(Lane::new(None, true, UNLIMITED, 0)); + 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, UNLIMITED, 0)); + 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); @@ -490,19 +440,19 @@ mod tests { assert_eq!(t.net(), bytes(100)); // Frame 1. - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + 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, UNLIMITED, 0)); + 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, UNLIMITED, 0)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(11)); t.refund(bytes(2)); let before_revert = t.net(); @@ -512,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, UNLIMITED, 0)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(6)); t.refund(bytes(1)); let before_success = t.net(); @@ -541,9 +491,9 @@ mod tests { 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, UNLIMITED, 0)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); t.record_log_and_code_bytes(10); - t.push(Lane::new(None, false, UNLIMITED, 0)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record_log_and_code_bytes(100); assert_eq!(t.log_and_code_bytes(), 115); @@ -551,7 +501,7 @@ mod tests { 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, UNLIMITED, 0)); + 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); @@ -564,7 +514,7 @@ mod tests { 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, UNLIMITED, 0)); + 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"); @@ -573,48 +523,11 @@ mod tests { assert_eq!(t.log_and_code_bytes(), 0); } - /// Each lane holds outside its frame the state gas charged before the first frame and what - /// each caller held when it suspended on the frame above it. A frame that returned leaves its - /// caller where it was, a caller that suspends again hands its next child what it holds then, - /// and a lane discarded before its frame returns keeps what its frame held outside it. - #[test] - fn test_each_lane_holds_what_its_callers_held_when_it_started() { - let mut t = FrameLimitTracker::default(); - assert_eq!(t.state_gas_held(7), 7, "outside any frame, what is charged is all of it"); - - t.set_state_gas_before_frames(100); - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); - assert_eq!(t.state_gas_held(0), 100, "the first frame starts on what was charged before"); - assert_eq!(t.state_gas_held(20), 120); - - t.set_state_gas_at_suspension(20); - t.push(Lane::new(None, false, UNLIMITED, 0)); - assert_eq!(t.state_gas_held(5), 125, "a child counts its caller's twenty"); - t.set_state_gas_at_suspension(5); - t.push(Lane::empty(0)); - assert_eq!(t.state_gas_held(-5), 120, "a grandchild that refilled its caller's fill"); - assert_eq!(t.depth(), 3); - - t.discard_running_lane(); - assert_eq!(t.state_gas_held(0), 125, "the discarded lane keeps what it holds outside"); - t.pop(false); - t.pop(true); - assert_eq!(t.state_gas_held(30), 130, "the first frame, holding its child's merged gas"); - - t.set_state_gas_at_suspension(30); - t.push(Lane::new(None, false, UNLIMITED, 0)); - assert_eq!(t.state_gas_held(0), 130, "the next child starts on what its caller holds now"); - - t.reset(); - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); - assert_eq!(t.state_gas_held(0), 0, "a reset forgets what was charged before the frames"); - } - /// 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, UNLIMITED, 0)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(10)); t.refund(bytes(100)); assert_eq!(t.net(), LimitUsage::ZERO); @@ -629,16 +542,16 @@ 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, UNLIMITED, 0)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, UNLIMITED, 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, UNLIMITED, 0)); + t.push(Lane::new(None, true, u64::MAX, 0)); t.record_caller(true, 0); t.record(WRITE_RECORD); t.pop(false); @@ -653,7 +566,7 @@ mod tests { /// nothing. #[test] fn test_what_a_return_hands_its_caller_unchecked() { - let budget = LimitUsage { data_size: 200, write_records: 10 }; + 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 [ @@ -666,14 +579,14 @@ mod tests { ] { let case = format!("creator {creator}, {counted} bytes, success {success}"); let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, UNLIMITED, 0)); + 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.crossing(budget).is_some(); + let past_budget = handed.exceeds_data_size(budget); if success { assert_eq!(past_budget, unchecked, "{case}: a success hands over what it kept"); } else { @@ -686,15 +599,14 @@ mod tests { /// 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 budget = LimitUsage { data_size: 200, write_records: 10 }; let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, budget, 0)); + 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, UNLIMITED, 0)); + 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"); } @@ -706,9 +618,9 @@ mod tests { #[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, UNLIMITED, 0)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); t.record(bytes(10)); - t.push(Lane::new(None, false, bytes(100), 7)); + t.push(Lane::new(None, false, 100, 7)); t.record_caller(false, 3); t.record(WRITE_RECORD); t.record_log_and_code_bytes(5); @@ -719,7 +631,7 @@ mod tests { assert!(!lane.records_made); assert_eq!(lane.used, LimitUsage::ZERO); assert_eq!(lane.address, None); - assert_eq!(lane.budget, UNLIMITED); + 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); @@ -732,11 +644,13 @@ mod tests { // 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, UNLIMITED, 0)); + 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)); - assert_eq!(t.pop(true).unwrap().history_refund(true), 0); + 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(); @@ -750,9 +664,9 @@ mod tests { 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, UNLIMITED, 0)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); t.record(bytes(7)); - t.push(Lane::new(None, true, UNLIMITED, 0)); + 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)); @@ -769,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, UNLIMITED, 0)); - t.push(Lane::new(Some(ADDR), true, UNLIMITED, 0)); + 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, UNLIMITED, 0)); - t.push(Lane::new(Some(other), false, UNLIMITED, 0)); + 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, UNLIMITED, 0)); + 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, UNLIMITED, 0)); + 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 8b9f1a158..6cc04a504 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -16,34 +16,34 @@ use super::{ 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 state gas the transaction holds outside each frame, the -/// record the Host staged for the running opcode, and where the transaction stands with its -/// limits — within them or latched by one — and whether it is exempt from all of them. +/// 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, which answers an exempt transaction with [`LimitCheck::WithinLimit`] -/// whatever it crossed — a transaction limit or a frame budget, in any dimension — and never -/// latches it. +/// 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)] @@ -51,15 +51,19 @@ pub struct AdditionalLimit { pub(crate) tracker: FrameLimitTracker, staged: Option, limits: EvmTxRuntimeLimits, - /// Where the transaction stands with its limits: within them, or stopped by the - /// transaction-level limit it latched, which is sticky for the transaction. - standing: LimitCheck, /// 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, @@ -84,6 +88,10 @@ pub struct AdditionalLimit { /// 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, @@ -121,9 +129,10 @@ impl AdditionalLimit { pub(crate) fn reset(&mut self) { self.tracker.reset(); self.staged = None; - self.standing = LimitCheck::WithinLimit; 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; @@ -131,6 +140,7 @@ impl AdditionalLimit { 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; @@ -150,14 +160,34 @@ impl AdditionalLimit { self.transfer_logs && moves_value(input) } - /* The latch and the exemption */ + /* The stops and the exemption */ - /// The stop a transaction-level limit latched, if any. - pub const fn latched(&self) -> Option<&LimitCheck> { - match &self.standing { - latched @ LimitCheck::ExceedsLimit { .. } => Some(latched), - LimitCheck::WithinLimit => None, - } + /// 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. @@ -174,83 +204,48 @@ impl AdditionalLimit { self.exempt = true; } - /// 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, and an exempt transaction is not - /// latched at all: the verdict is then [`LimitCheck::WithinLimit`]. - pub fn latch(&mut self, kind: LimitKind, limit: u64, used: u64) -> LimitCheck { - self.crossed(kind, limit, used, false) - } - - /// The verdict on `used` crossing `kind`'s `limit`: a frame budget's stop when `frame_local`, - /// which reverts the running frame alone, and the transaction's latch otherwise. + /// 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, so this is where the exemption applies: an - /// exempt transaction's verdict is [`LimitCheck::WithinLimit`], whatever it crossed. - fn crossed(&mut self, kind: LimitKind, limit: u64, used: u64, frame_local: bool) -> LimitCheck { + /// 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; } - let crossed = LimitCheck::ExceedsLimit { kind, limit, used, frame_local }; - if frame_local { - return crossed; - } - if !self.standing.exceeded_limit() { - self.standing = crossed; - } - self.standing + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Checks the limits after the running frame counted something: what the transaction keeps - /// against its limits (latching on a crossing), then what the running frame keeps against its - /// budget. In each, data size comes before the write records. - fn check(&mut self) -> LimitCheck { - if let Some((kind, limit, used)) = self.tracker.net().crossing(self.limits.tx_usage_limit()) - { - return self.latch(kind, 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() { - if let Some((kind, limit, used)) = lane.net().crossing(lane.budget) { - return self.crossed(kind, limit, used, 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 } - /// Whether [`check`](Self::check) would find nothing to stop the running frame for, asked - /// without latching anything: the transaction keeps no more than its limits, and the running - /// frame no more than its budget. An exempt transaction is stopped by nothing, and a latched - /// one by nothing but the latch, which [`stop_before_run`](Self::stop_before_run) takes - /// first. - fn check_finds_nothing(&self) -> bool { - if self.is_exempt() || self.latched().is_some() { - return true; - } - self.tracker.net().crossing(self.limits.tx_usage_limit()).is_none() && - self.tracker.current().is_none_or(|lane| lane.net().crossing(lane.budget).is_none()) - } - - /// The stop the running frame returns instead of running another instruction: the latched - /// one, or the one [`on_frame_return`](Self::on_frame_return) left for a caller its child put - /// over its budget. Taking it clears the latter, which stops one frame. - pub(crate) fn stop_before_run(&mut self) -> Option { - let resume_stop = self.resume_stop.take(); - self.latched().copied().or(resume_stop) - } - - /// Rewrites `result` to the latched stop, when the transaction is latched: a success, a revert - /// or a halt becomes the latched revert, on the gas the result carries. - /// - /// No frame runs an instruction once the transaction is latched, so no out-of-gas can happen - /// after the latch: the frame that crossed returns the stop, and every frame above it returns - /// it again without running. A halt that reaches here under the latch was made by an - /// inspector's rewrite, which cannot turn the stop into a halt any more than into a success. - /// A real halt before the latch is left alone: it was returned before the latch was set. - pub(crate) fn apply_latch(&self, result: &mut FrameResult) { - let Some(latched) = self.latched() else { return }; - let interpreter_result = result.interpreter_result_mut(); - 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 @@ -280,18 +275,10 @@ impl AdditionalLimit { self.intrinsic_history_bytes = bytes; } - /// The history bytes the last settled transaction appended, 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 of its value movements are data size and - /// not history, and are not among them. - /// - /// Every one of them is priced at the cost per history byte, and + /// 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 - /// that price. The two part by what the history allowances of its value transfers paid, which - /// no gas ledger carries. They are the bytes the schedule prices, not the chain's physical - /// growth: a transaction exempt from history gas appended none that anybody priced, and - /// reports none, and the body counts its fixed write records whichever fee accounts are - /// written. + /// their price. pub const fn history_bytes(&self) -> u64 { self.history_bytes } @@ -323,6 +310,17 @@ impl AdditionalLimit { 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. /// @@ -440,35 +438,49 @@ impl AdditionalLimit { (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. A body that crosses the - /// transaction limit latches it, and the first frame is then answered with the stop. - pub(crate) fn record_tx_body(&mut self, bytes: u64) -> LimitCheck { + /// 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 { - return LimitCheck::WithinLimit; + if bytes != 0 { + self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); } - self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); - self.check() + } + + /// 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 @@ -476,82 +488,50 @@ impl AdditionalLimit { /// /// 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`, which has been charged `state_gas` so far. + /// one of them, from the transaction's `sender`. /// - /// The limits are checked before the records are made — the state gas the authorities were - /// charged first, then their records: a crossing latches the transaction and records nothing, - /// and the caller takes the authorizations back with the gas they charged, 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, - state_gas: i64, - ) -> LimitCheck { + ) { self.sender = sender; - let check = self.check_state_gas(state_gas); - if check.exceeded_limit() { - return check; - } - let records = WRITE_RECORD.times(authorities); - let used = self.tracker.net().saturating_add(records); - if let Some((kind, limit, used)) = used.crossing(self.limits.tx_usage_limit()) { - let check = self.latch(kind, limit, used); - if check.exceeded_limit() { - return check; - } - } self.target_is_authority = target_is_authority; - self.tracker.record(records); - LimitCheck::WithinLimit - } - - /* The state-gas limit */ - - /// Holds the state gas the transaction holds to its limit, the running frame — or, outside - /// any frame, the transaction — holding `running`, and latches the transaction when it is - /// crossed. - /// - /// Called where state gas has just been charged, so a charge the frame could not pay is an - /// out-of-gas whatever the limit: the limit holds what was paid. What a frame refilled, and - /// what a failed frame rolled back, is out of what it holds, so a write taken back gives its - /// room back. - pub(crate) fn check_state_gas(&mut self, running: i64) -> LimitCheck { - let used = self.tracker.state_gas_held(running); - let limit = self.limits.tx_state_gas_limit; - if used > limit { - return self.latch(LimitKind::StateGrowth, limit, used); - } - LimitCheck::WithinLimit - } - - /// Records the state gas the transaction was charged before its first frame, `spent`, which - /// the first frame's lane holds outside it, and holds to the limit the part of it that stands - /// whatever the first frame does, `stands`: all of it but the account EIP-2780 charges the - /// first frame's start for, which is held once revm has decided the frame, as every frame's - /// upfront charge is. A crossing latches the transaction, and its first frame is answered with - /// the stop before it is built. - pub(crate) fn on_state_gas_before_frames(&mut self, stands: i64, spent: i64) { - self.tracker.set_state_gas_before_frames(spent); - self.check_state_gas(stands); - } - - /// Records the state gas `held` by the running frame as it suspends on a child, which the - /// child's lane counts as held outside it. - #[inline] - pub(crate) fn on_frame_suspend(&mut self, held: i64) { - self.tracker.set_state_gas_at_suspension(held); + 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 */ @@ -577,24 +557,14 @@ impl AdditionalLimit { /// 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, and it is called only for a start revm - /// makes as far as the caller's account decides it. A start revm refuses there — a value its - /// caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes - /// nothing, and gets an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)); so - /// does a start past the call-stack limit, which the depth guard answers before it is counted. - /// The one refusal decided after the count is a creation onto an occupied address: revm reads - /// the created address's account only once it builds the frame. Its records and transfer log - /// are counted, a crossing they cause stops the creation before revm could refuse it, and - /// without a crossing revm's refusal fails the creation and discards them. + /// 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().copied() { - self.push_empty_frame(); - return latched; - } self.push_lane(input, depth); if self.frame_start_transfer_log(input) { self.tracker.record(TRANSFER_LOG); @@ -602,9 +572,8 @@ impl AdditionalLimit { self.check() } - /// Holds the code a creation deposits to the limits, and names the stop when it crosses one: - /// first the state gas `return_create` charged for the bytes, then the bytes themselves, - /// counted on the creation's own lane. + /// 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 @@ -620,10 +589,7 @@ impl AdditionalLimit { /// 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 state gas is held with what the creation already holds, and before the bytes, as it is - /// wherever both cross at one site. A deposit the schedule charges no state gas for adds none, - /// and holding what the creation already held finds nothing its own charges did not. The same - /// bytes are history beside the write records, counted here on the same lane, so the + /// 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> { @@ -631,41 +597,29 @@ impl AdditionalLimit { if bytes == 0 { return Ok(()); } - let check = self.check_state_gas(deposit.gas_after.state_gas_spent()); - if check.exceeded_limit() { - return Err(check.revert_data()); - } 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(check.revert_data()); + return Err(self.note_frame_stop(&check)); } Ok(()) } - /// The budget of the frame about to start, in data-size bytes and in write records. + /// The data-size budget of the frame about to start. /// - /// In each dimension 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), - /// [`frame_kv_update_limit`](EvmTxRuntimeLimits::frame_kv_update_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) -> LimitUsage { + /// 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) => { - let remaining = caller.remaining_budget(); - LimitUsage { - data_size: share_of_remaining(remaining.data_size), - write_records: share_of_remaining(remaining.write_records), - } - } - None => self.limits.tx_usage_limit().saturating_sub(self.tracker.net()), + 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_usage_limit()) + forwarded.min(self.limits.frame_data_size_limit) } fn push_lane(&mut self, input: &FrameInput, depth: usize) { @@ -681,15 +635,15 @@ 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); @@ -717,6 +671,7 @@ impl AdditionalLimit { 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); } @@ -754,6 +709,28 @@ impl AdditionalLimit { 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. @@ -810,7 +787,7 @@ impl AdditionalLimit { /// 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 its budget, goes with it: the frame is + /// 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; @@ -847,14 +824,12 @@ impl AdditionalLimit { } /// 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 neither a success nor a - /// halt passes it. + /// 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)): its own frame-local revert for its budget, - /// the latch for the transaction's limit. + /// 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 @@ -870,11 +845,19 @@ impl AdditionalLimit { /// 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: &mut FrameResult) -> u64 { - self.apply_latch(result); + 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; @@ -887,7 +870,7 @@ impl AdditionalLimit { check.exceeded_limit().then_some(check) } else { debug_assert!( - self.check_finds_nothing(), + self.check().within_limit(), "a frame's return put its caller over a limit no check held it to" ); None @@ -897,24 +880,18 @@ 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. + /// 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 go too, and the halt stays a halt. The body is not one of those records. It is put - /// back after the reset. - /// - /// A latch goes with the reset. Only the body's can be set by then: authorities whose records - /// cross the limit are taken back before anything else is charged, and a latched transaction's - /// runtime phase charges nothing but the account a deposit-like transaction creates for its - /// caller. That account exists whatever the transaction does, so a transaction that cannot pay - /// for it is out of gas with or without a stop, and it reports the halt. An exemption stays: - /// it is the transaction's, not its frames'. - pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { + /// 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.standing = LimitCheck::WithinLimit; self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); return; } @@ -924,8 +901,6 @@ impl AdditionalLimit { // 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"); - } else { - self.apply_latch(result); } } } @@ -944,6 +919,13 @@ const fn share_of_remaining(remaining: u64) -> u64 { 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 @@ -1057,6 +1039,37 @@ mod tests { })) } + /// 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 { @@ -1083,14 +1096,14 @@ mod tests { ); } - /// A frame answered without running — by the depth guard, the latch, an interceptor or an + /// 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. The latch's and an interceptor's answers are also reached through + /// 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() { @@ -1104,14 +1117,14 @@ mod tests { limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); limit.push_empty_frame(); - let mut result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); - assert_eq!(limit.on_frame_return(&mut result), 3_000, "{answer:?}: all of it back"); + 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 mut result = + let result = crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&mut result); + limit.on_last_frame_return(&result); limit.settle_history_bytes(true); assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); } @@ -1129,80 +1142,105 @@ mod tests { 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 — in data-size bytes and in - /// write records alike, each from its own limit. + /// 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 tx_limit = LimitUsage { data_size: 10_000, write_records: 1_000 }; - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(tx_limit.data_size) - .with_tx_kv_update_limit(tx_limit.write_records), - ); + 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 }); - let share = |usage: LimitUsage| LimitUsage { - data_size: share_of_remaining(usage.data_size), - write_records: share_of_remaining(usage.write_records), - }; limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let first = LimitUsage { data_size: 10_000 - 310, write_records: 1_000 }; + 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(first); - assert_eq!(child, LimitUsage { data_size: 9_496, write_records: 980 }); + 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(child); + 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(grandchild), + share_of_remaining(grandchild), "the fourth frame, at depth 3, still takes 98% of what is left" ); } - /// Each frame cap binds when it is tighter than the share of what the parent has left, in its - /// own dimension and in no other. + /// 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) - .with_tx_kv_update_limit(1_000), + .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, - LimitUsage { data_size: 100, write_records: 1_000 } - ); + 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, - LimitUsage { data_size: 98, write_records: 980 } - ); - - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(1_000) - .with_frame_kv_update_limit(10), - ); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!( - limit.tracker.current().unwrap().budget, - LimitUsage { data_size: 1_000, write_records: 10 } - ); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - assert_eq!( - limit.tracker.current().unwrap().budget, - LimitUsage { data_size: 980, write_records: 9 } - ); + 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 @@ -1214,7 +1252,7 @@ mod tests { 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.data_size, 98); + assert_eq!(limit.tracker.current().unwrap().budget, 98); (limit, child) } @@ -1227,9 +1265,9 @@ mod tests { 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 mut result = + let result = crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&mut result); + let _ = limit.on_frame_return(&result); let stop = limit.stop_before_run(); let expected = caller_stopped.then_some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, @@ -1250,11 +1288,10 @@ mod tests { #[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 = crate::limit::UNLIMITED; + limit.tracker.current_mut().unwrap().budget = u64::MAX; limit.tracker.record(LimitUsage { data_size: 101, write_records: 0 }); - let mut result = - crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&mut result); + 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, @@ -1282,57 +1319,104 @@ mod tests { /// 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) - .with_tx_kv_update_limit(0) - .with_frame_kv_update_limit(0) - .with_tx_state_gas_limit(0) + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0) } - /// Counts a body, a value call's two records and some state gas, and reports each verdict. - fn count_a_transaction(limit: &mut AdditionalLimit) -> [LimitCheck; 3] { - let body = limit.record_tx_body(crate::TX_BODY_SIZE); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 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); - [body, records, limit.check_state_gas(1_000)] + [first, records] } - /// A transaction that is not exempt is stopped by the first limit it crosses: its body latches - /// it. + /// 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 [body, ..] = count_a_transaction(&mut limit); - assert!(body.exceeded_limit() && !body.is_frame_local()); - assert_eq!(limit.latched(), Some(&body)); + 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, nothing is latched and no caller is stopped. What - /// it uses is counted all the same. + /// 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; 3]); - assert_eq!(limit.latch(LimitKind::DataSize, 0, 1), LimitCheck::WithinLimit); - assert_eq!(limit.latched(), None); + 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 mut result = crate::synthetic_frame_result( + let result = crate::synthetic_frame_result( &call_from_to(CALLEE, TARGET, U256::from(1)), InstructionResult::Stop, Bytes::new(), ); - let _ = limit.on_frame_return(&mut result); - assert_eq!(result.instruction_result(), InstructionResult::Stop, "nothing is rewritten"); - assert_eq!(limit.stop_before_run(), None, "and the caller runs on"); + 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. @@ -1340,29 +1424,28 @@ mod tests { fn test_an_exempt_transaction_records_its_authorities() { let mut limit = AdditionalLimit::new(zero_limits()); limit.exempt(); - let check = limit.record_applied_authorities(SENDER, 2, false, 1_000); - assert!(!check.exceeded_limit(), "{check:?}"); + 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. A latch cleared before the first frame keeps it. + /// 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 mut result = crate::synthetic_frame_result( + let result = crate::synthetic_frame_result( &call_from_to(SENDER, CALLEE, U256::ZERO), InstructionResult::OutOfGas, Bytes::new(), ); - limit.on_last_frame_return(&mut result); + 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 [body, ..] = count_a_transaction(&mut limit); - assert!(body.exceeded_limit(), "after a reset the body latches again"); + 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`. @@ -1462,12 +1545,10 @@ mod tests { "the recipient of each move — the inner one's caller is the outer one's — and two logs", ); - let mut result = - crate::synthetic_frame_result(&inner, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&mut result); - let mut result = - crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&mut result); + 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); } @@ -1482,14 +1563,14 @@ mod tests { limit.on_frame_init(&inner, 1); assert_eq!(limit.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); - let mut result = - crate::synthetic_frame_result(&inner, InstructionResult::Revert, Bytes::new()); - let _ = limit.on_frame_return(&mut result); + 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: its own budget reverts it alone, the transaction's limit latches. The records alone + /// 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() { @@ -1516,7 +1597,6 @@ mod tests { frame_local: true, }, ); - assert_eq!(limit.latched(), None, "a frame budget does not latch"); } } @@ -1540,7 +1620,6 @@ mod tests { frame_local: false, }, ); - assert_eq!(limit.latched(), Some(&check)); } } @@ -1551,7 +1630,6 @@ mod tests { fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { let destruction = |beneficiary| StagedRecord::SelfDestruct { had_value: true, - target_exists: true, to_other_account: true, beneficiary, }; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 4aa7f25b1..226bf53c8 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -3,15 +3,16 @@ //! 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 fill these in: the -//! data-size limit, the KV limit and the state-gas limit below, and detention for compute gas. +//! 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 a transaction -//! through the same latch ([`AdditionalLimit::latch`]), with the compute the transaction may reach -//! as the limit, and its compute at the crossing as what was used ([`LimitCheck::ExceedsLimit`]). +//! 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 those limits meter at the sites the data-size limit counts: data-size +//! 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. //! @@ -21,10 +22,14 @@ //! 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 its budget reverts alone and its caller resumes; a transaction that crosses its limit -//! is stopped through the latch ([`AdditionalLimit`]). 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 budget with it before it runs on, and reverts alone if it crossed. +//! 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: //! @@ -60,68 +65,35 @@ //! 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. A body over the limit latches the transaction before it runs, and then nothing is -//! charged for what the stop takes back: no authorization is applied, no record made outside a -//! frame is charged, the first frame's start is charged nothing, and the first frame is answered -//! with the stop. The account a deposit-like transaction creates for its caller is charged all the -//! same, because it exists whatever the transaction does. +//! first. //! -//! # The KV limit +//! 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. //! -//! The KV count is the write-record count the lanes keep: 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. [`EvmTxRuntimeLimits::tx_kv_update_limit`] holds it -//! by the data-size limit's rules in its own unit: the transaction's own frame gets what the -//! transaction has left, a child the same share of what its parent has left, under -//! [`EvmTxRuntimeLimits::frame_kv_update_limit`]; a frame over its budget reverts alone and a -//! transaction over its limit is stopped. Every check holds the data size before the records. +//! # Write records //! -//! A record weighs [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so -//! the KV count never weighs more than the data size, and a KV limit binds only below the -//! data-size limit's fortieth. +//! 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 state-gas limit +//! # State growth //! -//! EIP-8037 charges state gas for exactly the state a transaction adds, so the state a transaction -//! grows is the state gas it spends: [`EvmTxRuntimeLimits::tx_state_gas_limit`] holds it, and -//! nothing counts new accounts and slots beside it. What is held is net — what a frame refilled -//! and what a failed frame rolled back is out of it — and is the state gas charged before the -//! first frame plus what every frame on the call stack holds (the `frame_limit` module). The limit -//! is per transaction, with no frame budget: a crossing anywhere stops the transaction, reported as -//! [`LimitKind::StateGrowth`] with the limit in gas. +//! 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 limit holds each charge where it is made, once it is made, so a charge the frame cannot -//! pay is an out-of-gas whatever the limit: the authorities' before the first frame, which are -//! taken back on a crossing; a fresh slot and a destruction's new beneficiary, which stop the -//! frame; and a new account a frame's start adds — the first frame's recipient or created account, -//! which EIP-2780 charges the transaction for, and the account a `CALL`, `CREATE` or `CREATE2` -//! adds, which its opcode is charged for — held once revm has decided the frame. A frame refused — -//! a value its caller cannot fund, one past the call-stack limit — or answered with a failure gives -//! that charge back and is never held for it; a frame revm builds, or answers with a success, -//! returns the stop, and an answer of the transaction's own frame takes its writes back with it. +//! # The limits //! -//! Deployed code is held once `return_create` has charged every part of its deposit and before it -//! commits the creation, as its bytes are ([`ContextTr::admit_code_deposit`]), so a crossing -//! leaves no code behind: the creation reverts with the stop, on the gas it had before the -//! deposit. A creation that cannot pay a part of its deposit — the regular costs, the state gas, -//! the history — runs out of gas there whatever the limit. -//! -//! [`ContextTr::admit_code_deposit`]: revm::context::ContextTr::admit_code_deposit -//! -//! Wherever the state gas and a record cross together at one site, the state gas is the stop -//! reported. At a frame start the records are held before revm builds the frame, and a frame they -//! stop adds no account, so its upfront state gas is given back rather than held. -//! -//! It is a limit on gas, so it counts state at the SALT price: a slot or an account in a bucket -//! `m` times the minimum costs `m` times the schedule's entry, and reaches the limit that many -//! times sooner. -//! -//! Every limit is unlimited unless a caller sets it, gas detention's caps aside. A block executor -//! installs the chain's, the per-transaction half of the Satin fork's parameters -//! ([`ProtocolLimits`](crate::ProtocolLimits)), whose default holds a transaction to -//! [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, to detention's caps and to -//! nothing else. +//! 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 //! @@ -129,11 +101,10 @@ //! 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, the KV count, the state gas and the frame budgets of the first two. 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 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 //! @@ -169,6 +140,7 @@ 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. @@ -180,6 +152,14 @@ 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. @@ -206,6 +186,16 @@ pub const TX_BODY_SIZE: u64 = TX_BASE_SIZE + WRITE_RECORD_SIZE * TX_FIXED_WRITE_ /// 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; @@ -224,9 +214,9 @@ pub const FRAME_DATA_SHARE_DENOMINATOR: u64 = 100; /// What a transaction or a frame counts: data-size bytes and write records. /// -/// The write-record count is the KV count a node reports, and the KV limit holds it; it has no -/// tracker of its own. 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`. +/// 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. @@ -235,70 +225,45 @@ pub struct LimitUsage { pub write_records: u64, } -/// Limits one transaction's data size, write records, state gas and compute after a read of -/// volatile data. -/// -/// [`tx_data_size_limit`](Self::tx_data_size_limit) and -/// [`tx_kv_update_limit`](Self::tx_kv_update_limit) stop the transaction. A frame's own budget in -/// each dimension is derived from them: 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. +/// Limits one transaction's data size and its compute after a read of volatile data. /// -/// [`frame_data_size_limit`](Self::frame_data_size_limit) and -/// [`frame_kv_update_limit`](Self::frame_kv_update_limit) are a further cap on every frame's -/// budget. +/// [`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_state_gas_limit`](Self::tx_state_gas_limit) holds the transaction's state gas and stops -/// the transaction; it has no frame budget. +/// [`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. They default to -/// the spec's, [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] and [`ORACLE_ACCESS_COMPUTE_GAS`]; every other -/// limit is unlimited unless a caller sets it. [`no_limits`](Self::no_limits) leaves every one -/// unlimited, the caps included, and a transaction whose caps are both unlimited is not detained: -/// limits built from it do not execute the chain. +/// 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. /// -/// Every value here changes a transaction's result, so in block execution they are the chain's: -/// the per-transaction half of [`ProtocolLimits`](crate::ProtocolLimits), which the block executor -/// installs before every transaction. [`MegaEvmFactory`](crate::MegaEvmFactory) resolves the same -/// for an EVM it creates outside block execution; set on a standalone EVM, they are its caller's -/// choice. -/// -/// [`BLOCK_ENV_ACCESS_COMPUTE_GAS`]: crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS -/// [`ORACLE_ACCESS_COMPUTE_GAS`]: crate::constants::ORACLE_ACCESS_COMPUTE_GAS +/// 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, /// 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 most write records the transaction may keep: its KV count. Crossing it stops the - /// transaction. - pub tx_kv_update_limit: u64, - /// A cap on every frame's write-record budget, applied after the share of what its parent has - /// left. Crossing it reverts the frame alone. - pub frame_kv_update_limit: u64, - /// The most EIP-8037 state gas the transaction may hold, net of what it refilled and of what - /// its failed frames rolled back: the limit on the state it grows. Crossing it stops the - /// transaction. - /// - /// It is a limit on gas, so it counts the state at the price the transaction pays for it: a - /// slot or an account in a crowded SALT bucket costs its bucket's multiple of the schedule's - /// entry, and reaches the limit that many times sooner. - pub tx_state_gas_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 stops the - /// transaction. + /// 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 stops the transaction. + /// 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 @@ -307,11 +272,10 @@ pub struct EvmTxRuntimeLimits { } impl Default for EvmTxRuntimeLimits { - /// Gas detention's caps at the spec's, every other limit unlimited. + /// The limits of the default spec's table: what a [`MegaContext`](crate::MegaContext) of that + /// spec runs under. fn default() -> Self { - Self::no_limits() - .with_block_env_access_compute_gas_limit(crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) - .with_oracle_access_compute_gas_limit(crate::constants::ORACLE_ACCESS_COMPUTE_GAS) + crate::ProtocolLimits::for_spec(crate::MegaSpecId::default()).tx_runtime_limits } } @@ -321,17 +285,15 @@ impl EvmTxRuntimeLimits { /// /// 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 own ([`ProtocolLimits`](crate::ProtocolLimits)), whose - /// detention caps must be below - /// [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a + /// 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, - tx_kv_update_limit: u64::MAX, - frame_kv_update_limit: u64::MAX, - tx_state_gas_limit: u64::MAX, block_env_access_compute_gas_limit: u64::MAX, oracle_access_compute_gas_limit: u64::MAX, } @@ -349,24 +311,6 @@ impl EvmTxRuntimeLimits { self } - /// Sets the transaction's KV limit: the most write records it may keep. - pub const fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { - self.tx_kv_update_limit = limit; - self - } - - /// Caps every frame's write-record budget at `limit`. - pub const fn with_frame_kv_update_limit(mut self, limit: u64) -> Self { - self.frame_kv_update_limit = limit; - self - } - - /// Sets the transaction's state-gas limit: the most state gas it may hold. - pub const fn with_tx_state_gas_limit(mut self, limit: u64) -> Self { - self.tx_state_gas_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 { @@ -379,19 +323,6 @@ impl EvmTxRuntimeLimits { self.oracle_access_compute_gas_limit = limit; self } - - /// The transaction's limits on what it keeps, one per dimension of [`LimitUsage`]. - pub(crate) const fn tx_usage_limit(&self) -> LimitUsage { - LimitUsage { data_size: self.tx_data_size_limit, write_records: self.tx_kv_update_limit } - } - - /// The caps on every frame's budget, one per dimension of [`LimitUsage`]. - pub(crate) const fn frame_usage_limit(&self) -> LimitUsage { - LimitUsage { - data_size: self.frame_data_size_limit, - write_records: self.frame_kv_update_limit, - } - } } /// One write record. @@ -402,32 +333,13 @@ pub(crate) const WRITE_RECORD: LimitUsage = pub(crate) const TRANSFER_LOG: LimitUsage = LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }; -/// A budget with no bound in either dimension. -pub(crate) const UNLIMITED: LimitUsage = - LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; - impl LimitUsage { /// Nothing counted. pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; - /// The first dimension in which `self` is over `limit` — data size, then write records — with - /// the limit crossed and the usage that crossed it; `None` when both hold. - pub(crate) const fn crossing(self, limit: Self) -> Option<(LimitKind, u64, u64)> { - if self.data_size > limit.data_size { - return Some((LimitKind::DataSize, limit.data_size, self.data_size)); - } - if self.write_records > limit.write_records { - return Some((LimitKind::KVUpdate, limit.write_records, self.write_records)); - } - None - } - - /// Each counter the smaller of the two. - pub(crate) fn min(self, other: Self) -> Self { - Self { - data_size: self.data_size.min(other.data_size), - write_records: self.write_records.min(other.write_records), - } + /// 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. @@ -468,20 +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: the write records a transaction keeps, one per account or storage - /// write; metered by the KV limit. - KVUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, - /// Net new state, metered in EIP-8037 state gas by the state-gas limit: the `limit` of its - /// stop is the transaction's state-gas limit, in gas. The legacy engine counted the same - /// dimension in new accounts and slots. - StateGrowth, } impl LimitKind { @@ -489,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, } } @@ -499,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, } } @@ -509,9 +412,9 @@ 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. A transaction exempt from the limits +/// 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 { @@ -532,13 +435,6 @@ pub enum LimitCheck { /// 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. - /// - /// For [`LimitKind::StateGrowth`] it is the state gas the transaction held where the limit - /// was crossed. Before the first frame that is what stands whatever the frame does — a - /// deposit's created caller, the applied authorities — and not the account EIP-2780 - /// charges the first frame's start for, which is held once revm has decided the frame: a - /// deposit whose created caller alone crosses the limit reports that account, even where - /// its first frame would add another. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, @@ -575,6 +471,56 @@ 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. +#[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::*; @@ -597,25 +543,18 @@ mod tests { } /// `no_limits` leaves every dimension unlimited: it is what the execution-spec gate installs - /// in equivalence mode, and what a bare context runs under. Every field is named, so a limit - /// added later cannot be left out of it. + /// 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, - tx_kv_update_limit, - frame_kv_update_limit, - tx_state_gas_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, - tx_kv_update_limit, - frame_kv_update_limit, - tx_state_gas_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, ] { @@ -623,16 +562,18 @@ mod tests { } } - /// The default holds gas detention's caps at the spec's and leaves every other limit - /// unlimited; a caller's limits change either cap alone. + /// 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_caps_detention_at_the_specs_and_nothing_else() { - use crate::constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}; + fn test_the_default_is_the_specs_table() { let default = EvmTxRuntimeLimits::default(); - assert_eq!(default.block_env_access_compute_gas_limit, BLOCK_ENV_ACCESS_COMPUTE_GAS); - assert_eq!(default.oracle_access_compute_gas_limit, ORACLE_ACCESS_COMPUTE_GAS); + 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() @@ -685,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()), @@ -701,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, @@ -716,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 38fcc4973..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. @@ -99,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, .. } => { @@ -186,7 +182,6 @@ mod tests { ); let to_other = StagedRecord::SelfDestruct { had_value: true, - target_exists: true, to_other_account: true, beneficiary: OTHER, }; @@ -201,13 +196,7 @@ mod tests { 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); @@ -215,7 +204,6 @@ 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, }; @@ -228,7 +216,6 @@ mod tests { fn test_only_a_destruction_to_another_account_moves_value() { let sd = |had_value, to_other_account, beneficiary| StagedRecord::SelfDestruct { had_value, - target_exists: true, to_other_account, beneficiary, }; diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index a316269c2..5f450ba7b 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## OVERVIEW -The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, the system-address transaction, and the pre-block deploy of those six plus the EIP-7997 factory, and the `SequencerRegistry`'s pre-block steps: the due-change read and the `applyPendingChanges()` system call. The live system address is read by a transaction of the system shape when it is validated, not before the block. +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. Its storage is read by the Host (`evm/host.rs`), through the oracle environment. @@ -9,10 +9,10 @@ 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, the [`SequencerRegistryConfig`] that seeds it, 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 `inspect_system_address`, the journal read of `_currentSystemAddress` a system-shaped transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. -- `deploy.rs`: the declarative spec, `transact_deploy`, the EIP-7997 factory, and the list of seven predeploys. +- `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 (`is_live_system_transaction`) 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. @@ -25,13 +25,13 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 is not forwarded is not counted. +- 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. The shape is tested first, on the transaction's own fields, and only a shaped transaction reads the registry: every other transaction pays two comparisons and reads nothing, and one of another shape from the system address is an ordinary transaction. -- The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The chain id, the nonce and EIP-3607 are checked there, each under the configuration switch a user transaction obeys. -- Accounts and slots read during validation are read without warming them, so the transaction pays what any other transaction would pay for its first touch: the registry's account and slot, and the system address's account. +- 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 @@ -40,14 +40,13 @@ The contract for a new or modified helper: - Never call `db.commit(...)` inside the helper. Return the prepared state; let the executor commit. -- On an idempotent no-change path (the contract is already deployed with the correct code hash), return `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. +- 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 real-change path, include every account and storage slot the helper touched. -- Present with different code is an error, not an overwrite. - A system address holding foreign bytecode is a broken chain. +- 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 hands it to the pre-block observer, then commits: the sequence the observer sees is the witness a stateless client needs. +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. @@ -60,20 +59,20 @@ The executor hands it to the pre-block observer, then commits: the sequence the - 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 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 make a transaction that lacks the system shape read the registry: the shape test is what keeps every other transaction free of the read. +- 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 hides the step from a witness generator. + 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 overwrite foreign code at a system address. +- 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 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` calls. +- 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 `deploy.rs::system_contract_specs`, seeded from chain params if it has storage. -- Change how a block deploys the contracts: `block/executor.rs::apply_pre_execution_changes` iterates the spec list, delivers each witness to the pre-block observer, and commits. -- 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 deploys, in that order. -- Change how the live system address is read or which transactions read it: `sequencer_registry.rs::inspect_system_address` and `tx.rs::is_live_system_transaction`, which `MegaHandler::validate_env` calls; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). +- 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 67d80edeb..23d017262 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -63,7 +63,9 @@ pub const SLOT_NUM_ACCESS_TYPE: u8 = 12; /// for the frame that made the call — the caller, one level above the frame the call would start: /// /// - `disableVolatileDataAccess()` switches volatile-data access off for the caller and every frame -/// below it. A switch already off from a frame above stays as it is. +/// 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. @@ -105,7 +107,7 @@ pub(crate) fn intercept( let (result, output) = match method { Method::Disable => { if let Some(caller) = caller { - detention.disable_access(caller); + detention.disable_access_on_answer(caller); } (InstructionResult::Return, Bytes::new()) } diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs deleted file mode 100644 index e3ea8a09e..000000000 --- a/crates/mega-evm/src/system/deploy.rs +++ /dev/null @@ -1,318 +0,0 @@ -//! Shared primitive for deploying `MegaETH` system contracts and the EIP-7997 factory. -//! -//! Every predeploy is one state patch: install the account's bytecode, optionally seed storage, -//! and mark the account touched and created. [`SystemContractSpec`] names those differences; -//! [`transact_deploy`] applies them and never commits. The caller — the block executor today, -//! the CLI later — commits the returned [`EvmState`]. -//! -//! [`system_contract_specs`] is the single list both iterate: the six `MegaETH` contracts in -//! address order, then the factory. There is one version of each (the bytecode -//! `mega-system-contracts` ships; the Oracle and the `SequencerRegistry` are their v2.0.0), and -//! a system address that already holds different code is an error rather than an upgrade. - -#[cfg(not(feature = "std"))] -use alloc as std; -use core::fmt; -use std::vec::Vec; - -use alloy_primitives::{address, b256, bytes, keccak256, Address, Bytes, B256, U256}; -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, -}; -use revm::{ - primitives::KECCAK_EMPTY, - state::{Account, Bytecode, EvmState, EvmStorageSlot, TransactionId}, - Database, -}; - -use super::{ - keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH}, - SequencerRegistryConfig, 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 contracts [`system_contract_specs`] returns: the six `MegaETH` system contracts and -/// the EIP-7997 factory. -pub const SYSTEM_CONTRACT_DEPLOY_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"); - -/// Nonce a freshly created contract account starts at (EIP-161). The factory is created, so it -/// is 1; the six `MegaETH` contracts use the same number. -pub const CREATE2_FACTORY_NONCE: u64 = 1; - -/// 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. - pub code: Bytes, - /// Keccak-256 hash of [`code`](Self::code). Used for the idempotence check. - pub code_hash: B256, - /// Nonce written on a fresh deploy. Created contract accounts start at 1. - pub nonce: u64, - /// Flat storage slots to seed `(slot, value)` on a fresh deploy. Empty for every contract - /// except the `SequencerRegistry`. - pub seed: Vec<(U256, U256)>, - /// When set, matching code with nonce 0 is an error rather than a read-only entry. - /// - /// EIP-7997 requires the factory to hold its runtime **and a nonzero nonce**. The six - /// `MegaETH` contracts are not EIP-7997, so they leave this unset: matching code is - /// accepted regardless of nonce, because the matching-code path must not rewrite an - /// already-deployed contract. - pub require_nonzero_nonce: bool, -} - -impl SystemContractSpec { - /// A spec with nonce 1, no seeded storage, and no nonce requirement on a matching account. - pub fn new(address: Address, code: Bytes, code_hash: B256) -> Self { - Self { address, code, code_hash, nonce: 1, seed: Vec::new(), require_nonzero_nonce: false } - } - - /// Sets the seeded storage slots applied on a fresh deploy. - pub fn with_seed(mut self, seed: Vec<(U256, U256)>) -> Self { - self.seed = seed; - self - } - - /// Requires a matching existing account to hold a nonzero nonce (EIP-7997). - pub fn require_nonzero_nonce(mut self) -> Self { - self.require_nonzero_nonce = true; - self - } -} - -/// Why [`transact_deploy`] could not produce a witness. -#[derive(Debug)] -pub enum SystemContractDeployError { - /// The database could not load the account at the spec's address. - Database(DbError), - /// `address` already holds bytecode whose hash is `found`, not `expected`. - /// - /// A system address holding foreign code is a broken chain, not something to overwrite. - ForeignCode { - /// The system-contract address that already has code. - address: Address, - /// The hash this engine deploys. - expected: B256, - /// The hash already in state. - found: B256, - }, - /// The EIP-7997 factory already holds the right runtime but nonce 0, which the EIP - /// forbids. The matching-code path does not rewrite a nonce, so this cannot be repaired - /// by deploying again. - ZeroFactoryNonce { - /// The factory address. - address: Address, - }, - /// The address has empty code but a used nonce. Prefunding with balance alone is the - /// bootstrap path; a used account at a system address is not overwritten silently. - UsedEmptyAccount { - /// The system-contract address. - address: Address, - /// The nonce already on the account. - nonce: u64, - }, -} - -impl From for SystemContractDeployError { - fn from(error: DbError) -> Self { - Self::Database(error) - } -} - -impl fmt::Display for SystemContractDeployError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Database(error) => write!(f, "{error}"), - Self::ForeignCode { address, expected, found } => { - write!( - f, - "system contract at {address} has unexpected code hash {found}, expected {expected}; refusing to overwrite" - ) - } - Self::ZeroFactoryNonce { address } => { - write!( - f, - "EIP-7997 factory at {address} has matching code but nonce 0; refusing to accept a zero-nonce factory" - ) - } - Self::UsedEmptyAccount { address, nonce } => { - write!( - f, - "system contract at {address} has empty code but nonce {nonce}; refusing to overwrite a used account" - ) - } - } - } -} - -impl core::error::Error - for SystemContractDeployError -{ - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - match self { - Self::Database(error) => Some(error), - Self::ForeignCode { .. } | - Self::ZeroFactoryNonce { .. } | - Self::UsedEmptyAccount { .. } => None, - } - } -} - -/// Deploys the contract `spec` describes, returning the [`EvmState`] witness. Nothing is -/// committed. -/// -/// - Already deployed with [`SystemContractSpec::code_hash`]: the account as a read-only entry -/// (neither touched nor created, no seeding), so the witness records the read. A nonce of 7 stays -/// 7. If [`SystemContractSpec::require_nonzero_nonce`] is set (the EIP-7997 factory) and the -/// nonce is 0, this is [`SystemContractDeployError::ZeroFactoryNonce`] instead: the matching-code -/// path does not rewrite a nonce, so a genesis factory with the right code and nonce 0 would -/// otherwise stay invalid forever. The six `MegaETH` contracts leave that flag unset; they -/// are not EIP-7997, and matching code is accepted regardless of nonce. -/// - Absent, or present with empty code and nonce 0: the created account with its bytecode, nonce -/// and every seeded slot, all marked. An existing balance is kept. Marking the account created -/// clears any storage it had; that is the accepted bootstrap path (prefunding with balance -/// alone). An empty-code account with a nonzero nonce is -/// [`SystemContractDeployError::UsedEmptyAccount`]: a used account at a system address is not -/// overwritten silently. -/// - Present with different non-empty code: [`SystemContractDeployError::ForeignCode`]. -/// -/// # Errors -/// -/// [`SystemContractDeployError::Database`] when the account cannot be loaded; -/// [`SystemContractDeployError::ForeignCode`] when the address already holds other bytecode; -/// [`SystemContractDeployError::ZeroFactoryNonce`] when the factory holds matching code at -/// nonce 0; -/// [`SystemContractDeployError::UsedEmptyAccount`] when the address has empty code and a -/// used nonce. -pub fn transact_deploy( - db: &mut DB, - spec: &SystemContractSpec, -) -> Result> { - debug_assert_eq!( - keccak256(spec.code.as_ref()), - spec.code_hash, - "SystemContractSpec code_hash does not match code for {:?}", - spec.address - ); - - let existing = db.basic(spec.address).map_err(SystemContractDeployError::Database)?; - - if let Some(info) = &existing { - if info.code_hash == spec.code_hash { - if spec.require_nonzero_nonce && info.nonce == 0 { - return Err(SystemContractDeployError::ZeroFactoryNonce { address: spec.address }); - } - // `Account::from` copies the info and leaves status empty: neither touched nor - // created, which is the read-only witness entry. An existing nonce is kept. - return Ok(EvmState::from_iter([(spec.address, Account::from(info.clone()))])); - } - if info.code_hash != KECCAK_EMPTY { - return Err(SystemContractDeployError::ForeignCode { - address: spec.address, - expected: spec.code_hash, - found: info.code_hash, - }); - } - if info.nonce != 0 { - return Err(SystemContractDeployError::UsedEmptyAccount { - address: spec.address, - nonce: info.nonce, - }); - } - } - - let mut info = existing.unwrap_or_default(); - info.code_hash = spec.code_hash; - info.code = Some(Bytecode::new_raw(spec.code.clone())); - info.nonce = spec.nonce; - - let mut account: Account = info.into(); - account.mark_touch(); - account.mark_created(); - for (slot, value) in &spec.seed { - account - .storage - .insert(*slot, EvmStorageSlot::new_changed(U256::ZERO, *value, TransactionId::ZERO)); - } - - Ok(EvmState::from_iter([(spec.address, account)])) -} - -/// The seven predeploys in deploy order: Oracle, high-precision timestamp, `KeylessDeploy`, -/// `MegaAccessControl`, `MegaLimitControl`, `SequencerRegistry`, then the EIP-7997 factory. -/// -/// The registry's seeded slots come from `config`. The factory has nonce 1 and no storage. -pub fn system_contract_specs( - config: &SequencerRegistryConfig, -) -> [SystemContractSpec; SYSTEM_CONTRACT_DEPLOY_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, - ) - .with_seed(registry_seed(config)), - SystemContractSpec::new( - CREATE2_FACTORY_ADDRESS, - CREATE2_FACTORY_CODE, - CREATE2_FACTORY_CODE_HASH, - ) - .require_nonzero_nonce(), - ] -} - -/// 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) -} - -/// The seven bootstrap slots the `SequencerRegistry` is created with. -fn registry_seed(config: &SequencerRegistryConfig) -> Vec<(U256, U256)> { - Vec::from([ - (CURRENT_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), - (CURRENT_SEQUENCER, address_to_storage_value(config.initial_sequencer)), - (ADMIN, address_to_storage_value(config.initial_admin)), - (INITIAL_SYSTEM_ADDRESS, address_to_storage_value(config.initial_system_address)), - (INITIAL_SEQUENCER, address_to_storage_value(config.initial_sequencer)), - (INITIAL_FROM_BLOCK, U256::from(config.initial_from_block)), - (MIN_ROTATION_DELAY, U256::from(config.min_rotation_delay)), - ]) -} diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 11d262d59..ccc65c088 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -9,7 +9,7 @@ use alloy_evm::Database; use alloy_primitives::{Address, Bytes, U256}; use alloy_sol_types::SolCall; use revm::{ - context::{Cfg, ContextError, ContextTr, Transaction}, + context::{Cfg, ContextError, ContextTr, JournalTr, Transaction}, context_interface::{ cfg::{GasId, StateGasCharge, StateGasSite}, Host, @@ -24,6 +24,7 @@ use revm::{ }; use crate::{ + charge_write_records_history, limit::FrameStartRecords, synthetic_call_result, system::{ @@ -34,8 +35,7 @@ use crate::{ KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, - untouched_call_gas, write_record_history_gas, ExternalEnvTypes, JournalInspectTr, MegaContext, - VolatileDataAccess, + untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; /// Where a `keylessDeploy` call's frame stands, from its start to its answer: what its first run @@ -66,6 +66,9 @@ pub(crate) struct Started { 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 @@ -75,8 +78,7 @@ pub(crate) struct Started { /// 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. A transaction the latch already stopped never reaches the dispatch: its frame -/// is answered with the stop before. +/// with empty data. /// /// The depth is tested first: every frame below the transaction's own leaves after one /// comparison. @@ -101,8 +103,8 @@ pub(crate) fn is_dispatched( /// /// 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 holds it -/// from the fork that deploys it on, before any transaction. +/// 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, @@ -138,8 +140,8 @@ pub(crate) fn runs( /// 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 — the latch, or its own budget, which the nonce record a failed -/// creation leaves the call can cross — returns it before this runs, as any frame does. +/// 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, @@ -180,8 +182,8 @@ pub(crate) fn run( /// 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 cold and without its -/// code, so the address is in the transaction's state and in a witness without its bytecode. +/// 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 — @@ -204,11 +206,10 @@ 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 and KV budgets, its -/// records, its forward and the reservoir it inherits, the state-gas limit, the latch. 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. +/// (`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, @@ -245,6 +246,7 @@ fn start( 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)))) } @@ -365,7 +367,15 @@ fn prepare( let deploy_address = calculate_keyless_deploy_address(signer); let checks_code = !ctx.cfg().is_eip3607_disabled(); - let signer_info = ctx.journal_mut().inspect_account(signer, checks_code)?.info.clone(); + 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 @@ -395,7 +405,7 @@ fn prepare( } } forward!(); - if ctx.journal_mut().inspect_account_code_hash(deploy_address)? != KECCAK_EMPTY { + if ctx.journal_mut().load_account(deploy_address)?.data.info.code_hash != KECCAK_EMPTY { refuse!(KeylessDeployError::ContractAlreadyExists); } if signer_info.balance < tx.value { @@ -420,16 +430,15 @@ fn prepare( } let records = FrameStartRecords { on_lane: 1, caller: signer != ctx.tx().caller() }; let record_charges = if ctx.prices_history() { - let (Some(on_lane), Some(caller)) = ( - write_record_history_gas(records.on_lane), - write_record_history_gas(u64::from(records.caller)), - ) else { - return Ok(Err(Refusal::OutOfGas)); - }; - if !on_lane.checked_add(caller).is_some_and(|cost| gas.record_history_cost(cost)) { + 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)); } - Some((on_lane, caller)) + charged } else { None }; diff --git a/crates/mega-evm/src/system/keyless/error.rs b/crates/mega-evm/src/system/keyless/error.rs index f005da0de..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) @@ -52,21 +52,6 @@ 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. - /// - /// The legacy engine's, which ran the deployment with a budget of its own and preflighted it. - /// Kept in the ABI with no producer here: a native deployment is held to the call's own - /// budgets as it runs. - 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 @@ -83,16 +68,6 @@ 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. - /// - /// Kept in the ABI with no producer here: the overhead is regular gas, and a call that - /// cannot pay it runs out of gas. - 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 /// (EIP-3860), which no validation of the outer transaction holds it to. InitCodeTooLarge { @@ -104,18 +79,6 @@ pub enum KeylessDeployError { /// 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, - /// An internal failure (a failed read). Selector-only, so the error ABI does not depend on - /// upstream `Display` text. - /// - /// Kept in the ABI with no producer here: a failed read or SALT lookup fails the transaction - /// with its cause, as it does at every other site. - InternalError, - /// The inner transaction failed its validation as a transaction. Selector-only for the same - /// reason as `InternalError`. - /// - /// The legacy engine's, which ran the deployment as a transaction of its own. Kept in the - /// ABI with no producer here: the deployment is a creation, not a transaction. - InvalidTransaction, /// The keylessDeploy call was not intercepted (only returned by Solidity contract for inner /// calls) NotIntercepted, @@ -157,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() } @@ -177,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(), } } @@ -241,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 }); } @@ -269,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); } @@ -285,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`, @@ -319,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 235dbb621..e121e7df4 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -26,8 +26,8 @@ //! - 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 holds it from the fork that -//! deploys it on. +//! 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 @@ -50,6 +50,13 @@ //! 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, @@ -58,22 +65,30 @@ //! - `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 it as it stops any frame: a frame budget reverts the -//! creation, and the call returns `ExecutionReverted` with the limit's revert data; a transaction -//! limit stops the transaction, and the call reverts with the stop, taking back the signer's -//! nonce with everything else. +//! - 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 contract's errors are unchanged, and so are the rules that produce them and the order they -//! are checked in, so a call several rules refuse reports the legacy engine's error. Four have -//! no producer here: `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. -//! `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 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 //! @@ -94,7 +109,7 @@ pub use error::*; pub use tx::*; pub(crate) use dispatch::{is_dispatched, ready, run, runs, KeylessFrame}; -pub(crate) use settle::{returning, settle}; +pub(crate) use settle::{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 3637f9de9..6ee7de062 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -9,7 +9,9 @@ use revm::{ result::{HaltReason, OutOfGasError}, ContextError, ContextTr, FrameStack, JournalTr, }, - context_interface::{cfg::gas::GasTracker, journaled_state::account::JournaledAccountTr}, + 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, @@ -88,6 +90,32 @@ fn returns_into_the_call(stack: &mut FrameStack>) -> bo 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`]). /// @@ -111,7 +139,7 @@ fn returns_into_the_call(stack: &mut FrameStack>) -> bo /// 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 its budget: the call is held to its limits again without it, and the stop it returns on +/// 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, @@ -170,6 +198,9 @@ fn answer_of( ) -> (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); diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index e08e202ae..a062c4c1c 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -5,8 +5,8 @@ //! [`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. The EIP-7997 `CREATE2` factory -//! lives at its canonical address beside them; [`deploy`] is the single list that deploys all -//! seven. +//! 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` @@ -19,25 +19,25 @@ pub mod keyless; mod control; -mod deploy; mod intercept; mod limit_control; mod oracle; +mod predeploys; mod sequencer_registry; mod timestamp; mod tx; pub use control::*; -pub use deploy::*; 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 { @@ -60,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 e8b03e963..c4ab0bc23 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -14,9 +14,15 @@ 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"); @@ -29,8 +35,9 @@ 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 @@ -52,17 +59,20 @@ pub use mega_system_contracts::oracle::IOracle; /// 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 @@ -81,8 +91,10 @@ pub(crate) fn intercept( 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. @@ -90,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 c3f477f3a..f7cda377b 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -5,36 +5,35 @@ //! to it is an ordinary call. Its Solidity source is //! `crates/system-contracts/contracts/SequencerRegistry.sol`. //! -//! The contract is deployed by [`transact_deploy`](crate::system::transact_deploy) with the -//! bootstrap slots [`SequencerRegistryConfig`] names, before every block. 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 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 the transaction itself, and only by a transaction that has the system shape -//! ([`has_system_transaction_shape`](crate::system::has_system_transaction_shape)): validation -//! reads `_currentSystemAddress` from the journal without warming it ([`inspect_system_address`]) -//! and compares it with the caller. 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. +//! 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, U256}; +use alloy_primitives::{address, Address, Bytes, B256, U256}; use alloy_sol_types::SolCall; use op_revm::OpHaltReason; use revm::{ - context::result::ResultAndState, + context::{result::ResultAndState, JournalTr}, + primitives::KECCAK_EMPTY, state::{Account, EvmState, EvmStorageSlot, TransactionId}, }; -use super::MEGA_SYSTEM_ADDRESS; -use crate::{ - transact_pre_block_call, ExternalEnvTypes, HardforkParams, HardforkParamsError, - JournalInspectTr, MegaBlockExecutionError, MegaEvm, MegaHardfork, -}; +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, @@ -52,87 +51,16 @@ pub use mega_system_contracts::sequencer_registry::LATEST_CODE_HASH as SEQUENCER pub use mega_system_contracts::sequencer_registry::{storage_slots, ISequencerRegistry}; -/// Delay the unknown-chain placeholder seeds, in blocks. -/// -/// A zero delay would disable the reaction window the field exists to guarantee. Ten matches -/// the contract's own tests: long enough that a rotation cannot activate in the same block. -pub const PLACEHOLDER_MIN_ROTATION_DELAY: u64 = 10; - -/// Bootstrap configuration for the `SequencerRegistry`, attached to Satin via [`HardforkParams`]. -/// -/// These values seed the registry's storage on a fresh deploy. After that the live roles are -/// whatever the contract holds, rotated by the `applyPendingChanges()` pre-block call. The contract -/// has no setter for `_minRotationDelay`, so a matching-code registry cannot be repaired later -/// through this helper: the delay must be seeded here, and it must not be zero. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SequencerRegistryConfig { - /// Seeded into `_currentSystemAddress` and `_initialSystemAddress`. - pub initial_system_address: Address, - /// Seeded into `_currentSequencer` and `_initialSequencer`. - pub initial_sequencer: Address, - /// Seeded into `_admin`. - pub initial_admin: Address, - /// Seeded into `_initialFromBlock`: the first block at which historical lookups are valid. - pub initial_from_block: u64, - /// Seeded into `_minRotationDelay`. Must be nonzero: a zero delay disables the reaction - /// window the field exists to guarantee. - pub min_rotation_delay: u64, -} - -impl SequencerRegistryConfig { - /// Placeholder roles for a chain that has none published: [`MEGA_SYSTEM_ADDRESS`] for every - /// address, block zero, and [`PLACEHOLDER_MIN_ROTATION_DELAY`]. - /// - /// The unknown-chain fallback schedule uses this so a local chain can start. A real network - /// attaches the roles governance chose. - pub const fn placeholder() -> Self { - Self { - initial_system_address: MEGA_SYSTEM_ADDRESS, - initial_sequencer: MEGA_SYSTEM_ADDRESS, - initial_admin: MEGA_SYSTEM_ADDRESS, - initial_from_block: 0, - min_rotation_delay: PLACEHOLDER_MIN_ROTATION_DELAY, - } - } -} - -impl HardforkParams for SequencerRegistryConfig { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "SequencerRegistryConfig"; - - fn validate(&self) -> Result<(), HardforkParamsError> { - if self.initial_system_address.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.initial_system_address must not be zero".into(), - }); - } - if self.initial_sequencer.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.initial_sequencer must not be zero".into(), - }); - } - if self.initial_admin.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.initial_admin must not be zero".into(), - }); - } - if self.min_rotation_delay == 0 { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.min_rotation_delay must not be zero".into(), - }); - } - Ok(()) - } -} - /// 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 hands on whether or +/// 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. +/// 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 /// @@ -211,44 +139,80 @@ where 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. /// -/// `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. Block execution -/// never leaves such a registry behind — the pre-block deploy puts this code there or refuses the -/// block, and the contract writes no zero address — so these are states an EVM run outside block -/// execution may meet, and in none of them is any transaction a system-address transaction. +/// 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. /// -/// The registry's account and the one slot are loaded cold and without the code: they are in the -/// transaction's state, so a stateless witness carries the read, and the transaction's own access -/// to either pays what it would have paid without it. +/// `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 inspect_system_address( +pub(crate) fn load_system_address( journal: &mut J, -) -> Result, J::DBError> { - // The expected hash is the registry code this engine deploys, the latest version. When the +) -> 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. - if journal.inspect_account_code_hash(SEQUENCER_REGISTRY_ADDRESS)? != - SEQUENCER_REGISTRY_CODE_HASH - { - return Ok(None); - } - let current = journal - .inspect_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)? - .present_value(); - Ok((!current.is_zero()).then(|| Address::from_word(current.into()))) + (code_hash == SEQUENCER_REGISTRY_CODE_HASH && !current.is_zero()) + .then(|| Address::from_word(current.into())) } #[cfg(test)] mod tests { use super::*; - use crate::{MegaContext, MegaSpecId}; + use crate::{system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId}; use alloy_primitives::address; use revm::{ context::{BlockEnv, ContextTr, JournalTr, Transaction}, @@ -505,84 +469,113 @@ mod tests { /// Reads the live system address out of `db` through a fresh journal, and answers it with the /// journal the read left behind. - fn inspect(db: InMemoryDB) -> (Option
, revm::Journal) { + fn load(db: InMemoryDB) -> (Option
, revm::Journal) { let mut journal = revm::Journal::new(db); - let address = inspect_system_address(&mut journal).expect("the read succeeds"); + let address = load_system_address(&mut journal).expect("the read succeeds"); (address, journal) } - /// A registry holding the code this engine deploys names the address it stores. The read - /// leaves the registry's account and the one slot it read in the journal, cold, untouched and - /// unchanged: a witness of the read, and nothing a later access would find warm. - #[test] - fn test_inspect_answers_the_stored_system_address_and_warms_nothing() { - let db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); - let (address, journal) = inspect(db); - assert_eq!(address, Some(NEXT_SYSTEM_ADDRESS)); - + /// 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_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert!(registry.is_cold_transaction_id(journal.transaction_id), "the account stays cold"); + 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 stays cold"); + assert!(!slot.is_cold, "the slot is warm"); assert!(!slot.is_changed()); - assert_eq!(slot.present_value(), word(NEXT_SYSTEM_ADDRESS)); - assert!(journal.inner.journal.is_empty(), "the read leaves no journal entry"); + 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 - /// deploys: it names no address, and its slot is not read. + /// 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_inspect_refuses_the_v1_code_hash() { + fn test_the_read_refuses_the_v1_code_hash() { use mega_system_contracts::sequencer_registry::V1_0_0_CODE; - let (address, journal) = inspect(registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS))); + let (address, journal) = load(registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS))); assert_eq!(address, None); - assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].storage.is_empty()); + assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); } /// A registry holding foreign code names no address, whatever it stores. #[test] - fn test_inspect_refuses_foreign_code() { + fn test_the_read_refuses_foreign_code() { let db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); - let (address, journal) = inspect(db); + let (address, journal) = load(db); assert_eq!(address, None); - assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].storage.is_empty()); + 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_inspect_answers_no_address_for_a_zero_slot() { - let (address, journal) = inspect(registry_holding(SEQUENCER_REGISTRY_CODE, None)); + 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!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS] - .storage - .contains_key(&CURRENT_SYSTEM_ADDRESS)); + assert_warm_and_unchanged(&journal, U256::ZERO); } /// A state without the registry names no address, and the read records the account's - /// absence. + /// absence and the slot it would hold, zero. #[test] - fn test_inspect_answers_no_address_without_a_registry() { - let (address, journal) = inspect(InMemoryDB::default()); + fn test_the_read_answers_no_address_without_a_registry() { + let (address, journal) = load(InMemoryDB::default()); assert_eq!(address, None); - let registry = &journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(registry.is_loaded_as_not_existing()); - assert!(registry.storage.is_empty()); + 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_inspect_reports_a_database_error() { + 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 err = inspect_system_address(&mut revm::Journal::new(db)).expect_err("the read fails"); + 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 be3cecc34..a5c613f7c 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -8,18 +8,15 @@ //! //! A system-address transaction has a fixed shape //! ([`has_system_transaction_shape`]): a legacy transaction calling a contract on -//! [`MEGA_SYSTEM_TX_WHITELIST`]. Validation tests the shape first, on the transaction's own -//! fields, and only a transaction that has it reads the live system address out of the registry -//! and compares it with its caller ([`is_live_system_transaction`]). A transaction of any other -//! shape reads nothing and is never a system-address transaction, whoever sent it: one from the -//! system address is an ordinary transaction, validated and charged as a user's is. -//! -//! "Ordinary" is the engine's view, not the contracts': the Oracle's `onlySystemAddress` tests -//! the sender alone. So a non-legacy transaction signed by the system key to the Oracle is -//! accepted by the Oracle, and its writes land, executed as a user's transaction: it pays fees, -//! is held to every per-transaction limit, is detained, is priced by bucket, and pays history. -//! Both the legacy engine and this one refused it at validation before the shape test came -//! first. +//! [`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`]): @@ -28,37 +25,46 @@ //! - 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. +//! 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::{ContextTr, Transaction}, + context::{ContextTr, JournalTr, Transaction}, context_interface::{cfg::Cfg, result::InvalidTransaction}, handler::pre_execution::validate_account_nonce_and_code, }; use crate::{ - system::{inspect_system_address, ORACLE_CONTRACT_ADDRESS}, - types::MegaTransaction, - ExternalEnvTypes, JournalInspectTr, MegaContext, + system::ORACLE_CONTRACT_ADDRESS, types::MegaTransaction, ExternalEnvTypes, MegaContext, }; -/// The system address the unknown-chain placeholder schedule seeds the `SequencerRegistry` with. +/// The initial system address of the `SequencerRegistry`: the one Rex5 created it naming, which a +/// chain's registry holds until a rotation. /// /// 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 of the -/// system shape ([`has_system_transaction_shape`]), and never falls back to this address. +/// 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")`. /// @@ -90,9 +96,8 @@ pub fn check_if_mega_system_transaction( /// [`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 decides whether a transaction reads the live system address at all, so it looks at the -/// transaction's own fields only: the type, then the destination against the one-entry whitelist. -/// A transaction that fails it, which is almost every transaction, reads nothing. +/// 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 { @@ -101,35 +106,25 @@ pub fn has_system_transaction_shape(tx_type: u8, tx_kind: TxKind) -> bool { } } -/// Whether the running transaction is a system-address transaction: it has the system shape -/// ([`has_system_transaction_shape`]) and its caller is the live system address, read out of the -/// `SequencerRegistry` in the journal without warming it. +/// 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`]). /// -/// A transaction of any other shape reads nothing. The registry cannot change its system address -/// inside a block after the pre-block step — 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 same address, the -/// one the block's pre-block step left, and an EVM run outside block execution reads the one in -/// the state it runs on. A registry that names no trusted address (see the registry's reader) -/// makes no transaction a system-address transaction. -/// -/// # Errors -/// -/// The database's, when the registry's account or its slot cannot be read. -pub(crate) fn is_live_system_transaction( - ctx: &mut MegaContext, -) -> Result { - let tx = ctx.tx(); - if !has_system_transaction_shape(tx.tx_type(), tx.kind()) { +/// 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); } - let caller = tx.caller(); - Ok(inspect_system_address(ctx.journal_mut())? == Some(caller)) -} - -/// 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) + 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` @@ -139,7 +134,14 @@ pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address /// 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, and no per-transaction limit stops it, so @@ -154,18 +156,24 @@ pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bo 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 system-address transaction and promotes it to a deposit. /// -/// Called for the running transaction once [`is_live_system_transaction`] said it is one, before +/// 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), each under the configuration switch a user transaction -/// obeys. +/// here (see the module documentation): the chain id always, the nonce and the code each under +/// the configuration switch a user transaction obeys. +/// +/// 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, + check_account: bool, ) -> Result<(), ERROR> where DB: Database, @@ -173,29 +181,28 @@ where ERROR: From + From, { 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 (system_address, tx_nonce) = (ctx.tx().caller(), 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. @@ -209,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"); @@ -238,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] @@ -258,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)); } 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 27ba51acd..aeda79c25 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -9,9 +9,92 @@ use revm::{ }; use crate::system::{ - storage_slots::CURRENT_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + 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 { @@ -27,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; @@ -103,15 +192,31 @@ impl MemoryDatabase { self } - /// Installs the `SequencerRegistry` this engine deploys, naming `system_address` the live - /// system address: a legacy call from it to a whitelisted contract is then a system-address - /// transaction, as it is on a chain whose registry names it. - pub fn sequencer_registry(self, system_address: Address) -> Self { - self.account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE).account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - U256::from_be_bytes(system_address.into_word().0), - ) + /// 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 } } @@ -161,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, + } } } @@ -199,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 {}) } } @@ -208,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/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 5f53f6ee0..f3f3de534 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -9,6 +9,7 @@ mod neutral; mod opcode_gen; mod price_guard; mod scenario; +mod witness; pub use bytes::*; pub use database::*; @@ -19,3 +20,4 @@ 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 index 2fa41ea08..2306bee31 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -11,10 +11,16 @@ //! 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 neither the data-size, the KV nor the state-gas limit binds, at the transaction or -//! at 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. +//! 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 @@ -30,9 +36,13 @@ use revm::{ interpreter::instructions::{gas_table_spec, GasTable}, precompile::{PrecompileSpecId, Precompiles}, primitives::eip7954, + state::{Account, EvmState}, }; -use crate::{EthSpecId, ExternalEnvTypes, MegaEvm, MegaSpecId}; +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. @@ -90,7 +100,7 @@ pub fn neutral_precompiles(fork: EthSpecId) -> Option { /// 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 its Osaka base's. +/// instruction table carries Amsterdam's. pub fn neutral_gas_table(fork: EthSpecId) -> Option { neutral_cfg(fork)?; Some(gas_table_spec(fork)) @@ -113,6 +123,28 @@ pub fn neutralize_evm( 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::*; @@ -225,21 +257,22 @@ mod tests { } } - /// Satin's instruction table prices opcodes as its Osaka base does, so Osaka's static prices - /// change nothing; Amsterdam's differ in EIP-8038's two-read base for `EXTCODESIZE` and - /// `EXTCODECOPY` alone. + /// 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::OSAKA)); + let mut evm = MegaEvm::new(context(EthSpecId::AMSTERDAM)); let satin = *evm.all_mut().1.gas_table(); - assert_eq!(neutral_gas_table(EthSpecId::OSAKA), Some(satin)); + assert_eq!(neutral_gas_table(EthSpecId::AMSTERDAM), Some(satin)); - let amsterdam = neutral_gas_table(EthSpecId::AMSTERDAM).expect("a neutral fork"); + let osaka = neutral_gas_table(EthSpecId::OSAKA).expect("a neutral fork"); let changed: Vec<_> = - (0..=u8::MAX).filter(|&op| amsterdam[op as usize] != satin[op as usize]).collect(); + (0..=u8::MAX).filter(|&op| osaka[op as usize] != satin[op as usize]).collect(); assert_eq!(changed, vec![EXTCODESIZE, EXTCODECOPY]); - assert_eq!(amsterdam[EXTCODESIZE as usize], 200); + assert_eq!(osaka[EXTCODESIZE as usize], 100); + assert_eq!(satin[EXTCODESIZE as usize], 200); assert!(neutral_gas_table(EthSpecId::PRAGUE).is_none()); } @@ -249,11 +282,11 @@ mod tests { #[test] fn test_neutralize_evm_installs_the_fork_s_static_prices() { use revm::bytecode::opcode::EXTCODESIZE; - let mut evm = MegaEvm::new(context(EthSpecId::AMSTERDAM)); + 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], 100); - - assert!(neutralize_evm(&mut evm, EthSpecId::AMSTERDAM).is_some()); 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 641cf2031..0b288cf31 100644 --- a/crates/mega-evm/src/test_utils/opcode_gen.rs +++ b/crates/mega-evm/src/test_utils/opcode_gen.rs @@ -142,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) @@ -334,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 index 3b3c9b250..5eed4b57b 100644 --- a/crates/mega-evm/src/test_utils/price_guard.rs +++ b/crates/mega-evm/src/test_utils/price_guard.rs @@ -1,10 +1,15 @@ -//! The note a test leaves when the byte prices in effect leave it nothing to run. +//! 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`] appends its 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. +/// 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`. /// @@ -15,13 +20,35 @@ pub const PRICE_GUARD_LOG_ENV_VAR: &str = "MEGA_PRICE_GUARD_LOG"; /// 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: some tests return early, because {reason}"); + let _ = writeln!(std::io::stderr(), "note: {first}"); } if !noted.insert((test.clone(), reason.to_owned())) { return; 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 ce52889e3..000000000 --- a/crates/mega-evm/tests/_pending/README.md +++ /dev/null @@ -1,348 +0,0 @@ -# Pending tests - -The test inventory made for the engine rewrite kept a set of the legacy engine's tests; every one of them has since been ported into a real test target or retired, and none is parked here any more. -This file records where each one went: the sections below list them by the mechanism that ported or retired them. -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. - -The directory holds this record alone. -It has no `main.rs`, and Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`, so nothing here is built; do not add one. - -## Tests ported in place - -These rows came back with the code they test and run in `crates/mega-evm/src`. - -| 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 ported by the common execution layer - -These 45 rows run in a real test target now, adapted to the Satin API. - -| 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. - -| 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. - -| 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. - -| 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. - -| 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 ported by history gas - -These 28 rows run in a real test target now, adapted to the Satin API and to the history ledger the decision they cite fixes. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `rex4/storage_call_stipend.rs` | history gas (12) | 12 | `crates/mega-evm/src/limit/limit.rs`, `tests/satin/storage_call_stipend.rs` | -| `rex5/stipend_accounting.rs` | history gas (6) | 6 | `tests/satin/storage_call_stipend.rs` | -| `rex6/fee_reward_accounting.rs` | history gas (6) | 6 | `tests/satin/history_gas.rs` | -| `src/limit/limit.rs` | history gas (4) | 4 | `tests/satin/history_exemption.rs` | -| **Total** | | **28** | | - -## Tests ported by system contract deployment - -These 29 rows run in a real test target now, adapted to the Satin API and to the single-spec deploy. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `block_executor/sequencer_registry.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | -| `mini_rex/oracle.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | -| `rex2/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/block/deploy.rs` | -| `rex4/deployment.rs` | system contract deployment (2) | 2 | `tests/block/deploy.rs` | -| `src/system/control.rs` | system contract deployment (6) | 6 | `tests/system/control.rs`, `tests/system/deploy.rs` | -| `src/system/deploy.rs` | system contract deployment (1) | 1 | `tests/system/deploy.rs` | -| `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | `tests/system/deploy.rs` | -| `src/system/limit_control.rs` | system contract deployment (3) | 3 | `tests/system/deploy.rs` | -| `src/system/oracle.rs` | system contract deployment (4) | 4 | `tests/system/deploy.rs` | -| `src/system/sequencer_registry.rs` | system contract deployment (9) | 9 | `tests/block/deploy.rs`, `tests/system/deploy.rs` | -| **Total** | | **29** | | - -## Tests ported by compute gas - -These 24 rows run in a real test target now, adapted to the Satin API and to a compute figure read off the gas revm settles. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `compute_gas/claims.rs` | compute gas (2) | 2 | `tests/satin/compute_gas.rs` | -| `compute_gas/main.rs` | compute gas (1) | 1 | `tests/satin/compute_gas.rs` | -| `mini_rex/compute_gas_limit.rs` | compute gas (21) | 21 | `tests/satin/compute_gas.rs` | -| **Total** | | **24** | | - -## Tests ported by the data-size limit - -These 47 rows run in a real test target now, adapted to the Satin API and to the byte table and budget rule the decision they cite fixes. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `compute_gas/claims.rs` | the data-size limit (1) | 1 | `tests/satin/data_size.rs` | -| `mini_rex/tx_data_and_kv_update_limit.rs` | the data-size limit (18) | 18 | `tests/satin/data_size_counts.rs` | -| `rex4/frame_limits.rs` | the data-size limit (10) | 10 | `tests/satin/data_size.rs` | -| `rex4/intrinsic_limit_bypass.rs` | the data-size limit (9) | 9 | `tests/satin/data_size.rs`, `tests/satin/data_size_counts.rs` | -| `rex5/selfdestruct_beneficiary.rs` | the data-size limit (1) | 1 | `tests/satin/data_size_counts.rs` | -| `rex6/beneficiary_detention.rs` | the data-size limit (2) | 2 | `tests/satin/data_size_counts.rs` | -| `rex6/frame_local_accounting.rs` | the data-size limit (3) | 3 | `tests/satin/data_size_counts.rs` | -| `rex6/self_transfer_account_dedup.rs` | the data-size limit (1) | 1 | `tests/satin/data_size_counts.rs` | -| `src/limit/data_size.rs` | the data-size limit (2) | 2 | `crates/mega-evm/src/limit/frame_limit.rs`, `crates/mega-evm/src/limit/mod.rs` | -| **Total** | | **47** | | - -## Tests ported by the state-growth and KV limits - -These 54 rows run in a real test target now, adapted to the Satin API: the state growth they pin is held as EIP-8037 state gas by a per-transaction state-gas limit, and the KV updates they count are the write records the common execution layer keeps, held to a KV limit that follows the data-size limit's transaction and frame rules. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `block_executor/block_limits.rs` | the state-growth and KV limits (2) | 2 | `tests/block/limits.rs` | -| `mini_rex/state_growth_limit.rs` | the state-growth and KV limits (4) | 4 | `tests/satin/state_gas_limit.rs` | -| `mini_rex/tx_data_and_kv_update_limit.rs` | the state-growth and KV limits (6) | 6 | `tests/satin/kv_limit.rs` | -| `rex4/frame_limits.rs` | the state-growth and KV limits (9) | 9 | `tests/satin/kv_limit.rs` | -| `rex4/intrinsic_limit_bypass.rs` | the state-growth and KV limits (3) | 3 | `tests/satin/kv_limit.rs` | -| `rex5/eip7702_state_growth.rs` | the state-growth and KV limits (8) | 8 | `tests/satin/state_gas_limit.rs` | -| `rex5/selfdestruct_beneficiary.rs` | the state-growth and KV limits (4) | 4 | `tests/satin/state_gas_limit.rs` | -| `rex6/beneficiary_detention.rs` | the state-growth and KV limits (1) | 1 | `tests/satin/state_gas_limit.rs` | -| `rex6/eip7702_authority_accounting.rs` | the state-growth and KV limits (16) | 16 | `tests/satin/state_gas_limit.rs` | -| `src/limit/kv_update.rs` | the state-growth and KV limits (1) | 1 | `tests/satin/kv_limit.rs` | -| **Total** | | **54** | | - -## Tests ported by detention - -These 89 rows run in a real test target now, adapted to the Satin API and to the relative cap, the revert-class stop and the load-time marking the decisions they cite fix. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `mini_rex/access_beneficiary_balance.rs` | detention (9) | 9 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `mini_rex/block_env_access_tracking.rs` | detention (3) | 3 | `tests/satin/volatile_access.rs` | -| `mini_rex/block_env_gas_limit.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `mini_rex/compute_gas_limit.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `mini_rex/oracle.rs` | detention (5) | 5 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex/oracle.rs` | detention (3) | 3 | `tests/satin/volatile_access.rs` | -| `rex3/oracle_gas_limit.rs` | detention (7) | 7 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex3/system_address.rs` | detention (2) | 2 | `tests/satin/volatile_access.rs` | -| `rex4/access_control.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex4/beneficiary_detention.rs` | detention (12) | 12 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex4/gas_detention.rs` | detention (3) | 3 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex5/sandbox_accounting.rs` | detention (6) | 6 | `tests/system/keyless/detention.rs` | -| `rex5/selfdestruct_beneficiary.rs` | detention (2) | 2 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex6/beneficiary_detention.rs` | detention (13) | 13 | `tests/satin/detention.rs`, `tests/satin/volatile_access.rs` | -| `rex6/eip7702_authority_accounting.rs` | detention (2) | 2 | `tests/satin/volatile_access.rs` | -| `src/access/volatile.rs` | detention (4) | 4 | `crates/mega-evm/src/access/volatile.rs` | -| `src/limit/compute_gas.rs` | detention (1) | 1 | `tests/satin/detention.rs` | -| **Total** | | **89** | | - -## Tests ported by the oracle and control contracts - -These 77 rows run in a real test target now, adapted to the Satin API: the Oracle's storage is read through the oracle environment, `MegaAccessControl` steers gas detention's switch, and `remainingComputeGas()` answers from the caller's regular gas and detention's allowance, as the decisions they cite fix. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `mini_rex/oracle.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle_storage.rs` | -| `rex2/oracle_hint.rs` | the oracle and control contracts (6) | 6 | `tests/system/oracle.rs` | -| `rex4/access_control.rs` | the oracle and control contracts (46) | 46 | `tests/system/access_control.rs` | -| `rex4/limit_control.rs` | the oracle and control contracts (9) | 9 | `tests/system/remaining_compute_gas.rs` | -| `rex5/oracle_hint_metering.rs` | the oracle and control contracts (8) | 8 | `tests/system/oracle.rs` | -| `rex6/oracle_hint_volatile_access.rs` | the oracle and control contracts (4) | 4 | `tests/system/oracle.rs` | -| **Total** | | **77** | | - -## Tests ported by native keyless deployment - -These 69 rows run in a real test target now, adapted to the Satin API: a keyless deployment is a native creation below its `keylessDeploy` call, validated by the same rules and answered in the same error ABI, so what the sandbox merged back is counted, charged and limited as any frame's is. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `rex2/keyless_deploy.rs` | native keyless deployment (36) | 36 | `tests/system/keyless/charges.rs`, `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | -| `rex4/keyless_deploy.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/deploy.rs` | -| `rex5/db_error.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | -| `rex5/keyless_empty_code_logs.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/deploy.rs` | -| `rex5/keyless_fee_free.rs` | native keyless deployment (12) | 12 | `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | -| `rex5/keyless_gas_cap_postcap_recheck.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/rules.rs` | -| `rex5/keyless_replay_barrier.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/deploy.rs`, `tests/system/keyless/rules.rs` | -| `rex5/sandbox_accounting.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/charges.rs`, `tests/system/keyless/deploy.rs` | -| `rex6/keyless_sandbox_hardening.rs` | native keyless deployment (3) | 3 | `tests/system/keyless/deploy.rs` | -| `src/sandbox/execution.rs` | native keyless deployment (2) | 2 | `tests/system/keyless/rules.rs` | -| **Total** | | **69** | | - -## Tests ported by the pre-block system calls - -These 45 rows run in a real test target now, adapted to the Satin API: a system call runs on at most 30,000,000 of regular gas with the rest of its gas limit as its state-gas reservoir, priced at the minimum SALT bucket and held to no per-transaction limit; a pre-block call that does not succeed refuses the block; and a due `SequencerRegistry` change is applied by a pre-block call before the live system address is read out of the registry. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `block_executor/sequencer_registry.rs` | the pre-block system calls (7) | 7 | `tests/block/sequencer_registry.rs` | -| `rex5/apply_pending_changes_gas_budget.rs` | the pre-block system calls (4) | 4 | `tests/block/sequencer_registry.rs`, `tests/satin/system_call.rs` | -| `rex5/pre_block_system_calls.rs` | the pre-block system calls (11) | 11 | `tests/block/eips.rs` | -| `rex6/sequencer_registry_rotation.rs` | system contract deployment (5) | 5 | `tests/block/eips.rs`, `tests/block/sequencer_registry.rs` | -| `src/evm/mod.rs` | the pre-block system calls (3) | 3 | `src/evm/mod.rs` | -| `src/system/sequencer_registry.rs` | the pre-block system calls (9), system contract deployment (6) | 15 | `src/system/sequencer_registry.rs` | -| **Total** | | **45** | | - -## Tests ported by revert-class aborts - -These 17 rows run in a real test target now, adapted to the Satin API: a transaction-level limit — data size, KV updates, state gas or gas detention's compute limit — stops the transaction with a revert carrying `MegaLimitExceeded`, which settles like an EIP-8037 revert, where the legacy engine halted and rescued the remaining gas; a frame budget reverts its frame alone. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `mini_rex/access_beneficiary_balance.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | -| `mini_rex/block_env_gas_limit.rs` | revert-class aborts (3) | 3 | `tests/satin/stops.rs` | -| `mini_rex/oracle.rs` | revert-class aborts (3) | 3 | `tests/satin/stops.rs` | -| `mini_rex/tx_data_and_kv_update_limit.rs` | revert-class aborts (4) | 4 | `tests/satin/stops.rs` | -| `rex3/oracle_gas_limit.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | -| `rex4/beneficiary_detention.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | -| `rex4/frame_limits.rs` | revert-class aborts (1) | 1 | `tests/satin/stops.rs` | -| `rex4/gas_detention.rs` | revert-class aborts (2) | 2 | `tests/satin/stops.rs` | -| `rex5/oracle_hint_metering.rs` | revert-class aborts (1) | 1 | `tests/system/oracle.rs` | -| **Total** | | **17** | | - -## Tests ported by inspector support - -These 4 rows run in a real test target now, adapted to the Satin API: block execution admits an inspector only when it is declared an observer, so an inspector that answers a frame has no route to a block and is exercised on the EVM, where a frame it answers, or a failed frame it rewrites into a success, settles as a frame that kept nothing; and a body over the data-size limit is stopped before any inspector's answer to its first frame. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `block_executor/inspector.rs` | inspector support (3) | 3 | `tests/block/inspector.rs` | -| `rex4/intrinsic_limit_bypass.rs` | inspector support (1) | 1 | `tests/satin/inspector.rs` | -| **Total** | | **4** | | - -## Tests ported when the last rows were settled - -These 28 rows were the last ones parked, and run in a real test target now. -The CREATE and CREATE2 rows owed to the common execution layer keep their transactions and what Satin keeps of their expectations: the halt reasons, and the order in which revm's own `CREATE2` checks its operands, at the Satin init-code limit; what they compared with another legacy spec or read off the legacy compute ledger has no counterpart. -Six of them are the static-callee rows, whose Satin assertions already ran in `tests/satin/static_callee.rs` under the same names; the rest of each compared with a legacy spec. -The rows that waited for D57 and D58 take the answer the engine gives, which is Ethereum's: a preload-warm address (a precompile, the block beneficiary, an access-list address) is charged warm on its first touch, and a call or creation forwards all but a 64th of its gas. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `compute_gas/claims.rs` | none (5) | 5 | `tests/satin/inherited_costs.rs` | -| `mini_rex/gas.rs` | none (2) | 2 | `tests/satin/inherited_costs.rs` | -| `rex4/create_safety.rs` | the common execution layer (1) | 1 | `tests/satin/create_opcodes.rs` | -| `rex5/create2_empty_initcode.rs` | the common execution layer (5) | 5 | `tests/satin/create_opcodes.rs` | -| `rex5/create2_resize_gas_metering.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | -| `rex6/create2_metering_order.rs` | the common execution layer (11) | 11 | `tests/satin/create_opcodes.rs`, `tests/satin/static_callee.rs` | -| `rex6/error_paths.rs` | the common execution layer (2) | 2 | `tests/satin/create_opcodes.rs` | -| **Total** | | **28** | | - -## Tests retired after the inventory - -These 21 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. - -| Legacy file | Owner in the inventory | Tests | Why | -|---|---|---:|---| -| `mini_rex/compute_gas_limit.rs` | compute gas (2) | 2 | Satin's compute limit is the execution cap the spec fixes, not a limit a caller sets, so there is no zero or one limit to configure; a gas limit below a transaction's intrinsic gas is rejected at validation | -| `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 | -| `src/system/control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | -| `src/system/deploy.rs` | system contract deployment (3) | 3 | Satin has no bytecode upgrade path: a system address with different code is an error, not a storage-preserving upgrade; Satin has no bytecode upgrade path: a system address with different code is an error, not a force-created upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version table to pin | -| `src/system/keyless_deploy.rs` | system contract deployment (1) | 1 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | -| `src/system/limit_control.rs` | system contract deployment (2) | 2 | Satin is a single spec with no per-fork deploy gate: the contract is deployed at every block; Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade | -| `src/system/oracle.rs` | system contract deployment (3) | 3 | Satin does not overwrite foreign code: a system address with different code is an error, not an in-place upgrade; Satin is a single spec and ships one Oracle bytecode; there is no per-fork version gate to pin | -| **Total** | | **21** | | 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/protocol_limits.rs b/crates/mega-evm/tests/block/building_policy.rs similarity index 68% rename from crates/mega-evm/tests/block/protocol_limits.rs rename to crates/mega-evm/tests/block/building_policy.rs index b7f8c1532..e663d833a 100644 --- a/crates/mega-evm/tests/block/protocol_limits.rs +++ b/crates/mega-evm/tests/block/building_policy.rs @@ -1,13 +1,13 @@ -//! The chain's limits and the builder's policy: the limits a block is held to are the ones its -//! schedule carries, whatever the node puts in the block context, and a builder's policy changes -//! which transactions it packs, never what a packed block computes. +//! 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, MegaHardforkConfig, MegaTransactionExt, MegaTxEnvelope, + BlockLimits, LimitCheck, LimitKind, MegaSpecId, MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use op_alloy_consensus::OpReceiptEnvelope; @@ -83,84 +83,79 @@ fn tx_from( Recovered::new_unchecked(common::tx(0, to, input, gas_limit), sender) } -/// A schedule that carries `limits` the way a chain configuration does: through the checked -/// route, so the values are ones a chain may carry. -fn chain_with(limits: ProtocolLimits) -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated() - .with_params(common::registry_config()) - .with_params(limits) +/// 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) } -/// A chain whose limits are not the defaults is held to its own: a transaction that crosses the -/// chain's data-size limit is stopped at that limit, and the block refuses a transaction once it -/// reached the chain's KV budget. The node passed no limits at all. +/// 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_block_is_held_to_the_limits_its_chain_carries() { - // One storage write fits the transaction's data size; a second crosses it. - let tx_data_size_limit = TX_BODY_SIZE + WRITE_RECORD_SIZE; - let limits = ProtocolLimits::DEFAULT - .with_tx_runtime_limits( - ProtocolLimits::DEFAULT.tx_runtime_limits.with_tx_data_size_limit(tx_data_size_limit), - ) - .with_block_kv_update_limit(1); - assert_ne!(limits, ProtocolLimits::DEFAULT); +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 mut state = State::builder().with_database(database()).build(); - let mut executor = common::executor_with_spec( - &mut state, - common::block_ctx(BlockLimits::default()), - chain_with(limits), + 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), ); - assert_eq!(executor.protocol_limits(), Some(&limits)); - assert_eq!(*executor.evm().tx_runtime_limits(), limits.tx_runtime_limits); - assert_eq!(executor.limiter().limits.block_kv_update_limit, 1); + + 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"); - // Two writes: stopped at the chain's transaction limit, and included with the stop. let outcome = executor - .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), GAS_LIMIT)) + .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 * WRITE_RECORD_SIZE, + 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.write_records, 0, "the stop kept no record"); + 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" + ); - // One write fits, and fills the chain's KV budget. let outcome = executor - .run_transaction(&tx_from(SENDERS[1], WRITES_ONE, Bytes::new(), GAS_LIMIT)) + .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.write_records, 1); - - // The block has reached the chain's KV budget: the next transaction is refused. - let err = executor - .run_transaction(&tx_from(SENDERS[2], WRITES_ONE, Bytes::new(), GAS_LIMIT)) - .expect_err("the block's write records have reached the chain's limit"); - assert!(err.to_string().contains("Block KV update limit reached"), "{err}"); - assert!(err.to_string().contains("limit=1"), "{err}"); - - // On the default chain the same two-write transaction keeps both writes. - let mut state = State::builder().with_database(database()).build(); - let mut executor = common::executor_with_spec( - &mut state, - common::unlimited_ctx(), - chain_with(ProtocolLimits::DEFAULT), + 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" ); - executor.apply_pre_execution_changes().expect("the block starts"); - let outcome = executor - .run_transaction(&tx_from(SENDERS[0], WRITES_TWO, Bytes::new(), GAS_LIMIT)) - .expect("the transaction runs"); - assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); - assert_eq!(outcome.inner.limit_exceeded, None); } /// What a block produced, with the state it left behind: the receipts, the counters and every @@ -175,7 +170,7 @@ struct Block { slots: Vec, } -/// Executes `candidates` in order on a fresh block of the chain `limits` describes, packed under +/// 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( @@ -185,8 +180,7 @@ fn build( ) -> (Block, Vec>) { let mut state = State::builder().with_database(database()).build(); let result = { - let mut executor = - common::executor_with_spec(&mut state, common::block_ctx(policy), chain_with(limits)); + let mut executor = executor_under(&mut state, policy, limits); executor.apply_pre_execution_changes().expect("the block starts"); let packed: Vec<_> = candidates .iter() @@ -219,13 +213,14 @@ fn build( } /// 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 chain'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. A -/// validator on a chain whose limits differ does not, which is why those travel with the chain. +/// 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::DEFAULT; + 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; @@ -243,7 +238,7 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl 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 chain's. + // 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]); @@ -287,7 +282,7 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl 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 chain's own data-size budget" + "the block is well inside the protocol's own data-size budget" ); let block: Vec<_> = packed.iter().map(|index| candidates[*index].clone()).collect(); @@ -302,10 +297,10 @@ fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_bl assert_eq!(validated, built, "{policy:?}: the validator computes the builder's block"); } - // The same block under a chain whose limits differ computes a different result: the first - // transaction's write crosses that chain's data-size limit and is stopped. - let stricter = ProtocolLimits::DEFAULT.with_tx_runtime_limits( - ProtocolLimits::DEFAULT.tx_runtime_limits.with_tx_data_size_limit(TX_BODY_SIZE + 32), + // 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"); diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 7148b4908..f4358c7a2 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -1,20 +1,25 @@ //! 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::{ - system::{IOracle, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - test_utils::MemoryDatabase, + 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, PreBlockStateSource, ProtocolLimits, + MegaTxEnvelope, ProtocolLimits, }; use op_alloy_consensus::TxDeposit; use revm::{ @@ -24,7 +29,6 @@ use revm::{ inspector::NoOpInspector, state::EvmState, }; -use std::sync::{Arc, Mutex}; /// The sender every test transaction comes from. pub(crate) const CALLER: Address = address!("0x2000000000000000000000000000000000000002"); @@ -44,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 @@ -70,48 +75,62 @@ pub(crate) fn evm_env() -> EvmEnv { EvmEnv::new(cfg_env, block_env) } -/// The sequencer the tests seed into the registry, distinct from the system address and admin. +/// The sequencer the tests' registry names, distinct from the system address and admin. pub(crate) const SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); -/// The admin the tests seed into the registry, distinct from the system address and sequencer. +/// The admin the tests' registry names, distinct from the system address and sequencer. pub(crate) const ADMIN: Address = address!("0x3333333333333333333333333333333333333333"); -/// Registry params the block tests attach to a Satin-at-genesis schedule. -pub(crate) fn registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - initial_system_address: MEGA_SYSTEM_ADDRESS, - initial_sequencer: SEQUENCER, - initial_admin: ADMIN, - initial_from_block: 1, +/// 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, can seed the `SequencerRegistry`, and holds its -/// blocks to the loosest limits a chain may carry. +/// A schedule that activates Satin at genesis. /// -/// Its limits are [`ProtocolLimits::loosest`]: most block tests exercise one mechanism and take -/// the limits out, and a test that holds a block or a transaction to a limit attaches its own -/// ([`chain_spec_with`]). Every limit is unlimited but gas detention's caps, which no transaction -/// of a block this size reaches, so a transaction that reads volatile data is detained and never -/// stopped. +/// 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 { - chain_spec_with(ProtocolLimits::loosest()) + MegaHardforkConfig::default().with_all_activated() } -/// [`chain_spec`], holding its blocks to `limits`, which must be limits a chain may carry: the -/// block executor refuses a block under any other. -pub(crate) fn chain_spec_with(limits: ProtocolLimits) -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated() - .with_params(registry_config()) - .with_params(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 [`ProtocolLimits::loosest`], for a test that holds a block's -/// transactions to one limit and no other. +/// The per-transaction half of [`loosest`]. pub(crate) const fn loosest_tx() -> EvmTxRuntimeLimits { - ProtocolLimits::loosest().tx_runtime_limits + 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`. @@ -169,13 +188,13 @@ pub(crate) fn executor_with_env( build(state, ctx, env, chain_spec()) } -/// An executor over `state`, for a block the chain holds to `limits`, packed under no building -/// policy. +/// 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(limits)) + build(state, unlimited_ctx(), evm_env(), chain_spec()).with_protocol_limits(limits) } /// An executor over `state`, for a block on the chain `spec` describes. @@ -208,24 +227,68 @@ fn build( MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } -/// Shared log of pre-block states an executor observer records. -pub(crate) type PreBlockLog = Arc>>; - -/// Installs a recording observer on `executor` and returns the log it writes. -pub(crate) fn record_pre_block(executor: &mut TestExecutor<'_>) -> PreBlockLog { - let log = Arc::new(Mutex::new(Vec::new())); - let captured = Arc::clone(&log); - executor.set_pre_block_observer(Some(Box::new( - move |source: PreBlockStateSource, state: &EvmState| { - captured.lock().expect("pre-block observer").push((source, state.clone())); - }, - ))); - log +/// 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() + }) + }) } -/// The states the log holds, in execution order. -pub(crate) fn pre_block_states(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { - log.lock().expect("pre-block observer").clone() +/// 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 @@ -241,22 +304,35 @@ 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. diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 8f2489b32..9c6557888 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -5,7 +5,7 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ test_utils::{transfer_log, BytecodeBuilder}, - BlockGasCounters, BlockLimits, MegaTxEnvelope, + BlockGasCounters, MegaTxEnvelope, }; use revm::{ bytecode::opcode::{CALL, LOG0, LOG3, POP, PUSH0}, @@ -104,90 +104,6 @@ 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. -#[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); -} - -/// A deposit is not a transaction the builder chose: the block derived from L1 must include it, -/// so the execution-gas limit never refuses one, however far past it the block is. It still -/// counts, so an ordinary transaction after the deposits finds the room they used. -#[test] -fn test_a_deposit_is_never_refused_by_the_execution_limit() { - let deposit = || common::deposit_tx_to(RECIPIENT, Bytes::new(), 1_000_000); - - // What one deposit spends on the execution ledger, so two of them cross the limit below. - 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(&deposit()).expect("the probe executes"); - probe.gas().execution - }; - assert!(spent > 0); - - let mut state = state_with_writer(); - let mut executor = executor( - &mut state, - common::block_ctx( - BlockLimits::no_limits().with_block_execution_gas_limit(spent + spent / 2), - ), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor.execute_transaction(&deposit()).expect("the block has room"); - executor.execute_transaction(&deposit()).expect("the deposit that crosses the limit"); - assert_eq!(executor.gas().execution, 2 * spent, "two deposits crossed the limit between them"); - - executor - .execute_transaction(&deposit()) - .expect("a deposit is included whatever the block's execution gas"); - assert_eq!(executor.gas().execution, 3 * spent, "and it counts"); - - // Each deposit bumped the sender's nonce, so this one is valid and refused for room alone. - let err = executor - .execute_transaction(&user_tx(3, 1_000_000)) - .expect_err("an ordinary transaction finds no execution gas left"); - assert!(format!("{err}").contains("Block execution gas limit reached"), "{err}"); - assert!(format!("{err}").contains(&format!("block_used={}", 3 * spent)), "{err}"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 3); - assert_eq!(result.gas.execution, 3 * spent); -} - /// 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. @@ -317,3 +233,83 @@ fn test_a_floor_bound_transaction_adds_its_floor_to_the_block() { 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, + ) + }; + + // 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/deploy.rs b/crates/mega-evm/tests/block/deploy.rs deleted file mode 100644 index 92317ed33..000000000 --- a/crates/mega-evm/tests/block/deploy.rs +++ /dev/null @@ -1,315 +0,0 @@ -//! System contract deployment at the start of a block, and the EIP-7997 factory round trip. - -use alloy_evm::block::BlockExecutor; -use alloy_primitives::{Address, Bytes, B256, U256}; -use mega_evm::{ - system::{ - keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, - storage_slots::{ - ADMIN as ADMIN_SLOT, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, - INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, - }, - SequencerRegistryConfig, 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, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_DEPLOY_COUNT, - }, - test_utils::MemoryDatabase, - MegaHardfork, MegaHardforkConfig, MegaHardforks, PreBlockStateSource, ProtocolLimits, -}; -use revm::{context::result::ExecutionResult, database::State, state::Account, Database}; - -use crate::common::{ - self, executor, executor_with_spec, pre_block_states, record_pre_block, recovered, - registry_config, tx, unlimited_ctx, ADMIN, SEQUENCER, -}; - -fn expected_hashes() -> [(Address, B256); SYSTEM_CONTRACT_DEPLOY_COUNT] { - [ - (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), - ] -} - -fn assert_deployed(state: &mut State) { - for (address, hash) in expected_hashes() { - let info = state.basic(address).expect("readable").expect("deployed"); - assert_eq!(info.code_hash, hash, "{address} has the wrong code"); - assert_eq!(info.nonce, 1, "{address} is a created contract"); - assert!(info.code.is_some(), "{address} carries its bytecode"); - } -} - -fn deploy_sources() -> [PreBlockStateSource; SYSTEM_CONTRACT_DEPLOY_COUNT] { - expected_hashes().map(|(address, _)| PreBlockStateSource::SystemContract(address)) -} - -/// The two EIP calls, the seven deploys, then the read of the registry's pending changes, which -/// finds none due on these blocks. The live system address is not read before the block: a -/// system-address transaction reads it itself. -fn assert_pre_block_order(outcomes: &[(PreBlockStateSource, revm::state::EvmState)]) { - assert_eq!(outcomes.len(), 2 + SYSTEM_CONTRACT_DEPLOY_COUNT + 1); - assert_eq!(outcomes[0].0, PreBlockStateSource::Eip2935); - assert_eq!(outcomes[1].0, PreBlockStateSource::Eip4788); - for (i, source) in deploy_sources().iter().enumerate() { - assert_eq!(outcomes[2 + i].0, *source); - } - assert_eq!(outcomes[2 + SYSTEM_CONTRACT_DEPLOY_COUNT].0, PreBlockStateSource::PendingChanges); -} - -fn assert_registry_account_seed(account: &Account, config: &SequencerRegistryConfig) { - let addr_val = |address: Address| U256::from_be_bytes(address.into_word().0); - let slot = |key: U256| account.storage.get(&key).expect("seeded").present_value; - assert_eq!(slot(CURRENT_SYSTEM_ADDRESS), addr_val(config.initial_system_address)); - assert_eq!(slot(CURRENT_SEQUENCER), addr_val(config.initial_sequencer)); - assert_eq!(slot(ADMIN_SLOT), addr_val(config.initial_admin)); - assert_eq!(slot(INITIAL_SYSTEM_ADDRESS), addr_val(config.initial_system_address)); - assert_eq!(slot(INITIAL_SEQUENCER), addr_val(config.initial_sequencer)); - assert_eq!(slot(INITIAL_FROM_BLOCK), U256::from(config.initial_from_block)); - assert_eq!(slot(MIN_ROTATION_DELAY), U256::from(config.min_rotation_delay)); -} - -fn assert_registry_seed(state: &mut State, config: &SequencerRegistryConfig) { - let addr_val = |address: Address| U256::from_be_bytes(address.into_word().0); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS).unwrap(), - addr_val(config.initial_system_address) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER).unwrap(), - addr_val(config.initial_sequencer) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN_SLOT).unwrap(), - addr_val(config.initial_admin) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SYSTEM_ADDRESS).unwrap(), - addr_val(config.initial_system_address) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SEQUENCER).unwrap(), - addr_val(config.initial_sequencer) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_FROM_BLOCK).unwrap(), - U256::from(config.initial_from_block) - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY).unwrap(), - U256::from(config.min_rotation_delay) - ); -} - -/// The first block deploys all seven predeploys with the pinned hashes, nonce 1, and the -/// registry's seeded slots. The executor's own observer sees the two EIP calls, the seven deploy -/// states and the two reads of the registry, in that order. -#[test] -fn test_the_first_block_deploys_every_system_contract() { - let mut state = common::state(); - let outcomes = { - let mut executor = executor(&mut state, unlimited_ctx()); - let log = record_pre_block(&mut executor); - executor.apply_pre_execution_changes().expect("the block starts"); - assert_eq!(executor.gas().execution, 0); - assert_eq!(executor.gas().state, 0); - assert_eq!(executor.gas().history, 0); - pre_block_states(&log) - }; - assert_pre_block_order(&outcomes); - let config = registry_config(); - for (i, (address, hash)) in expected_hashes().into_iter().enumerate() { - let account = outcomes[2 + i] - .1 - .get(&address) - .unwrap_or_else(|| panic!("{address} is in the deploy state")); - assert!(account.is_touched(), "{address} is touched"); - assert!(account.is_created(), "{address} is created"); - assert_eq!(account.info.code_hash, hash, "{address} has the wrong code"); - assert_eq!(account.info.nonce, 1, "{address} is a created contract"); - if address == SEQUENCER_REGISTRY_ADDRESS { - assert_registry_account_seed(account, &config); - } else { - assert!(account.storage.is_empty(), "{address} has no seeded storage"); - } - } - assert_deployed(&mut state); - assert_registry_seed(&mut state, &config); - assert_eq!(config.initial_system_address, MEGA_SYSTEM_ADDRESS); - assert_eq!(config.initial_sequencer, SEQUENCER); - assert_eq!(config.initial_admin, ADMIN); -} - -/// A second block changes nothing in the seven deploys: the executor's own observer reports -/// exactly seven read-only account entries, the two EIP calls still precede them and the two -/// reads of the registry follow them. -#[test] -fn test_the_second_block_is_seven_read_only_entries() { - let mut state = common::state(); - { - let mut executor = executor(&mut state, unlimited_ctx()); - executor.apply_pre_execution_changes().expect("the first block deploys"); - } - - let outcomes = { - let mut executor = executor(&mut state, unlimited_ctx()); - let log = record_pre_block(&mut executor); - executor.apply_pre_execution_changes().expect("the second block is a no-op"); - assert_eq!(executor.gas().execution, 0); - assert_eq!(executor.gas().state, 0); - assert_eq!(executor.gas().history, 0); - pre_block_states(&log) - }; - assert_pre_block_order(&outcomes); - for (i, (address, hash)) in expected_hashes().into_iter().enumerate() { - let state = &outcomes[2 + i].1; - assert_eq!(state.len(), 1, "{address} is the only account in its witness"); - let account = state.get(&address).unwrap(); - assert!(!account.is_touched(), "{address} is not touched"); - assert!(!account.is_created(), "{address} is not created"); - assert!(account.storage.is_empty(), "{address} is not re-seeded"); - assert_eq!(account.info.code_hash, hash); - } - assert_deployed(&mut state); - assert_registry_seed(&mut state, ®istry_config()); -} - -/// A factory that already holds the right code is left as it is, including a balance it already -/// had. -#[test] -fn test_a_pre_existing_factory_with_the_right_code_is_untouched() { - let mut db = common::database(); - db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); - db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 1); - db.set_account_balance(CREATE2_FACTORY_ADDRESS, U256::from(42)); - 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"); - } - - let info = state.basic(CREATE2_FACTORY_ADDRESS).unwrap().unwrap(); - assert_eq!(info.code_hash, CREATE2_FACTORY_CODE_HASH); - assert_eq!(info.nonce, 1); - assert_eq!(info.balance, U256::from(42), "a matching factory keeps its balance"); -} - -/// A factory that already holds the right code but nonce 0 fails the block: EIP-7997 requires a -/// nonzero nonce, and the matching-code path will not rewrite it. -#[test] -fn test_a_factory_with_matching_code_and_nonce_zero_fails_the_block() { - let mut db = common::database(); - db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); - db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 0); - let mut state = State::builder().with_database(db).build(); - let mut executor = executor(&mut state, unlimited_ctx()); - let err = executor - .apply_pre_execution_changes() - .expect_err("a zero-nonce factory must fail the block"); - let message = err.to_string(); - assert!(message.contains("nonce 0"), "unexpected error: {message}"); - assert!(message.contains(&CREATE2_FACTORY_ADDRESS.to_string())); -} - -/// An empty-code account with a used nonce at a system address fails the block rather than -/// being reset to a fresh deploy. -#[test] -fn test_a_used_empty_account_at_a_system_address_fails_the_block() { - let mut db = common::database(); - db.set_account_nonce(ORACLE_CONTRACT_ADDRESS, 42); - let mut state = State::builder().with_database(db).build(); - let mut executor = executor(&mut state, unlimited_ctx()); - let err = executor - .apply_pre_execution_changes() - .expect_err("a used empty account must fail the block"); - let message = err.to_string(); - assert!(message.contains("nonce 42"), "unexpected error: {message}"); - assert!(message.contains(&ORACLE_CONTRACT_ADDRESS.to_string())); -} - -/// Foreign code at any of the seven addresses fails the block. -#[test] -fn test_foreign_code_at_a_system_address_fails_the_block() { - for (address, _) in expected_hashes() { - let mut db = common::database(); - db.set_account_code(address, Bytes::from_static(&[0xfe])); - let mut state = State::builder().with_database(db).build(); - let mut executor = executor(&mut state, unlimited_ctx()); - let err = - executor.apply_pre_execution_changes().expect_err("foreign code must fail the block"); - let message = err.to_string(); - assert!( - message.contains("refusing to overwrite"), - "{address}: unexpected error: {message}" - ); - assert!(message.contains(&address.to_string()), "{address}: error names the address"); - } -} - -/// A scheduled Satin without registry params fails at load, and a block built from one anyway -/// fails when it tries to deploy. -#[test] -fn test_missing_registry_params_fail_at_load_and_at_the_block() { - let missing = MegaHardforkConfig::default() - .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)) - .with_params(ProtocolLimits::DEFAULT); - assert_eq!( - missing.validate_schedule().unwrap_err().to_string(), - "hardfork Satin is scheduled but its SequencerRegistryConfig params are not configured" - ); - - let mut state = common::state(); - let mut executor = executor_with_spec(&mut state, unlimited_ctx(), missing); - let err = executor - .apply_pre_execution_changes() - .expect_err("a block without registry params cannot deploy"); - assert!(err.to_string().contains("SequencerRegistryConfig"), "unexpected error: {err}"); -} - -/// 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 factory is deployed"); - - 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/deposits.rs b/crates/mega-evm/tests/block/deposits.rs index 64dcec28a..847284bac 100644 --- a/crates/mega-evm/tests/block/deposits.rs +++ b/crates/mega-evm/tests/block/deposits.rs @@ -1,23 +1,24 @@ -//! A deposit is never refused by a block's packing budgets. +//! A deposit is never refused by a block's packing budget. //! -//! The execution-gas, state-gas, data-size and KV limits of a block budget the transactions its -//! builder chooses. A deposit is not chosen: the block derived from L1 must include it. So none -//! of the four refuses a deposit — not before it executes, not after, and not when an outcome -//! executed earlier is committed through either commit path — and every deposit still counts -//! towards all four, so the ordinary transactions after the deposits find the room they used. +//! 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, Signed, TxLegacy}; +use alloy_consensus::{transaction::Recovered, Sealed}; use alloy_evm::block::BlockExecutor; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +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, CHAIN_ID}; +use crate::common::{self, executor}; /// Sets the slot the first calldata word names to one. const WRITER: Address = address!("0x1000000000000000000000000000000000000d01"); @@ -48,6 +49,9 @@ fn state() -> State { .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() } @@ -58,31 +62,40 @@ fn input(slot: u64) -> Bytes { Bytes::from(input) } -/// A deposit that fills the fresh `slot`: execution gas, state gas, data size and a write record, -/// all four. -fn deposit(slot: u64) -> Recovered { - common::deposit_tx_to(WRITER, input(slot), gas_limit()) +/// 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) } -/// An ordinary transaction that fills the fresh `slot`, so each of the four limits has something -/// to refuse it on. -fn ordinary(slot: u64) -> Recovered { - let tx = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce: 0, - gas_price: 1_000_000, - gas_limit: gas_limit(), +/// 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), }; - Recovered::new_unchecked( - MegaTxEnvelope::Legacy(Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::repeat_byte(0x0d), - )), + 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, ) } @@ -99,50 +112,6 @@ fn one_deposit() -> (BlockGasCounters, LimitUsage) { (gas, usage) } -/// The block limits the test holds a block to. -#[derive(Clone, Copy, Debug)] -enum Cap { - ExecutionGas, - StateGas, - DataSize, - KvUpdates, - All, -} - -impl Cap { - /// Limits with room for a deposit and a half on this cap, so the second deposit crosses it. A - /// deposit keeps one record, so on the write records that is room for one. - fn limits(self, gas: &BlockGasCounters, usage: &LimitUsage) -> BlockLimits { - let half_again = |one: u64| one + one / 2; - let limits = BlockLimits::no_limits(); - let execution = limits.with_block_execution_gas_limit(half_again(gas.execution)); - let state = limits.with_block_state_gas_limit(half_again(gas.state)); - let data = limits.with_block_txs_data_limit(half_again(usage.data_size)); - let kv = limits.with_block_kv_update_limit(half_again(usage.write_records)); - match self { - Self::ExecutionGas => execution, - Self::StateGas => state, - Self::DataSize => data, - Self::KvUpdates => kv, - Self::All => execution - .with_block_state_gas_limit(half_again(gas.state)) - .with_block_txs_data_limit(half_again(usage.data_size)) - .with_block_kv_update_limit(half_again(usage.write_records)), - } - } - - /// What the refusal of the ordinary transaction names. With all four limits reached, the - /// execution-gas limit is the first the block checks. - const fn refusal(self) -> &'static str { - match self { - Self::ExecutionGas | Self::All => "Block execution gas limit reached", - Self::StateGas => "Block state gas limit reached", - Self::DataSize => "Block transactions data limit reached", - Self::KvUpdates => "Block KV update limit reached", - } - } -} - /// How the deposits reach the block. #[derive(Clone, Copy, Debug)] enum Route { @@ -156,91 +125,85 @@ enum Route { TraitCommit, } -/// Deposits cross each block limit and are included all the same, through every route; each one -/// counts towards all four dimensions; and an ordinary transaction after them is refused — before -/// it executes, and, as a candidate executed before the deposits committed, at its commit. +/// 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(); - for cap in [Cap::ExecutionGas, Cap::StateGas, Cap::DataSize, Cap::KvUpdates, Cap::All] { - // A deposit that adds no state gas cannot cross a state-gas cap, and the ordinary - // transaction after it adds none to be refused for. - if matches!(cap, Cap::StateGas) && common::state_is_free() { - continue; - } - for route in [Route::OneByOne, Route::CheckedCommit, Route::TraitCommit] { - let name = format!("{cap:?} by {route:?}"); - let limits = cap.limits(&gas, &usage); - 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}")); - } + // 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( + } + Route::CheckedCommit | Route::TraitCommit => { + let deposits: Vec<_> = (1..=3) + .map(|slot| { 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); - } + .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.gas().execution > limits.block_execution_gas_limit || - executor.gas().state > limits.block_state_gas_limit || - executor.limiter().usage.data_size > limits.block_txs_data_limit || - executor.limiter().usage.write_records > limits.block_kv_update_limit, - "{name}: the deposits crossed the limit", - ); - + 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 - .execute_transaction(&ordinary(101)) - .expect_err("an ordinary transaction finds the room the deposits used"); - assert!(format!("{err}").contains(cap.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(cap.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}"); + .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 index e7a5be16b..7a67dd985 100644 --- a/crates/mega-evm/tests/block/detention.rs +++ b/crates/mega-evm/tests/block/detention.rs @@ -5,7 +5,6 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::Bytes; use mega_evm::{ constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, LimitCheck, LimitKind, - ProtocolLimits, }; use revm::{ bytecode::opcode::{JUMP, JUMPDEST, MCOPY, POP, PUSH0, TIMESTAMP}, @@ -38,13 +37,9 @@ fn test_a_stopped_transaction_is_included_with_a_failed_receipt_that_bills_what_ 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 chain's default holds the spec's detention caps. - let mut executor = executor_with_env_and_spec( - &mut state, - common::unlimited_ctx(), - env, - common::chain_spec_with(ProtocolLimits::DEFAULT), - ); + // 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; diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index b61bdb7e2..6a72eb556 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -2,8 +2,8 @@ //! //! 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. A call that does not succeed refuses the block, and its state -//! reaches neither the observer nor the database. +//! 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. @@ -22,9 +22,9 @@ use alloy_primitives::{Address, Bytes, B256, U256}; use mega_evm::{ constants::SLOT_STATE_GAS, pre_block_call_gas_limit, - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + test_utils::{BytecodeBuilder, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, PreBlockStateSource, ProtocolLimits, + MegaSpecId, }; use revm::{ bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, @@ -34,8 +34,7 @@ use revm::{ }; use crate::common::{ - self, executor_with_env, executor_with_env_and_spec, pre_block_states, record_pre_block, - BLOCK_NUMBER, + self, call_state, eip_calls, executor_with_env, executor_with_env_and_spec, BLOCK_NUMBER, }; /// The parent hash the EIP-2935 call records. @@ -56,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(); @@ -109,25 +121,18 @@ fn pre_block_calls( recorded(&mut state) } -/// The pre-block calls a block at `number` on the chain `spec` describes handed to the observer, -/// in order, and whether the block started. -fn observed_calls( +/// 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>) { +) -> (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 log = record_pre_block(&mut executor); let started = executor.apply_pre_execution_changes(); - let calls = pre_block_states(&log) - .into_iter() - .map(|(source, _)| source) - .filter(|source| { - matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) - }) - .collect(); - (calls, started) + (eip_calls(&committed.states()), started) } /// The environment of a block at [`BLOCK_NUMBER`] whose gas limit is `gas_limit`. @@ -151,24 +156,17 @@ fn fresh_writes(slots: u16) -> Bytes { .build() } -/// Starts a block at [`BLOCK_NUMBER`] in `env` over `db` and reports the pre-block calls the -/// observer received, and how the block's start ended. +/// 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>) { +) -> (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 log = record_pre_block(&mut executor); let started = executor.apply_pre_execution_changes(); - let calls = pre_block_states(&log) - .into_iter() - .map(|(source, _)| source) - .filter(|source| { - matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) - }) - .collect(); - (calls, started) + (eip_calls(&committed.states()), started) } /// Both calls run on a block of a chain past Prague and Cancun, and the executor commits what @@ -182,18 +180,97 @@ 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 limits a chain may carry, which their bodies, their writes and their state gas cross, -/// both calls still record. +/// 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 limits = common::loosest_tx() - .with_tx_data_size_limit(mega_evm::TX_BODY_SIZE) - .with_frame_data_size_limit(1) - .with_tx_kv_update_limit(1) - .with_frame_kv_update_limit(1) - .with_tx_state_gas_limit(1); - let spec = common::chain_spec_with(ProtocolLimits::loosest().with_tx_runtime_limits(limits)); - assert_eq!(pre_block_calls(spec, BLOCK_NUMBER, ctx()), (PARENT_HASH, PARENT_BEACON_ROOT)); + 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 @@ -208,9 +285,9 @@ fn test_the_block_hashes_call_waits_for_prague() { "nothing was recorded for the parent hash" ); - let (calls, started) = observed_calls(before_prague, BLOCK_NUMBER, ctx()); + let (calls, started) = committed_calls(before_prague, BLOCK_NUMBER, ctx()); started.expect("a block before Prague starts"); - assert_eq!(calls, [PreBlockStateSource::Eip4788], "no block hashes call reached the observer"); + 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 @@ -225,9 +302,9 @@ fn test_the_beacon_root_call_waits_for_cancun() { "nothing was recorded for the beacon root" ); - let (calls, started) = observed_calls(before_cancun, BLOCK_NUMBER, ctx_without_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, [PreBlockStateSource::Eip2935], "no beacon root call reached the observer"); + 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 @@ -247,16 +324,16 @@ fn test_the_genesis_block_makes_no_pre_block_call() { "neither contract was called" ); - let (calls, started) = observed_calls(common::chain_spec(), 0, genesis); + let (calls, started) = committed_calls(common::chain_spec(), 0, genesis); started.expect("the genesis block starts"); - assert!(calls.is_empty(), "no pre-block call reached the observer: {calls:?}"); + 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. The block hashes call makes no call at genesis, so nothing reached the observer. +/// 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 (calls, started) = observed_calls(common::chain_spec(), 0, ctx()); + 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:?}"); @@ -278,9 +355,9 @@ fn test_the_genesis_block_refuses_a_non_zero_beacon_root() { #[test] fn test_a_block_without_a_parent_beacon_root_is_refused() { let (calls, started) = - observed_calls(common::chain_spec(), BLOCK_NUMBER, ctx_without_beacon_root()); + 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, [PreBlockStateSource::Eip2935]); + assert_eq!(calls, [HISTORY_STORAGE_ADDRESS]); assert!( matches!( @@ -291,20 +368,20 @@ fn test_a_block_without_a_parent_beacon_root_is_refused() { ); } -/// With the contracts' own code, both calls succeed, reach the observer in order and are -/// committed: the parent hash in the EIP-2935 ring buffer, the timestamp and the root in the -/// EIP-4788 one. +/// 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)); - let log = record_pre_block(&mut executor); executor.apply_pre_execution_changes().expect("both calls succeed"); - let calls: Vec<_> = pre_block_states(&log).into_iter().map(|(source, _)| source).collect(); - assert_eq!(&calls[..2], [PreBlockStateSource::Eip2935, PreBlockStateSource::Eip4788]); + let calls = common::named_accounts(&committed.states()); + assert_eq!(&calls[..2], [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]); drop(executor); let ring = 8191; @@ -322,8 +399,8 @@ fn test_the_successful_pre_block_calls_commit_normally() { ); } -/// A block hashes call that halts refuses the block with the EIP-2935 error, and its state -/// reaches neither the observer nor the database; the beacon root call after it never runs. It +/// 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] @@ -365,44 +442,7 @@ fn test_a_block_is_refused_when_its_beacon_root_call_halts() { ), "{err}" ); - assert_eq!(calls, [PreBlockStateSource::Eip2935]); -} - -/// A pre-block call that reverts refuses the block just as one that halts does. -#[test] -fn test_a_block_is_refused_when_a_pre_block_call_reverts() { - let reverts = BytecodeBuilder::default().revert().build(); - - let mut db = common::database(); - db.set_account_code(HISTORY_STORAGE_ADDRESS, reverts.clone()); - let (calls, started) = start_block(db, common::evm_env()); - let err = started.expect_err("a reverted block hashes call refuses the block"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) - if message.contains("EIP-2935 pre-block call did not succeed") - && message.contains("Revert") - ), - "{err}" - ); - assert!(calls.is_empty(), "{calls:?}"); - - let mut db = common::database(); - db.set_account_code(BEACON_ROOTS_ADDRESS, reverts); - let (calls, started) = start_block(db, common::evm_env()); - let err = started.expect_err("a reverted beacon root call refuses the block"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { - message, - .. - }) if message.contains("EIP-4788 pre-block call did not succeed") - ), - "{err}" - ); - assert_eq!(calls, [PreBlockStateSource::Eip2935]); + 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 @@ -428,14 +468,12 @@ fn test_the_block_aware_budget_accepts_a_pre_block_call_above_30m() { }; 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)); - let log = record_pre_block(&mut executor); executor.apply_pre_execution_changes().expect("a 250M block holds both calls"); - let states = pre_block_states(&log); - assert_eq!(states[0].0, PreBlockStateSource::Eip2935); - assert_eq!(states[0].1[&HISTORY_STORAGE_ADDRESS].storage.len(), usize::from(SLOTS)); - assert_eq!(states[1].0, PreBlockStateSource::Eip4788); - assert_eq!(states[1].1[&BEACON_ROOTS_ADDRESS].storage.len(), usize::from(SLOTS)); + 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()); @@ -492,12 +530,12 @@ fn test_a_database_error_in_the_beacon_root_call_is_internal() { assert!(err.to_string().contains("injected basic() error"), "{err}"); } -/// What the observer receives 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 +/// 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_the_observer_receives_a_pre_block_call_as_op_revm_runs_it() { +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}, @@ -525,11 +563,11 @@ fn test_the_observer_receives_a_pre_block_call_as_op_revm_runs_it() { 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)); - let log = record_pre_block(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); - let (source, delivered) = pre_block_states(&log).into_iter().next().expect("a first step"); - assert_eq!(source, PreBlockStateSource::Eip2935); + 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); @@ -550,7 +588,7 @@ fn test_the_observer_receives_a_pre_block_call_as_op_revm_runs_it() { assert!(result.expect("op-revm runs the call").is_success()); let expected = op.finalize(); - assert_eq!(delivered, expected, "the observer sees op-revm's state"); + 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}"); diff --git a/crates/mega-evm/tests/block/external_envs.rs b/crates/mega-evm/tests/block/external_envs.rs index 1df735b70..42e8b91e7 100644 --- a/crates/mega-evm/tests/block/external_envs.rs +++ b/crates/mega-evm/tests/block/external_envs.rs @@ -15,7 +15,6 @@ use alloy_sol_types::SolCall; use mega_evm::{ satin_gas_params, system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, - test_utils::BytecodeBuilder, BucketId, ExternalEnvFactory, ExternalEnvs, MegaBlockExecutorFactory, MegaEvmFactory, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, }; @@ -55,17 +54,6 @@ fn bucket(slot: u64) -> BucketId { ::bucket_id_for_slot(WRITER, U256::from(slot)) } -/// Code that writes 1 into the slot named by the first byte of its calldata. -fn writer() -> alloy_primitives::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() -} - /// 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 @@ -84,7 +72,7 @@ fn test_a_blocks_environments_come_from_the_factory() { ); let mut db = common::database(); - db.set_account_code(WRITER, writer()); + 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()); diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index b9c4c8d97..0a2aa1ddc 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -1,11 +1,10 @@ //! The two ways to reach a block executor, and the limits both install. //! -//! The limits a block's transactions run under are the chain's: the schedule carries them -//! ([`ProtocolLimits`]), 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 the schedule's, -//! so a caller that did not pre-apply them, or applied others, 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}, @@ -17,62 +16,44 @@ use alloy_sol_types::SolError; use mega_evm::{ test_utils::{BytecodeBuilder, GasInspector}, DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, - MegaLimitExceeded, ProtocolLimits, + 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 schedule. -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; - -/// The chain's limits in these tests. +/// The limits every route installs: Satin's. fn limits() -> ProtocolLimits { - ProtocolLimits::loosest().with_tx_runtime_limits( - common::loosest_tx() - .with_tx_data_size_limit(TX_DATA_SIZE_LIMIT) - .with_frame_data_size_limit(FRAME_DATA_SIZE_LIMIT), - ) + ProtocolLimits::for_spec(MegaSpecId::SATIN) } -/// A factory over a chain that carries [`limits`]. -fn factory() -> common::TestFactory { - common::factory_on(common::chain_spec_with(limits())) -} - -/// The factory trait installs the chain's limits on an EVM the caller built without them. -#[test] -fn test_trait_path_applies_the_chains_runtime_limits() { - let mut state = common::state(); - let factory = factory(); - // Built by an EVM factory that was not given the chain's schedule: the case a caller that - // forgot it produces, whose EVM runs under the protocol's defaults, not the chain's. - let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); - - let executor = factory.create_executor(evm, common::unlimited_ctx()); - - 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 = factory(); + 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::unlimited_ctx()); assert_eq!( *executor.evm().tx_runtime_limits(), limits().tx_runtime_limits, - "the EVM runs under exactly the chain's limits" + "the EVM runs under exactly the spec's limits" ); - assert_eq!(executor.protocol_limits(), Some(&limits())); + assert_eq!(executor.protocol_limits(), &limits()); } /// The two routes to an executor install the same limits, so neither is a way around them. @@ -80,15 +61,18 @@ fn test_trait_path_applies_every_runtime_limit_field() { fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let trait_path = { let mut state = common::state(); - let factory = factory(); - let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + let factory = common::factory(); + 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() }; let inspector_path = { let mut state = common::state(); - let factory = factory(); + let factory = common::factory(); let executor = factory.create_executor_with_trusted_inspector( &mut state, common::evm_env(), @@ -100,69 +84,36 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { assert_eq!(trait_path, limits().tx_runtime_limits); assert_eq!(inspector_path, limits().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 = factory(); - let evm = factory - .evm_factory() - .create_evm(&mut state, common::evm_env()) - .with_tx_runtime_limits(limits().tx_runtime_limits); - - let executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert_eq!(*executor.evm().tx_runtime_limits(), limits().tx_runtime_limits); } -/// Limits a caller applied to the EVM are not the chain's, and the chain's replace them. -#[test] -fn test_trait_path_replaces_limits_the_caller_applied() { - let mut state = common::state(); - let factory = factory(); - let evm = factory - .evm_factory() - .create_evm(&mut state, common::evm_env()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(1)); - - let executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert_eq!(*executor.evm().tx_runtime_limits(), limits().tx_runtime_limits); -} - -/// The constructor a node calls directly installs the chain'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_the_chains_runtime_limits() { +fn test_direct_construction_applies_the_specs_runtime_limits() { let mut state = common::state(); - // Built by an EVM factory that was not given the chain's schedule: the case a caller that - // forgot it produces, whose EVM runs under the protocol's defaults, not the chain's. - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - assert_eq!(*evm.tx_runtime_limits(), ProtocolLimits::DEFAULT.tx_runtime_limits); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_tx_runtime_limits(others()); let executor = MegaBlockExecutor::new( evm, common::unlimited_ctx(), - common::chain_spec_with(limits()), + common::chain_spec(), OpAlloyReceiptBuilder::default(), ); assert_eq!( *executor.evm().tx_runtime_limits(), limits().tx_runtime_limits, - "the EVM runs under exactly the chain's 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 chain allows is stopped with `MegaLimitExceeded`, even when the caller loosened the EVM's -/// limits after building the executor — every transaction runs under the chain's. +/// 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_chains_data_size_limit() { +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; @@ -176,11 +127,11 @@ fn test_direct_construction_stops_a_transaction_over_the_chains_data_size_limit( .build(), ); let mut state = State::builder().with_database(db).build(); - // `common::executor_with_limits` builds the executor with `MegaBlockExecutor::new` and an EVM - // that carries no limits of its own. + // `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, - ProtocolLimits::loosest() + 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"); @@ -215,22 +166,3 @@ fn test_direct_construction_stops_a_transaction_over_the_chains_data_size_limit( other => panic!("expected a revert-class stop, got {other:?}"), } } - -/// A node gives its EVM factory the schedule it gives its block executor factory: an EVM the -/// factory creates, for a block or for an RPC call, then runs under the chain's limits before any -/// executor installs them, and the executor installs the same. -#[test] -fn test_an_evm_factory_on_the_chains_schedule_creates_evms_under_its_limits() { - let spec = common::chain_spec_with(limits()); - let factory = mega_evm::MegaBlockExecutorFactory::new( - OpAlloyReceiptBuilder::default(), - spec.clone(), - MegaEvmFactory::new().with_schedule(spec), - ); - let mut state = common::state(); - 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 executor = factory.create_executor(evm, common::unlimited_ctx()); - assert_eq!(*executor.evm().tx_runtime_limits(), limits().tx_runtime_limits); -} diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 8d1bd8399..82a3430ca 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,7 +1,7 @@ //! The admission gate: which inspectors reach block execution, and what a declared observer sees //! of a block's phases. -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; +use alloy_consensus::transaction::Recovered; use alloy_eips::{ eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, @@ -10,12 +10,12 @@ use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, Evm, EvmFactory, FromRecoveredTx, }; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, + test_utils::{BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase}, transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, - MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, MegaTxEnvelope, - PreBlockStateSource, + MegaBlockExecutionError, MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, + MegaTxEnvelope, }; use revm::{ bytecode::opcode::{ADD, POP, PUSH0, SLOAD, SSTORE}, @@ -24,16 +24,12 @@ use revm::{ handler::FrameResult, inspector::NoOpInspector, interpreter::{ - CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, - Interpreter, InterpreterResult, InterpreterTypes, + CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, Interpreter, + InterpreterResult, InterpreterTypes, }, - state::EvmState, Inspector, }; -use std::{ - cell::Cell, - sync::{Arc, Mutex}, -}; +use std::cell::Cell; use crate::common::{self, empty_call_gas, system_tx, user_tx}; @@ -61,7 +57,9 @@ fn test_a_declared_observer_reaches_block_execution() { } /// 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(); @@ -80,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. @@ -246,6 +250,7 @@ fn recording_ctx() -> MegaBlockExecutionCtx { #[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, @@ -253,31 +258,20 @@ fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() recording_ctx(), DeclaredObserver::new(Seen::default()), ); - let pre_block = Arc::new(Mutex::new(Vec::new())); - let log = Arc::clone(&pre_block); - executor.set_pre_block_observer(Some(Box::new( - move |source: PreBlockStateSource, state: &EvmState| { - let wrote = - state.values().any(|account| account.storage.values().any(|s| s.is_changed())); - log.lock().unwrap().push((source, wrote)); - }, - ))); executor.apply_pre_execution_changes().expect("a declared observer is admitted"); - let calls: Vec<_> = pre_block - .lock() - .unwrap() - .iter() - .filter(|(source, _)| { - matches!(source, PreBlockStateSource::Eip2935 | PreBlockStateSource::Eip4788) - }) - .copied() - .collect(); + let states = committed.states(); assert_eq!( - calls, - [(PreBlockStateSource::Eip2935, true), (PreBlockStateSource::Eip4788, true)], - "both pre-block calls ran and wrote" + 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"); @@ -384,50 +378,6 @@ impl Inspector for SkipNested } } -/// Answers every creation itself with a success and no address, and counts those answers and every -/// creation's end. -#[derive(Default)] -struct SkipCreateInspector { - creates_intercepted: Cell, - create_ends: Cell, -} - -impl Inspector for SkipCreateInspector { - fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { - self.creates_intercepted.set(self.creates_intercepted.get() + 1); - Some(CreateOutcome::new( - InterpreterResult::new( - InstructionResult::Stop, - Bytes::new(), - Gas::new(inputs.gas_limit()), - ), - None, - )) - } - - fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, _: &mut CreateOutcome) { - self.create_ends.set(self.create_ends.get() + 1); - } -} - -/// A legacy creation from [`common::CALLER`] running `init_code`. -fn creation_tx(nonce: u64, gas_limit: u64, init_code: Bytes) -> Recovered { - let tx = TxLegacy { - chain_id: Some(common::CHAIN_ID), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - }; - common::recovered(MegaTxEnvelope::Legacy(Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::repeat_byte(0xc0), - ))) -} - /// Runs `tx` on an EVM over `state` under `inspector`, outside block execution: the route a tool /// takes. fn run_as_a_tool<'a, I>( @@ -480,36 +430,3 @@ fn test_inspector_early_return_with_additional_limits() { assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); assert_eq!(outcome.gas.state, 0); } - -/// An inspector that answers a creation rewrites what execution produces, so block execution -/// refuses it before the transaction runs. On the EVM, the transaction's own creation answered -/// with a success and no address settles as a creation that never started: no account, so the -/// state gas EIP-2780 charged for it and the history of its write record come back, and the -/// transaction keeps only its body. -#[test] -fn test_inspector_early_return_create_with_additional_limits() { - let tx = creation_tx(0, 10_000_000, Bytes::from_static(&[0x00])); - - let mut state = common::state(); - let evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(SkipCreateInspector::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().creates_intercepted.get(), 0, "nothing ran"); - - let mut state = common::state(); - let mut inspector = SkipCreateInspector::default(); - let (tx, outcome) = run_as_a_tool(&mut state, &tx, &mut inspector); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(inspector.creates_intercepted.get(), 1, "the creation was answered"); - assert_eq!(inspector.create_ends.get(), 1, "and ended"); - let body = transaction_body_bytes(&tx); - assert_eq!(outcome.gas.state, 0, "no account, so no state gas"); - assert_eq!(outcome.gas.history_bytes, body, "and no record: the body alone"); - assert_eq!(outcome.gas.history, mega_evm::history_gas(body).unwrap()); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); - let created = common::CALLER.create(0); - assert!(outcome.state.get(&created).is_none_or(|account| account.info.is_empty())); -} 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 aea3f4504..c29782cec 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -4,8 +4,7 @@ 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, LimitCheck, LimitKind, - MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, + test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, MegaTransactionExt, MegaTxEnvelope, }; use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, @@ -16,7 +15,7 @@ use revm::{ Database as _, }; -use crate::common::{self, empty_call_gas, executor, incompressible, user_tx, CALLER, CONTRACT}; +use crate::common::{self, executor, incompressible, user_tx, CALLER, CONTRACT}; const CALLER2: Address = address!("0x2000000000000000000000000000000000000003"); const CALLER3: Address = address!("0x2000000000000000000000000000000000000004"); @@ -87,49 +86,6 @@ fn test_block_custom_data_limit() { 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, log_call_gas(100)); - 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, log_call_gas(2_000))).expect("packed"); - } - assert!( - executor.execute_transaction(&user_tx(3, log_call_gas(2_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"); -} - /// 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 { @@ -166,58 +122,28 @@ fn state_with_incrementing_contract( revm::database::State::builder().with_database(db).build() } -/// The block's KV limit: the transaction that crosses it is packed, however far past the limit -/// it takes the block, and the next one is refused before it runs. +/// 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_custom_kv_update_limit() { +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 both transactions whatever fifty slots cost, so the block's - // write records are what refuses the second. + // 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().with_block_kv_update_limit(1)), - env, - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor - .execute_transaction(&user_tx(0, incrementing_gas(50))) - .expect("the crossing transaction"); - assert_eq!(executor.limiter().usage.write_records, 50, "the block has crossed its limit"); - - let err = executor - .execute_transaction(&user_tx(1, incrementing_gas(50))) - .expect_err("the block has no write records left"); - assert!(format!("{err}").contains("Block KV update limit reached"), "{err}"); - assert!(format!("{err}").contains("block_used=50"), "{err}"); -} - -/// The same limit mid-block, one record a transaction: the transactions up to the one that -/// reaches the limit are packed, and the block ends there. -#[test] -fn test_block_kv_limit_exceeded_mid_block() { - let mut state = state_with_incrementing_contract(1); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_kv_update_limit(3)), - ); + 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 { - let tx = user_tx(nonce, incrementing_gas(1)); - let gas = executor.execute_transaction(&tx).expect("packed"); - assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); + 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, incrementing_gas(1))).is_err(), - "the block has no write records 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.usage.write_records, 3, "the block reports its KV count"); + 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. @@ -252,86 +178,37 @@ fn test_block_no_state_commit_on_limit_exceeded() { assert!(result.receipts().is_empty()); } -/// The block's data-size limit never refuses a deposit, and a deposit still counts towards it. -/// -/// Two data-heavy deposits cross the limit between them, a third finds the block past it and is -/// still included, and the ordinary transaction after them is refused on the room they used. The -/// deposits add nothing to the data-availability size. +/// 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_the_block_data_size_limit_never_refuses_a_deposit() { - const CALLDATA: usize = 1_000; - let per_deposit = mega_evm::TX_BODY_SIZE + CALLDATA as u64; - let limit = per_deposit + per_deposit / 2; - let mut state = common::state(); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(limit)), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - for (n, what) in ["the first deposit", "the deposit that crosses", "the deposit past the limit"] - .into_iter() - .enumerate() - { - let deposit = common::deposit_tx(incompressible(CALLDATA), 1_000_000); - let outcome = - executor.run_transaction(&deposit).unwrap_or_else(|err| panic!("{what}: {err}")); - assert!(outcome.inner.result.is_success(), "{what}: {:?}", outcome.inner.result); - assert_eq!(outcome.inner.usage.data_size, per_deposit, "{what}"); - executor.commit_transaction_outcome(outcome).unwrap_or_else(|err| panic!("{what}: {err}")); - assert_eq!(executor.limiter().usage.data_size, per_deposit * (n as u64 + 1), "{what}"); - } - assert!(executor.limiter().usage.data_size > limit, "the deposits crossed the limit"); - assert_eq!( - executor.limiter().block_da_size_used, - 0, - "a deposit adds no data-availability size" - ); - - let err = executor - .execute_transaction(&user_tx(3, empty_call_gas())) - .expect_err("the deposits used the room an ordinary transaction would need"); - assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); - assert!(format!("{err}").contains(&format!("block_used={}", per_deposit * 3)), "{err}"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 3, "every deposit is packed, and nothing after them"); -} - -/// The per-transaction data-size limit is not a block limit: it stops a deposit's own execution -/// the way it stops any transaction's, and the deposit is included with the stop as its result. -#[test] -fn test_the_transaction_data_size_limit_stops_a_deposit_that_is_still_included() { +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, - ProtocolLimits::loosest() + 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 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::Revert { .. }), - "{:?}", - outcome.inner.result - ); - let stop = outcome.inner.limit_exceeded.expect("the data-size limit stopped the deposit"); assert!( matches!( - stop, - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: l, frame_local: false, .. } - if l == limit + outcome.inner.result, + ExecutionResult::Halt { reason: op_revm::OpHaltReason::FailedDeposit, .. } ), - "{stop:?}" + "{:?}", + 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"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 1); - assert!(!result.receipts()[0].status(), "the stopped deposit's receipt reports a failure"); + assert!(!result.receipts()[0].status(), "the failed deposit's receipt reports a failure"); } /// With no size limit configured, a transaction of any size is admitted. @@ -348,23 +225,6 @@ fn test_block_tx_size_limit_default_unlimited() { 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] @@ -439,6 +299,47 @@ fn test_block_tx_size_limit_with_varying_sizes() { .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 /// adds is checked against the block once more before it is committed. /// @@ -540,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"); @@ -551,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); @@ -607,30 +508,6 @@ 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. -#[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); -} - /// 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 @@ -669,36 +546,6 @@ fn test_no_building_policy_refuses_a_deposit() { assert_eq!(result.receipts().len(), 1, "the deposit alone is packed"); } -/// 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, empty_call_gas())) - .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); -} - /// 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. /// diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 9030d94d7..f4d0c9747 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -1,21 +1,31 @@ //! Tests of the block executor. +mod activation; mod block_hashes; +mod bucket_ids; +mod building_policy; mod common; mod counters; -mod deploy; mod deposits; mod detention; mod eips; mod external_envs; mod factory; mod inspector; +mod l1_attributes; mod limits; -mod protocol_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 bfbefe046..773c81d99 100644 --- a/crates/mega-evm/tests/block/receipts.rs +++ b/crates/mega-evm/tests/block/receipts.rs @@ -1,22 +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, empty_call_gas, 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. @@ -37,35 +23,3 @@ fn test_the_receipts_are_readable_during_the_block_and_leave_with_its_result() { 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 1ee2c1ad3..fcadeae17 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -25,7 +25,11 @@ use crate::common::{ /// 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()); @@ -45,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) @@ -80,22 +84,6 @@ 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. -#[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, 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}"); - assert!(executor.receipts().is_empty(), "nothing was packed"); -} - /// 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. @@ -113,21 +101,6 @@ fn test_activation_block_rejects_a_mega_system_transaction() { 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] @@ -386,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/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index e34c1ddd5..e39fbaf8e 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -1,22 +1,14 @@ //! The schedule a block runs on, and what is checked of it before the block starts. -use core::any::{Any, TypeId}; - -use alloy_evm::{ - block::{BlockExecutionError, BlockExecutor}, - Evm, EvmFactory, -}; -use alloy_hardforks::{EthereumHardfork, EthereumHardforks, ForkCondition}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_op_hardforks::{OpHardfork, OpHardforks}; +use alloy_evm::block::BlockExecutor; +use alloy_hardforks::{EthereumHardfork, ForkCondition, Hardfork}; +use alloy_op_hardforks::OpHardfork; use mega_evm::{ - chain_activation, mainnet_hardforks, system::SequencerRegistryConfig, testnet_hardforks, - HardforkParams, MegaBlockExecutionError, MegaBlockExecutor, MegaEvmFactory, MegaHardfork, - MegaHardforkConfig, MegaHardforks, ProtocolLimits, 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, empty_call_gas, registry_config, user_tx}; +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 @@ -34,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)), @@ -49,165 +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!( - missing.require_params::(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Satin, - params: "SequencerRegistryConfig", - }), - "the load refuses it" - ); - assert_eq!( - missing.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Satin, - params: "SequencerRegistryConfig", - }), - ); - - // The registry's alone is not enough: Satin requires its limits too. - let registry_only = missing.with_params(registry_config()); - assert_eq!(registry_only.require_params::(), Ok(())); - assert_eq!( - registry_only.validate_schedule(), - Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "ProtocolLimits" }), - ); - - // With both attached the schedule loads, and a block runs on it. - let loaded = registry_only.with_params(ProtocolLimits::DEFAULT); - assert_eq!(loaded.require_params::(), Ok(())); - assert_eq!(loaded.validate_schedule(), Ok(())); - assert_eq!(loaded.fork_params::(), Some(®istry_config())); - assert_eq!(loaded.fork_params::(), Some(&ProtocolLimits::DEFAULT)); + assert_eq!(satin.validate_schedule(), Ok(())); let mut state = common::state(); - let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), loaded); + 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"); } -/// 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.require_params::(), Ok(())); - assert_eq!(unscheduled.validate_schedule(), Ok(())); +/// 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) } -/// A node's own schedule type: it attaches its parameters without `with_params`, and answers with -/// whatever it holds, checked or not. This one holds `limits` for Satin and answers everything -/// else as [`common::chain_spec`] does. -struct NodeSchedule { - inner: MegaHardforkConfig, - limits: ProtocolLimits, +/// 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(), + }) } -impl EthereumHardforks for NodeSchedule { - fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { - self.inner.ethereum_fork_activation(fork) +/// 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!( + schedule.validate_schedule().unwrap_err().to_string(), + "hardfork Satin activates at timestamp 1800000000, where the Karst fork it runs on is \ + not active", + ); + + 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:?}"); } } -impl OpHardforks for NodeSchedule { - fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { - self.inner.op_fork_activation(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:?}"); + } } } -impl MegaHardforks for NodeSchedule { - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { - self.inner.mega_fork_activation(fork) +/// 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:?}"); } - fn fork_params_any( - &self, - fork: MegaHardfork, - params: TypeId, - ) -> Option<&(dyn Any + Send + Sync)> { - if fork == MegaHardfork::Satin && params == TypeId::of::() { - Some(&self.limits) - } else { - self.inner.fork_params_any(fork, params) - } + 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(())); } -/// The refusal of this engine an internal error carries. -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:?}")) +/// The schedules the engine builds itself put every base fork at genesis, so they load whenever +/// Satin activates. +#[test] +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}"); + } } -/// Limits their own check refuses run no block, even when they reach the block executor without -/// the load-time check: a node's own schedule type hands them over as it holds them. The executor -/// installs nothing on the EVM and refuses the block at every entry point — its start, a -/// transaction, its end — as an internal error: the schedule is the node's configuration, not the -/// block. +/// 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_limits_the_check_refuses_run_no_block() { - let invalid = ProtocolLimits::no_limits(); - let schedule = NodeSchedule { inner: common::chain_spec(), limits: invalid }; - let message = invalid.validate().expect_err("no chain may carry them").message; - assert_eq!( - schedule.validate_schedule(), - Err(ScheduleError::InvalidParams { - fork: MegaHardfork::Satin, - params: "ProtocolLimits", - message: message.clone(), - }), - "the load-time check refuses them, for a node that runs it" - ); +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(())); +} - let mut state = common::state(); - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - let built_with = *evm.tx_runtime_limits(); - let mut executor = MegaBlockExecutor::new( - evm, - common::unlimited_ctx(), - &schedule, - OpAlloyReceiptBuilder::default(), - ); - assert_eq!(executor.protocol_limits(), None); - assert_eq!(*executor.evm().tx_runtime_limits(), built_with, "nothing is installed"); - - let refusal = MegaBlockExecutionError::InvalidProtocolLimits { - timestamp: common::BLOCK_TIMESTAMP, - message, - }; - let error = executor.apply_pre_execution_changes().expect_err("the block does not start"); - assert_eq!(internal(&error), &refusal); - assert!(executor.evm().db().bundle_state.state.is_empty(), "no pre-block step ran"); - let error = executor - .execute_transaction(&user_tx(0, empty_call_gas())) - .expect_err("no transaction runs either"); - assert_eq!(internal(&error), &refusal); - assert!(executor.receipts().is_empty()); - let Err(error) = executor.finish() else { panic!("nor is the block finished") }; - assert_eq!(internal(&error), &refusal); - - // The same schedule holding limits a chain may carry runs the block. - let schedule = NodeSchedule { inner: common::chain_spec(), limits: ProtocolLimits::DEFAULT }; +/// 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(())); - let mut state = common::state(); - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - let mut executor = MegaBlockExecutor::new( - evm, - common::unlimited_ctx(), - &schedule, - OpAlloyReceiptBuilder::default(), - ); - assert_eq!(executor.protocol_limits(), Some(&ProtocolLimits::DEFAULT)); - executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); } diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index f0464555e..a21e470ee 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -1,39 +1,41 @@ //! The `SequencerRegistry`'s role changes, applied before a block's transactions, and the live //! system address read out of it. //! -//! The registry is deployed before every block. After the deploy, the executor reads whether a -//! role change is due in the block and, when one is, makes the `applyPendingChanges()` system -//! call. Each step's state reaches the pre-block observer before it is committed. The executor -//! does not read the system address: a transaction of the system shape 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 std::sync::{Arc, Mutex}; - -use alloy_consensus::transaction::Recovered; +//! 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, B256, U256}; +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, MIN_ROTATION_DELAY, PENDING_ADMIN, - PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_ADMIN, PENDING_SEQUENCER, + PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }, - IOracle, ISequencerRegistry, SequencerRegistryConfig, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, - SEQUENCER_REGISTRY_CODE_HASH, + IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, + SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE, }, - test_utils::MemoryDatabase, + test_utils::{CommittedStates, MemoryDatabase, SequencerRegistryRoles}, BlockLimits, ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaContext, - MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, PreBlockStateSource, - TestExternalEnvs, MIN_BUCKET_SIZE, + 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 revm::{database::State, inspector::NoOpInspector, state::EvmState, Database}; -use crate::common::{self, pre_block_states, PreBlockLog, BLOCK_NUMBER}; +use crate::common::{self, applies_pending_changes, BLOCK_NUMBER}; /// The outcome of a transaction the tests run. type Outcome = mega_evm::MegaBlockTxResult; @@ -61,21 +63,10 @@ type Executor<'a> = MegaBlockExecutor< MegaHardforkConfig, >; -fn word(address: Address) -> U256 { - U256::from_be_bytes(address.into_word().0) -} - -/// A database holding a deployed registry with `slots` on top of the bootstrap roles, and the -/// accounts the tests' transactions come from. +/// 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(); - db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE); - db.set_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - word(MEGA_SYSTEM_ADDRESS), - ); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER, word(common::SEQUENCER)); for &(slot, value) in slots { db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, slot, value); } @@ -85,7 +76,7 @@ fn registry_with(slots: &[(U256, U256)]) -> MemoryDatabase { /// The slots of a system-address change due at `activation`. fn system_address_change(activation: u64) -> [(U256, U256); 2] { [ - (PENDING_SYSTEM_ADDRESS, word(NEXT_SYSTEM_ADDRESS)), + (PENDING_SYSTEM_ADDRESS, common::word(NEXT_SYSTEM_ADDRESS)), (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(activation)), ] } @@ -93,7 +84,7 @@ fn system_address_change(activation: u64) -> [(U256, U256); 2] { /// The slots of a sequencer change due at `activation`. fn sequencer_change(activation: u64) -> [(U256, U256); 2] { [ - (PENDING_SEQUENCER, word(NEXT_SEQUENCER)), + (PENDING_SEQUENCER, common::word(NEXT_SEQUENCER)), (SEQUENCER_ACTIVATION_BLOCK, U256::from(activation)), ] } @@ -128,45 +119,19 @@ fn executor_on( MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } -/// Installs a recording observer on `executor` and returns the log it writes. -fn record(executor: &mut Executor<'_>) -> PreBlockLog { - let log = Arc::new(Mutex::new(Vec::new())); - let captured = Arc::clone(&log); - executor.set_pre_block_observer(Some(Box::new( - move |source: PreBlockStateSource, state: &EvmState| { - captured.lock().expect("pre-block observer").push((source, state.clone())); - }, - ))); - log -} - -/// The registry's own steps the observer received, in order: the deploy of it, the read of its -/// pending changes and the call that applies them. -fn registry_steps(log: &PreBlockLog) -> Vec<(PreBlockStateSource, EvmState)> { - pre_block_states(log) - .into_iter() - .filter(|(source, _)| { - matches!( - source, - PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS) | - PreBlockStateSource::PendingChanges | - PreBlockStateSource::ApplyPendingChanges - ) - }) - .collect() -} - -/// Starts a block at [`BLOCK_NUMBER`] over `state` and answers the registry's steps the observer -/// received. -fn start_block( - state: &mut State, - envs: Envs, - gas_limit: u64, -) -> Vec<(PreBlockStateSource, EvmState)> { +/// 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); - let log = record(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); - registry_steps(&log) + committed + .states() + .into_iter() + .filter(|state| state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)) + .collect() } /// The registry's `slot`, as the block left it. @@ -174,14 +139,10 @@ fn slot(state: &mut State, slot: U256) -> U256 { state.storage(SEQUENCER_REGISTRY_ADDRESS, slot).expect("the registry is readable") } -fn sources(steps: &[(PreBlockStateSource, EvmState)]) -> Vec { - steps.iter().map(|(source, _)| *source).collect() -} - /// 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 observer receives -/// the read that found the change due, then the call's state. +/// 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); @@ -189,41 +150,27 @@ fn test_a_due_change_is_applied_under_a_crowded_bucket() { 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!( - sources(&steps), - [ - PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), - PreBlockStateSource::PendingChanges, - PreBlockStateSource::ApplyPendingChanges, - ] - ); + 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), word(NEXT_SYSTEM_ADDRESS)); + 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 observer receives the read that found nothing -/// due, both pending slots and nothing else, read-only. On the chain's first block that read -/// finds the registry the deploy before it just created. +/// 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() { - for db in [common::database(), registry_with(&[])] { - let mut state = State::builder().with_database(db).build(); - let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); - assert_eq!( - sources(&steps), - [ - PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), - PreBlockStateSource::PendingChanges, - ] - ); - let registry = &steps[1].1[&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)); - } + 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. @@ -232,9 +179,9 @@ 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!(!sources(&steps).contains(&PreBlockStateSource::ApplyPendingChanges)); - assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), word(MEGA_SYSTEM_ADDRESS)); - assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), word(NEXT_SYSTEM_ADDRESS)); + 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 @@ -244,28 +191,20 @@ 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!(sources(&steps).contains(&PreBlockStateSource::ApplyPendingChanges)); - assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(NEXT_SEQUENCER)); + 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), word(MEGA_SYSTEM_ADDRESS)); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), common::word(MEGA_SYSTEM_ADDRESS)); } -/// The system address a chain's schedule seeds the registry with, distinct from -/// [`MEGA_SYSTEM_ADDRESS`], so a test can tell the one read out of the registry from the default. -const GENESIS_SYSTEM_ADDRESS: Address = address!("0x5000000000000000000000000000000000000005"); +/// 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 Satin-at-genesis schedule whose registry is seeded with [`GENESIS_SYSTEM_ADDRESS`]. -fn chain_seeding_genesis_system_address() -> MegaHardforkConfig { - common::chain_spec().with_params(SequencerRegistryConfig { - initial_system_address: GENESIS_SYSTEM_ADDRESS, - ..common::registry_config() - }) -} - /// 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. @@ -331,77 +270,30 @@ fn assert_carries_the_system_address_read(state: &EvmState, system_address: Addr 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(), word(system_address)); + assert_eq!(slot.present_value(), common::word(system_address)); } -/// A fresh chain's first block deploys the registry seeded with the system address its schedule -/// names, and that address is the system address from the block's first transaction: the -/// registry's, not the engine's default. No pre-block step reads it; the system-address -/// transaction does, and its state carries the read. -#[test] -fn test_the_bootstrap_block_promotes_the_seeded_system_address() { - let mut state = common::state(); - let mut executor = executor_on( - &mut state, - envs_at(1), - common::BLOCK_GAS_LIMIT, - chain_seeding_genesis_system_address(), - ); - let log = record(&mut executor); - executor.apply_pre_execution_changes().expect("the block starts"); - let sources = sources(®istry_steps(&log)); - assert_eq!( - sources, - [ - PreBlockStateSource::SystemContract(SEQUENCER_REGISTRY_ADDRESS), - PreBlockStateSource::PendingChanges, - ] - ); - let outcome = assert_is_the_system_address(&mut executor, GENESIS_SYSTEM_ADDRESS); - assert_carries_the_system_address_read(&outcome.inner.state, GENESIS_SYSTEM_ADDRESS); - assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); - drop(executor); - - // The registry is the one this engine ships, seeded with the schedule's roles and delay. - assert_eq!( - state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, - SEQUENCER_REGISTRY_CODE_HASH, - ); - assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), word(GENESIS_SYSTEM_ADDRESS)); - assert_eq!( - slot(&mut state, MIN_ROTATION_DELAY), - U256::from(common::registry_config().min_rotation_delay) - ); - assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(common::SEQUENCER)); - - // The default schedule seeds the engine's default address, and it is the system address. - let mut state = common::state(); - let mut default = self::executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); - default.apply_pre_execution_changes().expect("the block starts"); - assert_is_the_system_address(&mut default, MEGA_SYSTEM_ADDRESS); -} - -/// Once the registry is in place, no pre-block step carries the system address's slot: the -/// deploy leaves the registry as a read-only entry without storage, and the read of the pending -/// changes reads the pending slots alone. The slot is in the system-address transaction's own -/// state instead, read-only and cold, as its validation read it. +/// 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); - let log = record(&mut executor); executor.apply_pre_execution_changes().expect("the block starts"); - for (source, state) in pre_block_states(&log) { + 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(), "{source:?} carries the system address's slot"); + 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 left the slot cold"); + 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, @@ -409,27 +301,14 @@ fn test_the_slot_is_in_the_system_transactions_state_not_the_pre_block_witness() /// system address, it is an ordinary transaction. #[test] fn test_system_tx_uses_resolved_system_address() { - let mut state = common::state(); - let mut executor = executor_on( - &mut state, - envs_at(1), - common::BLOCK_GAS_LIMIT, - chain_seeding_genesis_system_address(), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - assert_is_the_system_address(&mut executor, GENESIS_SYSTEM_ADDRESS); - assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); -} - -/// A system-address rotation due in this block governs this block: the new address sends the -/// protocol's transactions, and the old one no longer can. -#[test] -fn test_system_address_change() { + let roles = + SequencerRegistryRoles { system_address: CHAIN_SYSTEM_ADDRESS, ..common::registry_roles() }; let mut state = - State::builder().with_database(registry_with(&system_address_change(BLOCK_NUMBER))).build(); + 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"); - assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS); + 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); } @@ -514,6 +393,130 @@ fn test_an_evm_outside_block_execution_promotes_the_rotated_address() { ); } +/// 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() { @@ -538,26 +541,14 @@ fn test_dual_change_in_same_block() { 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), word(NEXT_SEQUENCER)); -} - -/// A rotation scheduled for a later block leaves this block's system address as it was. -#[test] -fn test_pending_not_yet_due_is_noop() { - let mut state = State::builder() - .with_database(registry_with(&system_address_change(BLOCK_NUMBER + 8_999))) - .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_SYSTEM_ADDRESS); + 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(&[(ADMIN, word(common::ADMIN))]); + 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(); @@ -578,7 +569,7 @@ fn test_admin_handoff_via_block_executor() { } drop(executor); - assert_eq!(slot(&mut state, ADMIN), word(NEXT_ADMIN)); + assert_eq!(slot(&mut state, ADMIN), common::word(NEXT_ADMIN)); assert_eq!(slot(&mut state, PENDING_ADMIN), U256::ZERO); } @@ -670,7 +661,7 @@ fn schedule( succeeded } -/// A state whose registry the first block deploys, with a funded admin. +/// 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))); @@ -683,30 +674,134 @@ fn state_with_funded_admin() -> State { #[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_config().min_rotation_delay; + 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), word(next)); + 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), word(common::SEQUENCER), "not before"); + 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), word(next), "applied at its block"); + 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_config().min_rotation_delay; + 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 index 66e4ce37c..a1c4549c3 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -1,47 +1,18 @@ -//! The block's state-gas limit: the transaction that reaches it is packed, every later one that -//! adds state gas is skipped, and one that adds none still fits. - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, Evm as _}; -use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, - BlockLimits, MegaContext, MegaEvm, MegaSpecId, MegaTxEnvelope, -}; +//! 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, TxEnv}, + context::BlockEnv, database::State, - interpreter::{interpreter::EthInterpreter, Interpreter}, - Database, Inspector, }; -use crate::common::{self, executor, CALLER, CHAIN_ID, CONTRACT}; - -/// Two more senders, so candidates of one block can be executed before any of them commits. -const CALLER2: Address = address!("0x2000000000000000000000000000000000000022"); -const CALLER3: Address = address!("0x2000000000000000000000000000000000000033"); - -/// An account with no code: a call to it adds no state gas. -const EMPTY: Address = address!("0x3000000000000000000000000000000000000003"); - -/// Runs [`slot_toggler`]. -const TOGGLER: Address = address!("0x1000000000000000000000000000000000000004"); - -/// Runs [`reverting_slot_writer`]. -const REVERTER: Address = address!("0x1000000000000000000000000000000000000005"); - -/// Below the execution cap, where the reservoir is empty and state gas spills onto regular gas: -/// 1,000,000 of regular gas on top of what one fresh slot, its record and the body cost at the -/// byte prices in effect. -fn gas_limit() -> 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") -} +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; @@ -57,346 +28,38 @@ fn slot_writer() -> Bytes { .build() } -/// Code that fills the slot the first calldata word names and empties it again: the first -/// `SSTORE` charges the slot's state gas, and the second gives it back. -fn slot_toggler() -> Bytes { - BytecodeBuilder::default() - .push_number(1_u8) - .append(PUSH0) - .append(CALLDATALOAD) - .append(SSTORE) - .append(PUSH0) - .append(PUSH0) - .append(CALLDATALOAD) - .append(SSTORE) - .stop() - .build() -} - -/// Code that fills the slot the first calldata word names and reverts: the frame's failure rolls -/// the slot's state gas back. -fn reverting_slot_writer() -> Bytes { - BytecodeBuilder::default() - .push_number(1_u8) - .append(PUSH0) - .append(CALLDATALOAD) - .append(SSTORE) - .revert() - .build() -} - fn state() -> State { let mut db = common::database(); db.set_account_code(CONTRACT, slot_writer()); - db.set_account_code(TOGGLER, slot_toggler()); - db.set_account_code(REVERTER, reverting_slot_writer()); - for caller in [CALLER2, CALLER3] { - db.set_account_balance(caller, U256::from(1_000_000_000_000_000_u64)); - } State::builder().with_database(db).build() } -/// A transaction from `caller` to `to`, carrying `input`. -fn tx_from( - caller: Address, - nonce: u64, - to: Address, - input: Bytes, - gas_limit: u64, -) -> Recovered { - let tx = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(to), - value: U256::ZERO, - input, - }; - let hash = B256::from(U256::from(nonce) + (U256::from_be_slice(caller.as_slice()) << 64)); - Recovered::new_unchecked( - MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), hash)), - caller, - ) -} - /// 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 { - let input = Bytes::from(U256::from(slot).to_be_bytes::<32>()); - tx_from(CALLER, nonce, CONTRACT, input, gas_limit) -} - -/// The state gas a transaction that fills one fresh slot spends, read off a probe block. -/// -/// `None` when a state byte costs nothing: no transaction adds state gas then, and the block's -/// state-gas limit has nothing to hold. -fn one_slot() -> Option { - if common::state_is_free() { - return None; - } - 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(&writes(0, 1, gas_limit())).expect("the probe executes"); - let slot = probe.gas().state; - assert_eq!(slot, common::slot_state_gas(), "a fresh slot draws its state gas"); - Some(slot) -} - -/// A block with room for one slot and a half: the second slot crosses the limit. -fn limits(slot: u64) -> BlockLimits { - BlockLimits::no_limits().with_block_state_gas_limit(slot + slot / 2) -} - -/// The n-th transaction finds the block below its limit and crosses it: it is packed. The -/// (n+1)-th adds state gas and is skipped with the state dimension's own error, leaving nothing -/// behind. A transaction after it that adds none still fits. -#[test] -fn test_the_crossing_transaction_is_packed_and_the_next_that_adds_state_is_skipped() { - let Some(slot) = one_slot() else { return }; - let mut state = state(); - let mut executor = executor(&mut state, common::block_ctx(limits(slot))); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor.execute_transaction(&writes(0, 1, gas_limit())).expect("the block has room"); - executor - .execute_transaction(&writes(1, 2, gas_limit())) - .expect("the transaction that crosses the limit is still packed"); - assert_eq!(executor.gas().state, 2 * slot, "the block overshoots by that one transaction"); - - let err = executor - .execute_transaction(&writes(2, 3, gas_limit())) - .expect_err("the next transaction adds state gas"); - assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); - assert_eq!( - executor.evm_mut().db_mut().storage(CONTRACT, U256::from(3)).unwrap(), + common::legacy_from( + CALLER, + nonce, + TxKind::Call(CONTRACT), U256::ZERO, - "the skipped transaction wrote nothing", - ); - - // The same nonce again, now writing a slot that already holds its value: no state gas. - executor - .execute_transaction(&writes(2, 1, gas_limit())) - .expect("a transaction that adds no state gas still fits"); - executor - .execute_transaction(&tx_from(CALLER, 3, EMPTY, Bytes::new(), gas_limit())) - .expect("and so does one that writes nothing at all"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 4); - assert_eq!(result.gas.state, 2 * slot, "the skipped transaction counted nothing"); -} - -/// A deposit is not a transaction the builder chose: the block derived from L1 must include it, -/// so the state-gas limit never refuses one, however far past it the block is. It still counts, -/// so an ordinary transaction after the deposits finds the room they used. -#[test] -fn test_a_deposit_is_never_refused_by_the_state_gas_limit() { - let Some(slot) = one_slot() else { return }; - let mut state = state(); - let mut executor = executor(&mut state, common::block_ctx(limits(slot))); - executor.apply_pre_execution_changes().expect("the block starts"); - - let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - let deposit = |slot: u64| common::deposit_tx_to(CONTRACT, slot_word(slot), gas_limit()); - - executor.execute_transaction(&deposit(1)).expect("the block has room"); - executor.execute_transaction(&deposit(2)).expect("the deposit that crosses the limit"); - assert_eq!(executor.gas().state, 2 * slot, "two deposits crossed the limit between them"); - - executor - .execute_transaction(&deposit(3)) - .expect("a deposit is included whatever the block's state gas"); - assert_eq!(executor.gas().state, 3 * slot, "and it counts"); - - let err = executor - .execute_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(4), gas_limit())) - .expect_err("an ordinary transaction that adds state gas finds no room left"); - assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); - assert!(format!("{err}").contains(&format!("block_used={}", 3 * slot)), "{err}"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 3); - assert_eq!(result.gas.state, 3 * slot); -} - -/// A builder that executes candidates against the same pre-state and then picks among them gets -/// the same rule at commit: the block's state gas may have been reached while a candidate waited. -#[test] -fn test_the_state_gas_limit_is_checked_again_at_commit() { - let Some(slot) = one_slot() else { return }; - let mut state = state(); - let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); - let mut executor = executor(&mut state, common::block_ctx(limits)); - executor.apply_pre_execution_changes().expect("the block starts"); - - let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - let first = executor.run_transaction(&writes(0, 1, gas_limit())).expect("the block has room"); - let second = executor - .run_transaction(&tx_from(CALLER2, 0, CONTRACT, slot_word(2), gas_limit())) - .expect("nothing has committed yet"); - let third = executor - .run_transaction(&tx_from(CALLER3, 0, EMPTY, Bytes::new(), gas_limit())) - .expect("nothing has committed yet"); - assert!(second.gas.state > 0 && third.gas.state == 0); - - executor.commit_transaction_outcome(first).expect("the block has room"); - assert_eq!(executor.gas().state, slot, "the block has spent exactly its limit"); - - let err = executor - .commit_transaction_outcome(second) - .expect_err("the block reached its state gas while this transaction waited"); - assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); - executor.commit_transaction_outcome(third).expect("a transaction that adds none still fits"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 2); - assert_eq!(result.gas.state, slot); -} - -/// Reads the transaction's own frame's state gas after every instruction it runs, and keeps the -/// most it rose above where the frame started. -#[derive(Default)] -struct PeakStateGas { - start: Option, - peak: i64, -} - -impl Inspector for PeakStateGas { - fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { - self.start.get_or_insert_with(|| interp.gas.state_gas_spent()); - } - - fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { - let start = self.start.expect("a step starts before it ends"); - self.peak = self.peak.max(interp.gas.state_gas_spent() - start); - } -} - -/// The state gas a call from [`CALLER2`] to `to` carrying `input` draws partway through, on an EVM -/// of its own: the most its frame's state gas rose while it ran. The transaction ends with none. -fn state_gas_drawn_partway(to: Address, input: Bytes) -> u64 { - let ctx = MegaContext::new(state(), MegaSpecId::SATIN) - .with_block(BlockEnv { gas_limit: gas_limit(), ..Default::default() }) - .with_chain(zero_fee_l1_block_info()); - let mut evm = MegaEvm::new(ctx).with_inspector(PeakStateGas::default()); - let tx = OpTx(op_transaction(TxEnv { - caller: CALLER2, - kind: TxKind::Call(to), - data: input, - gas_limit: gas_limit(), - ..Default::default() - })); - let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - assert_eq!(outcome.gas.state, 0, "it ends with no state gas"); - u64::try_from(evm.inspector().peak).expect("state gas does not fall below where it started") -} - -/// A transaction whose state gas rises while it runs and comes back to zero before it ends adds -/// none: after the block reached its limit it still fits, whether a write-back gave the slot's -/// state gas back or its frame's failure rolled it back. The limit reads the state gas a -/// transaction ends with, not what it drew on the way. Below the execution cap and above it. -#[test] -fn test_a_transaction_whose_state_gas_comes_back_to_zero_still_fits() { - let Some(slot) = one_slot() else { return }; - let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - assert_eq!(state_gas_drawn_partway(TOGGLER, slot_word(7)), slot, "the write-back's"); - assert_eq!(state_gas_drawn_partway(REVERTER, slot_word(8)), slot, "the reverted write's"); - - for gas_limit in [gas_limit(), ABOVE_CAP] { - 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::block_ctx(limits(slot)), env); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor.execute_transaction(&writes(0, 1, gas_limit)).expect("the block has room"); - executor.execute_transaction(&writes(1, 2, gas_limit)).expect("the crossing is packed"); - assert_eq!(executor.gas().state, 2 * slot, "the block has reached its limit"); - - for (caller, to, slot_index) in [(CALLER2, TOGGLER, 7), (CALLER3, REVERTER, 8)] { - let outcome = executor - .run_transaction(&tx_from(caller, 0, to, slot_word(slot_index), gas_limit)) - .expect("a transaction that ends with no state gas fits"); - assert_eq!(outcome.gas.state, 0, "{to} at {gas_limit}"); - if gas_limit > TX_GAS_LIMIT_CAP { - assert_eq!( - outcome.gas.reservoir_remaining, - gas_limit - TX_GAS_LIMIT_CAP - outcome.gas.history, - "{to} at {gas_limit}: what the reservoir paid for the slot came back to it", - ); - } - executor.commit_transaction_outcome(outcome).expect("and it commits"); - } - - let err = executor - .execute_transaction(&writes(2, 3, gas_limit)) - .expect_err("one that ends with state gas is still refused"); - assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 4); - assert_eq!(result.gas.state, 2 * slot); - } -} - -/// 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 above -/// refuses. The trait's commit makes the same check in a debug build and trips on it. -#[cfg(debug_assertions)] -#[test] -fn test_the_trait_commit_trips_on_an_outcome_the_block_has_no_room_for() { - let Some(slot) = one_slot() else { return }; - let mut state = state(); - let limits = BlockLimits::no_limits().with_block_state_gas_limit(slot); - let mut executor = executor(&mut state, common::block_ctx(limits)); - executor.apply_pre_execution_changes().expect("the block starts"); - - let slot_word = |slot: u64| Bytes::from(U256::from(slot).to_be_bytes::<32>()); - let first = executor - .execute_transaction_without_commit(&writes(0, 1, gas_limit())) - .expect("the block has room"); - let second = executor - .execute_transaction_without_commit(&tx_from( - CALLER2, - 0, - CONTRACT, - slot_word(2), - gas_limit(), - )) - .expect("nothing has committed yet"); - assert!(second.gas.state > 0); - - BlockExecutor::commit_transaction(&mut executor, first); - assert_eq!(executor.gas().state, slot, "the block has spent exactly its limit"); - // Caught rather than expected of the whole test, which returns early where no transaction - // adds state gas. - 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}"); + 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 and caps it the -/// same way: the ledger is the state gas spent, whichever pool paid it. +/// 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_state_gas_limit_counts_what_the_reservoir_paid() { - let Some(slot) = one_slot() else { return }; +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::block_ctx(limits(slot)), 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)] { + 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"); @@ -405,18 +68,10 @@ fn test_the_state_gas_limit_counts_what_the_reservoir_paid() { outcome.gas.reservoir_remaining, ABOVE_CAP - TX_GAS_LIMIT_CAP - outcome.gas.state - outcome.gas.history, ); - executor.commit_transaction_outcome(outcome).expect("the crossing transaction is packed"); + executor.commit_transaction_outcome(outcome).expect("no block limit refuses it"); } - let err = executor - .execute_transaction(&writes(2, 3, ABOVE_CAP)) - .expect_err("the next transaction adds state gas"); - assert!(format!("{err}").contains("Block state gas limit reached"), "{err}"); - executor - .execute_transaction(&writes(2, 1, ABOVE_CAP)) - .expect("a transaction that adds no state gas still fits"); - let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 3); - assert_eq!(result.gas.state, 2 * slot); + 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 index 5dbce049c..1276242de 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -6,10 +6,10 @@ //! 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, Signed, TxLegacy, TxReceipt}; +use alloy_consensus::{transaction::Recovered, Sealed, TxReceipt}; use alloy_evm::block::BlockExecutor; use alloy_primitives::{ - address, logs_bloom, Address, BloomInput, Bytes, Log, Signature, TxKind, B256, U256, + address, keccak256, logs_bloom, Address, BloomInput, Bytes, Log, TxKind, B256, U256, }; use alloy_sol_types::SolCall; use mega_evm::{ @@ -20,9 +20,14 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use op_alloy_consensus::{OpReceiptEnvelope, TxDeposit}; -use revm::{bytecode::opcode::LOG1, database::State}; +use revm::{ + bytecode::opcode::{LOG1, POP}, + context::ContextTr, + database::State, + Database, +}; -use crate::common::{self, executor, CALLER, CHAIN_ID}; +use crate::common::{self, executor, CALLER}; /// An account with no code. const PAYEE: Address = address!("0x7000000000000000000000000000000000000001"); @@ -74,21 +79,7 @@ fn legacy( value: u64, input: Bytes, ) -> Recovered { - let tx = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce, - gas_price: 1_000_000, - gas_limit: gas_limit(), - to, - value: U256::from(value), - input, - }; - let signed = Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::repeat_byte(nonce as u8 + 0x10), - ); - Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), signer) + 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`. @@ -235,3 +226,92 @@ fn test_a_system_transaction_receipt_logs_no_transfer() { 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 34137b6d7..e70acfc35 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -2,14 +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::{note_price_guard, op_transaction, zero_fee_l1_block_info}, - LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionOutcome, + 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, }; @@ -39,17 +40,6 @@ pub(crate) fn call_with_data( tx(caller, TxKind::Call(to), data, U256::ZERO, gas_limit) } -/// A call from `caller` to `to` carrying `value` and `data`. -pub(crate) fn call_with_value_and_data( - caller: Address, - to: Address, - value: U256, - data: Bytes, - gas_limit: u64, -) -> MegaTransaction { - tx(caller, TxKind::Call(to), data, value, 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) @@ -118,6 +108,40 @@ pub(crate) fn execute( 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 @@ -164,6 +188,22 @@ pub(crate) fn history_is_free() -> bool { 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 { @@ -175,13 +215,24 @@ 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. +/// 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 { - mega_evm::history_gas(bytes).expect("the bytes have a price") + 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. +/// 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_history_bytes(calldata_len, 0, 0, 0)) + 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 index 8f8314a99..279485668 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -23,7 +23,7 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADD, CALL, DUP1, GAS, JUMPDEST, JUMPI, LOG0, MLOAD, MSTORE, MUL, POP, PUSH0, PUSH1, PUSH3, + ADD, CALL, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, MSTORE, MUL, POP, PUSH0, PUSH1, PUSH3, SELFDESTRUCT, SLOAD, SUB, SWAP1, }, context::{ @@ -31,6 +31,7 @@ use revm::{ transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, + context_interface::cfg::GasId, interpreter::{interpreter::EthInterpreter, Interpreter}, precompile::{ bn254::pair, @@ -42,7 +43,7 @@ use revm::{ use crate::{ common::{call, call_with_data, context, execute, runs_at_measurement_prices}, - salt::{crowded_account, minimal_envs}, + salt::{crowded_account, entry, minimal_envs}, }; const CALLER: Address = address!("0000000000000000000000000000000000c00000"); @@ -267,23 +268,6 @@ fn test_memory_expansion_is_computed() { assert_eq!(computed_beyond_empty(code), 3 + 3 + (3 + 3 * 3) + 3 + 3 + 2); } -/// A log's own price is computation — its static cost, eight gas a byte and the memory it reads — -/// and its bytes are history, on their own ledger. -#[test] -fn test_a_log_is_computed_and_its_bytes_are_history() { - if runs_at_measurement_prices() { - return; - } - let code = || BytecodeBuilder::default().push_number(32_u8).append(PUSH0).append(LOG0).stop(); - // `PUSH1`, `PUSH0`, then `LOG0`: 375, eight a byte, and one word of memory. - assert_eq!(computed_beyond_empty(code().build()), 3 + 2 + 375 + 8 * 32 + 3); - for gas_limit in GAS_LIMITS { - let logged = computes(code().build(), gas_limit); - let quiet = computes(Bytes::new(), gas_limit); - assert_eq!(logged.history - quiet.history, (32 + 32) * COST_PER_HISTORY_BYTE); - } -} - /// 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] @@ -306,18 +290,21 @@ fn test_storage_computes_what_is_neither_state_nor_history() { 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 — the cold surcharge and Osaka's price for - // setting a slot, which the schedule keeps beside the state gas; `PUSH0`; a warm `SLOAD`; - // `POP`. - assert_eq!(computed, 3 + 3 + (2_100 + 20_000) + 2 + 100 + 2); + // 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 (EIP-3529). - const SSTORE_CLEARS_SCHEDULE: u64 = 4_800; + // 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( @@ -334,12 +321,9 @@ fn test_a_refund_does_not_lower_the_compute_figure() { 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; the history the transaction pays lifts the cap past the refund at the - // spec's prices. - let cap = overwritten.gas_used / - mega_evm::satin_gas_params() - .get(revm::context_interface::cfg::GasId::max_refund_quotient()); - assert_eq!(overwritten.gas_used - cleared.gas_used, SSTORE_CLEARS_SCHEDULE.min(cap)); + // 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()); } @@ -556,11 +540,8 @@ fn test_a_nested_call_cannot_compute_past_the_cap() { } /// 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 83,328 addresses is 2,400 gas each +/// 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. -/// -/// Calldata reaches the cap through its floor first, sixty-four gas a byte against sixteen, and is -/// rejected the same way. #[test] fn test_intrinsic_gas_past_the_execution_cap_is_rejected_before_it_runs() { if runs_at_measurement_prices() { @@ -583,29 +564,16 @@ fn test_intrinsic_gas_past_the_execution_cap_is_rejected_before_it_runs() { err.as_invalid_tx_err().and_then(InvalidTxError::as_invalid_tx_err).cloned() }; - let admitted = execute(funded(), with_addresses(83_327)); + 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 + 2_400 * 83_327); - assert_eq!( - rejection(with_addresses(83_328)), - Some(InvalidTransaction::GasFloorMoreThanGasLimit { - gas_floor: EMPTY_CALL + 2_400 * 83_328, - gas_limit: TX_GAS_LIMIT_CAP, - }), - ); - - let calldata = (TX_GAS_LIMIT_CAP - EMPTY_CALL) / 64 + 1; - let tx = call_with_data( - CALLER, - CALLEE, - Bytes::from(vec![0; calldata as usize]), - TX_GAS_LIMIT_CAP + 400_000_000, - ); + assert_eq!(admitted.gas.regular, EMPTY_CALL + address * inside); assert_eq!( - rejection(tx), + rejection(with_addresses(inside as usize + 1)), Some(InvalidTransaction::GasFloorMoreThanGasLimit { - gas_floor: EMPTY_CALL + 64 * calldata, + gas_floor: EMPTY_CALL + address * (inside + 1), gas_limit: TX_GAS_LIMIT_CAP, }), ); diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs index cb0e4f916..22c935f7b 100644 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -15,7 +15,6 @@ use mega_evm::{ 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, history}; @@ -92,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() { @@ -110,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() { @@ -143,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, @@ -187,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/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 2dd958a02..8188ca906 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -1,12 +1,13 @@ //! 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 reverts the -//! child alone and its parent resumes. Crossing the transaction's own limit stops the transaction -//! through the same latch every other transaction-level limit uses. +//! 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. 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. +//! 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}; @@ -20,20 +21,21 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, CREATE2, GAS, ISZERO, LOG0, POP, PUSH0, RETURN, RETURNDATACOPY, - RETURNDATASIZE, REVERT, SELFDESTRUCT, SSTORE, STOP, + 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, CreateInputs, CreateOutcome, InstructionResult, Interpreter, + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + InstructionResult, Interpreter, }, Database, Inspector, }; use crate::common::{ - account_state_gas, body_history, call, call_with_data, context, create, history, - slot_state_gas, state_is_free, + 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"); @@ -50,10 +52,13 @@ fn gas_for_history(bytes: u64) -> u64 { GAS_LIMIT + 2 * history(bytes) } -/// 98% of `remaining`, the share a child frame is given. -fn share(remaining: u64) -> u64 { - (u128::from(remaining) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / - u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 +/// 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. @@ -102,8 +107,8 @@ fn budget_at_depth_3(cap: u64) -> u64 { } /// 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 is not -/// latched. +/// `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; @@ -116,23 +121,23 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { let result = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); ( result, - evm.ctx().additional_limit().latched().copied(), + 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, latched, usage) = run(budget - 32); + let (fits, stop, usage) = run(budget - 32); assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(latched, None); + 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, latched, usage) = run(budget - 31); + let (over, stop, usage) = run(budget - 31); assert!(over.result.is_success(), "the callers resume: {:?}", over.result); - assert_eq!(latched, None, "a frame budget does not latch the transaction"); + 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!( @@ -142,49 +147,35 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { } /// The same depth, with the transaction's limit tighter than the frame budgets. `D`'s log crosses -/// the transaction limit, so the latch stops every caller: the slots they wrote are not kept, and -/// the revert names the transaction limit. +/// 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_stops_the_transaction() { +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 db = chain(log0(TX_LIMIT)); - let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) - .unwrap(); + 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()); - assert!(!outcome.result.is_halt(), "a data-size stop is a revert: {:?}", outcome.result); - // Nothing was written before the log, so the crossing usage is the body plus the log: 32 for - // its address and `TX_LIMIT` of data. The revert drops the log; the body stays. - let crossed = mega_evm::TX_BODY_SIZE + 32 + TX_LIMIT; - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: TX_LIMIT, - used: crossed, - frame_local: false, - }) - ); + 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!( - outcome.usage.data_size, - mega_evm::TX_BODY_SIZE, - "the revert drops the log and keeps the body" + evm.inspector().calls.first(), + Some(&(D, InstructionResult::Revert, Bytes::from(stop.abi_encode()))), + "D returned the stop" ); - match &outcome.result { - revm::context::result::ExecutionResult::Revert { output, .. } => { - assert_eq!( - output.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: TX_LIMIT } - .abi_encode() - ); - } - other => panic!("expected the latched revert, got {other:?}"), - } - assert!(!stored(&outcome.state, A) && !stored(&outcome.state, B) && !stored(&outcome.state, C)); + 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 stays inside the limit and keeps every caller's slot. + // 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), @@ -193,14 +184,17 @@ fn test_depth_3_transaction_limit_stops_the_transaction() { .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. +/// 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 { @@ -208,6 +202,16 @@ impl Inspector, EthInterpreter> for Probe { 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, @@ -218,16 +222,6 @@ impl Inspector, EthInterpreter> for Probe { } } -/// Init code that returns `size` zero bytes as the deployed contract. -fn constructor_returning(size: u64) -> Bytes { - BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() -} - -/// Init code that reverts with `len` bytes and deploys nothing. -fn reverting_with(len: u8) -> Bytes { - BytecodeBuilder::default().push_number(len).push_number(0_u8).append(REVERT).build() -} - /// A contract that `CREATE`s `deployed` bytes and stops. fn factory_deploying(deployed: u64) -> Bytes { let init = constructor_returning(deployed); @@ -276,43 +270,10 @@ fn test_calldata_counts_in_the_body() { assert_eq!(run(0xff), expected, "a non-zero byte"); } -/// A body that crosses the transaction limit stops the transaction before its code runs. The -/// body stays counted: it is what crossed. -#[test] -fn test_a_body_over_the_limit_stops_before_any_frame() { - let db = funded().account_code( - A, - BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), - ); - let limit = mega_evm::TX_BODY_SIZE - 1; - let mut evm = MegaEvm::new( - context(db) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), - ) - .with_inspector(Probe::default()); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - - assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); - assert_eq!(evm.inspector().steps, 0, "the callee never ran"); - assert_eq!( - evm.ctx().additional_limit().latched().copied(), - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: mega_evm::TX_BODY_SIZE, - frame_local: false, - }) - ); - assert_eq!( - evm.ctx().additional_limit().usage(), - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, - ); - assert!( - result.state.get(&A).is_none_or(|account| { - account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) - }), - "the callee's write was never made", - ); +/// 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 @@ -397,24 +358,24 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { ( result, evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().latched().copied(), + evm.ctx().additional_limit().limit_exceeded().copied(), evm.inspector().clone(), ) }; for inspect in [false, true] { - let (kept, usage, latched, _) = run(fits, inspect); + let (kept, usage, stop, _) = run(fits, inspect); assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); - assert_eq!(latched, None); + 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, latched, probe) = run(fits + 1, inspect); + let (over, usage, stop, probe) = run(fits + 1, inspect); assert!(over.result.is_success(), "the caller resumes: {:?}", over.result); - assert_eq!(latched, None, "a frame budget does not latch the transaction"); + 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 }, @@ -468,9 +429,10 @@ fn factory_noting_failure(init: &Bytes) -> Bytes { /// 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, crosses the transaction's limit and stops it: 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. +/// 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 @@ -528,34 +490,27 @@ fn test_code_return_create_refuses_is_not_counted() { max * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + history(max) + 1_000_000_000; - let (stopped, _) = run(&deployable, inspect, roomy); + 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!( - stopped.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: mega_evm::TX_BODY_SIZE + at_start + len.min(max), - frame_local: false, - }), - "{case}", + 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", + ); + } } } } -/// The output of a reverting creation is revert data, not deployed code, so it is not counted. -#[test] -fn test_a_reverting_creation_does_not_count_its_output() { - let init = reverting_with(40); - let (outcome, _) = run_create(init.clone(), EvmTxRuntimeLimits::no_limits(), false); - assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.limit_exceeded, None, "the revert is the init code's, not a stop"); - assert_eq!( - outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + init.len() as u64, write_records: 0 }, - ); -} - fn run_at(db: MemoryDatabase, tx: mega_evm::MegaTransaction, limit: u64) -> MegaTransactionOutcome { MegaEvm::new( context(db) @@ -578,32 +533,6 @@ fn assert_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { ); } -/// Calldata is in the body. One byte over that count stops the transaction before the callee -/// runs, so a store the callee would have made is not part of the crossing figure. -#[test] -fn test_calldata_one_byte_over_stops_before_the_callee() { - let data = Bytes::from(vec![0xab; 50]); - let body = mega_evm::TX_BODY_SIZE + data.len() as u64; - let db = || { - funded().account_code( - A, - BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), - ) - }; - - let fits = run_at(db(), call_with_data(CALLER, A, data.clone(), GAS_LIMIT), body + 40); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.usage, LimitUsage { data_size: body + 40, write_records: 1 }); - - let over = run_at(db(), call_with_data(CALLER, A, data, GAS_LIMIT), body - 1); - assert_stopped(&over, body - 1, body); - assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); - assert!(over.result.logs().is_empty()); - assert!(over.state.get(&A).is_none_or(|account| { - account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) - })); -} - /// 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] @@ -699,7 +628,9 @@ enum Bound { 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 transaction reports. + /// 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, @@ -711,19 +642,65 @@ fn fresh_slot() -> Bytes { } /// `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. +/// two accounts, `A`'s and [`FRESH`]'s, answering as [`answer_the_call`] does. fn value_call_to_fresh() -> Bytes { - BytecodeBuilder::default() + let code = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) .push_number(1_u8) .push_address(FRESH) .append(GAS) - .append(CALL) - .append(POP) - .stop() + .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 { @@ -749,9 +726,18 @@ fn bound_at(code: &Bytes, gas_limit: u64, data_limit: u64) -> Bound { assert!(outcome.limit_exceeded.is_some(), "{:?}", outcome.result); Bound::DataSize } - ExecutionResult::Success { .. } => { + ExecutionResult::Success { output, .. } => { assert_eq!(outcome.limit_exceeded, None); - Bound::Success + // 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, + } } }, } @@ -785,14 +771,14 @@ fn gas_where_the_write_is_counted(code: &Bytes, data_limit: u64) -> u64 { /// | 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,100 cold, 19,900 set | 22,100 | +/// | 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** | **162,306** | +/// | **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 = 162_306; +const FRESH_SLOT_COUNTED_AT: u64 = 152_306; /// A write meets two limits, and the one that binds first is the one reported. /// @@ -872,24 +858,39 @@ fn test_the_fresh_slot_boundary_is_the_sum_of_its_parts() { } 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), (22_100, 97_920)); + 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 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 = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let start = START_ON_THE_CALLER + START_ON_THE_FRAME; let crosses = mega_evm::TX_BODY_SIZE + start - 1; - let fits = mega_evm::TX_BODY_SIZE + start; + 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); @@ -897,6 +898,316 @@ fn test_a_frame_start_is_charged_before_its_records_are_counted() { 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 ---------- */ @@ -909,26 +1220,7 @@ 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 { - use revm::{ - context::{transaction::TransactionType, TxEnv}, - context_interface::{ - either::Either, - transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, - }, - }; - let authorization = Either::Right(RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::ZERO, address: B, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY), - )); - alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { - tx_type: TransactionType::Eip7702 as u8, - caller: CALLER, - kind: alloy_primitives::TxKind::Call(A), - gas_limit, - gas_priority_fee: Some(0), - authorization_list: vec![authorization], - ..Default::default() - })) + 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 @@ -958,98 +1250,37 @@ fn smallest_gas_limit(high: u64, accepted: impl Fn(u64) -> bool) -> u64 { high } -/// A body over the limit is the stop at every gas limit validation accepts. -/// -/// A gas limit that covers the intrinsic cost and no more cannot pay what the transaction's start -/// costs past it: the account a value transfer or a creation adds, the write record of it, and an -/// authorization's delegation. Without a limit, each of these transactions runs out of gas there, -/// before its first frame. With the body over the limit none of those writes is made — the first -/// frame is answered with the stop — so none is charged, and the transaction reports the stop that -/// bound first. It pays its intrinsic cost and nothing else. +/// 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_the_stop_at_the_smallest_valid_gas_limit() { +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), - ("an authorization", authorizing_call, mega_evm::AUTHORIZATION_SIZE), + // 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 body = mega_evm::TX_BODY_SIZE + extra; - let limit = body - 1; + 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), limit).is_some()), + smallest_gas_limit(GAS_LIMIT, |gas| outcome_at(tx(gas), at).is_some()), valid, - "{name}: the limit does not move validation" + "{name}: a limit the transaction fits does not move validation" ); - - let stopped = outcome_at(tx(valid), limit).unwrap(); - // Where a state byte and a record's history are both free the start costs nothing past - // the intrinsic gas, and there is no out-of-gas for the stop to stand in for. Where a - // history byte is cheap enough, the calldata floor lifts the smallest valid gas limit past - // the intrinsic cost, which the stop spends alone, and what it covers past it may pay the - // start. - let free = state_is_free() && history(WRITE_RECORD_SIZE) == 0; - if !free && valid == stopped.result.gas().total_gas_spent() { - let unlimited = outcome_at(tx(valid), u64::MAX).unwrap(); - assert!( - matches!( - unlimited.result, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), - .. - } - ), - "{name}: without a limit the start runs out of gas, got {:?}", - unlimited.result - ); + 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:?}")); } - - assert_stopped(&stopped, limit, body); - assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); - assert_eq!(stopped.result.gas().tx_gas_used(), valid, "{name}: the intrinsic cost only"); - - // A gas limit above the smallest one pays the same: nothing past the intrinsic cost is - // charged, so nothing is burnt either. - let above = outcome_at(tx(valid + 10_000), limit).unwrap(); - assert_stopped(&above, limit, body); - assert_eq!(above.result.gas().tx_gas_used(), valid, "{name}: the stop burns nothing"); } } -/// A creation transaction stopped at the smallest gas limit validation accepts still bumps its -/// sender's nonce, and an authorization its body carried is not applied. -#[test] -fn test_a_stopped_start_bumps_a_creators_nonce_and_applies_no_authorization() { - let init = constructor_returning(1); - let limit = mega_evm::TX_BODY_SIZE + init.len() as u64 - 1; - let valid = smallest_gas_limit(GAS_LIMIT, |gas| { - outcome_at(create(CALLER, init.clone(), gas), limit).is_some() - }); - let stopped = outcome_at(create(CALLER, init, valid), limit).unwrap(); - assert!(stopped.limit_exceeded.is_some(), "{:?}", stopped.result); - assert_eq!(stopped.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); - assert!(stopped - .state - .get(&CALLER.create(0)) - .is_none_or(|account| account.info.is_empty_code_hash() && account.info.nonce == 0)); - - let limit = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE - 1; - let valid = - smallest_gas_limit(GAS_LIMIT, |gas| outcome_at(authorizing_call(gas), limit).is_some()); - let stopped = outcome_at(authorizing_call(valid), limit).unwrap(); - assert!(stopped.limit_exceeded.is_some(), "{:?}", stopped.result); - assert!( - stopped - .state - .get(&AUTHORITY) - .is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), - "the delegation was not applied" - ); -} - /* ---------- the 98% share, measured in slots ---------- */ /// Enough gas for a hundred fresh slots and a call or two around them. @@ -1140,7 +1371,7 @@ fn test_a_child_gets_98_percent_of_what_its_parent_has_left_in_slots() { 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 does not latch"); + 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| { @@ -1154,45 +1385,6 @@ fn test_a_child_gets_98_percent_of_what_its_parent_has_left_in_slots() { } } -/// The child that crosses its share reverts with `MegaLimitExceeded` naming the data size and -/// the share it crossed, which is what its caller reads. -#[test] -fn test_a_child_that_crosses_its_share_reverts_with_the_share() { - let returns_revert_data = then_call(BytecodeBuilder::default(), B) - .append(RETURNDATASIZE) - .append_many([PUSH0, PUSH0]) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(RETURN) - .build(); - let db = funded() - .account_code(A, returns_revert_data) - .account_code(B, write_slots(BytecodeBuilder::default(), 99).stop().build()); - let outcome = run_slots(db, room_for(100)); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let reverted = MegaLimitExceeded::abi_decode(outcome.result.output().unwrap()).unwrap(); - assert_eq!(reverted.kind, LimitKind::DataSize.as_u8()); - assert_eq!(reverted.limit, 98 * WRITE_RECORD_SIZE); -} - -/// The transaction's own frame gets what the body leaves: with room for 5 slots, 5 are kept and a -/// sixth stops the transaction. Its frame's budget is the transaction's own limit, so the -/// crossing is the transaction's, not a frame-local revert. -#[test] -fn test_the_first_frame_gets_what_the_body_leaves() { - let run = |n| { - run_slots( - funded().account_code(A, write_slots(BytecodeBuilder::default(), n).stop().build()), - room_for(5), - ) - }; - let fits = run(5); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.usage.data_size, room_for(5)); - assert_stopped(&run(6), room_for(5), room_for(6)); -} - /// 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] @@ -1210,10 +1402,10 @@ fn test_the_body_and_the_execution_add_up_to_the_stop() { } } -/// A body over the limit is stopped before an interceptor could answer the transaction's own -/// call: the stop is the first frame's answer, whatever the frame's target. +/// 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_stopped_before_an_interceptor() { +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; @@ -1222,18 +1414,11 @@ fn test_a_body_over_the_limit_is_stopped_before_an_interceptor() { || 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 stopped = run_at(funded(), tx(), body - 1); - assert_stopped(&stopped, body - 1, body); - assert_eq!( - stopped.result.output().unwrap(), - &LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: body - 1, - used: body, - frame_local: false, - } - .revert_data(), - ); + 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 ---------- */ @@ -1313,7 +1498,7 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { 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 does not latch"); + 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 }, diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 7d0253814..24c041faf 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -16,13 +16,15 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, RETURN, SELFDESTRUCT, - SLOAD, SSTORE, STATICCALL, STOP, + CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, SELFDESTRUCT, SLOAD, + SSTORE, STATICCALL, STOP, }, context::result::ExecutionResult, }; -use crate::common::{call, call_with_data, context, create, execute}; +use crate::common::{ + call, call_with_data, constructor_returning, context, create, execute, execute_under, +}; const CALLER: Address = address!("0000000000000000000000000000000000400000"); const CALLEE: Address = address!("0000000000000000000000000000000000400001"); @@ -51,11 +53,6 @@ const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { kept(0, records * WRITE_RECORD_SIZE + moves * TRANSFER_LOG_SIZE, records) } -/// Init code that returns `size` zero bytes as the deployed contract. -fn constructor_returning(size: u64) -> Bytes { - BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() -} - /// A contract that `CREATE`s `init` and stops. fn factory(init: &Bytes) -> Bytes { BytecodeBuilder::default() @@ -380,16 +377,11 @@ 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 = MegaEvm::new(context(db()).with_tx_runtime_limits( + 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), - )) - .execute_transaction(call_with_data( - CALLER, - CALLEE, - Bytes::from(vec![0xab; calldata]), - GAS_LIMIT, - )) - .unwrap(); + ); assert!(outcome.result.is_success(), "{calldata} bytes: {:?}", outcome.result); assert_eq!(outcome.usage.data_size, limit); assert_eq!(outcome.limit_exceeded, None); diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index cf6cf4383..3f05874bc 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -1,96 +1,257 @@ -//! Deployed code is held to the limits only once `return_create` charged every part of its -//! deposit. +//! 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. //! -//! `return_create` charges a creation's deposit in this order: the regular deposit cost, the -//! regular cost of hashing the code under EIP-8037, then the code's state gas — the reservoir -//! first, then regular gas — and last the code's history, the same way. A creation that cannot -//! pay one of them runs out of gas there, alone, and the chain keeps none of its code. The -//! state-gas limit and the data-size limit both hold the deposit after the last of those charges -//! and before `return_create` commits it: a creation that cannot pay a charge runs out of gas -//! whatever the limit, and its caller goes on. +//! 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. //! -//! Each case finds its boundary on the engine: the least gas `A` can call the creator `B` with for -//! the creation to deposit its code when no limit is set. The creation then has no regular gas left -//! after the deposit, so it is exactly enough. With that gas a limit the deposit crosses stops the -//! creation; one gas short the creation runs out of gas, under the limit exactly as without it. -//! -//! Which charge the creation runs out of gas on follows from where the gas comes from. Above the -//! execution cap the reservoir pays the code's state gas and history, so the last regular charge -//! 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. 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, BytecodeBuilder, MemoryDatabase}, - EthSpecId, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, - MegaTransactionOutcome, + 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, MSTORE, POP, PUSH0, RETURN, RETURNDATASIZE, SSTORE}, + bytecode::opcode::{CALL, CREATE, MLOAD, POP, PUSH0, RETURN, STOP}, context_interface::cfg::GasId, inspector::NoOpInspector, - interpreter::{interpreter::EthInterpreter, CreateInputs, CreateOutcome}, + interpreter::{ + interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, + InterpreterResult, + }, Database, Inspector, }; -use crate::common::{call, context, history_is_free, state_is_free}; +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, keeps what `B` answers in slot 1, then writes slot 0. +/// Calls `B` with a chosen gas and stops. const A: Address = address!("0000000000000000000000000000000000a00001"); -/// Creates the code with everything it has, and answers with the size of what the creation -/// returned: a stop's revert data, or nothing. +/// Creates the code with all but a 64th of what it has, and stops. const B: Address = address!("0000000000000000000000000000000000a00002"); -/// The bytes the creation deploys. -/// -/// Enough that the deposit, and not `B`, binds at any byte price. `B` keeps a sixty-fourth of what -/// it forwards, and below the execution cap it pays the history of the creation's two write -/// records, 80 bytes, out of it after the forward; the creation pays the history of every byte of -/// its code at the same price, and their state gas on top. More than 63 × 80 bytes of code outweigh -/// the records whatever the prices, where a kilobyte does only while a state byte is dear. -const CODE_LEN: u16 = 6 * 1_024; - -/// At the execution cap: the whole gas limit is regular gas, there is no reservoir, and every state -/// charge is paid out of regular gas. Half of it pays for the creation's deposit at any byte price -/// up to several times the dearest one considered. -const BELOW_CAP: u64 = TX_GAS_LIMIT_CAP; -/// Above the execution cap: the reservoir pays every state and history charge. -const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; - -/// The neutral configuration's gas limit: Osaka holds a transaction to 2^24 gas (EIP-7825). -const NEUTRAL_GAS_LIMIT: u64 = 10_000_000; +/// 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)] -enum Setup { - /// Satin's own configuration, with this gas limit. - Satin(u64), +#[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, } -/// `A` calling `B` with `gas`. +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. /// -/// The creation's init code touches memory far out before it returns the code, which costs it a -/// few thousand gas: `B` keeps a sixty-fourth of what it forwards, and that has to be enough for -/// it to answer however little the creation gives back. +/// 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 = BytecodeBuilder::default() - .push_number(0x8000_u16) - .append(MLOAD) - .append(POP) - .push_number(CODE_LEN) - .push_number(0_u8) - .append(RETURN) - .build(); + let init = init_code(); let creator = BytecodeBuilder::default() .mstore(0, &init) .push_number(init.len() as u64) @@ -98,26 +259,15 @@ fn world(gas: u64) -> MemoryDatabase { .push_number(0_u64) .append(CREATE) .append(POP) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(MSTORE) - .push_number(32_u8) - .append(PUSH0) - .append(RETURN) + .append(STOP) .build(); let caller = BytecodeBuilder::default() - .push_number(32_u8) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(B) - .push_number(gas) + .push_number(u32::try_from(gas).expect("the forward fits a PUSH4")) .append(CALL) .append(POP) - .append(PUSH0) - .append(MLOAD) - .push_number(1_u8) - .append(SSTORE) - .sstore(U256::ZERO, U256::from(1)) - .stop() + .append(STOP) .build(); MemoryDatabase::default() .account_balance(CALLER, U256::from(10u64.pow(18))) @@ -126,14 +276,14 @@ fn world(gas: u64) -> MemoryDatabase { } fn evm( - setup: Setup, - gas: u64, + pool: Pool, + forward: u64, limits: EvmTxRuntimeLimits, ) -> MegaEvm { - let ctx = context(world(gas)); - match setup { - Setup::Satin(_) => MegaEvm::new(ctx.with_tx_runtime_limits(limits)), - Setup::NeutralOsaka => { + 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"); @@ -142,33 +292,30 @@ fn evm( } } -const fn gas_limit(setup: Setup) -> u64 { - match setup { - Setup::Satin(gas_limit) => gas_limit, - Setup::NeutralOsaka => NEUTRAL_GAS_LIMIT, - } +/// 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") } -/// Runs the transaction with `A` calling `B` with `gas`, under `limits`. -fn run(setup: Setup, gas: u64, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { - evm(setup, gas, limits) - .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit(setup))) - .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 { - outcome.state.get(&B.create(0)).is_some_and(|account| !account.info.is_empty_code_hash()) -} - -/// The size of what `B`'s creation returned, as `A` kept it. -fn creation_answer(outcome: &MegaTransactionOutcome) -> U256 { - outcome.state[&A].storage.get(&U256::from(1)).map(|slot| slot.present_value).unwrap_or_default() + 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 @@ -180,6 +327,18 @@ struct CreationEnd { 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, @@ -187,185 +346,278 @@ impl Inspector, EthInterpreter> for CreationEnd { _: &CreateInputs, outcome: &mut CreateOutcome, ) { - let gas = outcome.result.gas; - *self = Self { - deposited: outcome.result.is_ok(), - charged_state_gas: gas.state_gas_spent() > 0, - remaining: gas.remaining(), - reverted_with: outcome.result.is_revert().then(|| outcome.result.output.clone()), - }; + *self = Self::of(&outcome.result); } } -/// How the creation ends when `A` calls `B` with `gas` and no limit is set. -fn creation_end(setup: Setup, gas: u64) -> CreationEnd { - creation_end_under(setup, gas, EvmTxRuntimeLimits::no_limits()) +/// 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 `A` calls `B` with `gas`, under `limits`. -fn creation_end_under(setup: Setup, gas: u64, limits: EvmTxRuntimeLimits) -> CreationEnd { - let mut evm = evm(setup, gas, limits).with_inspector(CreationEnd::default()); - evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit(setup))).unwrap(); +/// 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() } -/// The least gas `A` can call `B` with for the creation to deposit its code, with no limit set; -/// and the unlimited outcome one gas short of it. -/// -/// At the boundary the creation has no regular gas left after the deposit's last charge, so it is -/// exactly enough; one gas short the creation runs out of gas and deploys nothing. The search -/// starts from half the transaction's gas, which leaves `A` the other half for its own writes. -fn boundary(setup: Setup) -> (u64, MegaTransactionOutcome) { - let (mut short, mut enough) = (0, gas_limit(setup) / 2); - assert!( - !creation_end(setup, short).deposited && creation_end(setup, enough).deposited, - "{setup:?}: the search brackets the boundary" - ); - while enough - short > 1 { - let middle = short + (enough - short) / 2; - if creation_end(setup, middle).deposited { - enough = middle; - } else { - short = middle; - } - } - let end = creation_end(setup, enough); - assert_eq!(end.remaining, 0, "{setup:?}: exactly enough: {end:?}"); +/* ---------- what each outcome looks like, by hand ---------- */ - let outcome = run(setup, short, EvmTxRuntimeLimits::no_limits()); - assert!(outcome.result.is_success(), "{setup:?}: {:?}", outcome.result); - assert!(!deployed(&outcome), "{setup:?}: one gas short, the creation runs out of gas"); - assert_eq!(creation_answer(&outcome), U256::ZERO, "{setup:?}: an out-of-gas returns nothing"); - (enough, outcome) +/// 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, + } } -/// The state gas the creation holds once its code's state gas is charged: the created account -/// and the code. -fn creation_state_gas() -> u64 { - crate::salt::entry(GasId::create_state_gas()) + - u64::from(CODE_LEN) * crate::salt::entry(GasId::code_deposit_state_gas()) +/// 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"); } -/// Under a state-gas limit one gas short of what the creation holds with its code, the creation -/// that reaches the charge is stopped, and the one that cannot runs out of gas as it does without -/// the limit: the transaction succeeds with no code deployed and the same gas. +/// 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]. /// -/// The stop latches the transaction, so the whole transaction reverts whichever frame crossed; a -/// limit held anywhere after the deposit — at `A`'s next `SSTORE`, which holds the state gas the -/// transaction has by then — would report the same stop and deploy nothing as well. The creation's -/// own end tells them apart: the deposit is held where it is made when the creation itself reverts -/// with the stop. -fn assert_state_gas_limit_stands_aside(setup: Setup) { - let (enough, short) = boundary(setup); - let creation = creation_state_gas(); - assert!(short.gas.state > 0 && short.gas.state < creation, "{setup:?}: the slot alone fits"); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(creation - 1); - - let stopped = run(setup, enough, limits); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::StateGrowth, - limit: creation - 1, - used: creation, - frame_local: false, - }; - assert_eq!(stopped.limit_exceeded, Some(stop), "{setup:?}: exactly enough, the check fires"); - assert!(!deployed(&stopped), "{setup:?}"); - let end = creation_end_under(setup, enough, limits); - assert!(!end.deposited, "{setup:?}: the deposit is refused: {end:?}"); +/// `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.reverted_with, - Some(stop.revert_data()), - "{setup:?}: the creation that made the deposit is the one the stop ends", + 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 ran_out = run(setup, enough - 1, limits); - assert!(ran_out.result.is_success(), "{setup:?}: {:?}", ran_out.result); - assert_eq!(ran_out.limit_exceeded, None, "{setup:?}: one gas short, it stands aside"); - assert!(!deployed(&ran_out), "{setup:?}"); - assert_eq!(creation_answer(&ran_out), U256::ZERO, "{setup:?}: the creation ran out of gas"); - assert_eq!(ran_out.gas, short.gas, "{setup:?}: as without the limit"); + 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); } -/// Under a frame cap the creation's code crosses, the creation that reaches the charge is stopped -/// alone — it answers with the stop's revert data — and the one that cannot runs out of gas as it -/// does without the cap. -fn assert_data_size_limit_stands_aside(setup: Setup) { - let (enough, short) = boundary(setup); - 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, +/// 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 stopped = run(setup, enough, limits); - assert!(stopped.result.is_success(), "{setup:?}: {:?}", stopped.result); + 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!( - creation_answer(&stopped), - U256::from(stop.revert_data().len()), - "{setup:?}: exactly enough, the check fires and the creation reverts with the stop", + outcome.usage, + LimitUsage { data_size: bytes, write_records: 2 }, + "{name}: the creator's nonce, the created account, and the code", ); - assert!(!deployed(&stopped), "{setup:?}"); + assert_ledgers(name, pool, regular_deposit(pool), &outcome, state, bytes); +} + +/* ---------- the four charges, one gas short of each ---------- */ - let ran_out = run(setup, enough - 1, limits); - assert!(ran_out.result.is_success(), "{setup:?}: {:?}", ran_out.result); - assert_eq!(creation_answer(&ran_out), U256::ZERO, "{setup:?}: one gas short, it stands aside"); - assert!(!deployed(&ran_out), "{setup:?}"); - assert_eq!(ran_out.gas, short.gas, "{setup:?}: as without the limit"); - assert_eq!(ran_out.usage, short.usage, "{setup:?}: and it keeps what it keeps without it"); +/// 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"); } -/// Above the execution cap the reservoir pays the code's state gas and history: a creation that -/// cannot pay the hash of its code runs out of gas on it, whatever the state-gas limit. +/// 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_that_cannot_pay_the_hash_runs_out_of_gas_under_the_state_gas_limit() { - // A deposit that adds no state gas has no state-gas limit to cross. +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 setup = Setup::Satin(ABOVE_CAP); - let (enough, _) = boundary(setup); - let end = creation_end(setup, enough - 1); - assert!(!end.charged_state_gas, "one gas short, the hash is what it cannot pay: {end:?}"); - assert_state_gas_limit_stands_aside(setup); -} - -/// Below the execution cap the code's state gas and then its history are paid out of regular gas: -/// a creation that can pay its state gas but not its history runs out of gas on the history, -/// whatever the state-gas limit. The limit holds the deposit once all of it is paid, not at the -/// state gas: a creation that could pay the state gas alone would otherwise be stopped by a limit -/// it never reaches. + 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_that_cannot_pay_its_history_runs_out_of_gas_under_the_state_gas_limit() { - // A deposit that pays no history has no history to run out of gas on, and one that adds no - // state gas has no state-gas limit to cross. - if history_is_free() || state_is_free() { +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 setup = Setup::Satin(BELOW_CAP); - let (enough, _) = boundary(setup); - let end = creation_end(setup, enough - 1); - assert!( - end.charged_state_gas && !end.deposited, - "one gas short, the history is what it cannot pay: {end:?}" + 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_state_gas_limit_stands_aside(setup); + 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(Setup::Satin(ABOVE_CAP)); - assert_data_size_limit_stands_aside(Setup::Satin(BELOW_CAP)); + 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: a creation that cannot -/// pay it runs out of gas whatever the data-size limit. +/// 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 end = creation_end(Setup::NeutralOsaka, boundary(Setup::NeutralOsaka).0); - assert!(end.deposited && !end.charged_state_gas, "no state gas without EIP-8037: {end:?}"); - assert_data_size_limit_stands_aside(Setup::NeutralOsaka); + 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 index 62c6de164..4b0a209e6 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -9,9 +9,9 @@ //! //! 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 transaction the cap stops keeps its body alone. 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. +//! 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. @@ -23,12 +23,16 @@ use mega_evm::{ transaction_body_bytes, EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; -use revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult}; +use revm::{ + bytecode::opcode::*, context::TxEnv, context_interface::cfg::GasId, + interpreter::InstructionResult, +}; use crate::{ detention::{ - assert_stopped, context, intrinsic, memory_cost, op, run_on, spin, Calls, Charges, Run, - BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, + 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}, }; @@ -92,12 +96,16 @@ fn charges_to_the_call(len: u64, call: u64) -> Charges { } /// A value call's own charges to a cold contract: the cold access and the transfer. -const CALL_TO_A_CONTRACT: u64 = 2_600 + 9_000; +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 account the transfer adds, whose regular price Satin keeps beside its state -/// gas. -const CALL_TO_AN_EMPTY_PRECOMPILE: u64 = 100 + 9_000 + 25_000; +/// 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`]. @@ -193,9 +201,10 @@ fn balance(run: &Run, address: Address) -> U256 { /// /// - 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: nothing -/// moves and no log is journaled, and the transaction stops at the limit, billed its intrinsic -/// gas and its compute at the call, and keeping its body alone. Without the read the call +/// - 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 @@ -224,9 +233,10 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { 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) + let charges = charges_to_the_call(above.len() as u64, call_to_an_empty_precompile()) .then(&[price.unwrap()]); - assert_stopped(&detained, intrinsic_with(&above, gas_limit), charges.left(CAP)); + 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 }); @@ -309,8 +319,10 @@ fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { /// 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 of 2,600, which revm charges after it journaled the move and its transfer log. -const DESTRUCT_AFTER_READ: u64 = 2 + 3 + 5_000 + 2_600; +/// 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. /// @@ -340,14 +352,14 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { 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)); + (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 - 2_600 - 1] { + 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, 2_600]).left(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 }); @@ -375,7 +387,7 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { // 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, 2_600, 3, 5_000, 2_600, 2]) + .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); @@ -396,8 +408,8 @@ struct Start { input: fn() -> Vec, /// What [`CONTRACT`] holds. held: u64, - /// When the cap stops the transaction: the regular charges it makes after the read, with - /// calldata of the given length. + /// 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>, } @@ -410,7 +422,9 @@ struct 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. +/// 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; @@ -428,7 +442,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { 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)), + 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", @@ -461,7 +475,7 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { 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()]) + charges_to_the_call(len, call_to_an_empty_precompile()).then(&[price.unwrap()]) }), }, Start { @@ -552,7 +566,8 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { assert_counts_its_transfer_logs(&detained, body, &case); if let Some(charges) = start.stops { let left = charges(input.len() as u64).left(CAP); - assert_stopped(&detained, intrinsic_with(&input, gas_limit), left); + 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); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index dc46eb88f..32ad40f7c 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -16,11 +16,13 @@ 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, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, - MegaTransactionOutcome, ProtocolLimits, VolatileDataAccess, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, OracleRead, ProtocolLimits, VolatileDataAccess, + TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::*, @@ -47,8 +49,40 @@ 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 22,100. -pub(crate) const FRESH_WRITE: u64 = 3 + 3 + 22_100; +/// 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. @@ -198,6 +232,34 @@ pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { 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: @@ -239,7 +301,12 @@ impl Charges { /// 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, mut allowance: u64) -> u64 { + 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 { @@ -253,13 +320,13 @@ impl Charges { allowance -= round * rounds; for charge in charges { if *charge > allowance { - return allowance; + return Some(allowance); } allowance -= charge; } unreachable!("a round the allowance cannot pay whole has a charge it cannot pay"); } - panic!("the program ends within the allowance") + None } /// The charges of [`spin`]'s loop in a frame whose memory holds `words` words: `JUMPDEST`, the @@ -298,7 +365,7 @@ impl Charges { /// 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, 100, 22_000], count) + self.repeat(&[3, 3, sstore_static(), fresh_sstore()], count) } } @@ -526,8 +593,9 @@ pub(crate) fn with_delegation( } /// Every read caps the transaction from where it read, not from its start: the transaction first -/// spends more 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. +/// 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 { @@ -547,6 +615,14 @@ fn test_every_volatile_read_caps_the_transaction_from_where_it_read() { 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); } } } @@ -599,53 +675,17 @@ fn test_without_a_read_nothing_is_capped() { } } -/// A transaction whose sender, recipient or applied EIP-7702 authority is the beneficiary is -/// detained from its first instruction: its limit is the cap. +/// A transaction whose sender is the beneficiary is detained from its first instruction: its limit +/// is the cap. #[test] -fn test_a_transaction_touching_the_beneficiary_is_detained_from_the_start() { - use revm::{ - context::transaction::TransactionType, - context_interface::{ - either::Either, - transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, - }, - }; +fn test_a_transaction_from_the_beneficiary_is_detained_from_the_start() { for gas_limit in TIERS { - let intrinsic = intrinsic(gas_limit); - let spinner = spin(BytecodeBuilder::default()); // Detained before its first instruction: the whole program runs after the read. let left = Charges::default().spin(0).left(CAP); - - // The sender. - let db = MemoryDatabase::default().account_code(CONTRACT, spinner.clone()); - let run_sender = execute(db, tx(BENEFICIARY, CONTRACT, gas_limit)); + 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_sender, intrinsic, left), CAP, "the sender"); - - // The recipient. - let db = MemoryDatabase::default().account_code(BENEFICIARY, spinner.clone()); - let run_recipient = execute(db, tx(CALLER, BENEFICIARY, gas_limit)); - assert_eq!(assert_stopped(&run_recipient, intrinsic, left), CAP, "the recipient"); - - // An applied authority. - let authorization = Either::Right(RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::ZERO, address: CHILD, nonce: 0 }, - RecoveredAuthority::Valid(BENEFICIARY), - )); - let authorizing = 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() - })); - let db = MemoryDatabase::default().account_code(CONTRACT, spinner); - let run_authority = execute(db, authorizing); - assert_eq!(run_authority.limit, Some(CAP), "the authority"); - assert!(matches!(run_authority.outcome.result, ExecutionResult::Revert { .. })); - assert_eq!(run_authority.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!(assert_stopped(&run, intrinsic(gas_limit), left), CAP, "the sender"); } } @@ -773,10 +813,20 @@ fn test_the_most_restrictive_limit_binds_whatever_the_order() { // 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, 2_600, 2, 2_100, 2, 2]) + 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]) @@ -839,15 +889,18 @@ fn test_a_callers_limits_set_the_caps() { } /// The default runtime limits detain: [`EvmTxRuntimeLimits::default`], and the transaction half -/// of [`ProtocolLimits::DEFAULT`] that a block executor installs, hold each kind of read to the -/// spec's cap. It is `no_limits` that turns detention off, with every other per-transaction limit. +/// 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::DEFAULT.tx_runtime_limits] { + 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()) @@ -864,10 +917,6 @@ fn test_the_default_limits_detain() { (ORACLE_ACCESS_COMPUTE_GAS..ORACLE_ACCESS_COMPUTE_GAS + 100_000).contains(&limit), "{limit}" ); - - let run = run_under(EvmTxRuntimeLimits::no_limits(), ×tamp); - assert!(!run.detains); - assert_eq!(run.limit, None); } } @@ -904,8 +953,9 @@ 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, and so does a transaction -/// carrying value, whose own frame is given what the transaction has left and no stipend. +/// 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)); @@ -913,7 +963,7 @@ fn test_a_stipend_is_not_compute() { .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) .push_number(1_u8) .push_address(CHILD) - .append_many([GAS, CALL, POP, STOP]) + .append_many([GAS, CALL, STOP]) .build(); for gas_limit in TIERS { let db = MemoryDatabase::default() @@ -923,7 +973,7 @@ 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_stopped(&run, intrinsic(gas_limit), left); + assert_caught(&run, intrinsic(gas_limit), left, &Charges::default()); let db = MemoryDatabase::default() .account_code(CONTRACT, spin(op(BytecodeBuilder::default(), TIMESTAMP))) @@ -945,7 +995,7 @@ fn test_a_call_that_reads_counts_from_what_its_caller_paid() { // 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 + 9_000), + (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) }; @@ -993,10 +1043,12 @@ fn test_a_childs_read_caps_its_caller() { } } -/// When a child crosses the cap, no caller resumes: the caller's code after the call — a write -/// and a log — never runs, the child runs the last step, and every frame returns the stop. +/// 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_no_caller_resumes_after_the_stop() { +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)) @@ -1011,7 +1063,10 @@ fn test_no_caller_resumes_after_the_stop() { 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); - let limit = assert_stopped(&run, intrinsic, left); + // 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!( @@ -1021,10 +1076,9 @@ fn test_no_caller_resumes_after_the_stop() { (CONTRACT, InstructionResult::Revert, stop_data(limit)), ] ); - assert!(!evm.inspector().opcodes.contains(&SSTORE), "the caller did not resume"); - // A caller that resumed would fail its first charge on the withheld part, before its - // write, and report the same stop on the same bill: only its step shows it ran. - assert_eq!(evm.inspector().last_frame, Some(CHILD), "the child ran the last step"); + 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"); } } @@ -1043,8 +1097,14 @@ fn test_the_stop_bills_the_same_above_and_below_the_execution_cap() { .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_stopped(&run, intrinsic(*gas_limit), left); + 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"); @@ -1097,32 +1157,34 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { } /// 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, a thousand fresh slots — 22,106,000 of compute — -/// cross it and stop the transaction, at the first write's charge past it. Without a reservoir, +/// 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..=1_000_u64 { + 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 + 1_000 * fresh_write_spill(); + 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(1_000).left(CAP); + 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 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), @@ -1139,20 +1201,21 @@ fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { /// /// - 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 new account, and the +/// - 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(); - // 9,000 for the transfer and 25,000 for the new account do not fit in 30,000. + // 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(); - for (callee, gas) in [(ORACLE_CONTRACT_ADDRESS, 2_000_u32), (CHILD, 30_000)] { + 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) @@ -1301,7 +1364,8 @@ fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { .push_address(BENEFICIARY) .append(EXTCODECOPY) .build(), - 3 + 2 + 2 + 3 + 100, + // `EXTCODECOPY`'s static gas is EIP-8038's two warm reads, the account and its code. + 3 + 2 + 2 + 3 + 200, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( @@ -1361,9 +1425,10 @@ fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { } } -/// The refusal of a `SLOTNUM` names access type 12, one past the contract's enum; the others name -/// their enum variant, `BLOCKHASH`'s the hash it reads (7), as on the legacy engine, although -/// revm's instruction loads the block number first. +/// 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}; @@ -1380,14 +1445,6 @@ fn test_the_refusal_names_the_access_type() { ); } assert_eq!(VolatileDataAccessType::BlockHash as u8, 7); - let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); - assert_eq!(&slot_num[..4], IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR.as_slice()); - assert_eq!(U256::from_be_slice(&slot_num[4..]), U256::from(12)); - assert_eq!(mega_evm::system::SLOT_NUM_ACCESS_TYPE, 12); - assert_eq!( - mega_evm::decode_volatile_data_access_disabled(&slot_num), - Some(VolatileDataAccess::SLOT_NUM) - ); } /// The switch holds for the frame it is off from and every frame below, and a frame above it @@ -1437,7 +1494,7 @@ fn test_the_switch_is_scoped_to_its_subtree() { /// 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: 2,631. +/// 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(); @@ -1462,10 +1519,13 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { MemoryDatabase::default().account_code(CONTRACT, code), tx(CALLER, CONTRACT, gas_limit), ); - // The 2,631 spent up to the call's cold access; 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(&[2_631, 2, 3, 3, 3, 100, 22_000]).spin(1).left(CAP); + // 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 @@ -1500,7 +1560,7 @@ fn test_an_interceptors_answer_does_not_lift_the_cap() { 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 - 2_631), "what the cap leaves"); + assert_eq!(detained, U256::from(CAP - 31 - cold_access()), "what the cap leaves"); } } @@ -1545,22 +1605,52 @@ fn test_state_and_history_gas_are_not_compute() { 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 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!(gas.state + gas.history >= slots * spill, "{gas:?}"); - assert!(gas.regular < CAP, "{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", + ); } } @@ -1582,8 +1672,8 @@ fn test_gas_spilled_before_the_read_is_not_compute() { ); 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 22,100 of regular gas, a hundred times, then TIMESTAMP. - assert_eq!(limit - CAP, 100 * (3 + 3 + 22_100) + 2, "{gas_limit}"); + // Two pushes and a fresh slot's regular gas, a hundred times, then TIMESTAMP. + assert_eq!(limit - CAP, 100 * fresh_write() + 2, "{gas_limit}"); } } diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 7d62dc3fa..39e1dc3dc 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -16,6 +16,13 @@ //! 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 //! bucket is minimal and the multiplier is one, so the baseline holds; the last case crowds one @@ -30,7 +37,8 @@ use mega_evm::{ }, satin_gas_params, test_utils::{ - op_transaction, transfer_log, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + 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, @@ -81,6 +89,14 @@ fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Outcome, 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, @@ -125,9 +141,9 @@ fn both_evms( /// 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 as it is, 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`]). +/// 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"); @@ -153,7 +169,14 @@ fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { 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!(mega.state, op.state, "state"); + 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 @@ -245,6 +268,16 @@ fn test_value_transfer_matches_op_revm() { /// 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() { @@ -749,5 +782,122 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { // 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 index 73a720f8d..4bf3bce20 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -153,128 +153,6 @@ fn every_site_called(gas_limit: u64) -> MegaTransaction { call_with_data(CALLER, CALLEE, Bytes::from(vec![1; 10]), gas_limit) } -/// With no allowance anywhere, the bytes a transaction reports are its history gas at the price, -/// at every site that appends history and on every path that takes it back. -#[test] -fn test_without_an_allowance_the_bytes_are_the_history_gas_at_the_price() { - if runs_at_measurement_prices() { - return; - } - type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, u64); - let cases: [Case; 12] = [ - ( - "a body alone", - || callee_running(BytecodeBuilder::default()), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE, - ), - ( - "calldata, a byte a byte", - || callee_running(BytecodeBuilder::default()), - |gas| call_with_data(CALLER, CALLEE, Bytes::from(vec![0xab; 100]), gas), - TX_BODY_SIZE + 100, - ), - ( - "a log", - || callee_running(log(BytecodeBuilder::default(), 2, 50)), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE + log_bytes(2, 50), - ), - ( - "a storage write", - || callee_running(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1))), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "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), - TX_BODY_SIZE, - ), - ( - "a transfer that creates its recipient", - funded, - |gas| call(CALLER, FRESH, U256::from(1), gas), - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a creation transaction", - funded, - |gas| create(CALLER, deploying(), gas), - TX_BODY_SIZE + deploying().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, - ), - ( - "a nested creation: the created account, the creator's nonce and the code", - || callee_running(creating(BytecodeBuilder::default(), &deploying())), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + DEPLOYED, - ), - ( - "a nested creation that reverts with a word of data: the creator's nonce outlives \ - it, and the data is no code", - || callee_running(creating(BytecodeBuilder::default(), &[PUSH1, 32, PUSH0, REVERT])), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a child that logs and reverts", - || { - callee_running(calling(BytecodeBuilder::default(), CHILD, 0, 1_000_000)) - .account_code(CHILD, log(BytecodeBuilder::default(), 0, 32).revert().build()) - }, - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - TX_BODY_SIZE, - ), - ( - "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), - TX_BODY_SIZE, - ), - ( - "every site at once", - every_site, - every_site_called, - // 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, - ), - ]; - - for (name, db, tx, bytes) in cases { - for gas_limit in GAS_LIMITS { - let outcome = execute(db(), tx(gas_limit)); - assert_eq!(outcome.gas.history_bytes, bytes, "{name} at {gas_limit}: the bytes"); - 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); - } - } -} - /// 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 @@ -514,203 +392,6 @@ fn limited_to(bytes: u64) -> EvmTxRuntimeLimits { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) } -/// The paths the first table does not take — what the body carries beside calldata, the -/// accounts a `SELFDESTRUCT` and an authorization write, a frame answered without running, a code -/// deposit that fails, a slot written back from another frame — each with its exact byte count -/// and, without an allowance on any of them, the history gas at the price. -#[test] -fn test_the_bytes_on_the_edge_paths_are_the_history_gas_at_the_price() { - if runs_at_measurement_prices() { - return; - } - type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, u64, u64); - let cases: [Case; 19] = [ - ( - "an access list: twenty bytes an address and thirty-two a key", - || callee_running(BytecodeBuilder::default()), - |gas| with_access_list(&[(CALLEE, 2), (PAYEE, 1), (FRESH, 0)], gas), - u64::MAX, - TX_BODY_SIZE + 3 * ACCESS_LIST_ADDRESS_SIZE + 3 * ACCESS_LIST_SLOT_SIZE, - ), - ( - "authorizations: each in the body, and a record for the one authority applied", - || callee_running(BytecodeBuilder::default()), - |gas| with_authorizations(&[(AUTHORITY, 0), (OTHER_AUTHORITY, 7)], gas), - u64::MAX, - TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, - ), - ( - "an authority applied twice is one record", - || callee_running(BytecodeBuilder::default()), - |gas| with_authorizations(&[(AUTHORITY, 0), (AUTHORITY, 1)], gas), - u64::MAX, - TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, - ), - ( - "the sender's own authorization: in the body, and no record beside it", - || callee_running(BytecodeBuilder::default()), - |gas| with_authorizations(&[(CALLER, 1)], gas), - u64::MAX, - TX_BODY_SIZE + AUTHORIZATION_SIZE, - ), - ( - "a SELFDESTRUCT that moves a balance to another account records it", - || funded().account_code(CALLEE, destructs_to(PAYEE)), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a SELFDESTRUCT that moves a balance to an account it creates records it", - || funded().account_code(CALLEE, destructs_to(FRESH)), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "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), - u64::MAX, - TX_BODY_SIZE, - ), - ( - "a SELFDESTRUCT that moves nothing records nothing", - || funded().account_code(RECEIVER, destructs_to(PAYEE)), - |gas| call(CALLER, RECEIVER, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE, - ), - ( - "a call an interceptor answers runs no frame, and its caller's write is kept", - || { - 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), - u64::MAX, - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a value call an interceptor refuses keeps none of the records its caller paid for", - || beside_access_control(asks_access_control(BytecodeBuilder::default(), 1)), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE, - ), - ( - "a limit stops the transaction before its first frame: the recipient is not written", - funded, - |gas| call(CALLER, FRESH, U256::from(1), gas), - TX_BODY_SIZE + WRITE_RECORD_SIZE - 1, - TX_BODY_SIZE, - ), - ( - "a limit stops a value call before its frame is built: nothing the transaction wrote \ - is kept", - || { - 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), - TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE - 1, - TX_BODY_SIZE, - ), - ( - "a limit crossed by a child's write: nothing the transaction wrote or logged 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), - TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1, - TX_BODY_SIZE, - ), - ( - "a nested creation whose code EIP-3541 refuses: the creator's nonce outlives it, and \ - nothing is deposited", - || callee_running(creating(BytecodeBuilder::default(), &refused_code())), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a nested creation whose code is past the size limit: the same", - || callee_running(creating(BytecodeBuilder::default(), &oversized_code())), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - u64::MAX, - TX_BODY_SIZE + WRITE_RECORD_SIZE, - ), - ( - "a creation transaction whose code EIP-3541 refuses: its body and init code alone", - funded, - |gas| create(CALLER, refused_code(), gas), - u64::MAX, - TX_BODY_SIZE + refused_code().len() as u64, - ), - ( - "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), - u64::MAX, - TX_BODY_SIZE, - ), - ( - "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), - u64::MAX, - TX_BODY_SIZE, - ), - ( - "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), - u64::MAX, - TX_BODY_SIZE, - ), - ]; - - for (name, db, tx, limit, bytes) in cases { - // 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"); - for gas_limit in GAS_LIMITS { - let outcome = MegaEvm::new(context(db()).with_tx_runtime_limits(limited_to(limit))) - .execute_transaction(tx(gas_limit)) - .expect("the transaction is valid"); - assert_eq!( - outcome.limit_exceeded.is_some(), - limit != u64::MAX, - "{name} at {gas_limit}: {:?}", - outcome.result, - ); - assert_eq!(outcome.gas.history_bytes, bytes, "{name} at {gas_limit}: the bytes"); - 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); - } - } -} - /// 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] @@ -855,8 +536,12 @@ fn beside_the_oracle() -> MemoryDatabase { enum Run { /// With no limit. Plain, - /// Under a transaction data-size limit of this many bytes, which the case crosses. + /// 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, } @@ -877,7 +562,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; 23] = [ + let cases: [Case; 35] = [ ( "the body", || callee_running(BytecodeBuilder::default()), @@ -1071,7 +756,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 0, ), ( - "a stop at a child's write", + "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( @@ -1080,8 +765,8 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { ) }, |gas| call(CALLER, CALLEE, U256::ZERO, gas), - Run::Limited(TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1), - TX_BODY_SIZE, + Run::Caught(TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1), + TX_BODY_SIZE + LOG_BASE_SIZE, 0, 0, ), @@ -1106,20 +791,164 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 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) => limit, + 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(_) => evm.execute_transaction(tx(gas_limit)), + Run::Plain | Run::Limited(_) | Run::Caught(_) => { + evm.execute_transaction(tx(gas_limit)) + } } .expect("the transaction is valid"); assert_eq!( diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index a3adcc7d5..099c248a1 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -13,18 +13,23 @@ 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::TX_GAS_LIMIT_CAP, - system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + 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}, - MegaEvm, MegaTransaction, + 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, runs_at_measurement_prices}; +use crate::common::{context, deposit, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000400000"); const CONTRACT: Address = address!("0000000000000000000000000000000000400001"); @@ -72,6 +77,19 @@ fn program_deploying(len: u64) -> Bytes { /// 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))) @@ -92,12 +110,31 @@ fn call_from(caller: Address, to: Address) -> MegaTransaction { })) } -/// Runs `tx` and reports its history and state ledgers. -fn ledgers(tx: MegaTransaction) -> (u64, u64) { +/// 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.gas.history, outcome.gas.state, outcome) } /// The control: a user transaction running the program pays for every byte of it, on top of its @@ -107,9 +144,12 @@ fn test_a_user_transaction_pays_history_for_the_program() { if runs_at_measurement_prices() { return; } - let (history, state) = ledgers(call_from(CALLER, CONTRACT)); + 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 @@ -143,22 +183,17 @@ fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { assert_eq!(ledgers(deposit(call_from(CALLER, CONTRACT))).0, 0, "a deposit pays none of it"); } -/// `tx` as a deposit: no fee, and a source hash a user's transaction could carry. -fn deposit(mut tx: MegaTransaction) -> MegaTransaction { - tx.0.deposit.source_hash = B256::repeat_byte(0x11); - tx.0.base.gas_price = 0; - tx -} - /// 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) = ledgers(deposit(call_from(CALLER, CONTRACT))); + 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 @@ -169,11 +204,26 @@ fn test_a_system_transaction_pays_no_history_gas() { 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 it writes a slot of its own. - let tx = call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + // 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 @@ -193,6 +243,8 @@ fn test_a_system_call_pays_no_history_gas() { "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 @@ -210,12 +262,12 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { } const RESERVOIR: u64 = 100_000_000; for gas_limit in [GAS_LIMIT, TX_GAS_LIMIT_CAP + RESERVOIR] { - let gas = |mut tx: MegaTransaction| { + let run = |mut tx: MegaTransaction| { tx.0.base.gas_limit = gas_limit; - let gas = MegaEvm::new(context(db())) + let outcome = MegaEvm::new(context(db())) .execute_transaction(tx) - .expect("the transaction is valid") - .gas; + .expect("the transaction is valid"); + let gas = outcome.gas; if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( gas.reservoir_remaining, @@ -223,10 +275,10 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { "the reservoir paid the state and history ledgers", ); } - gas + outcome }; - let paying = gas(call_from(CALLER, CONTRACT)); + let paying = run(call_from(CALLER, CONTRACT)).gas; assert!(paying.history_bytes > 0); assert_eq!( paying.history, @@ -234,10 +286,13 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { "at {gas_limit}: the control pays for every byte it reports", ); - let deposit = gas(deposit(call_from(CALLER, CONTRACT))); + 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 = gas(call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS)); + 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), @@ -269,4 +324,5 @@ fn test_the_exemption_does_not_outlive_its_transaction() { 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 index 3ce1eca47..0012dc7aa 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -11,11 +11,11 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}, + bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STOP}, context_interface::cfg::GasId, }; -use crate::common::{call, call_with_data, create, execute, runs_at_measurement_prices}; +use crate::common::{call, call_with_data, create, deploying, execute, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const CALLEE: Address = address!("0000000000000000000000000000000000200001"); @@ -36,11 +36,6 @@ fn funded() -> MemoryDatabase { MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) } -/// Init code that deploys `len` zero bytes: `PUSH len; PUSH0; RETURN`. -fn deploying(len: u64) -> Bytes { - BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() -} - /// Init code that reverts without deploying anything. fn reverting() -> Bytes { BytecodeBuilder::default().append_many([PUSH0, PUSH0, REVERT]).build() @@ -88,22 +83,6 @@ fn test_a_reverted_deployment_pays_no_code_deposit_history() { /* ---------- the transaction body ---------- */ -/// Every transaction pays for its own body before it runs: the envelope and the records of the -/// writes its inclusion makes, whatever else it does. -#[test] -fn test_every_transaction_pays_for_its_body() { - if runs_at_measurement_prices() { - return; - } - let db = || funded().account_code(CALLEE, Bytes::new()); - let empty = execute(db(), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - - assert!(empty.result.is_success(), "{:?}", empty.result); - assert_eq!(empty.gas.history, body(0)); - assert_eq!(empty.gas.history, 310 * 88, "310 bytes at the cost per history byte"); - assert_eq!(empty.gas.state, 0, "the body is history, not state"); -} - /// 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] @@ -142,40 +121,6 @@ fn logging(topics: u8, data_len: u64) -> Bytes { log_body(topics, data_len).stop().build() } -/// A log appends its own record for the address that emitted it, one record per topic and its -/// data, and pays history for every one of those bytes. -#[test] -fn test_a_log_pays_for_its_address_its_topics_and_its_data() { - 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 bare = run(logging(0, 0)); - let one_topic = run(logging(1, 32)); - let three_topics = run(logging(3, 32)); - - assert!(bare.result.is_success(), "{:?}", bare.result); - assert_eq!(bare.gas.history, body(0) + LOG_BASE_SIZE * CPHB, "the address alone"); - assert_eq!( - one_topic.gas.history, - body(0) + (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB, - "the address, one topic and 32 bytes of data", - ); - assert_eq!( - three_topics.gas.history, - body(0) + 160 * CPHB, - "a three-topic event carrying one word is 160 bytes", - ); - assert_eq!( - three_topics.gas.history - one_topic.gas.history, - 2 * LOG_TOPIC_SIZE * CPHB, - "two topics more", - ); -} - /// 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] @@ -206,65 +151,6 @@ fn test_a_log_pays_history_on_top_of_the_schedules_price() { ); } -/// A storage write leaves one write record, and the record is history: the first change of a slot -/// in the transaction pays for forty bytes, and writing the slot back to its original value takes -/// that charge back. -#[test] -fn test_a_storage_write_pays_for_its_record_and_a_write_back_takes_it_back() { - if runs_at_measurement_prices() { - return; - } - let run = |code: BytecodeBuilder| { - let db = funded().account_code(CALLEE, code.stop().build()); - execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) - }; - let one = run(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1))); - let three = run(BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::from(1), U256::from(1)) - .sstore(U256::from(2), U256::from(1))); - let rewritten = run(BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::from(2))); - let restored = run(BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::ZERO)); - - assert_eq!(one.gas.history, body(0) + WRITE_RECORD_SIZE * CPHB, "one record"); - assert_eq!(three.gas.history, body(0) + 3 * WRITE_RECORD_SIZE * CPHB, "three slots, three"); - assert_eq!(rewritten.gas.history, one.gas.history, "a slot already changed records once"); - assert_eq!(restored.gas.history, body(0), "the write-back took the record's charge back"); -} - -/// A frame that fails pays for nothing it appended: its logs and its write records go back with -/// it, and its caller keeps only what it did itself. -#[test] -fn test_a_failing_frame_gives_its_history_back() { - if runs_at_measurement_prices() { - return; - } - // `CALLEE` calls `CONTRACT` and carries on whatever it answers. - let caller_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(CONTRACT) - .append(GAS) - .append(CALL) - .append(POP) - .stop() - .build(); - let run = |callee: Bytes| { - let db = funded().account_code(CALLEE, caller_code.clone()).account_code(CONTRACT, callee); - execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) - }; - let quiet = run(BytecodeBuilder::default().stop().build()); - let kept = run(logging(1, 32)); - let reverted = run(log_body(1, 32).append_many([PUSH0, PUSH0, REVERT]).build()); - - assert!(kept.result.is_success() && reverted.result.is_success(), "the caller survives"); - assert_eq!(kept.gas.history - quiet.gas.history, (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB); - assert_eq!(reverted.gas.history, quiet.gas.history, "the reverted frame's log is not paid for"); -} - /* ---------- a frame-start charge the caller cannot pay ---------- */ /// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`: a value transfer that diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index b96a6b58d..9de582130 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -28,9 +28,11 @@ use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, LimitUsage, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{CALL, CREATE, GAS, POP, PUSH0, PUSH1, REVERT, STOP}; +use revm::bytecode::opcode::{CALL, CREATE, GAS, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}; -use crate::common::{call, execute, runs_at_measurement_prices}; +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"); @@ -226,3 +228,81 @@ fn test_an_intercepted_value_call_gives_its_records_back_once() { "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 index 897bb477f..7a3ff1e39 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -24,6 +24,7 @@ use revm::{ transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, + context_interface::cfg::GasId, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Interpreter, @@ -31,7 +32,10 @@ use revm::{ Database, Inspector, }; -use crate::common::{block, call, context, execute}; +use crate::{ + common::{block, call, context, execute}, + salt::entry, +}; const CALLER: Address = address!("0000000000000000000000000000000000e20000"); const CONTRACT: Address = address!("0000000000000000000000000000000000e20001"); @@ -40,9 +44,11 @@ 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: EIP-2929's cold account access less -/// its warm read. -const COLD_OVER_WARM: u64 = 2_600 - 100; +/// 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 ---------- */ @@ -95,7 +101,7 @@ fn plain() -> MegaTransaction { /// 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); + 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 @@ -214,7 +220,7 @@ fn test_a_call_forwards_all_but_a_64th_of_its_gas() { .build(); let (held, forwarded, outcome) = forward_of(code); assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - 2_600; + let left = held - entry(GasId::warm_storage_read_cost()) - cold_over_warm(); assert_eq!(forwarded, left - left / 64); } @@ -229,6 +235,6 @@ fn test_a_creation_forwards_all_but_a_64th_of_its_gas() { .build(); let (held, forwarded, outcome) = forward_of(code); assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - 32_000 - 2 - 3; + 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 98a72cd6b..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, WRITE_RECORD_SIZE, + 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,7 +19,9 @@ use revm::{ }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; -use crate::common::{account_state_gas, body_history, call, context, history, slot_state_gas}; +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"); @@ -238,36 +240,16 @@ 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. -#[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 creation its own frame budget stops is refused its revival too: the stop is the creation's -/// alone and latches nothing, so the creation failed as any failed creation does. Under a KV limit -/// of three, the creation's start makes two records, and the write in its init code is a third one -/// over its budget of 98% of the three, which the transaction's limit still holds; under a limit -/// of four the budget holds it, and the same creation succeeds. +/// 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_a_creation_its_frame_budget_stops_is_refused_its_revival() { +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) @@ -276,38 +258,45 @@ fn test_a_creation_its_frame_budget_stops_is_refused_its_revival() { .stop() .build(); let db = || MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); - let under = - |records: u64| mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(records); - let plain = |records: u64| { - MegaEvm::new(context(db()).with_tx_runtime_limits(under(records))) - .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())) - .unwrap() + 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(4); + 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(3); + let stopped = plain(122); assert!(stopped.result.is_success(), "{:?}", stopped.result); - assert_eq!(stopped.limit_exceeded, None, "a frame budget latches nothing"); + assert_eq!(stopped.limit_exceeded, None, "a frame budget below is no stop"); assert!(!created(&stopped), "the creation failed"); - let limits = under(3); - let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) - .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }); - match evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())) { - Err(EVMError::Custom(message)) => { - assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") - } - other => panic!("expected the refusal, got {other:?}"), - } + 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. @@ -352,6 +341,32 @@ fn test_declared_tracer_changes_nothing() { 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() { @@ -405,8 +420,8 @@ 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| { @@ -422,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. @@ -542,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, @@ -550,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 { @@ -582,6 +631,7 @@ 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)); @@ -669,7 +719,10 @@ fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { .unwrap(); assert!(inspected.is_success(), "{inspected:?}"); assert_eq!(*evm.inspector(), Seen { frames: 1, steps: 3 }, "PUSH0, POP, STOP"); - assert!(evm.ctx().additional_limit().latched().is_none(), "no limit holds a system call"); + 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. @@ -692,10 +745,9 @@ impl Inspector for SkipAllCallsInspector { } } -/// A body over the data-size limit latches the transaction before it runs, and its first frame is -/// answered with the stop — in place of the answer an inspector that answers every call gives it. -/// The transaction is the one no inspector runs: the stop, which settles like a revert, so the -/// sender gets back what the frame did not spend. +/// 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; @@ -710,32 +762,12 @@ fn test_intrinsic_data_size_overflow_with_inspector_early_return() { let plain = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) .execute_transaction(tx.clone()) - .unwrap(); + .expect_err("rejected"); let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) .with_inspector(SkipAllCallsInspector::default()); - let answered = evm.execute_transaction(tx).unwrap(); + let inspected = evm.execute_transaction(tx).expect_err("rejected"); - assert_eq!(evm.inspector().answered, 1, "the inspector answered the first frame"); - let stop = answered.limit_exceeded.expect("the transaction is stopped"); - assert!( - matches!( - stop, - mega_evm::LimitCheck::ExceedsLimit { - kind: mega_evm::LimitKind::DataSize, - limit: LIMIT, - .. - } - ), - "{stop:?}" - ); - assert!( - matches!(&answered.result, revm::context::result::ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "the stop, not the answer: {:?}", - answered.result - ); - assert_eq!(answered.result, plain.result); - assert_eq!(answered.gas, plain.gas); - assert_eq!(answered.usage, plain.usage); - assert!(answered.gas.gas_used < TX_GAS_LIMIT / 100, "the unspent gas comes back"); + 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_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 5d7ae65ae..0464dce67 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -28,7 +28,10 @@ use mega_evm::{ MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, + bytecode::{ + opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, + Bytecode, + }, context::{ContextTr, JournalTr}, context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr, Transaction}, interpreter::{ @@ -39,12 +42,9 @@ use revm::{ Inspector, }; -use crate::{ - common::state_is_free, - salt::{ - create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, - value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, - }, +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. @@ -417,35 +417,171 @@ fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { } /// 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, so it never stands against the state-gas -/// limit. The caller then fills a slot, and a limit one gas short of the slot and the account -/// together stops the caller whose call ran, and not the one whose call was answered. +/// 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_holds_nothing_against_the_state_gas_limit() { - // A slot and an account that add no state gas have no state-gas limit to cross. - if state_is_free() { - return; - } +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 limit = slot + entry(GasId::new_account_state_gas()) - 1; - let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit); let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); - let context = || salt_context(db(caller()), minimal_envs()).with_tx_runtime_limits(limits); + let context = || salt_context(db(caller()), minimal_envs()); let ran = MegaEvm::new(context()).execute_transaction(tx.clone()).unwrap(); - assert!(ran.limit_exceeded.is_some(), "the account and the slot cross: {:?}", ran.result); + 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_eq!(answered.limit_exceeded, None, "{:?}", answered.result); 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. diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index cee332aec..41dff06eb 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -3,9 +3,10 @@ //! //! 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 @@ -20,14 +21,16 @@ use mega_evm::{ test_utils::{op_transaction, MemoryDatabase}, 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}; @@ -38,9 +41,9 @@ 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 @@ -193,22 +196,24 @@ 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() { +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 + 2_400 + body_history(20)), + 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; @@ -219,16 +224,27 @@ fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { Ok(EMPTY_CALL + address_bytes + key_bytes * keys), "{keys} keys: the floor counts every byte at the same rate" ); - // The floor binds only where a history byte is cheap: the bill is the larger of the two. 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 + 2_400 + 1_900 * keys + body_history(20 + 32 * keys)).max(floor)), + 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 @@ -284,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; @@ -295,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() { @@ -344,26 +365,37 @@ 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. @@ -377,26 +409,30 @@ fn test_a_valid_call_still_passes() { /// 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. +/// 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); - let expected = |gas_limit| { - format!( - "{:?}", - InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas: minimum } - ) - }; for gas_limit in [EMPTY_CALL, EMPTY_CALL + 1, minimum - 1] { - assert_eq!( - gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, gas_limit)), - Err(expected(gas_limit)), - "a gas limit of {gas_limit} does not cover the body", + 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)); - assert_sender_untouched(); } diff --git a/crates/mega-evm/tests/satin/kv_limit.rs b/crates/mega-evm/tests/satin/kv_limit.rs deleted file mode 100644 index be7277798..000000000 --- a/crates/mega-evm/tests/satin/kv_limit.rs +++ /dev/null @@ -1,523 +0,0 @@ -//! The KV limit: the write records a transaction keeps, held to a limit of their own. -//! -//! The KV count is the write-record count the common execution layer keeps: 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 part of the transaction body, not records, so a transaction -//! that writes nothing counts none. -//! -//! The limit follows the data-size limit's rules in its own unit. A transaction is held to -//! `tx_kv_update_limit`; its own frame gets what the transaction has left and a child 98% of what -//! its parent has left, under `frame_kv_update_limit`. A frame that crosses its budget reverts -//! alone; a transaction that crosses its limit is stopped with a revert carrying -//! `MegaLimitExceeded(1, limit)`. - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaLimitExceeded, - MegaTransaction, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TX_BODY_SIZE, WRITE_RECORD_SIZE, -}; -use revm::bytecode::opcode::{ - CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, RETURNDATACOPY, RETURNDATASIZE, - SELFDESTRUCT, STOP, -}; - -use crate::common::{authorizing_call, call, call_with_data, context}; - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); -const A: Address = address!("0000000000000000000000000000000000500001"); -const B: Address = address!("0000000000000000000000000000000000500002"); -const C: Address = address!("0000000000000000000000000000000000500003"); -const DELEGATE: Address = address!("00000000000000000000000000000000000de1e5"); -const AUTHORITY_1: Address = address!("00000000000000000000000000000000000a0001"); -const AUTHORITY_2: Address = address!("00000000000000000000000000000000000a0002"); - -/// Enough gas for a few hundred fresh slots and the calls around them. -const GAS_LIMIT: u64 = 100_000_000; - -/// 98% of `remaining`, the share a child frame is given. -fn share(remaining: u64) -> u64 { - remaining * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR -} - -fn funded() -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_balance(A, U256::from(1_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 -} - -/// Code that writes the fresh slots `0..n` and stops. -fn slots(n: u64) -> Bytes { - write_slots(BytecodeBuilder::default(), n).stop().build() -} - -/// Appends a `CALL` to `target` carrying `value` with all the gas, dropping its success flag. -fn then_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) - .append(POP) -} - -/// Code that calls `target` with no value and stops. -fn calls(target: Address) -> Bytes { - then_call(BytecodeBuilder::default(), target, 0).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, 0) - .append(RETURNDATASIZE) - .append_many([PUSH0, PUSH0]) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(RETURN) - .build() -} - -fn run_under( - db: MemoryDatabase, - tx: MegaTransaction, - limits: EvmTxRuntimeLimits, -) -> MegaTransactionOutcome { - MegaEvm::new(context(db).with_tx_runtime_limits(limits)).execute_transaction(tx).unwrap() -} - -/// Runs a call from `CALLER` to `A` over `db` under a KV limit of `limit` and nothing else. -fn run_kv(db: MemoryDatabase, limit: u64) -> MegaTransactionOutcome { - run_under( - db, - call(CALLER, A, U256::ZERO, GAS_LIMIT), - EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit), - ) -} - -/// `n` records and the body, with nothing else counted. -const fn records(n: u64) -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, write_records: n } -} - -/// The outcome was stopped by the transaction's KV limit `limit`, crossed at `used`: a revert -/// carrying `MegaLimitExceeded(1, limit)`, not a halt. -fn assert_kv_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { - assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); - let stop = - LimitCheck::ExceedsLimit { kind: LimitKind::KVUpdate, limit, used, frame_local: false }; - assert_eq!(outcome.limit_exceeded, Some(stop)); - assert_eq!(outcome.result.output().unwrap(), &stop.revert_data()); -} - -fn slot_written(outcome: &MegaTransactionOutcome, address: Address, slot: u64) -> bool { - outcome.state.get(&address).is_some_and(|account| { - account.storage.get(&U256::from(slot)).is_some_and(|value| value.is_changed()) - }) -} - -/* ---------- the count ---------- */ - -/// The KV count is the write records kept, by the rules every record follows: a slot counts on -/// its first change and not again, a slot written back counts nothing, writing zero to an empty -/// slot is no change, and the sender is the body's. -#[test] -fn test_the_kv_count_is_the_write_records_kept() { - let cases: [(&str, Bytes, u64, u64); 7] = [ - ("an empty call", Bytes::new(), 0, 0), - ("three fresh slots", slots(3), 3, 0), - ( - "zero written to an empty slot", - BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(), - 0, - 0, - ), - ( - "one slot written twice", - BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::from(2)) - .stop() - .build(), - 1, - 0, - ), - ( - "one slot written and written back", - BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::ZERO) - .stop() - .build(), - 0, - 0, - ), - ( - "a value transfer: the frame's account and the recipient", - then_call(BytecodeBuilder::default(), B, 1).stop().build(), - 2, - 1, - ), - ( - "a destruction that moves value: its beneficiary", - BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(), - 1, - 1, - ), - ]; - for (name, code, kept, transfer_logs) in cases { - let outcome = run_kv(funded().account_code(A, code), u64::MAX); - assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - let transfer_log_bytes = transfer_logs * mega_evm::TRANSFER_LOG_SIZE; - let expected = records(kept); - assert_eq!( - outcome.usage, - LimitUsage { data_size: expected.data_size + transfer_log_bytes, ..expected }, - "{name}: the records, and the transfer log of the value it moved" - ); - } - - let transfer = run_under( - funded(), - call(CALLER, B, U256::from(1), GAS_LIMIT), - EvmTxRuntimeLimits::no_limits(), - ); - assert!(transfer.result.is_success()); - assert_eq!( - transfer.usage, - LimitUsage { - data_size: records(1).data_size + mega_evm::TRANSFER_LOG_SIZE, - write_records: 1 - }, - "a value transaction records its recipient alone, beside its transfer log" - ); -} - -/* ---------- the transaction's limit ---------- */ - -/// A limit equal to the count holds, and one below it stops the transaction at the write that -/// crosses it: a revert naming the KV dimension, with every write taken back. -#[test] -fn test_the_transaction_limit_holds_at_the_count_and_stops_one_above() { - let fits = run_kv(funded().account_code(A, slots(3)), 3); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.limit_exceeded, None); - assert_eq!(fits.usage, records(3)); - - let stopped = run_kv(funded().account_code(A, slots(4)), 3); - assert_kv_stopped(&stopped, 3, 4); - assert_eq!(stopped.usage, records(0), "the stop takes every write back"); - for slot in 0..4 { - assert!(!slot_written(&stopped, A, slot), "slot {slot} is not kept"); - } -} - -/// The transaction's own frame gets the whole transaction limit, so a crossing there is the -/// transaction's and not a frame-local revert: the stop is latched and reported, and it is still -/// a revert, never a halt. -#[test] -fn test_a_crossing_in_the_first_frame_is_the_transactions() { - let outcome = run_kv(funded().account_code(A, slots(101)), 100); - assert_kv_stopped(&outcome, 100, 101); - assert_eq!(outcome.usage, records(0)); -} - -/// A value transaction's recipient is the record its first frame's start makes. A limit it -/// crosses stops the transaction before that frame is built: nothing moves. -#[test] -fn test_a_value_transaction_over_the_limit_moves_nothing() { - let run = |limit| { - run_under( - funded(), - call(CALLER, B, U256::from(7), GAS_LIMIT), - EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit), - ) - }; - assert!(run(1).result.is_success()); - let stopped = run(0); - assert_kv_stopped(&stopped, 0, 1); - assert!(stopped.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value moved"); -} - -/// A nested value call records its caller's account and its recipient when it starts, two at -/// once. When the two cross the transaction's limit they stop the transaction, although they also -/// cross the child's own share: the transaction's limit is checked first. -#[test] -fn test_a_frame_start_over_the_transaction_limit_stops_the_transaction() { - let code = then_call(BytecodeBuilder::default(), B, 1).stop().build(); - let library = - BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).append(INVALID).build(); - let db = || funded().account_code(A, code.clone()).account_code(B, library.clone()); - - let stopped = run_kv(db(), 1); - assert_kv_stopped(&stopped, 1, 2); - assert!(stopped.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value moved"); - - // Without a limit the child starts, and its halt takes its two start records and its write - // back with it. - let ran = run_kv(db(), u64::MAX); - assert!(ran.result.is_success(), "{:?}", ran.result); - assert_eq!(ran.usage, records(0)); -} - -/// Data size is checked before the write records: a record that crosses both limits at once is -/// reported as a data-size stop. -#[test] -fn test_a_record_crossing_both_limits_reports_the_data_size() { - let outcome = run_under( - funded().account_code(A, slots(3)), - call(CALLER, A, U256::ZERO, GAS_LIMIT), - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) - .with_tx_kv_update_limit(2), - ); - assert!(!outcome.result.is_success() && !outcome.result.is_halt()); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, - used: TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE, - frame_local: false, - }) - ); -} - -/// A transaction that filled the limit leaves nothing of it to the next one the same EVM runs: -/// each is held to the limit from zero. -#[test] -fn test_each_transaction_is_held_to_the_limit_from_zero() { - let mut evm = MegaEvm::new( - context(funded().account_code(A, slots(3))) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(3)), - ); - for run in 0..2 { - let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert!(outcome.result.is_success(), "run {run}: {:?}", outcome.result); - assert_eq!(outcome.usage, records(3), "run {run}"); - } -} - -/* ---------- the frame budgets ---------- */ - -/// With room for 100 records, 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_records() { - assert_eq!((share(100), share(98), share(80)), (98, 96, 78)); - let stop = || BytecodeBuilder::default().stop().build(); - let parent_of_20 = - || then_call(write_slots(BytecodeBuilder::default(), 20), B, 0).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 record over its share", calls(B), slots(99), stop(), 0), - ("a child that fills what a parent of 20 left", parent_of_20(), slots(78), stop(), 98), - ("a child one record over what a parent of 20 left", parent_of_20(), slots(79), stop(), 20), - ("a grandchild that fills its share", calls(B), calls(C), slots(96), 96), - ("a grandchild one record 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, 0), C, 0).stop().build(), - slots(99), - slots(98), - 98, - ), - ( - "a parent that writes after its child crossed", - then_call(BytecodeBuilder::default(), B, 0) - .sstore(U256::from(500), U256::from(1)) - .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_kv(db, 100); - assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget does not latch"); - assert_eq!(outcome.usage, records(kept), "{name}"); - } -} - -/// The child that crosses its share reverts with `MegaLimitExceeded` naming the KV dimension and -/// the share it crossed, which is what its caller reads. -#[test] -fn test_a_child_that_crosses_its_share_reverts_with_the_share() { - let db = funded().account_code(A, call_and_return_its_output(B)).account_code(B, slots(99)); - let outcome = run_kv(db, 100); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let reverted = MegaLimitExceeded::abi_decode(outcome.result.output().unwrap()).unwrap(); - assert_eq!(reverted, MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 98 }); -} - -/// The frame cap binds every frame, the transaction's own included, and reverts the frame alone: -/// a top-level frame over the cap reverts without latching the transaction. -#[test] -fn test_the_frame_cap_binds_a_frame_alone() { - let run = |a: Bytes, b: Bytes| { - run_under( - funded().account_code(A, a).account_code(B, b), - call(CALLER, A, U256::ZERO, GAS_LIMIT), - EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(10), - ) - }; - let fits = run(slots(10), Bytes::new()); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.usage, records(10)); - - let over = run(slots(11), Bytes::new()); - assert!(!over.result.is_success() && !over.result.is_halt(), "{:?}", over.result); - assert_eq!(over.limit_exceeded, None, "a frame cap is not the transaction's limit"); - assert_eq!( - over.result.output().unwrap().as_ref(), - MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 10 }.abi_encode() - ); - - // A child's budget is the share of what its parent has left, under the same cap. - let child = run(call_and_return_its_output(B), slots(10)); - assert!(child.result.is_success(), "{:?}", child.result); - assert_eq!( - MegaLimitExceeded::abi_decode(child.result.output().unwrap()).unwrap(), - MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 9 }, - "the child may keep 98% of ten", - ); -} - -/// A creation too big for its share still bumps its creator's nonce, and the record of that -/// write lands on the creator: the creator is held to its budget with it before it runs on. -/// -/// `A` calls `B`, which may keep 98 records. `B` writes 97 or 98 slots, then creates: the -/// creation's two start records cross its share of what `B` has left, so it is stopped. With one -/// record left, `B` keeps the nonce record at exactly its budget. With none left, the record puts -/// `B` over it: `B` reverts alone, and `A` returns its revert. -#[test] -fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { - let creator = |written| { - write_slots(BytecodeBuilder::default(), written) - .append_many([PUSH0, PUSH0, PUSH0]) - .append(CREATE) - .append(POP) - .append(STOP) - .build() - }; - let run = |written| { - run_kv( - funded() - .account_code(A, call_and_return_its_output(B)) - .account_code(B, creator(written)), - 100, - ) - }; - - let fits = run(97); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.limit_exceeded, None); - assert_eq!(fits.usage, records(98), "97 slots and B's nonce, exactly B's budget"); - assert_eq!(fits.state[&B].info.nonce, 1); - - let over = run(98); - assert!(over.result.is_success(), "A resumes: {:?}", over.result); - assert_eq!(over.limit_exceeded, None, "a frame budget does not latch"); - assert_eq!(over.usage, records(0), "B's slots and nonce went with its revert"); - assert!(over.state.get(&B).is_none_or(|b| b.info.nonce == 0)); - assert_eq!( - over.result.output().unwrap().as_ref(), - MegaLimitExceeded { kind: LimitKind::KVUpdate.as_u8(), limit: 98 }.abi_encode(), - ); -} - -/* ---------- records made before the first frame ---------- */ - -/// The records of applied EIP-7702 authorities are made before the first frame. When they cross -/// the limit they are not applied: the limit is enforced before the writes it guards, and the -/// transaction is stopped at its first frame — whatever that frame's target, an intercepted -/// system contract included. Authorities that exist already are records all the same. -#[test] -fn test_authorities_crossing_the_kv_limit_are_not_applied() { - let db = || { - funded() - .account_balance(AUTHORITY_1, U256::from(1)) - .account_balance(AUTHORITY_2, U256::from(1)) - }; - let authorities = [(AUTHORITY_1, 0), (AUTHORITY_2, 0)]; - let run = |to: Address, data: Bytes, limit: u64| { - let mut tx = authorizing_call(CALLER, to, U256::ZERO, GAS_LIMIT, DELEGATE, &authorities); - tx.0.base.data = data; - run_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(limit)) - }; - let selector = Bytes::from(IMegaLimitControl::remainingComputeGasCall::SELECTOR.to_vec()); - for (to, data) in [(A, Bytes::new()), (LIMIT_CONTROL_ADDRESS, selector)] { - let applied = run(to, data.clone(), 2); - assert!(applied.result.is_success(), "{to}: {:?}", applied.result); - assert_eq!(applied.usage.write_records, 2, "{to}"); - - let stopped = run(to, data, 1); - assert_kv_stopped(&stopped, 1, 2); - assert_eq!(stopped.usage.write_records, 0, "{to}"); - for authority in [AUTHORITY_1, AUTHORITY_2] { - let account = stopped.state.get(&authority); - assert!( - account.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), - "{to}: {authority} was not delegated: {account:?}" - ); - } - } -} - -/// The records made before the first frame and the ones made in it add up to the limit: two -/// applied authorities leave the first frame room for one slot, and a second one stops it. -#[test] -fn test_authorities_and_execution_add_up_to_the_stop() { - let run = |written| { - let tx = authorizing_call( - CALLER, - A, - U256::ZERO, - GAS_LIMIT, - DELEGATE, - &[(AUTHORITY_1, 0), (AUTHORITY_2, 0)], - ); - run_under( - funded().account_code(A, slots(written)), - tx, - EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(3), - ) - }; - let fits = run(1); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.usage.write_records, 3); - let stopped = run(2); - assert_kv_stopped(&stopped, 3, 4); - assert_eq!(stopped.usage.write_records, 2, "the authorities outlive the first frame's stop"); -} - -/// Calldata is data size and never a record: however much of it a transaction carries, its KV -/// count is what it writes. -#[test] -fn test_calldata_is_not_a_record() { - let outcome = run_under( - funded().account_code(A, slots(1)), - call_with_data(CALLER, A, Bytes::from(vec![0xab; 1_000]), GAS_LIMIT), - EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(1), - ); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage.write_records, 1); -} diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index b7bb5603f..efe41c39e 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -1,29 +1,28 @@ //! Who is held to no per-transaction limit: a transaction the protocol itself sent, and a system //! call. //! -//! The data-size limit, the KV limit, the state-gas limit and the frame budgets of the first two -//! 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 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, B256, U256}; +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, MegaTransactionOutcome, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + 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, slot_state_gas, state_is_free}; +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. @@ -77,56 +76,29 @@ fn call_from(caller: Address, to: Address) -> MegaTransaction { })) } -/// `tx` as a user's deposit: no fee, and a source hash a user's transaction could carry. -fn deposit(mut tx: MegaTransaction) -> MegaTransaction { - tx.0.deposit.source_hash = B256::repeat_byte(0x11); - tx.0.base.gas_price = 0; - tx -} - /// Every per-transaction limit the program crosses, one at a time, and all of them together. -fn limits() -> [(&'static str, EvmTxRuntimeLimits); 6] { +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)), - ("the transaction's KV count", none.with_tx_kv_update_limit(1)), - ("a frame's KV count", none.with_frame_kv_update_limit(1)), - ("the transaction's state gas", none.with_tx_state_gas_limit(1)), - ( - "every limit at zero", - none.with_tx_data_size_limit(0) - .with_frame_data_size_limit(0) - .with_tx_kv_update_limit(0) - .with_frame_kv_update_limit(0) - .with_tx_state_gas_limit(0), - ), + ("every limit at zero", none.with_tx_data_size_limit(0).with_frame_data_size_limit(0)), ] } -fn execute( - db: MemoryDatabase, - tx: MegaTransaction, - limits: EvmTxRuntimeLimits, -) -> MegaTransactionOutcome { - MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(tx) - .expect("the transaction is valid") -} - /// 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(db(), tx(), EvmTxRuntimeLimits::no_limits()); + 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(db(), tx(), 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"); @@ -136,7 +108,11 @@ fn test_a_system_transaction_is_held_to_no_limit() { } /// 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. +/// 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| { @@ -146,69 +122,37 @@ fn test_a_system_call_is_held_to_no_limit() { ( result, evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().latched().copied(), + 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, latched) = run(limits); + let (result, usage, stop) = run(limits); assert!(result.result.is_success(), "{name}: {:?}", result.result); - assert_eq!(latched, None, "{name}"); + 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 KV count or the state gas, 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, 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 none = EvmTxRuntimeLimits::no_limits(); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); let cases = [ - ( - "a deposit", - deposit(call_from(CALLER, CONTRACT)), - none.with_tx_kv_update_limit(0), - LimitKind::KVUpdate, - ), - ( - "a deposit", - deposit(call_from(CALLER, CONTRACT)), - none.with_tx_state_gas_limit(0), - LimitKind::StateGrowth, - ), - ( - "a user's call to a system contract", - call_from(CALLER, ORACLE_CONTRACT_ADDRESS), - none.with_tx_data_size_limit(TX_BODY_SIZE), - LimitKind::DataSize, - ), - ( - "a user's call to a system contract", - call_from(CALLER, ORACLE_CONTRACT_ADDRESS), - none.with_tx_kv_update_limit(0), - LimitKind::KVUpdate, - ), - ( - "a user's call to a system contract", - call_from(CALLER, ORACLE_CONTRACT_ADDRESS), - none.with_tx_state_gas_limit(0), - LimitKind::StateGrowth, - ), + ("a deposit", deposit(call_from(CALLER, CONTRACT))), + ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), ]; - for (name, tx, limits, kind) in cases { - // A transaction that adds no state gas, where a state byte is free, crosses no state-gas - // limit. - if kind == LimitKind::StateGrowth && state_is_free() { - continue; - } - let outcome = execute(db(), tx, limits); - let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}, {kind:?}: stopped")); + 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: k, .. } if k == kind), + matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }), "{name}: {stop:?}" ); assert!( 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 b4ceb2cf3..dd2ee96c2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -3,6 +3,8 @@ mod common; mod compute_gas; mod contract_size; +mod corpus; +mod count_order; mod create_opcodes; mod data_size; mod data_size_counts; @@ -11,6 +13,8 @@ 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; @@ -21,10 +25,11 @@ mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; -mod kv_limit; mod limit_exemption; +mod limit_stop; mod neutral; mod outcome; +mod pool_validation; mod precompile_gas; mod pricing_table; mod salt; @@ -33,8 +38,11 @@ mod salt_deposit; mod salt_failure; mod salt_refund; mod schedule; +#[path = "../shared/snapshot.rs"] +mod snapshot; +mod spec_numbers; mod state; -mod state_gas_limit; +mod state_growth; mod static_callee; mod stops; mod storage_call_stipend; diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index 81dd71ebc..da8f4d79b 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -15,11 +15,11 @@ //! Each case runs on Osaka's configuration and on Amsterdam's. use alloy_op_evm::OpTx; -use alloy_primitives::{address, hex, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ test_utils::{ - neutral_cfg, neutralize_evm, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, - MemoryDatabase, + neutral_cfg, neutralize_evm, op_transaction, take_system_address_read, + zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, VolatileDataAccess, @@ -42,6 +42,8 @@ use revm::{ 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"); @@ -71,7 +73,8 @@ fn block() -> BlockEnv { /// 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. +/// 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")) @@ -86,8 +89,9 @@ fn run_both(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome 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 mega = - ExecResultAndState::new(outcome.result_and_state.result, outcome.result_and_state.state); + 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) @@ -213,7 +217,7 @@ fn test_neutral_nested_value_call_matches_op_revm() { /// /// 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. +/// 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 }; @@ -226,6 +230,7 @@ fn run_against_ethereum(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outc 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); @@ -338,25 +343,6 @@ fn test_neutral_extcodesize_matches_ethereum() { } } -/// 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 = - revm::precompile::kzg_point_evaluation::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 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] diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 4a29fe5c4..d65b69196 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -10,7 +10,7 @@ use mega_evm::{ }; use crate::common::{ - body_history, call, context, history, runs_at_measurement_prices, slot_state_gas, + body_history, call, context, execute_under, history, runs_at_measurement_prices, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000600000"); @@ -36,9 +36,7 @@ fn execute( 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 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 96dcd990c..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, 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 three 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 | @@ -68,25 +68,25 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | 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 | 165826 | 37106 | 97920 | 30800 | -| SSTORE 0 -> 1 -> 0 | 51594 | 37212 | 0 | 27280 | -| value CALL to an empty account | 267241 | 49321 | 183600 | 34320 | +| 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 | 165826 | 37106 | 97920 | 30800 | -| SSTORE 0 -> 1 | 2 | 263746 | 37106 | 195840 | 30800 | -| SSTORE 0 -> 1 | 8 | 851266 | 37106 | 783360 | 30800 | -| value CALL to an empty account | 1 | 267241 | 49321 | 183600 | 34320 | -| value CALL to an empty account | 2 | 450841 | 49321 | 367200 | 34320 | -| value CALL to an empty account | 8 | 1552441 | 49321 | 1468800 | 34320 | +| 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 d05dc1000..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, 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 three 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,38 +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. The - // history entry is the one Satin adds: upstream prices no history byte at all. + // 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", - ], + ["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() { @@ -346,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(); @@ -358,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 ae2f1e558..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`. @@ -27,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::{ @@ -36,7 +39,7 @@ use revm::{ context_interface::cfg::GasId, }; -use crate::common::{block, runs_at_measurement_prices, state_is_free}; +use crate::common::{block, history, state_is_free}; /// The sender of every probe. pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000c00000"); @@ -236,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 = @@ -286,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()), ); @@ -299,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 @@ -487,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()); -} + for caller in [SYSTEM_ADDRESS, CALLER] { + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); -/// 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); + 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 @@ -549,26 +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() { - // 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); - - 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 @@ -867,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() @@ -944,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; @@ -954,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() @@ -970,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] diff --git a/crates/mega-evm/tests/satin/salt_delegation.rs b/crates/mega-evm/tests/satin/salt_delegation.rs index 4f69695bc..a1761960b 100644 --- a/crates/mega-evm/tests/satin/salt_delegation.rs +++ b/crates/mega-evm/tests/satin/salt_delegation.rs @@ -198,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. /// @@ -292,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_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 494b220d4..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}, @@ -42,7 +42,7 @@ use revm::{ use crate::{ common::{history, state_is_free}, salt::{ - account_bucket, authorization_tx, call_contract, capacity, create_with, crowded_account, + 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, }, @@ -363,93 +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() { - // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. - if state_is_free() { - return; - } - 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. @@ -694,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 856ba71b6..9f5dd5078 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -11,13 +11,13 @@ 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::{ @@ -163,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. @@ -224,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] @@ -270,18 +210,6 @@ fn test_a_create_frame_rejected_for_its_first_byte_draws_no_state_gas() { 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. 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_gas_limit.rs b/crates/mega-evm/tests/satin/state_gas_limit.rs deleted file mode 100644 index 300de8ab8..000000000 --- a/crates/mega-evm/tests/satin/state_gas_limit.rs +++ /dev/null @@ -1,1416 +0,0 @@ -//! The state-gas limit: a transaction's state growth, held to a limit in state gas. -//! -//! EIP-8037 charges state gas for exactly the state a transaction adds, so the limit on its state -//! gas is the limit on its growth. A transaction is held to `tx_state_gas_limit` at every site -//! state gas is charged — a fresh slot, an account a value transfer, a creation or a destruction -//! adds, deployed code, an applied EIP-7702 authority, the first frame's recipient or created -//! account — on what it holds net of refills and of failed frames. A crossing stops the -//! transaction with a revert carrying `MegaLimitExceeded(3, limit)`, wherever on the call stack -//! it happens: there are no frame budgets. -//! -//! The figures are read off the engine rather than written out: each case first runs without a -//! limit, and the state gas it reports is what the limit is set against. Where a state byte costs -//! nothing, which only a measurement build arranges, no transaction adds state gas and the limit -//! has nothing to hold, so the cases that need a crossing, or an upfront charge to give back, -//! return early. - -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaTransaction, - MegaTransactionOutcome, AUTHORIZATION_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, -}; -use revm::{ - bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, INVALID, POP, PUSH0, PUSH1, RETURN, - REVERT, SELFDESTRUCT, STOP, - }, - interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, - InterpreterResult, - }, - Database, Inspector, -}; - -use crate::common::{ - authorizing_call, call, call_with_value_and_data, context, create, state_is_free, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000600000"); -const A: Address = address!("0000000000000000000000000000000000600001"); -const B: Address = address!("0000000000000000000000000000000000600002"); -const C: Address = address!("0000000000000000000000000000000000600003"); -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; -/// Above the execution cap: the reservoir pays every state charge. -const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_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])) -} - -fn run_under(db: MemoryDatabase, tx: MegaTransaction, limit: u64) -> MegaTransactionOutcome { - MegaEvm::new( - context(db) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit)), - ) - .execute_transaction(tx) - .unwrap() -} - -/// The outcome was stopped by the state-gas limit `limit`, crossed at `used`: a revert carrying -/// `MegaLimitExceeded(3, limit)`, never a halt. -fn assert_state_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::StateGrowth, 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 -} - -/// Appends a `CALL` to `target` with all the gas and `value`, dropping its success flag. -fn then_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) - .append(POP) -} - -/// 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() -} - -/// Appends a `CREATE` of `init` carrying no value, or a `CREATE2` with salt zero, dropping the -/// address. -fn then_create(builder: BytecodeBuilder, init: &Bytes, create2: bool) -> BytecodeBuilder { - let builder = builder.mstore(0, init); - // CREATE2 takes a salt below the size, the offset and the value. - let builder = if create2 { builder.push_number(0_u64) } else { builder }; - builder - .push_number(init.len() as u64) - .push_number(0_u64) - .push_number(0_u64) - .append(if create2 { CREATE2 } else { CREATE }) - .append(POP) -} - -/// The state gas `tx` holds when it runs without a limit. -fn state_gas_of(db: &MemoryDatabase, tx: &MegaTransaction) -> u64 { - let outcome = run_under(db.clone(), tx.clone(), u64::MAX); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - outcome.gas.state -} - -/// The state gas one fresh slot of `A` costs. -fn one_slot() -> u64 { - let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); - state_gas_of(&db, &call(CALLER, A, U256::ZERO, BELOW_CAP)) -} - -/// One case per site state gas is charged at: the transaction, and the state it holds. -fn sites(gas_limit: u64) -> Vec<(&'static str, MemoryDatabase, MegaTransaction)> { - let to_a = |code: BytecodeBuilder| funded().account_code(A, code.stop().build()); - let a = || call(CALLER, A, U256::ZERO, gas_limit); - let deployed = constructor_returning(32); - vec![ - ("a fresh slot", to_a(write_slots(BytecodeBuilder::default(), 0, 1)), a()), - ( - "a value call that creates its recipient", - to_a(then_call(BytecodeBuilder::default(), EMPTY, 1)), - a(), - ), - ( - "a nested creation", - to_a(then_create(BytecodeBuilder::default(), &Bytes::new(), false)), - a(), - ), - ( - "a nested CREATE2 that deposits code", - to_a(then_create(BytecodeBuilder::default(), &deployed, true)), - a(), - ), - ( - "a nested creation that deposits code", - to_a(then_create(BytecodeBuilder::default(), &deployed, false)), - a(), - ), - ( - "a destruction that creates its beneficiary", - to_a(BytecodeBuilder::default().push_address(EMPTY).append(SELFDESTRUCT)), - a(), - ), - ("a value transaction that creates its recipient", funded(), { - call(CALLER, EMPTY, U256::from(1), gas_limit) - }), - ("a creation transaction", funded(), create(CALLER, Bytes::new(), gas_limit)), - ( - "a creation transaction that deposits code", - funded(), - create(CALLER, deployed.clone(), gas_limit), - ), - ( - "an authority the transaction creates", - funded().account_code(A, Bytes::from_static(&[STOP])), - authorizing_call(CALLER, A, U256::ZERO, gas_limit, DELEGATE, &[(AUTHORITY_1, 0)]), - ), - ] -} - -/* ---------- every site ---------- */ - -/// At every site, a limit equal to the state gas a transaction holds lets it through with that -/// state gas, and one below it stops it at the charge that crosses — the last one it makes — with -/// the figure it reports. The stop keeps none of it, below and above the execution cap alike. -#[test] -fn test_every_site_is_held_to_the_limit_at_the_state_gas_it_reports() { - if state_is_free() { - return; - } - for gas_limit in [BELOW_CAP, ABOVE_CAP] { - for (name, db, tx) in sites(gas_limit) { - let name = format!("{name}, gas limit {gas_limit}"); - let held = state_gas_of(&db, &tx); - assert!(held > 0, "{name}"); - - let fits = run_under(db.clone(), tx.clone(), held); - assert!(fits.result.is_success(), "{name}: {:?}", fits.result); - assert_eq!(fits.limit_exceeded, None, "{name}"); - assert_eq!(fits.gas.state, held, "{name}"); - - let stopped = run_under(db, tx, held - 1); - assert_state_stopped(&name, &stopped, held - 1, held); - assert_eq!(stopped.gas.state, 0, "{name}: the stop keeps none of it"); - if gas_limit > TX_GAS_LIMIT_CAP { - assert_eq!( - stopped.gas.reservoir_remaining, - gas_limit - TX_GAS_LIMIT_CAP - stopped.gas.state - stopped.gas.history, - "{name}: the stop hands the reservoir back" - ); - } - } - } -} - -/// A crossing stops the transaction at the charge that crossed: nothing after it runs. Each case -/// crosses at its site and would then burn what its frame has left in a call to a contract that -/// halts; the stop spends none of it. -#[test] -fn test_the_crossing_charge_is_where_the_transaction_stops() { - if state_is_free() { - return; - } - let deployed = constructor_returning(32); - let cases: [(&str, BytecodeBuilder); 5] = [ - ("a fresh slot", write_slots(BytecodeBuilder::default(), 0, 1)), - ( - "a value call that creates its recipient", - then_call(BytecodeBuilder::default(), EMPTY, 1), - ), - ("a nested creation", then_create(BytecodeBuilder::default(), &Bytes::new(), false)), - ("deployed code", then_create(BytecodeBuilder::default(), &deployed, false)), - ("a nested CREATE2", then_create(BytecodeBuilder::default(), &Bytes::new(), true)), - ]; - for (name, site) in cases { - let db = funded().account_code(A, then_call(site, BURNER, 0).stop().build()); - let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); - let burned = run_under(db.clone(), tx.clone(), u64::MAX); - assert!(burned.gas.regular > BELOW_CAP / 2, "{name}: the burner burns: {:?}", burned.gas); - - let held = burned.gas.state; - let stopped = run_under(db, tx, held - 1); - assert_state_stopped(name, &stopped, held - 1, held); - assert!(stopped.gas.regular < 1_000_000, "{name}: nothing burned: {:?}", stopped.gas); - assert_eq!(stopped.gas.state, 0, "{name}"); - } -} - -/// Deployed code whose state gas crosses the limit is not left deployed, whether the creation is -/// the transaction's own or a nested one: the limit is held before `return_create` commits it. -#[test] -fn test_deployed_code_that_crosses_is_not_left_deployed() { - if state_is_free() { - return; - } - let deployed = constructor_returning(32); - let nested = funded() - .account_code(A, then_create(BytecodeBuilder::default(), &deployed, false).stop().build()); - let cases = [ - ( - "the transaction's creation", - funded(), - create(CALLER, deployed, BELOW_CAP), - CALLER.create(0), - ), - ("a nested creation", nested, call(CALLER, A, U256::ZERO, BELOW_CAP), A.create(0)), - ]; - for (name, db, tx, created) in cases { - let held = state_gas_of(&db, &tx); - let kept = run_under(db.clone(), tx.clone(), held); - assert_eq!( - kept.state[&created].info.code.as_ref().map(|code| code.original_bytes().len()), - Some(32), - "{name}" - ); - - let stopped = run_under(db, tx, held - 1); - assert_state_stopped(name, &stopped, held - 1, held); - assert!( - stopped.state.get(&created).is_none_or(|account| account.info.is_empty_code_hash()), - "{name}: no code is left at the created address" - ); - } -} - -/// A creation whose init code reverts deposits nothing, whatever its revert data: the limit holds -/// the account the creation would have added and the caller goes on. -#[test] -fn test_a_reverting_creation_is_not_held_for_its_revert_data() { - let reverting = - BytecodeBuilder::default().push_number(32_u8).push_number(0_u8).append(REVERT).build(); - let account = state_gas_of( - &funded().account_code( - A, - then_create(BytecodeBuilder::default(), &Bytes::new(), false).stop().build(), - ), - &call(CALLER, A, U256::ZERO, BELOW_CAP), - ); - let db = funded() - .account_code(A, then_create(BytecodeBuilder::default(), &reverting, false).stop().build()); - let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), account); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.limit_exceeded, None); - assert_eq!(outcome.gas.state, 0, "the failed creation's account charge came back"); -} - -/* ---------- a frame's upfront charge, held once revm has decided the frame ---------- */ - -/// The state gas one account a creation or a value transfer adds costs. -fn one_account() -> u64 { - state_gas_of( - &funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()), - &call(CALLER, A, U256::ZERO, BELOW_CAP), - ) -} - -/// Appends a `CALL` or `CALLCODE` to `target` with all the gas and `value`, dropping its success -/// flag. -fn then_call_with( - builder: BytecodeBuilder, - opcode: u8, - target: Address, - value: u64, -) -> BytecodeBuilder { - builder - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(value) - .push_address(target) - .append(GAS) - .append(opcode) - .append(POP) -} - -/// Appends a `CREATE`, or a `CREATE2` with salt zero, of empty init code carrying `value`, -/// dropping the address. -fn then_create_with(builder: BytecodeBuilder, create2: bool, value: u64) -> BytecodeBuilder { - let builder = if create2 { builder.push_number(0_u64) } else { builder }; - builder - .push_number(0_u64) - .push_number(0_u64) - .push_number(value) - .append(if create2 { CREATE2 } else { CREATE }) - .append(POP) -} - -/// A frame revm refuses once its caller's opcode charged the state gas of the account it would add -/// gives the charge back, and adds nothing: the limit does not hold it. Each case writes a fresh -/// slot after the refused frame and runs under limits the refused charge would cross — what the -/// transaction ends up holding, and one account less one gas — and succeeds exactly as it does -/// without a limit. -/// -/// Only the value `CALL` its caller cannot fund reaches revm with the charge made: its opcode -/// charges the new account before the balance is known, and revm refuses the frame when it moves -/// the value. The other cases pin that nothing is held where nothing is charged: `CALLCODE` moves -/// value within its caller's own account and never adds one, and under EIP-8037 `CREATE` and -/// `CREATE2` refuse a creation their caller cannot fund before they charge it, and charge only a -/// destination with nothing at it, which cannot collide. A frame past the call-stack limit is -/// refused with the charge made too; no transaction reaches that depth under the execution cap, -/// and the unit tests of the frame lifecycle pin it. -#[test] -fn test_a_frame_revm_refuses_is_not_held_for_its_upfront_charge() { - if state_is_free() { - return; - } - let account = one_account(); - let empty_init = Bytes::new(); - let taken = |address: Address| funded().account_nonce(address, 1); - let cases: [(&str, MemoryDatabase, BytecodeBuilder); 6] = [ - ( - "a CALL its caller cannot fund", - funded(), - then_call_with(BytecodeBuilder::default(), CALL, EMPTY, 2_000), - ), - ( - "a CALLCODE its caller cannot fund", - funded(), - then_call_with(BytecodeBuilder::default(), CALLCODE, EMPTY, 2_000), - ), - ( - "a CREATE its caller cannot fund", - funded(), - then_create_with(BytecodeBuilder::default(), false, 2_000), - ), - ( - "a CREATE2 its caller cannot fund", - funded(), - then_create_with(BytecodeBuilder::default(), true, 2_000), - ), - ( - "a CREATE whose address is taken", - taken(A.create(0)), - then_create_with(BytecodeBuilder::default(), false, 0), - ), - ( - "a CREATE2 whose address is taken", - taken(A.create2_from_code(B256::ZERO, &empty_init)), - then_create_with(BytecodeBuilder::default(), true, 0), - ), - ]; - for (name, db, site) in cases { - let db = db.account_code(A, write_slots(site, 0, 1).stop().build()); - let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); - let free = run_under(db.clone(), tx.clone(), u64::MAX); - assert!(free.result.is_success(), "{name}: {:?}", free.result); - assert_eq!(free.gas.state, one_slot(), "{name}: the slot alone"); - - for limit in [free.gas.state, account - 1] { - let limited = run_under(db.clone(), tx.clone(), limit); - assert!(limited.result.is_success(), "{name}, limit {limit}: {:?}", limited.result); - assert_eq!(limited.limit_exceeded, None, "{name}, limit {limit}"); - assert_eq!(limited.gas, free.gas, "{name}, limit {limit}: as without the limit"); - assert!( - limited.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero()), - "{name}, limit {limit}: nothing moved" - ); - } - } -} - -/// The result of each call to [`EMPTY`] an inspector saw end. -#[derive(Default)] -struct CallsToEmpty(Vec<(InstructionResult, Bytes)>); - -impl Inspector, EthInterpreter> for CallsToEmpty { - fn call_end( - &mut self, - _: &mut MegaContext, - inputs: &CallInputs, - outcome: &mut CallOutcome, - ) { - if inputs.target_address == EMPTY { - self.0.push((outcome.result.result, outcome.result.output.clone())); - } - } -} - -/// A frame revm decides to run, or answers with a success, adds the account its caller's opcode -/// was charged for, so the charge is held, and a crossing latches the transaction — one case per -/// opcode family. A value call to an account with no code is answered by revm without running and -/// rewritten to the stop at once, so an inspector sees the answer the caller gets. The stop keeps -/// none of what the frame's start wrote: no value moved, no account created, and the history of -/// its records given back. -#[test] -fn test_a_frame_revm_decides_is_held_for_its_upfront_charge() { - if state_is_free() { - return; - } - let account = one_account(); - let body = mega_evm::history_gas(TX_BODY_SIZE).expect("a body has a price"); - let cases: [(&str, BytecodeBuilder); 3] = [ - ( - "a value CALL that creates its recipient", - then_call(BytecodeBuilder::default(), EMPTY, 1), - ), - ("a CREATE", then_create_with(BytecodeBuilder::default(), false, 0)), - ("a CREATE2", then_create_with(BytecodeBuilder::default(), true, 0)), - ]; - for (name, site) in cases { - let db = funded().account_code(A, site.stop().build()); - let stopped = run_under(db.clone(), call(CALLER, A, U256::ZERO, BELOW_CAP), account - 1); - assert_state_stopped(name, &stopped, account - 1, account); - assert_eq!(stopped.gas.state, 0, "{name}"); - assert_eq!(stopped.gas.history, body, "{name}: the records' history came back"); - assert!(stopped.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); - assert!(stopped.state.get(&A.create(0)).is_none_or(|account| !account.is_created())); - } - - let db = - funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), - )) - .with_inspector(CallsToEmpty::default()); - let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)).unwrap(); - let stop = outcome.limit_exceeded.expect("the call is stopped"); - assert_eq!(evm.inspector().0, [(InstructionResult::Revert, stop.revert_data())]); -} - -/// The records a frame's start makes are held before revm builds the frame, and its upfront state -/// gas after revm has decided it. A value call whose records and transfer log cross the data-size -/// limit is answered with that stop, adds no account, and gives its upfront charge back: the -/// state-gas limit that charge would have crossed is not. -#[test] -fn test_a_frame_start_whose_records_cross_is_stopped_for_its_records() { - if state_is_free() { - return; - } - let account = one_account(); - let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; - let db = - funded().account_code(A, then_call(BytecodeBuilder::default(), EMPTY, 1).stop().build()); - let outcome = MegaEvm::new( - context(db).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_state_gas_limit(account - 1) - .with_tx_data_size_limit(limit), - ), - ) - .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) - .unwrap(); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: limit + 1, - frame_local: false, - }), - "the caller's account, the recipient's and the transfer log, over the limit by one byte", - ); - assert_eq!(outcome.gas.state, 0); -} - -/* ---------- the first frame's upfront charge, held once revm has decided the frame ---------- */ - -/// The identity precompile, which answers any input with a success. -const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); -/// The BN254 pairing precompile, which rejects an input that is not a whole number of pairs. -const BN254_PAIRING: Address = address!("0000000000000000000000000000000000000008"); - -/// A transaction of one wei from [`CALLER`] to `to` carrying `data`. -fn one_wei_to(to: Address, data: &[u8]) -> MegaTransaction { - call_with_value_and_data(CALLER, to, U256::from(1), Bytes::copy_from_slice(data), BELOW_CAP) -} - -/// The transaction's own frame is held for the account EIP-2780 charges its start for as every -/// frame is held for its opcode's upfront charge: once revm has decided the frame. A first frame -/// revm answers with a failure — a value transfer to a precompile that rejects its input — adds no -/// account, and its charge comes back, so no limit holds it: the transaction halts exactly as it -/// does without a limit, and nothing moves. -#[test] -fn test_a_first_frame_revm_answers_with_a_failure_is_not_held_for_its_upfront_charge() { - // Where a state byte is free the start is charged nothing for the account, and there is no - // charge to give back. - if state_is_free() { - return; - } - let account = one_account(); - let tx = one_wei_to(BN254_PAIRING, &[1]); - let free = run_under(funded(), tx.clone(), u64::MAX); - assert!(free.result.is_halt(), "the pairing rejects a one-byte input: {:?}", free.result); - assert_eq!(free.gas.state, 0, "the account charge came back"); - for limit in [account - 1, 0] { - let limited = run_under(funded(), tx.clone(), limit); - assert_eq!(limited.limit_exceeded, None, "limit {limit}"); - assert_eq!(limited.result, free.result, "limit {limit}: as without the limit"); - assert_eq!(limited.gas, free.gas, "limit {limit}"); - assert!( - limited.state.get(&BN254_PAIRING).is_none_or(|account| account.info.balance.is_zero()), - "limit {limit}: nothing moved" - ); - } -} - -/// A first frame revm builds, or answers with a success, adds the account EIP-2780 charged its -/// start for, so the charge is held once revm has decided the frame, and a crossing stops the -/// transaction: a built frame before its first instruction, an answer by being rewritten to the -/// stop. The stop keeps none of what the start wrote — no value moved, no account added, the -/// record and the transfer log not counted, the record's history given back — and bills what ran, -/// as a stop below the first frame does: a precompile answered with a success ran, and its price -/// stays spent. A creation transaction keeps its creator's nonce bump, so it cannot be replayed. -#[test] -fn test_a_first_frame_revm_decides_is_held_for_its_upfront_charge() { - // Where a state byte is free the start is charged nothing for the account, and there is no - // charge to hold. - if state_is_free() { - return; - } - let account = one_account(); - let word = [7_u8; 32]; - let cases = [ - ("a value transfer to an account with no code", one_wei_to(EMPTY, &[]), EMPTY, 0), - ( - "a value transfer to a precompile that answers", - one_wei_to(IDENTITY, &word), - IDENTITY, - 32, - ), - ("a creation transaction", create(CALLER, Bytes::new(), BELOW_CAP), CALLER.create(0), 0), - ]; - for (name, tx, added, calldata) in cases { - let free = run_under(funded(), tx.clone(), u64::MAX); - assert!(free.result.is_success(), "{name}: {:?}", free.result); - assert_eq!(free.gas.state, account, "{name}: the account EIP-2780 charged"); - - let stopped = run_under(funded(), tx, account - 1); - assert_state_stopped(name, &stopped, account - 1, account); - assert_eq!(stopped.gas.state, 0, "{name}"); - let body = mega_evm::history_gas(TX_BODY_SIZE + calldata).expect("a body has a price"); - assert_eq!(stopped.gas.history, body, "{name}: the record's history came back"); - assert_eq!(stopped.gas.regular, free.gas.regular, "{name}: what ran is billed"); - assert_eq!( - stopped.usage, - LimitUsage { data_size: TX_BODY_SIZE + calldata, write_records: 0 }, - "{name}: the body alone" - ); - let account = stopped.state.get(&added); - assert!( - account.is_none_or(|account| account.info.balance.is_zero() && !account.is_created()), - "{name}: nothing moved, nothing added" - ); - assert_eq!(stopped.state[&CALLER].info.nonce, 1, "{name}: the sender's nonce"); - } -} - -/// The first frame's start is held as every frame start is: its record and transfer log before -/// revm builds the frame, its upfront state gas after revm has decided it. A value transfer whose -/// record and transfer log cross the data-size limit is stopped for them and adds no account, so -/// the state-gas limit its upfront charge would have crossed is not what stops it. -#[test] -fn test_a_first_frame_start_whose_records_cross_is_stopped_for_its_records() { - // Where a state byte is free the start is charged nothing for the account, and there is no - // state-gas crossing for the records' stop to come before. - if state_is_free() { - return; - } - let account = one_account(); - let limit = TX_BODY_SIZE + WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE - 1; - let outcome = MegaEvm::new( - context(funded()).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_state_gas_limit(account - 1) - .with_tx_data_size_limit(limit), - ), - ) - .execute_transaction(one_wei_to(EMPTY, &[])) - .unwrap(); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: limit + 1, - frame_local: false, - }), - "the recipient's record and the transfer log, over the limit by one byte", - ); - assert_eq!(outcome.gas.state, 0); - assert!(outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); -} - -/// Answers every call to [`EMPTY`] itself, with a success. -struct AnswersEmpty; - -impl Inspector, EthInterpreter> for AnswersEmpty { - fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { - (inputs.target_address == EMPTY).then(|| { - CallOutcome::new( - InterpreterResult::new( - InstructionResult::Stop, - Bytes::new(), - Gas::new(inputs.gas_limit), - ), - inputs.return_memory_offset.clone(), - ) - }) - } -} - -/// A first frame an inspector answers in place of running never started: it adds no account, and -/// its upfront charge comes back whatever the answer. So no limit holds that charge, and the -/// transaction keeps the inspector's answer. -#[test] -fn test_a_first_frame_an_inspector_answers_is_not_held_for_its_upfront_charge() { - // Where a state byte is free the start is charged nothing for the account, and there is no - // charge to give back. - if state_is_free() { - return; - } - let account = one_account(); - let mut evm = MegaEvm::new(context(funded()).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), - )) - .with_inspector(AnswersEmpty); - let outcome = evm.execute_transaction(one_wei_to(EMPTY, &[])).unwrap(); - assert_eq!(outcome.limit_exceeded, None); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.state, 0); - assert!(outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero())); -} - -/* ---------- one limit for the whole call stack ---------- */ - -/// A child's crossing stops the whole transaction: there is no frame budget to revert it alone. -/// What its callers hold counts: `A`, `B` and `C` each write one slot, and a limit one gas short -/// of three slots is crossed in `C`, with the three slots as the figure. -#[test] -fn test_a_childs_crossing_latches_the_transaction() { - if state_is_free() { - return; - } - let slot = one_slot(); - let db = funded() - .account_code( - A, - then_call(write_slots(BytecodeBuilder::default(), 0, 1), B, 0).stop().build(), - ) - .account_code( - B, - then_call(write_slots(BytecodeBuilder::default(), 0, 1), C, 0).stop().build(), - ) - .account_code(C, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); - let tx = call(CALLER, A, U256::ZERO, BELOW_CAP); - - let fits = run_under(db.clone(), tx.clone(), 3 * slot); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.gas.state, 3 * slot); - - let stopped = run_under(db.clone(), tx.clone(), 3 * slot - 1); - assert_state_stopped("C crosses", &stopped, 3 * slot - 1, 3 * slot); - - let stopped = run_under(db, tx, 2 * slot - 1); - assert_state_stopped("B crosses", &stopped, 2 * slot - 1, 2 * slot); -} - -/// What was charged before the first frame and what the frames charge add up: an authority the -/// transaction creates and a slot its frame writes cross a limit neither crosses alone. -#[test] -fn test_charges_before_the_first_frame_and_in_it_add_up() { - if state_is_free() { - return; - } - let slot = one_slot(); - let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); - let tx = authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]); - let held = state_gas_of(&db, &tx); - let authority = held - slot; - assert!(authority > slot, "an authority costs an account and its delegation"); - - let stopped = run_under(db, tx, held - 1); - assert_state_stopped("the slot after the authority", &stopped, held - 1, held); - assert_eq!( - stopped.state[&AUTHORITY_1].info.nonce, 1, - "the authority fitted, and the stop in the frame does not take it back" - ); - assert_eq!(stopped.gas.state, authority, "the authority's state gas stays with it"); -} - -/// 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. -#[test] -fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { - if state_is_free() { - return; - } - let delegation = |outcome: &MegaTransactionOutcome| { - outcome.state[&AUTHORITY_1].info.code.as_ref().map(|code| code.original_bytes()) - }; - 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 held = state_gas_of(&writes, &tx); - let stopped = run_under(writes, tx.clone(), held - 1); - assert_state_stopped("the slot after the authority", &stopped, held - 1, held); - let applied = run_under(idle, tx, u64::MAX); - 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, 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. -#[test] -fn test_a_stopped_deposit_keeps_the_caller_it_created() { - if state_is_free() { - return; - } - 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 held = state_gas_of(&writes, &tx); - let stopped = run_under(writes, tx, held - 1); - assert_state_stopped("the slot after the caller", &stopped, held - 1, held); - let (idle, tx) = deposit(BytecodeBuilder::default().stop().build()); - let created = run_under(idle, tx, u64::MAX); - 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, one_account()); -} - -/// A stop reports as used the state gas held where the limit was crossed. Before the first frame -/// that is what stands whatever the frame does, a deposit's created caller, and not the account -/// EIP-2780 charges the first frame's start for, which is held once revm has decided the frame. -/// So a deposit that creates its caller and sends value to an account that does not exist -/// reports the caller alone when the caller crosses the limit, and both accounts when only both -/// do. -#[test] -fn test_a_stop_reports_the_state_gas_held_where_it_crossed() { - if state_is_free() { - return; - } - let fresh = address!("00000000000000000000000000000000006000fe"); - let deposit = || { - let mut tx = call(fresh, EMPTY, U256::from(1), BELOW_CAP); - tx.0.deposit.source_hash = B256::repeat_byte(0x11); - tx.0.deposit.mint = Some(5); - tx.0.base.gas_price = 0; - tx - }; - let account = one_account(); - let caller_alone = run_under(funded(), deposit(), account - 1); - assert_state_stopped("the created caller", &caller_alone, account - 1, account); - let both = run_under(funded(), deposit(), 2 * account - 1); - assert_state_stopped("the caller and the recipient", &both, 2 * account - 1, 2 * account); - for stopped in [&caller_alone, &both] { - assert!( - stopped.state.get(&EMPTY).is_none_or(|a| a.info.balance.is_zero()), - "no value moved" - ); - assert_eq!( - stopped.gas.state, account, - "the caller's account stays, the recipient's does not" - ); - } -} - -/* ---------- refills give their room back ---------- */ - -/// The limit holds what the transaction holds net: a slot written back gives its room back, and -/// so do a failed child's writes, a creation that failed, and a slot a delegate writes back -/// before writing another. Each case holds two slots' worth of charges over its run, and fits a -/// limit of one. -#[test] -fn test_what_is_given_back_gives_its_room_back() { - let slot = one_slot(); - let reverting = Bytes::from_static(&[PUSH0, PUSH0, REVERT]); - let restores_then_writes = BytecodeBuilder::default() - .sstore(U256::ZERO, U256::ZERO) - .sstore(U256::from(1), U256::from(1)) - .stop() - .build(); - 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 cases: [(&str, MemoryDatabase); 3] = [ - ( - "a slot written back, then another", - funded().account_code( - A, - BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .sstore(U256::ZERO, U256::ZERO) - .sstore(U256::from(1), U256::from(1)) - .stop() - .build(), - ), - ), - ( - "a child's slot rolled back with its revert, then a slot of the caller's", - funded() - .account_code( - A, - then_call(BytecodeBuilder::default(), B, 0) - .sstore(U256::ZERO, U256::from(1)) - .stop() - .build(), - ) - .account_code( - B, - BytecodeBuilder::default() - .sstore(U256::ZERO, U256::from(1)) - .append_many([PUSH0, PUSH0, REVERT]) - .build(), - ), - ), - ( - "a delegate that writes its caller's slot back, then another", - funded().account_code(A, delegate_to_b).account_code(B, restores_then_writes), - ), - ]; - for (name, db) in cases { - let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), slot); - assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!(outcome.limit_exceeded, None, "{name}"); - assert_eq!(outcome.gas.state, slot, "{name}"); - } - - // A creation that fails gives its account back to its creator, which then has room for a - // slot under a limit of one account. - let account = state_gas_of( - &funded().account_code( - A, - then_create(BytecodeBuilder::default(), &Bytes::new(), false).stop().build(), - ), - &call(CALLER, A, U256::ZERO, BELOW_CAP), - ); - let db = funded().account_code( - A, - then_create(BytecodeBuilder::default(), &reverting, false) - .sstore(U256::from(9), U256::from(1)) - .stop() - .build(), - ); - let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), account); - assert!(outcome.result.is_success(), "a failed creation: {:?}", outcome.result); - assert_eq!(outcome.gas.state, slot); -} - -/* ---------- SALT ---------- */ - -/// The limit is on state gas, so it counts state at the price SALT sets for it: a slot in a bucket -/// twice the minimum costs two slots of the limit, and a limit of two minimal slots admits two -/// slots in minimal buckets but crosses on the second when the first is in the crowded one. -#[test] -fn test_a_crowded_bucket_reaches_the_limit_sooner() { - if state_is_free() { - return; - } - use crate::salt::{crowded_slot, minimal_envs, salt_context}; - - let slot = one_slot(); - let db = - || funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 2).stop().build()); - let run = |envs| { - MegaEvm::new(salt_context(db(), envs).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(2 * slot), - )) - .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) - .unwrap() - }; - - let minimal = run(minimal_envs()); - assert!(minimal.result.is_success(), "{:?}", minimal.result); - assert_eq!(minimal.gas.state, 2 * slot); - - let unlimited = - MegaEvm::new(salt_context(db(), crowded_slot(minimal_envs(), A, U256::ZERO, 2))) - .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) - .unwrap(); - assert_eq!(unlimited.gas.state, 3 * slot, "the crowded slot costs two"); - let crowded = run(crowded_slot(minimal_envs(), A, U256::ZERO, 2)); - assert_state_stopped("the second slot after a crowded first", &crowded, 2 * slot, 3 * slot); - - let crowded = run(crowded_slot(minimal_envs(), A, U256::ZERO, 3)); - assert_state_stopped("a first slot three times the price", &crowded, 2 * slot, 3 * slot); -} - -/* ---------- authorities ---------- */ - -/// 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_under( - db.account_code(A, Bytes::from_static(&[STOP])), - authorizing(A, U256::ZERO, &authorizations), - u64::MAX, - ); - 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"); - } -} - -/// An authority in a crowded bucket costs the bucket's multiple of its new account and its -/// delegation, on the state ledger alone: its record and the data size do not move. -#[test] -fn test_a_crowded_authority_moves_the_state_ledger_alone() { - use crate::salt::{crowded_account, minimal_envs, salt_context}; - let (account, delegation) = account_and_delegation(); - // Room below the execution cap for the authority at the crowded price. - let gas_limit = BELOW_CAP + 100 * (account + delegation); - let run = |envs| { - let mut tx = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); - tx.0.base.gas_limit = gas_limit; - MegaEvm::new(salt_context(funded().account_code(A, Bytes::from_static(&[STOP])), envs)) - .execute_transaction(tx) - .unwrap() - }; - let minimal = run(minimal_envs()); - let crowded = run(crowded_account(minimal_envs(), AUTHORITY_1, 100)); - assert!(minimal.result.is_success() && crowded.result.is_success()); - assert_eq!(minimal.gas.state, account + delegation); - assert_eq!(crowded.gas.state, 100 * (account + delegation)); - assert_eq!(crowded.gas.regular, minimal.gas.regular, "the regular ledger does not move"); - assert_eq!(crowded.usage, minimal.usage, "the record and the data size do not move"); -} - -/// 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_under( - funded(), - authorizing(AUTHORITY_1, U256::from(1), &[(Some(AUTHORITY_1), 0, 0)]), - u64::MAX, - ); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.state, account + delegation); - assert_eq!(outcome.usage.write_records, 1); - - let unauthorized = - run_under(funded(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP), u64::MAX); - assert_eq!(unauthorized.gas.state, account, "the same transfer without it pays the account"); -} - -/// Authorities that cross a limit are not applied, whichever limit it is: the limit is enforced -/// before the writes it guards, the gas they charged is taken back, and the transaction is stopped -/// at its first frame. Their state gas is held first, then their records' data size and KV count, -/// so a transaction that crosses more than one limit reports the first of them. Taking them back -/// forgoes the refund an authority that existed would have earned: two transactions that differ -/// in that alone spend the same gas. -#[test] -fn test_authorities_crossing_any_limit_are_not_applied() { - if state_is_free() { - return; - } - let (account, delegation) = account_and_delegation(); - 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 held = 2 * (account + delegation); - let body = TX_BODY_SIZE + 2 * mega_evm::AUTHORIZATION_SIZE; - let limits = EvmTxRuntimeLimits::no_limits; - let state_stop = |limit, used| LimitCheck::ExceedsLimit { - kind: LimitKind::StateGrowth, - limit, - used, - frame_local: false, - }; - // (case, database, authorizations, limits, the stop) - type Case = (&'static str, MemoryDatabase, Vec, EvmTxRuntimeLimits, LimitCheck); - let cases: [Case; 6] = [ - ( - "a new authority under no state gas at all", - fresh(), - vec![both[0]], - limits().with_tx_state_gas_limit(0), - state_stop(0, account + delegation), - ), - ( - "two new authorities one gas short", - fresh(), - both.to_vec(), - limits().with_tx_state_gas_limit(held - 1), - state_stop(held - 1, held), - ), - ( - "two new authorities over the state-gas and the KV limit", - fresh(), - both.to_vec(), - limits().with_tx_state_gas_limit(held - 1).with_tx_kv_update_limit(0), - state_stop(held - 1, held), - ), - ( - "two existing authorities over the KV limit", - existing(), - both.to_vec(), - limits().with_tx_kv_update_limit(1), - LimitCheck::ExceedsLimit { - kind: LimitKind::KVUpdate, - limit: 1, - used: 2, - frame_local: false, - }, - ), - ( - "two new authorities over the data-size limit", - fresh(), - both.to_vec(), - limits().with_tx_data_size_limit(body + 2 * WRITE_RECORD_SIZE - 1), - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: body + 2 * WRITE_RECORD_SIZE - 1, - used: body + 2 * WRITE_RECORD_SIZE, - frame_local: false, - }, - ), - ( - "two existing authorities under no state gas at all", - existing(), - both.to_vec(), - limits().with_tx_state_gas_limit(0), - state_stop(0, 2 * delegation), - ), - ]; - for (name, db, authorizations, limits, stop) in cases { - let stopped = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(authorizing(A, U256::ZERO, &authorizations)) - .unwrap(); - assert!(!stopped.result.is_success() && !stopped.result.is_halt(), "{name}"); - assert_eq!(stopped.limit_exceeded, Some(stop), "{name}"); - assert_eq!(stopped.result.output().unwrap(), &stop.revert_data(), "{name}"); - assert_eq!(stopped.gas.state, 0, "{name}: their state gas was taken back"); - assert_eq!(stopped.usage.write_records, 0, "{name}: no record of them is kept"); - for authority in [AUTHORITY_1, AUTHORITY_2] { - let account = stopped.state.get(&authority); - assert!( - account.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), - "{name}: {authority} was not delegated: {account:?}" - ); - } - } - - let spent = |db: MemoryDatabase| { - MegaEvm::new(context(db).with_tx_runtime_limits(limits().with_tx_state_gas_limit(0))) - .execute_transaction(authorizing(A, U256::ZERO, &both)) - .unwrap() - .gas - .gas_used - }; - assert_eq!(spent(existing()), spent(fresh()), "no refund for an authority never applied"); - - let applied = run_under(fresh(), authorizing(A, U256::ZERO, &both), held); - assert!(applied.result.is_success(), "a limit they fit applies them: {:?}", applied.result); - assert_eq!(applied.usage.write_records, 2); -} - -/* ---------- destructions ---------- */ - -/// A `SELFDESTRUCT` grows the state only when the value it moves creates its beneficiary: one new -/// account, which is also one write record. Moving value to an account that exists is a record -/// and no state; moving nothing, or to itself, is neither. -#[test] -fn test_a_destruction_grows_state_only_when_it_creates_its_beneficiary() { - let (account, _) = account_and_delegation(); - let destroys_to = |beneficiary| { - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() - }; - let cases: [(&str, MemoryDatabase, u64, u64); 4] = [ - ("value to a new beneficiary", funded().account_code(A, destroys_to(EMPTY)), account, 1), - ("value to a beneficiary that exists", funded().account_code(A, destroys_to(BURNER)), 0, 1), - ( - "nothing to move", - funded().account_balance(A, U256::ZERO).account_code(A, destroys_to(EMPTY)), - 0, - 0, - ), - ("value to itself", funded().account_code(A, destroys_to(A)), 0, 0), - ]; - for (name, db, state_gas, records) in cases { - let outcome = run_under(db, call(CALLER, A, U256::ZERO, BELOW_CAP), u64::MAX); - 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"); - } -} - -/* ---------- fresh slots ---------- */ - -/// Three fresh slots fit a limit of three slots' state gas exactly; a fourth crosses it, on the -/// fourth `SSTORE`, and none of the four is kept. -#[test] -fn test_fresh_slots_fit_a_limit_of_their_state_gas_and_one_more_stops() { - if state_is_free() { - return; - } - let slot = one_slot(); - let run = |slots| { - run_under( - funded() - .account_code(A, write_slots(BytecodeBuilder::default(), 0, slots).stop().build()), - call(CALLER, A, U256::ZERO, BELOW_CAP), - 3 * slot, - ) - }; - let fits = run(3); - assert!(fits.result.is_success(), "{:?}", fits.result); - assert_eq!(fits.gas.state, 3 * slot); - - let stopped = run(4); - assert_state_stopped("a fourth slot", &stopped, 3 * slot, 4 * slot); - let written = - stopped.state.get(&A).map_or(0, |a| a.storage.values().filter(|v| v.is_changed()).count()); - assert_eq!(written, 0, "none of the slots is kept"); -} - -/* ---------- which limit binds first ---------- */ - -/// A fresh slot is charged its state gas inside `SSTORE`, before its record is counted, so a slot -/// that crosses the state-gas and data-size limits at once is the state-gas limit's stop. -#[test] -fn test_a_slot_crossing_both_limits_reports_the_state_gas() { - if state_is_free() { - return; - } - let slot = one_slot(); - let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); - let outcome = MegaEvm::new( - context(db).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_state_gas_limit(slot - 1) - .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE - 1), - ), - ) - .execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)) - .unwrap(); - assert_state_stopped("a slot over both", &outcome, slot - 1, slot); -} - -/// Each transaction the same EVM runs is held to the limit from zero. -#[test] -fn test_each_transaction_is_held_to_the_limit_from_zero() { - let slot = one_slot(); - let db = funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 2).stop().build()); - let mut evm = - MegaEvm::new(context(db).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(2 * slot), - )); - for run in 0..2 { - let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW_CAP)).unwrap(); - assert!(outcome.result.is_success(), "run {run}: {:?}", outcome.result); - assert_eq!(outcome.gas.state, 2 * slot, "run {run}"); - } -} 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/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 2b7288254..781397192 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1,40 +1,41 @@ //! The revert-class stop, pinned as a matrix. //! -//! A transaction-level limit — data size, KV updates, state gas, or gas detention's compute limit — -//! stops the transaction with a revert. The frame that crosses it reverts with -//! `MegaLimitExceeded(kind, limit)`, the transaction is latched, and every frame above returns the -//! same revert without running another instruction, whatever produced its result. The transaction -//! 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 reverts its frame alone, and its caller runs on. 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 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, without an inspector and under one that rewrites every frame result into a success, below -//! the execution cap and above it, where a reservoir pays the body first. What ran is read off a -//! twin of each transaction: the same frames, each reverting where the stopped one crossed its -//! limit or would have resumed. The twin runs without limits and revm settles its reverts itself, -//! so it bills exactly what the stop should, plus the two pushes each of its reverts costs. +//! 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 holds the same under that inspector, which revives a stopped creation: -//! once the transaction is latched the revival is not refused, and the creation reports the stop. +//! 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, a value call -//! whose new account crosses the state-gas limit, and a start whose records cross the data-size -//! limit before the frame is built — and settle the same way. +//! 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, }, - satin_gas_params, system::ORACLE_CONTRACT_ADDRESS, test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, 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, + 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::{ @@ -52,8 +53,8 @@ use revm::{ }; use crate::{ - common::{body_history, call, call_with_data, create, state_is_free}, - detention::{context, work, Charges, BENEFICIARY}, + 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}, }; @@ -78,38 +79,28 @@ const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; 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 call or its crossing: a write of it is an -/// instruction run after the stop. +/// 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 each of the twin's reverts cost. +/// What the two pushes before the twin's revert cost. const TWIN_REVERT: u64 = 4; -/// A transaction-level limit the matrix crosses. +/// A limit the matrix crosses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Limit { DataSize, - KvUpdates, - StateGas, Compute, } impl Limit { - const ALL: [Self; 4] = [Self::DataSize, Self::KvUpdates, Self::StateGas, Self::Compute]; - - /// Whether a transaction can cross this limit at the byte prices in effect: where a state byte - /// is free no transaction adds state gas, and the state-gas limit has nothing to hold. - fn crossable(self) -> bool { - !(self == Self::StateGas && state_is_free()) - } + const ALL: [Self; 2] = [Self::DataSize, Self::Compute]; const fn kind(self) -> LimitKind { match self { Self::DataSize => LimitKind::DataSize, - Self::KvUpdates => LimitKind::KVUpdate, - Self::StateGas => LimitKind::StateGrowth, Self::Compute => LimitKind::ComputeGas, } } @@ -132,10 +123,12 @@ fn revert(code: BytecodeBuilder) -> BytecodeBuilder { /// 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. The -/// frame at `crossing` then crosses the limit — a fresh slot's write, or a read of the block's -/// timestamp and more compute than the cap — and every frame above it calls the next. The stopped -/// transaction's frames then write [`MARKER`] and log again; the twin's frames revert instead. +/// 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 { @@ -143,19 +136,13 @@ fn frame_code(limit: Limit, depth: usize, crossing: usize, twin: bool) -> Bytes code = code.sstore(U256::from(slot), U256::from(1)); } } - code = if depth < crossing { - let code = call_all(code, CHAIN[depth + 1]); - if twin { - code - } else { - code.append(POP) - } - } else { - match limit { - Limit::Compute if twin => code.append(TIMESTAMP), - Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), - _ => code.sstore(CROSSING_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() @@ -184,15 +171,6 @@ fn intrinsic(gas_limit: u64) -> MegaTransactionOutcome { outcome } -/// The state gas of one fresh slot of `A`, at the price the engine runs. -fn one_slot() -> u64 { - let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); - let db = MemoryDatabase::default().account_code(A, code); - let outcome = execute(db, EvmTxRuntimeLimits::no_limits(), BELOW); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - outcome.gas.state -} - /// Runs a call from `CALLER` to `A` under `limits`. fn execute( db: MemoryDatabase, @@ -204,27 +182,48 @@ fn execute( .expect("the transaction is valid") } -/// Records the steps and the result of every frame it sees end, then rewrites that result into a -/// success with no output — a creation's too, which revives a creation that failed: a tool's -/// inspector the latch must see through. +/// 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 Rewriter { - /// The frame and opcode of the last step, and the slot it named when it was an `SSTORE`. - last: Option<(Address, u8, Option)>, - /// How many writes of [`MARKER`] ran. - marker_writes: usize, - /// The calls that ended, deepest first, with the result each had before the rewrite. +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 the rewrite. + /// The creations that ended, with the result each had before any rewrite. created: Vec<(InstructionResult, Bytes)>, } -impl Inspector, EthInterpreter> for Rewriter { +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.marker_writes += usize::from(slot == Some(MARKER)); - self.last = Some((interp.input.target_address, opcode, slot)); + self.steps.push((interp.input.target_address, opcode, slot)); } fn call_end( @@ -235,8 +234,10 @@ impl Inspector, EthInterpreter> for Rewriter { ) { let result = &mut outcome.result; self.ended.push((inputs.target_address, result.result, result.output.clone())); - result.result = InstructionResult::Stop; - result.output = Bytes::new(); + if self.rewrites { + result.result = InstructionResult::Stop; + result.output = Bytes::new(); + } } fn create_end( @@ -247,39 +248,59 @@ impl Inspector, EthInterpreter> for Rewriter { ) { let result = &mut outcome.result; self.created.push((result.result, result.output.clone())); - result.result = InstructionResult::Return; - result.output = Bytes::new(); + 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 a [`Rewriter`]. -fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { +/// 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 frames = crossing as u64 + 1; + let caught = crossing > 0; let intrinsic = intrinsic(gas_limit); - // The twin: the same frames, reverting where the stopped ones crossed or would resume. + // 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); - assert!( - matches!(&twin.result, ExecutionResult::Revert { output, .. } if output.is_empty()), - "{row}: the twin reverts: {:?}", - twin.result - ); + 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}"); - assert_eq!( - (twin.gas.state, twin.gas.history, twin.gas.reservoir_remaining), - (0, intrinsic.gas.history, intrinsic.gas.reservoir_remaining), - "{row}: a revert keeps nothing but the body", - ); // 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 * frames; + let before_crossing = twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT; - // The limit crossed, and the usage that crossed it: one more byte, record or unit of state gas - // 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, slot); + // 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 => { @@ -290,96 +311,129 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64, slot: u64) { 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(Rewriter::default()); - let rewritten = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); - let rewriter = evm.inspector(); + .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), ("rewritten", &rewritten)] { + for (column, outcome) in [("plain", &plain), ("recorded", &recorded)] { let cell = format!("{row}, {column}"); - // 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") + 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:?}"), } - 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" + ); } - assert_eq!(outcome.limit_exceeded, Some(stop), "{cell}"); - // The bill: intrinsic gas plus what ran, on the regular ledger alone. + // 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, 0, "{cell}: a 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.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, intrinsic.gas.reservoir_remaining, - "{cell}: the reservoir comes back, less the body it paid" + outcome.gas.reservoir_remaining, twin.gas.reservoir_remaining, + "{cell}: the reservoir comes back, less what was kept" ); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran, "{cell}: gas used"); + 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"); + } - // Nothing the stopped frames wrote or logged is kept; the body is all the transaction - // keeps. - assert!(outcome.result.logs().is_empty(), "{cell}: no log is kept"); + // 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] { - let kept = outcome - .state - .get(account) - .is_some_and(|account| account.storage.values().any(|slot| slot.is_changed())); - assert!(!kept, "{cell}: {account} kept a write"); + 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" + ); } - assert_eq!( - outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, - "{cell}: the body stays" - ); } - // No instruction ran after the crossing: the bill above has no marker's write in it, and under - // the inspector none ran at all. Every frame returned the stop, and the rewrites into successes - // did not reach a caller: the inspector changed nothing the transaction reports. - assert_eq!(rewritten.gas, plain.gas, "{row}"); - assert_eq!(rewriter.marker_writes, 0, "{row}: no frame ran on after the crossing"); - // A caller that resumed after a compute stop would fail its first charge on the withheld part - // and report the same stop on the same bill: only its step shows it ran. - assert_eq!( - rewriter.last.map(|(frame, ..)| frame), - Some(CHAIN[crossing]), - "{row}: the last step ran in the crossing frame" - ); - if limit != Limit::Compute { + // 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!( - rewriter.last, - Some((CHAIN[crossing], SSTORE, Some(CROSSING_SLOT))), - "{row}: the crossing write was the last step" + 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| (*frame, InstructionResult::Revert, stop.revert_data())) + .map(|frame| { + if *frame == CHAIN[crossing] { + (*frame, InstructionResult::Revert, stop.revert_data()) + } else { + (*frame, InstructionResult::Stop, Bytes::new()) + } + }) .collect(); - assert_eq!(rewriter.ended, ended, "{row}: every frame returned the stop, deepest first"); + assert_eq!( + recorder.ended, ended, + "{row}: the frame that crossed returned the stop, and every caller ended, deepest first" + ); } -/// Every transaction-level limit, crossed by the transaction's own frame and by a frame three calls -/// below it, stops the transaction the same way — below the execution cap and above it, with and -/// without an inspector that rewrites every frame result into a success. +/// 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_transaction_at_every_depth_and_tier() { - let slot = one_slot(); - for limit in Limit::ALL.into_iter().filter(|limit| limit.crossable()) { +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, slot); + assert_cell(limit, crossing, gas_limit); } } } } -/// Rewrites every frame result it sees end into `into`, and leaves its gas as it is. +/// Rewrites every call result it sees end into `into`, and leaves its gas as it is. struct Halter { into: InstructionResult, } @@ -395,22 +449,24 @@ impl Inspector, EthInterpreter> for Halter { } } -/// An inspector that rewrites every frame result into a halt cannot turn a stop into a halt either: -/// under the latch every result is the stop, whatever produced it, so the transaction reports the -/// stop and bills what ran, as it does without the inspector, rather than burning its gas. +/// 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_cannot_turn_a_stop_into_a_halt() { - let slot = one_slot(); +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.into_iter().filter(|limit| limit.crossable()) { + for limit in Limit::ALL { for crossing in [0, 3] { for gas_limit in TIERS { - let (configured, _) = limits_of(limit, crossing, slot); - let plain = execute(chain(limit, crossing, false), configured, gas_limit); + let (configured, _) = limits_of(limit, crossing); for into in halts { let case = format!("{limit:?} at depth {crossing}, gas limit {gas_limit}, {into:?}"); @@ -420,15 +476,14 @@ fn test_an_inspector_cannot_turn_a_stop_into_a_halt() { .with_inspector(Halter { into }); let halted = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); - assert!( - matches!(&halted.result, ExecutionResult::Revert { .. }), - "{case}: {:?}", - halted.result + 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" ); - assert_eq!(halted.result.output(), plain.result.output(), "{case}"); - assert_eq!(halted.limit_exceeded, plain.limit_exceeded, "{case}"); - assert_eq!(halted.gas, plain.gas, "{case}"); - assert_eq!(halted.usage, plain.usage, "{case}"); } } } @@ -437,7 +492,7 @@ fn test_an_inspector_cannot_turn_a_stop_into_a_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, slot: u64) -> (EvmTxRuntimeLimits, Option) { +fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { let frames = crossing as u64 + 1; match limit { Limit::DataSize => { @@ -445,13 +500,6 @@ fn limits_of(limit: Limit, crossing: usize, slot: u64) -> (EvmTxRuntimeLimits, O 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::KvUpdates => { - (EvmTxRuntimeLimits::default().with_tx_kv_update_limit(OWN_SLOTS), Some(OWN_SLOTS)) - } - Limit::StateGas => { - let value = (OWN_SLOTS + 1) * slot - 1; - (EvmTxRuntimeLimits::default().with_tx_state_gas_limit(value), Some(value)) - } Limit::Compute => (EvmTxRuntimeLimits::default(), None), } } @@ -510,8 +558,6 @@ fn creation_limits(creation: Creation, limit: Limit, gas_limit: u64) -> EvmTxRun if matches!(creation, Creation::NestedStart) { return match limit { Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), - Limit::KvUpdates => limits.with_tx_kv_update_limit(0), - Limit::StateGas => limits.with_tx_state_gas_limit(0), Limit::Compute => unreachable!("a start charges no compute past the cap"), }; } @@ -523,87 +569,73 @@ fn creation_limits(creation: Creation, limit: Limit, gas_limit: u64) -> EvmTxRun 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::KvUpdates => limits.with_tx_kv_update_limit(unlimited.usage.write_records - 1), - Limit::StateGas => limits.with_tx_state_gas_limit(unlimited.gas.state - 1), Limit::Compute => limits, } } -/// Under the latch a revived creation reports the stop, as a revived call does: an inspector that -/// rewrites a stopped creation into a success is not refused, because once the transaction is -/// stopped every frame's result is the stop, whatever produced it. 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 report the stop on the bill they have without the inspector, +/// 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. -/// -/// A nested creation's init code cannot be the first to cross the KV limit. A record is one unit, -/// so the record that crosses the transaction's limit comes when the creation already holds all -/// the transaction had left, and its budget — 98% of that, rounded down — is less unless nothing -/// was left, when the start's own records cross: the budget stops the creation alone first. #[test] -fn test_a_revived_creation_reports_the_stop() { +fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { let cases = [ (Creation::Transaction, Limit::ALL.as_slice()), - (Creation::Nested, [Limit::DataSize, Limit::StateGas, Limit::Compute].as_slice()), - (Creation::NestedStart, [Limit::DataSize, Limit::KvUpdates, Limit::StateGas].as_slice()), + (Creation::Nested, Limit::ALL.as_slice()), + (Creation::NestedStart, [Limit::DataSize].as_slice()), ]; for (creation, limits) in cases { - for &limit in limits.iter().filter(|limit| limit.crossable()) { + 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 plain = MegaEvm::new(context(db.clone()).with_tx_runtime_limits(configured)) - .execute_transaction(tx.clone()) - .expect("the transaction is valid"); - let stop = plain.limit_exceeded.expect("the transaction is stopped"); - assert!( - matches!( - stop, - LimitCheck::ExceedsLimit { kind, frame_local: false, .. } - if kind == limit.kind() - ), - "{case}: {stop:?}" - ); - assert!( - matches!(&plain.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{case}: {:?}", - plain.result - ); + 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(Rewriter::default()); + .with_inspector(FrameRecorder::rewriting()); let revived = evm.execute_transaction(tx).expect("the revival is not refused"); - assert_eq!(revived.result, plain.result, "{case}: the stop"); - assert_eq!(revived.limit_exceeded, plain.limit_exceeded, "{case}"); - assert_eq!(revived.gas, plain.gas, "{case}: the plain run's bill"); - assert_eq!(revived.usage, plain.usage, "{case}"); let rewriter = evm.inspector(); assert_eq!( rewriter.created, - [(InstructionResult::Revert, stop.revert_data())], + [(InstructionResult::Revert, stop)], "{case}: the creation ended with the stop before its revival" ); - let ended = match creation { - Creation::Transaction => vec![], - Creation::Nested | Creation::NestedStart => { - vec![(A, InstructionResult::Revert, stop.revert_data())] - } + 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_eq!(rewriter.ended, ended, "{case}: its creator returned the stop"); + 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"); } } } } -/* ---------- a detained callee does not burn its callers' gas ---------- */ +/* ---------- the frame the last step ran in ---------- */ /// Records the frame the last step ran in. -/// -/// After a compute stop the transaction's compute sits at the limit, so a caller that resumed -/// would fail its first charge on the withheld part and be stopped the same way, on the same bill: -/// the frame of the last step is what tells it ran. #[derive(Default)] struct LastStep(Option
); @@ -626,79 +658,6 @@ fn run_recording_steps( (outcome, evm.inspector().0) } -/// A callee at `depth` that reads the block's timestamp and then computes past the cap, below -/// callers that forward it all their gas and would write [`MARKER`] once it returned. -fn detained_callee_at(depth: usize) -> MemoryDatabase { - let callee = work(log(BytecodeBuilder::default()).append_many([TIMESTAMP, POP]), ROUNDS); - let callee = callee.sstore(MARKER, U256::from(1)).stop().build(); - (0..depth) - .fold(MemoryDatabase::default(), |db, caller| { - let code = call_all(BytecodeBuilder::default(), CHAIN[caller + 1]).append(POP); - db.account_code(CHAIN[caller], code.sstore(MARKER, U256::from(1)).stop().build()) - }) - .account_code(CHAIN[depth], callee) -} - -/// A callee that reads the block's timestamp and then computes past the cap does not make its -/// callers burn their gas: the stop bills the transaction its intrinsic gas plus its compute up to -/// the charge that crosses the limit the read set — its compute at the read plus the cap — and -/// nothing of what the callers held, whatever the gas limit, one call down or three, below the -/// execution cap and above it. No caller resumes: the callee runs the last step. -#[test] -fn test_a_callee_that_reads_the_timestamp_does_not_make_its_callers_burn_their_gas() { - for depth in [1, 3] { - let bills: Vec<_> = [BELOW, ABOVE, 1_000_000_000] - .into_iter() - .map(|gas_limit| { - let case = format!("depth {depth}, gas limit {gas_limit}"); - let intrinsic = intrinsic(gas_limit); - let tx = || call(CALLER, A, U256::ZERO, gas_limit); - let mut evm = MegaEvm::new(context(detained_callee_at(depth))); - let outcome = evm.execute_transaction(tx()).unwrap(); - let limit = evm.ctx().detention().compute_limit().expect("the read set a limit"); - let (recorded, last) = run_recording_steps( - detained_callee_at(depth), - EvmTxRuntimeLimits::default(), - tx(), - ); - assert_eq!(last, Some(CHAIN[depth]), "{case}: the last step ran in the callee"); - assert_eq!( - (&recorded.result, recorded.gas), - (&outcome.result, outcome.gas), - "{case}: the recorder changes nothing" - ); - // The read's `POP`, then the callee's work. - let used = limit - Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used, - frame_local: false, - }; - assert!( - matches!(&outcome.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{case}: {:?}", - outcome.result - ); - assert_eq!(outcome.limit_exceeded, Some(stop), "{case}"); - // The read came after the callers' calls and the callee's log: its compute then is - // theirs alone, a sliver of the cap. - assert!(limit - CAP < 50_000, "{case}: compute at the read {}", limit - CAP); - assert_eq!(outcome.gas.regular, intrinsic.gas.regular + used, "{case}"); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + used, "{case}"); - assert_eq!( - outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, - "{case}: the reservoir comes back" - ); - assert!(outcome.result.logs().is_empty(), "{case}"); - (outcome.gas.gas_used, outcome.gas.regular, outcome.gas.state, outcome.gas.history) - }) - .collect(); - assert!(bills.windows(2).all(|pair| pair[0] == pair[1]), "depth {depth}: {bills:?}"); - } -} - /* ---------- frame budgets ---------- */ /// The slot a frame stores its call's status in. @@ -777,60 +736,43 @@ fn slot_of(outcome: &MegaTransactionOutcome, account: Address, slot: U256) -> U2 .map_or(U256::ZERO, |slot| slot.present_value()) } -/// A frame three calls below the transaction's own that crosses its budget — in data size or in -/// write records — reverts alone with `MegaLimitExceeded(kind, budget)`, where the budget is what -/// the shares left it. Its caller resumes and reads the stop, every frame above runs on, nothing is -/// latched and the transaction succeeds, below and above the execution cap. +/// 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 data_budget = share(share(share(ROOM - LOG_BASE_SIZE) - LOG_BASE_SIZE) - LOG_BASE_SIZE); - const RECORDS: u64 = 100; - let record_budget = share(share(share(RECORDS))); - let rows = [ - ( - LimitKind::DataSize, - EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + ROOM), - data_budget, - // D's log and its writes cross its budget long before the transaction's limit. - writer(data_budget / WRITE_RECORD_SIZE + 1), - ), - ( - LimitKind::KVUpdate, - EvmTxRuntimeLimits::default().with_tx_kv_update_limit(RECORDS), - record_budget, - writer(record_budget + 1), - ), - ]; - for (kind, limits, budget, d) in rows { - for gas_limit in TIERS { - let case = format!("{kind:?}, 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 latches nothing"); - - // 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"); + 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"); } } @@ -838,10 +780,7 @@ fn test_a_frame_budget_crossed_three_calls_down_reverts_that_frame_alone() { /// 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) - .with_tx_kv_update_limit(1_000) - .with_tx_state_gas_limit(TX_GAS_LIMIT_CAP) + 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 @@ -967,13 +906,24 @@ fn test_the_transactions_own_frame_that_halts_burns_its_regular_gas() { // 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 a thousand fresh slots, so the -/// writes spend nothing but compute from the frame's regular gas. -const ROOMY: u64 = 1_000_000_000; +/// 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..=1,000`: 22,100,000 of compute, past the cap. -fn thousand_writes(code: BytecodeBuilder) -> BytecodeBuilder { - (1..=1_000_u64).fold(code, |code, slot| code.sstore(U256::from(slot), U256::from(slot))) +/// 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 @@ -996,23 +946,23 @@ fn with_oracle_read(db: MemoryDatabase) -> MemoryDatabase { ) } -/// Runs `db`'s `A` under `limits` with [`ROOMY`] gas and asserts the detention stop: 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. The frame `crossing` crossed it, and ran the last step: no -/// caller resumed. Returns the limit and what the transaction read. +/// 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, - crossing: Address, left: u64, ) -> (u64, mega_evm::VolatileDataAccess) { - let intrinsic = intrinsic(ROOMY); + let intrinsic = intrinsic(roomy()); let (recorded, last) = - run_recording_steps(db.clone(), limits, call(CALLER, A, U256::ZERO, ROOMY)); - assert_eq!(last, Some(crossing), "the last step ran in the crossing frame"); + 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(); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, roomy())).unwrap(); assert_eq!( (&recorded.result, recorded.gas), (&outcome.result, outcome.gas), @@ -1037,74 +987,78 @@ fn assert_detention_stop( (limit, detention.accessed()) } -/// The writes after a read: the read's `POP`, then the thousand fresh slots, of which the reservoir -/// pays the state and history gas. +/// 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(1_000) + Charges::default().then(&[2]).fresh_writes(slots_past_the_cap()) } -/// After the Oracle's read: its `POP`, its caller's, then the thousand fresh slots. +/// 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(1_000) + Charges::default().then(&[2, 2]).fresh_writes(slots_past_the_cap()) } -/// A frame that reads the block's timestamp and then writes a thousand fresh slots stops at the +/// 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 never runs on, and a caller whose child did its -/// work after the read. +/// 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 = thousand_writes(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); + 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(), A, left); + 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 a thousand fresh slots stops the -/// transaction: its caller's code after the call never runs. +/// 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 = thousand_writes(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); + 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 (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), B, left); + 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 a -/// thousand fresh slots stops at the limit its read set: the child's work counts towards it. +/// 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, thousand_writes(parent).stop().build()) + .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, 2_600, 3, 3, 3, 2, 2]) - .fresh_writes(1_000) + .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(), A, left); + 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 a thousand fresh slots: the transaction stops +/// 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 = thousand_writes(call_oracle(BytecodeBuilder::default(), None)); + 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(), A, left); + 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); } @@ -1112,25 +1066,38 @@ fn test_an_oracle_read_holds_the_transaction_to_its_cap() { /// 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 = thousand_writes(call_oracle(BytecodeBuilder::default(), Some(0xffff))); + 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(), A, left); + assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); } -/// A contract that calls one that reads the Oracle's storage and then writes a thousand fresh -/// slots: the stop reaches the outer contract, whose reads after the call never run. +/// 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 = thousand_writes(call_oracle(BytecodeBuilder::default(), None)); + 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(), B, left); + assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), left); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1141,10 +1108,10 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { 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, thousand_writes(code).stop().build()); + 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, A, left); + 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, @@ -1159,7 +1126,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(), A, left); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); assert!(limit - CAP < 1_000, "{}", limit - CAP); } @@ -1230,33 +1197,26 @@ fn test_detained_gas_is_restored() { ); } -/// A body over the transaction's data-size limit stops the transaction before its first frame: a -/// revert carrying the stop, not a halt, billed the intrinsic gas alone. -#[test] -fn test_data_limit_just_exceed() { - let limit = TX_BODY_SIZE - 1; - let db = || MemoryDatabase::default().account_code(A, writer(1)); - let outcome = - execute(db(), EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit), BELOW); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: TX_BODY_SIZE, - frame_local: false, - }; - assert!( - matches!(&outcome.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{:?}", - outcome.result - ); - assert_eq!(outcome.limit_exceeded, Some(stop)); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); - assert_eq!(outcome.gas.gas_used, intrinsic(BELOW).gas.gas_used, "nothing ran"); -} - -/// A library's write, one call down, crosses a limit one byte above the body: the stop is a -/// revert, and the transaction is billed what ran. +/// 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; @@ -1265,24 +1225,14 @@ fn test_data_limit_exceed_in_nested_call() { .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); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: TX_BODY_SIZE + WRITE_RECORD_SIZE, - frame_local: false, - }; - assert!( - matches!(&outcome.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{:?}", - outcome.result - ); - assert_eq!(outcome.limit_exceeded, Some(stop)); - assert!( - outcome.gas.gas_used < 200_000 + body_history(0), - "the stop burns nothing: {}", - outcome.gas.gas_used - ); + 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 @@ -1317,105 +1267,49 @@ fn test_state_revert_when_exceeding_limit() { assert_eq!(outcome.state[&CALLER].info.balance, U256::from(10_000), "the value did not move"); } -/// Data size is held before write records: a body that crosses the data-size limit is its stop -/// whatever the KV limit, and so is a write that crosses both. -#[test] -fn test_check_limit_priority_data_size_before_kv_update() { - let db = || MemoryDatabase::default().account_code(A, writer(1)); - let both = |data_size: u64| { - EvmTxRuntimeLimits::default().with_tx_data_size_limit(data_size).with_tx_kv_update_limit(0) - }; - for (data_size, used) in [ - (1, TX_BODY_SIZE), - (TX_BODY_SIZE + LOG_BASE_SIZE, TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE), - ] { - let outcome = execute(db(), both(data_size), BELOW); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: data_size, - used, - frame_local: false, - }), - "data size {data_size}" - ); - } -} - /// A transaction detained from its start — its sender is the block's beneficiary — whose body -/// crosses the data-size limit is the data-size stop, billed its intrinsic gas: detention adds -/// nothing to what it pays, which is what the same transaction pays within the limits. +/// 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| { - let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)); - let outcome = evm.execute_transaction(call(BENEFICIARY, A, U256::ZERO, ROOMY)).unwrap(); - (outcome, evm.ctx().detention().compute_limit()) + let run = |limits, sender| { + MegaEvm::new(context(db()).with_tx_runtime_limits(limits)).execute_transaction(call( + sender, + A, + U256::ZERO, + roomy(), + )) }; - let (within_limits, detained) = run(EvmTxRuntimeLimits::default()); - assert_eq!(detained, Some(CAP), "the beneficiary's transaction is detained from its start"); + 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 (stopped, detained) = run(EvmTxRuntimeLimits::default().with_tx_data_size_limit(100)); - assert_eq!(detained, Some(CAP), "the stopped one too"); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: TX_BODY_SIZE, - frame_local: false, - }; - assert!( - matches!(&stopped.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{:?}", - stopped.result - ); - assert_eq!(stopped.limit_exceeded, Some(stop)); - assert_eq!(stopped.gas, within_limits.gas, "the intrinsic gas alone, the reservoir back"); -} -/// The transaction's own frame crossing its frame budget — a frame cap of a hundred records' bytes, -/// crossed by the 101st write — reverts it alone: a revert, not a halt, and no latch. The body is -/// all the transaction keeps. -#[test] -fn test_data_size_top_level_exceed_is_frame_local_revert() { - let cap = 100 * WRITE_RECORD_SIZE; - let code = (1..=101_u64).fold(BytecodeBuilder::default(), |code, slot| { - code.sstore(U256::from(slot), U256::from(1)) - }); - let db = MemoryDatabase::default().account_code(A, code.stop().build()); - let outcome = execute(db, EvmTxRuntimeLimits::default().with_frame_data_size_limit(cap), BELOW); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: cap, - used: 0, - frame_local: true, - }; - assert!( - matches!(&outcome.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "{:?}", - outcome.result - ); - assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + 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 its own frame budget stopped, 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 its own budget, -/// and the transaction is the one no inspector runs: the rewrite changed only the flag `A` drops. +/// 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. /// -/// `A` has a frame cap of 1,000 bytes and gives `B` 98% of it. `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 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_its_budget_hands_its_caller_nothing() { - const FRAME_CAP: u64 = 1_000; +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 > FRAME_CAP, "the log would cross A's budget too") }; - let share = FRAME_CAP * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + 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)) @@ -1424,37 +1318,48 @@ fn test_a_call_revived_past_its_budget_hands_its_caller_nothing() { 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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(FRAME_CAP); - let plain = execute(db.clone(), limits, BELOW); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .with_inspector(Rewriter::default()); - let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW)).unwrap(); - let rewriter = evm.inspector(); - - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: share, - used: 0, - frame_local: true, + 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}"); } - .revert_data(); - assert_eq!( - rewriter.ended, - vec![(B, InstructionResult::Revert, stop), (A, InstructionResult::Stop, Bytes::new())], - "B crossed its budget; A did not" - ); - assert_eq!(rewriter.marker_writes, 1, "A ran on after its call returned"); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.limit_exceeded, None, "a frame budget latches nothing"); - assert_eq!( - outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, - "the body and A's marker: none of B's log" - ); - assert!(outcome.result.logs().is_empty(), "B's log was reverted with B"); - assert!(plain.result.is_success(), "{:?}", plain.result); - assert_eq!((&outcome.result, &outcome.state), (&plain.result, &plain.state)); - assert_eq!((outcome.gas, outcome.usage), (plain.gas, plain.usage)); } /* ---------- a frame three calls down, answered without running ---------- */ @@ -1462,8 +1367,7 @@ fn test_a_call_revived_past_its_budget_hands_its_caller_nothing() { /// 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 transaction-level -/// limit. +/// 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 @@ -1473,9 +1377,6 @@ enum Answered { /// `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`], which revm answers without running: the account it adds - /// crosses the state-gas limit. - NewAccount, /// `C` sends a wei to [`EMPTY`], whose start's records and transfer log cross the data-size /// limit, before revm builds the frame. StartRecords, @@ -1487,23 +1388,16 @@ impl Answered { match self { Self::PastTheAllowance => D, Self::Precompile => PRICED, - Self::NewAccount | Self::StartRecords => EMPTY, + Self::StartRecords => EMPTY, } } } -/// The chain `A` → `B` → `C` → the answered frame, stopped or its twin. `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 the stopped transaction's frames -/// drop the status and stop, and the twin's revert. -fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { - let end = |code: BytecodeBuilder| { - if twin { - revert(code).build() - } else { - code.append(POP).stop().build() - } - }; +/// 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() @@ -1513,7 +1407,7 @@ fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { .append_many([PUSH0, PUSH0]) .push_address(PRICED) .append_many([GAS, CALL]), - Answered::NewAccount | Answered::StartRecords => BytecodeBuilder::default() + Answered::StartRecords => BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) .push_number(1_u8) .push_address(EMPTY) @@ -1532,7 +1426,7 @@ fn answered_chain(answered: Answered, twin: bool) -> MemoryDatabase { /// `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 + 2_600; + 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, @@ -1540,11 +1434,9 @@ fn to_the_answer(answered: Answered) -> u64 { 2 + 2 * call_all + c } -/// The limits `answered`'s chain crosses its limit under, and the stop it reports. 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. The -/// state-gas limit is one gas short of the schedule's new account, which the test database prices -/// at the minimum bucket. +/// 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 }; @@ -1553,13 +1445,6 @@ fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { EvmTxRuntimeLimits::default(), stop(LimitKind::ComputeGas, 2 + CAP, 2 + to_the_answer(answered)), ), - Answered::NewAccount => { - let account = satin_gas_params().get(GasId::new_account_state_gas()); - ( - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(account - 1), - stop(LimitKind::StateGrowth, account - 1, account), - ) - } 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; @@ -1573,7 +1458,7 @@ fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { /// 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 [`Rewriter`] does. +/// rewrites that result into a success, as [`FrameRecorder`] does. struct AnswersD { rewrite: bool, ended: Vec<(Address, InstructionResult, Bytes)>, @@ -1626,7 +1511,7 @@ fn run_answered( rewrite: bool, ) -> AnsweredRun { let runs = Runs::default(); - let evm = MegaEvm::new(context(answered_chain(answered, false)).with_tx_runtime_limits(limits)) + 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 { @@ -1634,7 +1519,7 @@ fn run_answered( 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(Rewriter::default()); + 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 { @@ -1648,27 +1533,26 @@ fn run_answered( /// One answered cell, both columns: `answered`'s chain at `gas_limit`, without the rewrite and /// with it. /// -/// A compute stop bills its compute up to the answer past the intrinsic gas. Any other stop bills -/// what ran, read off the twin: the same frames without limits, each reverting once its call -/// returned, which bills what the stopped frames ran plus the two pushes of each revert. The twin -/// runs on the same engine, so that 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. +/// 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 + used + 3 * 2 } else { - let twin = - execute(answered_chain(answered, true), EvmTxRuntimeLimits::no_limits(), gas_limit); - assert!( - matches!(&twin.result, ExecutionResult::Revert { output, .. } if output.is_empty()), - "{row}: the twin reverts: {:?}", - twin.result - ); - twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT * 3 + 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); @@ -1676,15 +1560,10 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { for (column, run) in [("not rewritten", &plain), ("rewritten", &rewritten)] { let cell = format!("{row}, {column}"); let outcome = &run.outcome; - 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!(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}: a stop keeps no state gas"); + 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!( @@ -1698,10 +1577,7 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, "{cell}: the body stays" ); - assert!( - outcome.state.get(&EMPTY).is_none_or(|account| account.info.balance.is_zero()), - "{cell}: no value moved" - ); + 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"); @@ -1709,39 +1585,39 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { } assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); - let ended: Vec<_> = [answered.target(), C, B, A] - .into_iter() - .map(|frame| (frame, InstructionResult::Revert, stop.revert_data())) - .collect(); + 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, then every caller, ended stopped" + "{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, then every caller, ended stopped" + "{row}, not rewritten: the answered frame ended stopped, then every caller ended" ); } } -/// A frame three calls down that is answered without running, and whose answer crosses a limit, -/// stops the transaction as a frame that ran there does: an answer past what the compute limit -/// leaves the frame, a precompile run on that allowance and priced past it, and a value call to -/// an empty account whose new account crosses the state-gas limit. Below the execution cap and +/// 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, every caller returns it without running on, and the transaction settles -/// like any stop: it bills what ran, keeps the body's history and nothing else, and gets its -/// reservoir back. +/// 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_stops_the_transaction_at_either_tier() { - for answered in [Answered::PastTheAllowance, Answered::Precompile, Answered::NewAccount] { - // A new account that adds no state gas, where a state byte is free, crosses no state-gas - // limit. - if answered == Answered::NewAccount && state_is_free() { - continue; - } +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); } @@ -1749,9 +1625,9 @@ fn test_an_answer_three_calls_down_stops_the_transaction_at_either_tier() { } /// 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. The -/// transaction settles like any stop, below the execution cap and above it, with and without the -/// rewriting inspector. +/// 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 { diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 3d96b8798..0629017e7 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -24,16 +24,21 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, storage_call_stipend, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{is_transfer_log, transfer_log, BytecodeBuilder, MemoryDatabase}, + 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, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, POP, - PUSH0, PUSH1, STATICCALL, STOP, + ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, + POP, PUSH0, PUSH1, PUSH2, SSTORE, STATICCALL, STOP, SUB, SWAP1, }; -use crate::common::{call, context, runs_at_measurement_prices}; +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"); @@ -93,10 +98,6 @@ fn events(outcome: &MegaTransactionOutcome) -> Vec<&alloy_primitives::Log> { outcome.result.logs().iter().filter(|log| !is_transfer_log(log)).collect() } -fn run(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { - MegaEvm::new(context(db)).execute_transaction(tx).expect("the transaction is valid") -} - fn run_limited( db: MemoryDatabase, limits: EvmTxRuntimeLimits, @@ -132,7 +133,7 @@ fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { } let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); let receiver = event().append(STOP).build(); - let outcome = run(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -158,44 +159,214 @@ fn test_the_allowance_buys_one_event_and_no_more() { // 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 = run(db(sender, two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); } -/// The allowance pays for history and nothing else: a hook that computes rather than logs runs -/// out of gas at the same 2,300, because no part of the allowance is reachable as gas. +/// 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; } - // `JUMPDEST; PUSH0; JUMP`: burns whatever gas it is given. - let burner = Bytes::from_static(&[0x5b, 0x5f, 0x56]); - let sender = - call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append_many([PUSH0, PUSH0]).append(STOP).build(); - let outcome = run(db(sender, burner), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + assert_eq!((allowance(), record_history()), (14_080, 3_520), "160 and 40 bytes at 88 gas"); +} - assert!(outcome.result.is_success(), "the caller survives"); - assert_eq!(outcome.gas.history, body(), "the hook kept nothing"); +/// 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 either: a hook that writes a slot has only the 2,300 -/// gas for it, which the slot's own price is far above. +/// 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; } - let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let writer = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let outcome = run(db(sender, writer), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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; - assert!(outcome.result.is_success(), "the caller survives"); - assert_eq!(outcome.usage.write_records, 0, "the hook kept no write"); - assert_eq!(outcome.gas.history, body()); + 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 ---------- */ @@ -210,7 +381,7 @@ fn test_a_top_level_transfer_gets_no_allowance() { 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 = run(db(Bytes::new(), receiver), tx); + let outcome = execute(db(Bytes::new(), receiver), tx); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( @@ -232,8 +403,8 @@ fn test_a_call_without_value_gets_no_allowance() { 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 = run(db(without, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - let granted = run(db(with_value, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -255,7 +426,7 @@ fn test_callcode_is_granted_one_and_delegatecall_is_not() { 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(); - run(db(sender, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) + execute(db(sender, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) }; let call_code = at(CALLCODE, 1); @@ -315,12 +486,12 @@ fn test_an_intercepted_call_neither_takes_nor_adds_an_allowance() { .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) }; - let one = run(with_controls(one_event), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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 = run(with_controls(two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); } @@ -396,9 +567,12 @@ fn test_an_unspent_allowance_does_not_return_to_the_caller() { return; } let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let silent = run(db(sender.clone(), Bytes::new()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - let logging = - run(db(sender, event().append(STOP).build()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -432,7 +606,7 @@ fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { 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 = run(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -501,7 +675,7 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { .account_balance(CALLER, U256::from(10u64.pow(18))) .account_balance(SENDER, U256::from(10u64.pow(9))) .account_code(SENDER, self_calling_loop()); - let outcome = run(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -563,7 +737,7 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { ); assert!(spent.result.is_success(), "the caller resumes past a frame budget"); - assert_eq!(spent.limit_exceeded, None, "a frame budget latches nothing"); + 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 @@ -586,9 +760,11 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { 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 = - run(db(sender.clone(), drained_then_reverts), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - let quiet = run(db(sender, reverts), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); @@ -611,8 +787,10 @@ fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { return; } let sender = call_with(CALL, RECEIVER, 1, 0).append(STOP).build(); - let outcome = - run(db(sender, event().append(STOP).build()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + 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"); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 69eb97f23..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, history, runs_at_measurement_prices, slot_state_gas}; +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,14 +82,13 @@ 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 @@ -144,13 +147,19 @@ 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 above - // the body. +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(), @@ -158,120 +167,52 @@ fn test_cap_crossed_at_depth_three_stops_the_transaction() { 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: mega_evm::TX_BODY_SIZE + 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, mega_evm::TX_BODY_SIZE + 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() - }; - // 100 leaves D's second record (80 bytes) inside both the transaction limit and D's own - // budget, and D's third (120) over the transaction limit. The frame budget is over too; the - // transaction limit is checked first, so the stop is the latch and the code after the call - // does not run. A limit of 80 would revert D on its own budget instead, and the callers - // would resume. - 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(100))); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 100); - 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(100))); - let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&light_result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 100); - 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)); + 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() }; @@ -293,7 +234,7 @@ fn test_stop_refills_the_reservoir_at_any_gas_limit() { fn test_true_out_of_gas_still_halts_and_burns() { let db = MemoryDatabase::default().account_code(A, writer()); let gas_limit = 21_000 + body_history() + 5_000; - let (result, latched) = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); + let result = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); assert!( matches!( result.result, @@ -306,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) @@ -322,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) @@ -350,7 +303,7 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { "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(), @@ -367,9 +320,9 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { } /// 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) @@ -391,7 +344,7 @@ 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)); // B's budget is 98% of the 100 bytes A was capped at, and B had used none of A's own. @@ -399,36 +352,41 @@ fn test_frame_budget_reverts_the_frame_without_a_latch() { 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); @@ -463,22 +421,24 @@ 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, mega_evm::TX_BODY_SIZE + 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 init_code = writer(); let tx = crate::common::create(CALLER, init_code.clone(), 1_000_000_000); - let (result, _) = run(MemoryDatabase::default(), cap(39), tx); + 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), @@ -491,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)); + 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, @@ -510,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 { @@ -530,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( @@ -609,19 +556,3 @@ fn test_outcome_reports_history_gas() { assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); assert_eq!(stopped.gas.history, body_history()); } - -/// 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, mega_evm::TX_BODY_SIZE + 180); - assert!(outcome.limit_exceeded.is_some()); - assert_eq!( - outcome.usage, - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, - "every lane failed; the body stays" - ); - 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 index 7554e1c86..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, LimitUsage, MegaEvm, + EvmTxRuntimeLimits, LimitUsage, MegaEvm, }; use revm::{ context::{result::ExecutionResult, ContextTr, JournalTr}, @@ -218,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)) diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index e981e2a5a..5a077f0a1 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -356,9 +356,6 @@ fn test_a_system_call_with_a_reservoir_stays_exempt() { EvmTxRuntimeLimits::no_limits() .with_tx_data_size_limit(0) .with_frame_data_size_limit(0) - .with_tx_kv_update_limit(0) - .with_frame_kv_update_limit(0) - .with_tx_state_gas_limit(0) .with_block_env_access_compute_gas_limit(0), ); diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index f640c9054..fd026b07a 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -14,9 +14,9 @@ //! 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 stops the transaction; 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. +//! 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 @@ -24,23 +24,24 @@ //! counted, and revm refuses it after the count. use alloy_op_evm::OpTx; -use alloy_primitives::{address, keccak256, Address, Bytes, TxKind, B256, U256}; +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, + 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, - FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + MegaEvm, MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, TRANSFER_LOG_SIZE, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, DELEGATECALL, GAS, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP, + ADDRESS, CALL, CALLDATASIZE, DELEGATECALL, GAS, JUMPDEST, JUMPI, LOG1, POP, PUSH0, PUSH1, + REVERT, SELFDESTRUCT, STOP, }, context::{ result::{ExecutionResult, Output}, @@ -50,7 +51,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{account_state_gas, context}; +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 @@ -169,6 +170,23 @@ impl Site { } } + /// 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 { @@ -259,12 +277,6 @@ impl Site { } } -/// 98% of `remaining`, the share a child frame is given. -fn share(remaining: u64) -> u64 { - (u128::from(remaining) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / - u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 -} - /// 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 { @@ -279,16 +291,6 @@ fn cap_for(depth: u32, bytes: u64) -> u64 { cap } -fn execute( - db: MemoryDatabase, - tx: MegaTransaction, - limits: EvmTxRuntimeLimits, -) -> MegaTransactionOutcome { - MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(tx) - .expect("the transaction is valid") -} - /// 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 { @@ -329,6 +331,47 @@ fn assert_reservoir_paid(case: &str, gas_limit: u64, outcome: &MegaTransactionOu ); } +/// 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( @@ -364,23 +407,9 @@ fn test_each_site_counts_its_transfer_log() { 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(db, tx, EvmTxRuntimeLimits::no_limits()); - - assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - assert_eq!( - transfer_logs(&outcome), - [transfer_log(site.sender(), site.recipient(), U256::from(VALUE))], - "{case}: the receipt's transfer log", - ); - assert_eq!(balance(&outcome, site.recipient()), U256::from(VALUE), "{case}"); - assert_eq!( - outcome.usage, - LimitUsage { data_size: body + site.bytes(), write_records: site.records() }, - "{case}: the body, the records and one transfer log", - ); - let history_bytes = body + site.records() * WRITE_RECORD_SIZE; - assert_eq!(outcome.gas.history_bytes, history_bytes, "{case}: no history bytes"); - assert_eq!(outcome.gas.history, history_gas(history_bytes).unwrap(), "{case}"); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + + assert_completed(&case, site, Variant::Plain, &outcome, body); assert_reservoir_paid(&case, gas_limit, &outcome); } } @@ -388,8 +417,9 @@ 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 nothing is latched. The transaction's own -/// frame has no caller, so its stop reverts the transaction, still without a latch. +/// 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. @@ -404,15 +434,24 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { 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(db, tx, limits), body) + (execute_under(db, tx, limits), body) }; - let (fits, _) = run(cap); - assert!(fits.result.is_success(), "{case}: at the budget: {:?}", fits.result); - assert_eq!(fits.limit_exceeded, None, "{case}"); + 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); - assert_eq!(over.limit_exceeded, None, "{case}: a frame budget latches nothing"); + 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, @@ -443,11 +482,13 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { } } -/// The transaction's limit one byte short of the move stops the transaction there: it latches, the -/// stop names the data size and the limit, the whole transaction reverts, and the move's bytes are -/// reported in the figure that crossed. A `LOG3` of one word where the transfer log is, after the -/// same bytes of records, crosses the same way. At the transaction's own frame, whose budget is -/// the limit, a limit of exactly the bytes holds. +/// 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 { @@ -459,38 +500,49 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_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(db, tx, limits), body, 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, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: body + site.bytes(), - frame_local: false, - }), - "{case}: the transaction is stopped at the move", + outcome.limit_exceeded, own_frames, + "{case}: the outcome names the transaction's own frame's stop alone", ); - assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{case}"); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; assert_eq!( - outcome.result.output(), - Some(&Bytes::from(stop.abi_encode())), - "{case}: the stop is what the transaction reports", + outcome.result.is_success(), + site.depth() > 0, + "{case}: the caller resumes: {:?}", + outcome.result ); - assert!(outcome.result.logs().is_empty(), "{case}: every log went"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); - if variant == Variant::Plain { - let to = site.recipient(); - assert_eq!(balance(&outcome, to), U256::ZERO, "{case}: no value moved"); + 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, _, _) = run(0); - assert!(fits.result.is_success(), "{case}: at the limit: {:?}", fits.result); + let (fits, body, _) = run(0); + assert_completed(&format!("{case}: at the limit"), site, variant, &fits, body); + assert_reservoir_paid(&case, gas_limit, &fits); } } } @@ -507,7 +559,7 @@ fn test_a_failure_takes_each_sites_transfer_log_back() { 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(db, tx, EvmTxRuntimeLimits::no_limits()); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); assert_eq!(outcome.limit_exceeded, None, "{case}"); assert!(!outcome.result.is_halt(), "{case}: {:?}", outcome.result); @@ -527,7 +579,7 @@ fn test_a_failure_takes_each_sites_transfer_log_back() { /// `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 the caller cannot fund, or a system contract refuses, moves nothing at all. +/// 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); @@ -560,9 +612,25 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { })) }; let actor = BytecodeBuilder::default; - let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize); 8] = [ + // `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), - ("a CALL to itself", db(actor().call(ACTOR, 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), ( @@ -573,18 +641,11 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { 1, ), ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0), - ( - "a value CALL the caller cannot fund", - db(actor().call(RECEIVER, U256::from(100 * VALUE))), - call(ACTOR, 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(db, tx, EvmTxRuntimeLimits::no_limits()); + 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"); @@ -597,7 +658,7 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { "{name}", ); } - let burned = execute( + let burned = execute_under( db(actor().create(value, &burner)), call(ACTOR, 0), EvmTxRuntimeLimits::no_limits(), @@ -605,7 +666,7 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { 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(db(actor()), call(DESTRUCTOR, 0), EvmTxRuntimeLimits::no_limits()); + let older = execute_under(db(actor()), call(DESTRUCTOR, 0), EvmTxRuntimeLimits::no_limits()); assert_eq!(balance(&older, DESTRUCTOR), value, "an older account keeps its balance"); } @@ -651,32 +712,30 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { let frame_budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap_for(1, bytes - 1)); - let free = execute(db(VALUE - 1, &actor), tx.clone(), EvmTxRuntimeLimits::no_limits()); + 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(db(VALUE - 1, &actor), tx.clone(), limits); + 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(db(VALUE, &actor), tx.clone(), tx_limit); + 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.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: body + bytes - 1, - used: body + bytes, - frame_local: false, - }), - "{name}: funded to the last wei, the move is counted", + stopped.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{name}: funded to the last wei, the move is counted, and stopped at the limit", ); - let stopped = execute(db(VALUE, &actor), tx.clone(), frame_budget); + 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(), @@ -721,10 +780,22 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { 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(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + let refused = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); assert!(refused.result.is_success(), "{:?}", refused.result); - let funded = execute(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + 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 @@ -780,7 +851,7 @@ fn test_a_start_answered_before_its_init_leaves_no_refusal_for_the_next() { let limits = EvmTxRuntimeLimits::no_limits() .with_frame_data_size_limit(cap_for(1, 2 * WRITE_RECORD_SIZE - 1)); - let answer = execute( + let answer = execute_under( db(answered_call(BytecodeBuilder::default()).append(POP).return_returndata()), tx.clone(), limits, @@ -799,13 +870,13 @@ fn test_a_start_answered_before_its_init_leaves_no_refusal_for_the_next() { ), ]; for (name, actor) in cases { - let outcome = execute(db(actor), tx.clone(), limits); + 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 latches nothing"); + 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}"); } } @@ -834,7 +905,7 @@ fn test_an_answer_a_transaction_leaves_is_not_taken_by_the_next() { let user_deposit = || deposit(TxKind::Call(RECEIVER), 1_000, 400); let body = transaction_body_bytes(&user_deposit()); - let alone = execute(db.clone(), user_deposit(), EvmTxRuntimeLimits::no_limits()); + 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); @@ -910,14 +981,16 @@ fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { /// 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 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) - .stop() + .return_returndata() .build(); let db = || { MemoryDatabase::default() @@ -934,8 +1007,9 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() })); let body = transaction_body_bytes(&tx); - let free = execute(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + 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"); @@ -946,17 +1020,14 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() ); let limit = body + Site::Create2.bytes() - 1; - let stopped = execute(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); - assert_eq!( - stopped.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: body + Site::Create2.bytes(), - frame_local: false, - }), - ); - assert!(!stopped.result.is_success(), "the stop reverts the transaction"); + 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 @@ -969,7 +1040,7 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { let tx = deposit(TxKind::Call(RECEIVER), 1_000, 400); let body = transaction_body_bytes(&tx); - let outcome = execute(db(), tx, EvmTxRuntimeLimits::no_limits()); + let outcome = execute_under(db(), tx, EvmTxRuntimeLimits::no_limits()); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( outcome.result.logs(), @@ -983,14 +1054,17 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { ); assert_eq!((outcome.gas.history, outcome.gas.history_bytes), (0, 0), "a deposit pays none"); - let minted = - execute(db(), deposit(TxKind::Call(RECEIVER), 1_000, 0), EvmTxRuntimeLimits::no_limits()); + 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( + let stopped = execute_under( db(), deposit(TxKind::Call(RECEIVER), 1_000, 400), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), @@ -1015,7 +1089,7 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { 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(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + 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(), @@ -1026,7 +1100,7 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { let limit = body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; let limited = - execute(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + 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:?}"); @@ -1057,7 +1131,7 @@ fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ] { let db = MemoryDatabase::default().account_nonce(DEPOSITOR, u64::MAX); - let outcome = execute(db, tx.clone(), limits); + 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:?}"); @@ -1107,7 +1181,7 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { })) }; - let quiet = execute(db(), system(0), EvmTxRuntimeLimits::no_limits()); + 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"); @@ -1117,7 +1191,7 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { EvmTxRuntimeLimits::no_limits(), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0), ] { - let outcome = execute(db(), tx.clone(), limits); + let outcome = execute_under(db(), tx.clone(), limits); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None); assert_eq!( @@ -1134,3 +1208,81 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { ); } } + +/// 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 index d332fecff..39a429a00 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -7,26 +7,35 @@ //! called `disableVolatileDataAccess()` first. use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; -use alloy_sol_types::SolCall; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::ORACLE_ACCESS_COMPUTE_GAS, system::{ IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_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, - VolatileDataAccess, + 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 revm::{bytecode::opcode::*, context::TxEnv, interpreter::InstructionResult, state::Bytecode}; use crate::{ common::body_history, detention::{ - 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, + 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. @@ -37,31 +46,10 @@ const PAST_THE_CAP: u32 = 7_000; /* ---------- what records a read ---------- */ -/// Every block-environment opcode records its own kind; the transaction's and the chain's own -/// fields, and a contract's own balance, record nothing. +/// 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_block_environment_opcodes_record_their_kind_and_nothing_else_does() { - let reads: [(u8, VolatileDataAccess); 9] = [ - (NUMBER, VolatileDataAccess::BLOCK_NUMBER), - (TIMESTAMP, VolatileDataAccess::TIMESTAMP), - (COINBASE, VolatileDataAccess::COINBASE), - (DIFFICULTY, VolatileDataAccess::PREV_RANDAO), - (GASLIMIT, VolatileDataAccess::GAS_LIMIT), - (BASEFEE, VolatileDataAccess::BASE_FEE), - (BLOBBASEFEE, VolatileDataAccess::BLOB_BASE_FEE), - (SLOTNUM, VolatileDataAccess::SLOT_NUM), - (PUSH0, VolatileDataAccess::empty()), - ]; - for (opcode, access) in reads { - 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, access, "{opcode:#04x}"); - assert_eq!(run.accessed.count_block_env_accessed(), usize::from(!access.is_empty())); - } +fn test_the_transactions_own_fields_record_nothing() { for opcode in [ revm::bytecode::opcode::CALLER, ORIGIN, @@ -83,31 +71,6 @@ fn test_the_block_environment_opcodes_record_their_kind_and_nothing_else_does() } } -/// A transaction that reads several kinds records all of them, and the first read's limit, the -/// lowest, is the one that holds. -#[test] -fn test_several_reads_record_every_kind_and_the_first_limit_holds() { - for gas_limit in TIERS { - let code = op(BytecodeBuilder::default(), NUMBER); - let code = op(work(code, 300), TIMESTAMP); - let code = op(work(code, 300), BASEFEE); - let code = work(code, 300).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.accessed, - VolatileDataAccess::BLOCK_NUMBER | - VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::BASE_FEE - ); - assert_eq!(run.accessed.count_block_env_accessed(), 3); - assert_eq!(run.limit, Some(2 + CAP), "NUMBER, the first read, set the limit"); - } -} - /// 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] @@ -132,38 +95,6 @@ fn test_detention_starts_afresh_for_every_transaction() { assert!(second.outcome.gas.regular > CAP); } -/// A read that stays within the cap costs what it ran: the gas detention withheld is never -/// spent, below and above the execution cap. -#[test] -fn test_a_read_within_the_cap_bills_what_ran() { - for gas_limit in TIERS { - for opcode in [TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE] { - // The read, a word stored, a short loop, and the word returned. - let code = BytecodeBuilder::default().append(opcode).push_number(0_u8).append(MSTORE); - let code = work(code, 10).push_number(32_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(), "{opcode:#04x}"); - assert!(run.limit.is_some(), "{opcode:#04x}"); - // What it ran is well under 100,000; the body's history comes on top. - let used = run.outcome.result.gas().tx_gas_used(); - assert!( - used < 100_000 + body_history(0), - "{opcode:#04x}: {used}, not the gas it was given" - ); - } - let code = BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).stop().build(); - let run = execute( - MemoryDatabase::default().account_code(CONTRACT, code), - tx(CALLER, CONTRACT, gas_limit), - ); - assert!(run.outcome.result.is_success()); - assert!(run.outcome.result.gas().tx_gas_used() < 100_000 + body_history(0)); - } -} - /* ---------- which read sets the limit ---------- */ /// A read two frames down caps every caller: the middle frame and the transaction's own frame @@ -199,23 +130,6 @@ fn test_a_read_two_frames_down_caps_every_caller() { } } -/// A caller that already read keeps its own limit through a child that reads again. -#[test] -fn test_a_childs_second_read_leaves_the_callers_limit() { - let child = op(BytecodeBuilder::default(), NUMBER).stop().build(); - let parent = work(op(BytecodeBuilder::default(), TIMESTAMP), 300); - let parent = call(parent, CALL, CHILD).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()); - assert_eq!(run.limit, Some(2 + CAP), "TIMESTAMP, the caller's first opcode, set it"); - assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOCK_NUMBER); - } -} - /// 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] @@ -289,7 +203,8 @@ fn test_calling_the_oracle_without_reading_its_storage_detains_nothing() { } /// 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, and whether the call is a `CALL` or a `STATICCALL`. +/// 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); @@ -314,7 +229,7 @@ fn test_the_oracle_reading_its_own_storage_is_held_to_the_cap() { 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_stopped(&run, intrinsic, left); + assert_caught(&run, intrinsic, left, &Charges::default().then(&[2])); assert_eq!(run.accessed, VolatileDataAccess::ORACLE, "{scheme:#04x}"); } } @@ -396,6 +311,198 @@ fn test_the_system_address_is_not_detained() { ); } +/// 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 @@ -614,8 +721,10 @@ fn test_a_call_to_the_access_control_contract_costs_its_overhead() { ); 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 (2,600), POP and GAS. - assert_eq!(consumed, U256::from(17 + 2_600 + 2 + 2)); + // 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 ---------- */ diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 2f02e6814..d50e617d9 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -19,18 +19,14 @@ 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, - }, - IMegaAccessControl, VolatileDataAccessType, + 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}, - volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, - MegaContext, MegaEvm, MegaHaltReason, VolatileDataAccess, WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, + VolatileDataAccess, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::*, @@ -52,9 +48,10 @@ use revm::{ use crate::{ common::history, detention::{ - assert_stopped, burn, context, execute, fresh_write_spill, intrinsic, memory_cost, op, - run_on, spin, stop_data, tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, - CAP, CHILD, CONTRACT, FRESH_WRITE, TIERS, + 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, }, }; @@ -213,7 +210,7 @@ fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { .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"); + 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)] { @@ -251,6 +248,83 @@ fn test_the_sstore_sentry_reads_the_whole_regular_gas() { } } +/// 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: @@ -485,6 +559,57 @@ fn test_an_exp_that_cannot_pay_its_exponent_burns_what_its_frame_had() { } } +/// 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 @@ -497,6 +622,9 @@ fn test_an_exp_that_cannot_pay_its_exponent_burns_what_its_frame_had() { /// 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(); @@ -519,7 +647,7 @@ fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { let mut since_read = 2; let crossing = 'calls: { for call in 0..50 { - let access = if call == 0 { 2_600 } else { 100 }; + 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; @@ -545,13 +673,166 @@ fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { frame_local: false }) ); - assert_eq!(detained.outcome.gas.regular, intrinsic(gas_limit) + used); + 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]) @@ -563,10 +844,11 @@ fn call_keeping_value(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { /* ---------- crossing the cap ---------- */ /// A callee given all the gas after its caller's read, which computes past the cap, crosses it: -/// the transaction stops at the limit, and the caller never stores the status it would have -/// stored without the read. +/// 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_stops_the_transaction() { +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| { @@ -584,10 +866,14 @@ fn test_a_callee_computing_past_the_cap_stops_the_transaction() { 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, 2_600]).work(10_000, 0).left(CAP); - assert_stopped(&detained, intrinsic(gas_limit), left); - assert_eq!(slot(&detained, 0), None, "the caller never resumed"); + 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"); } } @@ -620,7 +906,7 @@ fn test_the_stop_reports_its_compute_whatever_a_callee_burned() { // 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, 2_600, *computed, 2]) + .then(&[2, 2, 2, 2, 2, 2, 3, 3, cold_access(), *computed, 2]) .spin(0) .left(CAP); let used = limit - left; @@ -669,8 +955,10 @@ fn test_a_halt_burns_what_its_frame_had_when_it_halted() { // 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, 2_600, callee, 2]).spin(0).left(CAP); + 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"); } @@ -1019,8 +1307,9 @@ fn run_precompile( /// /// 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 the transaction stops, -/// billed nothing of the allowance the precompile ran on. +/// 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 { @@ -1035,8 +1324,14 @@ fn test_a_precompile_runs_on_the_allowance() { let allowance = CAP - to_the_call.total(); let stopped = |run: &PrecompileRun, price: u64| { let input = U256::from(price).to_be_bytes::<32>(); - let left = to_the_call.clone().then(&[price, 3]).left(CAP); - assert_stopped(&run.run, intrinsic_with(&input, gas_limit), left); + 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. @@ -1064,11 +1359,11 @@ fn test_a_precompile_runs_on_the_allowance() { /// /// - 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 the transaction stops at the limit — without the read it computes; +/// 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 the -/// transaction stops at the limit. Without the read the call fails and its caller goes on: with -/// no price, it cannot be told from one priced within the forward. +/// - 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. @@ -1085,7 +1380,8 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { let (detained, plain) = (run(TIMESTAMP, None, &above), run(PUSH0, None, &above)); let allowance = CAP - charges_to_the_precompile(above.len(), None).total(); - assert_stopped(&detained.run, intrinsic_with(&above, gas_limit), allowance); + 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}"); @@ -1116,7 +1412,7 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { 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_stopped(&detained.run, intrinsic_with(&above, gas_limit), allowance); + 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()); @@ -1128,15 +1424,16 @@ fn test_a_precompile_is_held_to_what_the_limit_leaves() { /// 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; priced -/// past the forward, it runs out of gas as it does without the read, and its caller goes on. Below +/// 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. The same transaction from another sender -/// computes. +/// 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); @@ -1165,7 +1462,8 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { 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(); - assert_stopped(&called.run, intrinsic_with(&input, gas_limit), allowance); + 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| { @@ -1180,7 +1478,7 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { assert_eq!(forward, plain_forward, "the read leaves the forward as it is"); assert!(forward > CAP, "{forward}"); if price <= forward { - assert_stopped(&detained, intrinsic_with(&input, gas_limit), allowance); + 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"); @@ -1203,119 +1501,50 @@ fn test_a_precompile_priced_past_the_cap_computes_nothing() { assert_eq!(cases, (3, 1), "the stop above the cap for both, and below it for the cheaper"); } -/// The built-in modexp priced within the allowance runs as without the read: revm runs it, on the -/// whole forward, and it charges its price, the same result and the same bill. +/// The built-in modexp, priced from its input, is held from its price as the size-limited wrappers +/// are, below. #[test] -fn test_a_priced_precompile_within_the_allowance_runs_as_without_the_read() { +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!(price < CAP / 2, "{price}"); - for gas_limit in TIERS { - let run = |first| { - let db = MemoryDatabase::default() - .account_code(CONTRACT, calls_precompile(first, MODEXP, None)); - let mut evm = MegaEvm::new(context(db)).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(); - assert!(call.precompile_ran, "revm runs it"); - assert_eq!(call.spent, price, "it charges its price"); - run - }; - let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); - assert_as_without_read(&detained, &plain, "a price the allowance pays"); - assert_eq!(slot(&detained, 0), Some(U256::from(1))); - } -} - -/// A Satin address a node replaced is not priced from the built-in set, even when its precompile -/// carries the built-in's id: forwarded less than its price and more than the allowance, the -/// replaced modexp runs on the allowance and is the stop, where the built-in one, which the engine -/// prices, runs out of gas as without the read, and its caller goes on. -#[test] -fn test_a_replaced_precompile_is_not_priced_from_the_built_in_set() { - let input = costly_modexp_input(64, 0); - let price = mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&input).unwrap(); - assert!(price > CAP, "{price}"); - let short = u32::try_from(price - 1).unwrap(); - for gas_limit in TIERS { - let db = |first| { - MemoryDatabase::default() - .account_code(CONTRACT, calls_precompile(first, MODEXP, Some(short))) - }; - let replaced = - run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); - let allowance = CAP - charges_to_the_precompile(input.len(), Some(short)).total(); - assert_stopped(&replaced.run, intrinsic_with(&input, gas_limit), allowance); - assert_eq!(replaced.ran_on, [(allowance, false)], "run on the allowance"); - - let (built_in, plain) = ( - execute(db(TIMESTAMP), tx_with(&input, gas_limit)), - execute(db(PUSH0), tx_with(&input, gas_limit)), - ); - assert_as_without_read(&built_in, &plain, "a price past the forward"); - assert_eq!(slot(&built_in, 0), Some(U256::ZERO), "the call fails and its caller goes on"); - } + assert_held_from_its_price(MODEXP, &input, price); } -/// op-revm's wrapper of the BN254 pairing is priced, so a call forwarded less than its price and -/// more than the allowance — three pairs, 147,000 gas, forwarded 120,000 under a cap of 100,000 — -/// runs on its forward and runs out of gas as without the read, and its caller goes on, as the KZG -/// entry does — 100,000, forwarded 80,000 under a cap of 50,000. A node's own precompile, which the -/// engine cannot price, keeps the clamp: at the pairing's price and forward, it runs on the -/// allowance and is the stop. +/// 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_a_nodes_own_precompile_keeps_the_clamp_a_priced_wrapper_does_not() { - let pairing = vec![0_u8; 3 * 192]; - // EIP-1108: 45,000, and 34,000 a pair. - let price = 45_000 + 3 * 34_000; - let entry = mega_evm::satin_precompiles().get(&EC_PAIRING).unwrap(); - assert_eq!(entry.required_gas(&pairing), Some(price)); +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 own_input = U256::from(price).to_be_bytes::<32>(); - let limits = |cap| EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(50_000); for gas_limit in TIERS { - let run = |first, to, forward, cap, input: &[u8]| { + let run = |first| { let db = MemoryDatabase::default() - .account_code(CONTRACT, calls_precompile(first, to, Some(forward))); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits(cap))) + .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(input, gas_limit)); - let call = evm.inspector().calls.iter().find(|call| call.target == to).unwrap(); - assert_eq!(call.forward, u64::from(forward)); - assert!(call.precompile_ran, "{to}: revm runs it, on its forward"); + 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 = run(TIMESTAMP, EC_PAIRING, 120_000, 100_000, &pairing); - let plain = run(PUSH0, EC_PAIRING, 120_000, 100_000, &pairing); - 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"); - - let detained = run(TIMESTAMP, kzg_address, 80_000, 50_000, &kzg); - let plain = run(PUSH0, kzg_address, 80_000, 50_000, &kzg); + 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"); - - let runs = Runs::default(); - let db = MemoryDatabase::default() - .account_code(CONTRACT, calls_precompile(TIMESTAMP, PRICED, Some(120_000))); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits(100_000))) - .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])); - let own = run_on(&mut evm, tx_with(&own_input, gas_limit)); - let allowance = 100_000 - charges_to_the_precompile(32, Some(120_000)).total(); - assert_stopped(&own, intrinsic_with(&own_input, gas_limit), allowance); - assert_eq!(*runs.lock().unwrap(), [(allowance, false)], "run on the allowance"); } } /// 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, and the transaction stops; 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. +/// 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]; @@ -1332,7 +1561,8 @@ fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowan }; 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(); - assert_stopped(&detained, intrinsic_with(&input, gas_limit), allowance); + 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"); @@ -1346,8 +1576,8 @@ fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowan /// `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, and the transaction stops, where without the read -/// it computes; +/// 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 @@ -1375,7 +1605,8 @@ fn assert_held_from_its_price(to: Address, input: &[u8], price: u64) { 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}"); - assert_stopped(&detained, intrinsic_with(input, gas_limit), allowance); + 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"); @@ -1439,13 +1670,10 @@ fn test_the_bls12_pairing_is_held_from_its_price() { /// 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 both stop at it; +/// - 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; -/// - under a cap past both and one gas short of what the creation computes, the creation stops at -/// the limit where it would deploy, and the stop takes the deployment back; one gas more, and it -/// deploys as without the read; -/// - under the spec's cap, both run as without the read. +/// 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"); @@ -1488,12 +1716,6 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { "the answer without detention" ); let refused_intrinsic = answered.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; - let deployed = both(CALLER, 0, &deploys, CAP); - let answer = IKeylessDeploy::keylessDeployCall::abi_decode_returns( - deployed.outcome.result.output().unwrap(), - ) - .unwrap(); - assert_eq!(answer.deployedAddress, CREATE2_FACTORY_CONTRACT, "it deploys"); let deploy_intrinsic = intrinsic_with(&deploys, gas_limit); // Detained from its start, the call's overhead is its first charge, then the `CREATE` @@ -1502,7 +1724,6 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { let detained = both(BENEFICIARY, 1, &refused, cap); assert_eq!(detained.limit, Some(cap), "the sender is the beneficiary"); assert_stopped(&detained, refused_intrinsic, cap); - assert_stopped(&both(BENEFICIARY, 0, &deploys, cap), deploy_intrinsic, cap); let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + create - 1; let detained = both(BENEFICIARY, 1, &refused, cap); @@ -1513,32 +1734,6 @@ fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { assert_eq!(left, create - 1); assert_stopped(&stopped, deploy_intrinsic, left); assert_eq!(nonce_of(&stopped, CREATE2_FACTORY_DEPLOYER), 0, "the creation never started"); - - // The creation's own compute: the regular gas the deployment spent past the call's. - let creation = - deployed.outcome.gas.regular - deploy_intrinsic - KEYLESS_DEPLOY_OVERHEAD_GAS - create; - let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + create + creation - 1; - let stopped = both(BENEFICIARY, 0, &deploys, cap); - let code = deployed.outcome.state[&CREATE2_FACTORY_CONTRACT].info.code.clone().unwrap(); - let hash = 6 * (code.len() as u64).div_ceil(32); - let left = Charges::default() - .then(&[KEYLESS_DEPLOY_OVERHEAD_GAS, create, creation - hash, hash]) - .left(cap); - assert_eq!(left, hash - 1, "the hash of the deposited code crosses"); - assert_stopped(&stopped, deploy_intrinsic, left); - assert!( - stopped.outcome.state.get(&CREATE2_FACTORY_CONTRACT).is_none_or(|a| a.info.is_empty()), - "the stop takes the deployment back" - ); - assert_eq!(nonce_of(&stopped, CREATE2_FACTORY_DEPLOYER), 0, "the signer's nonce with it"); - let detained = both(BENEFICIARY, 0, &deploys, cap + 1); - assert_eq!(detained.outcome.result, deployed.outcome.result, "the creation fits"); - assert_eq!(detained.outcome.gas, deployed.outcome.gas); - - let detained = both(BENEFICIARY, 0, &deploys, CAP); - assert_eq!(detained.limit, Some(CAP)); - assert_eq!(detained.outcome.result, deployed.outcome.result, "as without the read"); - assert_eq!(detained.outcome.gas, deployed.outcome.gas); } } @@ -1590,24 +1785,6 @@ fn nonce_of(run: &Run, address: Address) -> u64 { run.outcome.state.get(&address).map_or(0, |account| account.info.nonce) } -/* ---------- the refusal's access type ---------- */ - -/// A `SLOTNUM` refusal carries access type 12, which `IMegaAccessControl`'s enum does not declare: -/// a decoder that validates the enum rejects it, while every other refusal decodes, `BLOCKHASH`'s -/// as `BlockHash`. The enum is the access-control contract's to extend. -#[test] -fn test_a_slotnum_refusal_is_past_the_enum() { - let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); - assert!(IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&slot_num).is_err()); - let block_hash = volatile_data_access_disabled_revert_data(VolatileDataAccess::BLOCK_HASH); - assert_eq!( - IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&block_hash) - .unwrap() - .accessType, - VolatileDataAccessType::BlockHash - ); -} - /// 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)] diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 1b217110f..f2aac4aba 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -19,8 +19,8 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, test_utils::{is_transfer_log, BytecodeBuilder, MemoryDatabase}, - LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, - TX_BODY_SIZE, WRITE_RECORD_SIZE, + LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -186,15 +186,6 @@ 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] @@ -352,26 +343,6 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { } } -/// 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, with_extra(body_only(), 32 + 2 * 32 + 10)); -} - /// `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. @@ -411,6 +382,147 @@ fn test_top_level_create_records_the_created_account() { 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 ---------- */ /// Records, after each opcode, what the layer holds. @@ -521,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; @@ -569,14 +663,6 @@ fn test_applied_authorities_record_once_each() { with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), "a wrong nonce applies nothing, and its tuple is still in the body" ); - - let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(CALLER, 1)])); - assert!(result.result.is_success()); - assert_eq!( - usage, - with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), - "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 @@ -717,43 +803,40 @@ 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 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 at_the_cap = with_cap(TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE); - assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); + 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 limit = TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE - 1; - let outcome = with_cap(limit); - assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: limit + 1, - frame_local: false, - }), - "the authority record is the byte that crosses, and nothing after it is counted" - ); - 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, with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE)); + 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 funded caller's database, for the runtime out-of-gas tests. @@ -1096,6 +1179,7 @@ fn paired_corpus() -> 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)])), @@ -1114,6 +1198,14 @@ fn paired_corpus() -> Vec { 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( @@ -1394,8 +1486,8 @@ impl Inspector, EthInterpreter> for KvWeighsNoMore /// 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 a KV limit binds only below the data-size limit's fortieth: at the production data-size -/// caps a transaction keeps at most 327,680 records, whatever its KV limit. +/// 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); 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 index a43fcce69..e1eec4ce0 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -7,27 +7,21 @@ //! The legacy engine's rows, on Satin's switch. The beneficiary is the block's, `Address::ZERO` in //! these tests. -use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +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, - NON_ZERO_TRANSFER_REVERT_DATA, ORACLE_CONTRACT_ADDRESS, + ORACLE_CONTRACT_ADDRESS, }, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, volatile_data_access_disabled_revert_data, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, - MegaTransaction, MegaTransactionOutcome, TestExternalEnvs, VolatileDataAccess, -}; -use revm::{ - bytecode::opcode::*, - context::{ContextTr, TxEnv}, - interpreter::{CallInputs, CallOutcome, InterpreterTypes}, - Inspector, + MegaTransaction, TestExternalEnvs, VolatileDataAccess, }; +use revm::bytecode::opcode::*; -use crate::common::{block, system_db, CALLER, GAS_LIMIT}; +use crate::common::{block, call_tx_with_gas, steer, system_db, Run, GAS_LIMIT}; const PARENT: Address = address!("0x0000000000000000000000000000000000200001"); const CHILD: Address = address!("0x0000000000000000000000000000000000200002"); @@ -41,49 +35,9 @@ const DISABLE: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELE const ENABLE: [u8; 4] = IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; const DISABLED_BY_PARENT: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; -const NOT_INTERCEPTED: [u8; 4] = IMegaAccessControl::NotIntercepted::SELECTOR; /* ---------- running a transaction ---------- */ -/// What a transaction did, and what gas detention made of its reads. -struct Run { - outcome: MegaTransactionOutcome, - accessed: VolatileDataAccess, - limit: Option, -} - -impl Run { - /// The output of the transaction, which must have succeeded. - 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. - fn word(&self) -> U256 { - U256::from_be_slice(&self.output()) - } - - /// The call status the log at `index` carries ([`log_status`]). - 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 - } -} - -/// A transaction from [`CALLER`] to `to` with `data` and `value`, carrying `gas_limit`. -fn tx(to: Address, data: &[u8], value: U256, gas_limit: u64) -> MegaTransaction { - OpTx(op_transaction(TxEnv { - caller: CALLER, - kind: TxKind::Call(to), - data: Bytes::copy_from_slice(data), - value, - gas_limit, - ..Default::default() - })) -} - /// 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() @@ -102,24 +56,11 @@ fn run(code: &[(Address, Bytes)]) -> Run { let db = code .iter() .fold(system_db(), |db, (address, code)| db.account_code(*address, code.clone())); - execute(db, tx(PARENT, &[], U256::ZERO, GAS_LIMIT)) + execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)) } /* ---------- code ---------- */ -/// Appends a `CALL` of `selector` on the access control contract, discarding its status. -fn steer(code: BytecodeBuilder, selector: [u8; 4]) -> BytecodeBuilder { - 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]) -} - fn disable(code: BytecodeBuilder) -> BytecodeBuilder { steer(code, DISABLE) } @@ -128,22 +69,6 @@ fn enable(code: BytecodeBuilder) -> BytecodeBuilder { steer(code, ENABLE) } -/// Appends a query of `isVolatileDataAccessDisabled()` and returns its answer. -fn query_and_return(code: BytecodeBuilder) -> BytecodeBuilder { - code.mstore(0x0, IS_DISABLED) - .push_number(32_u8) // retSize - .push_number(0x20_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]) - .push_number(32_u8) - .push_number(0x20_u8) - .append(RETURN) -} - /// 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); @@ -445,19 +370,34 @@ fn test_oracle_sload_reverts_when_volatile_access_disabled() { assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Oracle); } -/// A creation whose init code reads volatile data fails below a frame that switched access off. +/// 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 = disable(BytecodeBuilder::default()) - .mstore(0x40, &init_code) - .push_number(init_code.len() as u64) - .push_number(0x40_u8) - .push_number(0_u8) - .append(CREATE); - let run = run(&[(PARENT, return_word(parent))]); - assert_eq!(run.word(), U256::ZERO, "the creation failed"); + 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: @@ -547,7 +487,7 @@ fn test_the_switch_does_not_carry_into_the_next_transaction() { let mut evm = MegaEvm::new(ctx); let one = evm - .execute_transaction(tx(PARENT, &[], U256::ZERO, GAS_LIMIT)) + .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); @@ -559,7 +499,7 @@ fn test_the_switch_does_not_carry_into_the_next_transaction() { assert_eq!(evm.ctx().detention().accessed(), VolatileDataAccess::empty()); let two = evm - .execute_transaction(tx(SIBLING, &[], U256::ZERO, GAS_LIMIT)) + .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); @@ -626,30 +566,6 @@ fn test_staticcall_disable_volatile_data_access_is_intercepted() { /* ---------- 8. isVolatileDataAccessDisabled() ---------- */ -/// The query answers `false` where nothing switched access off, `true` in the frame that did, and -/// `true` in a child of it. -#[test] -fn test_query_returns_false_when_not_disabled() { - let run = run(&[(PARENT, query_and_return(BytecodeBuilder::default()).build())]); - assert_eq!(run.word(), U256::ZERO); -} - -/// See [`test_query_returns_false_when_not_disabled`]. -#[test] -fn test_query_returns_true_for_disabling_frame() { - let run = run(&[(PARENT, query_and_return(disable(BytecodeBuilder::default())).build())]); - assert_eq!(run.word(), U256::ONE); -} - -/// See [`test_query_returns_false_when_not_disabled`]. -#[test] -fn test_query_returns_true_when_parent_disabled() { - let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); - let run = - run(&[(PARENT, parent), (CHILD, query_and_return(BytecodeBuilder::default()).build())]); - assert_eq!(run.word(), U256::ONE); -} - /// 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] @@ -717,53 +633,7 @@ fn test_the_query_answers_for_the_caller_at_every_depth() { ); } -/* ---------- 9. a transaction calling the contract directly ---------- */ - -/// A transaction that calls the contract directly is answered: the switches succeed, the query -/// answers `false`, a value-bearing call is refused with `NonZeroTransfer()`, and a selector the -/// contract does not intercept reverts in its bytecode with `NotIntercepted()`. -#[test] -fn test_direct_tx_disable_volatile_data_access() { - for selector in [DISABLE, ENABLE] { - let run = - execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &selector, U256::ZERO, GAS_LIMIT)); - assert!(run.output().is_empty()); - } -} - -/// See [`test_direct_tx_disable_volatile_data_access`]. -#[test] -fn test_direct_tx_disable_volatile_data_access_with_value_reverts() { - let run = execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &DISABLE, U256::ONE, GAS_LIMIT)); - assert!(!run.outcome.result.is_success()); - assert_eq!( - run.outcome.result.output().cloned().unwrap_or_default(), - Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA) - ); -} - -/// See [`test_direct_tx_disable_volatile_data_access`]. -#[test] -fn test_direct_tx_is_volatile_data_access_disabled() { - let run = execute(system_db(), tx(ACCESS_CONTROL_ADDRESS, &IS_DISABLED, U256::ZERO, GAS_LIMIT)); - assert_eq!(run.word(), U256::ZERO); -} - -/// See [`test_direct_tx_disable_volatile_data_access`]. -#[test] -fn test_direct_tx_unknown_selector_falls_through_and_reverts_not_intercepted() { - let run = execute( - system_db(), - tx(ACCESS_CONTROL_ADDRESS, &[0xde, 0xad, 0xbe, 0xef], U256::ZERO, GAS_LIMIT), - ); - assert!(!run.outcome.result.is_success()); - assert_eq!( - run.outcome.result.output().cloned().unwrap_or_default(), - Bytes::from_static(&NOT_INTERCEPTED) - ); -} - -/* ---------- 10. schemes that do not reach the interceptor ---------- */ +/* ---------- 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. @@ -786,44 +656,7 @@ fn test_delegatecall_to_access_control_not_intercepted() { } } -/* ---------- 11. an inspector sees the answered call ---------- */ - -/// Records the targets of every call an inspector is shown, as it starts and as it ends. -#[derive(Default)] -struct Calls { - starts: Vec
, - ends: Vec
, -} - -impl Inspector for Calls { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - self.starts.push(inputs.target_address); - None - } - - fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.ends.push(inputs.target_address); - } -} - -/// An inspector sees the call the interceptor answered start and end like any other. -#[test] -fn test_inspector_sees_system_contract_call() { - let child = BytecodeBuilder::default().append_many([PUSH0, POP, STOP]).build(); - let db = system_db() - .account_code(PARENT, disables_then_calls_child(CALL)) - .account_code(CHILD, child); - let ctx = MegaContext::new(db, MegaSpecId::SATIN) - .with_block(block()) - .with_chain(zero_fee_l1_block_info()); - let mut evm = MegaEvm::new(ctx).with_inspector(Calls::default()); - let outcome = evm.execute_transaction(tx(PARENT, &[], U256::ZERO, GAS_LIMIT)).unwrap(); - assert!(outcome.result.is_success()); - assert_eq!(evm.inspector().starts, vec![PARENT, ACCESS_CONTROL_ADDRESS, CHILD]); - assert_eq!(evm.inspector().ends, vec![ACCESS_CONTROL_ADDRESS, CHILD, PARENT]); -} - -/* ---------- 12. below and above the execution cap ---------- */ +/* ---------- 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. @@ -834,7 +667,7 @@ fn test_the_switch_is_the_same_below_and_above_the_execution_cap() { let at = |gas_limit: u64| { let db = system_db().account_code(PARENT, parent.clone()).account_code(CHILD, reads(TIMESTAMP)); - execute(db, tx(PARENT, &[], U256::ZERO, gas_limit)) + 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] { diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs index fe87f75a5..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); @@ -156,13 +203,73 @@ 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. +/// 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 { - mega_evm::history_gas(bytes).expect("the bytes have a price") + 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. +/// 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_history_bytes(calldata_len, 0, 0, 0)) + 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 7ad958cfa..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,11 +18,7 @@ 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 diff --git a/crates/mega-evm/tests/system/deploy.rs b/crates/mega-evm/tests/system/deploy.rs deleted file mode 100644 index 66c703c6e..000000000 --- a/crates/mega-evm/tests/system/deploy.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! The system-contract deploy helper: the spec list, a fresh deploy, the idempotent read, and -//! foreign code. - -use alloy_primitives::{address, keccak256, Address, Bytes, U256}; -use mega_evm::{ - system::{ - keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, - storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, - INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, - }, - system_contract_specs, transact_deploy, SequencerRegistryConfig, SystemContractDeployError, - SystemContractSpec, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH, - CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE, CREATE2_FACTORY_CODE_HASH, - CREATE2_FACTORY_NONCE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE_HASH, - MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, - ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, - SYSTEM_CONTRACT_DEPLOY_COUNT, - }, - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - HardforkParams, -}; -use revm::{primitives::KECCAK_EMPTY, DatabaseCommit}; - -const SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); -const ADMIN_ADDR: Address = address!("0x3333333333333333333333333333333333333333"); - -fn config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - initial_system_address: MEGA_SYSTEM_ADDRESS, - initial_sequencer: SEQUENCER, - initial_admin: ADMIN_ADDR, - initial_from_block: 7, - min_rotation_delay: 100, - } -} - -fn oracle_spec() -> SystemContractSpec { - SystemContractSpec::new( - ORACLE_CONTRACT_ADDRESS, - ORACLE_CONTRACT_CODE, - ORACLE_CONTRACT_CODE_HASH, - ) -} - -/// The factory's pinned hash is the hash of the runtime the spec installs. -#[test] -fn test_the_factory_code_hashes_to_its_pinned_hash() { - assert_eq!(keccak256(CREATE2_FACTORY_CODE), CREATE2_FACTORY_CODE_HASH); - assert_eq!(CREATE2_FACTORY_NONCE, 1); -} - -/// The spec list is the six `MegaETH` contracts in address order, then the factory. -#[test] -fn test_the_spec_list_is_the_seven_predeploys_in_order() { - let specs = system_contract_specs(&config()); - assert_eq!(specs.len(), SYSTEM_CONTRACT_DEPLOY_COUNT); - assert_eq!( - [ - specs[0].address, - specs[1].address, - specs[2].address, - specs[3].address, - specs[4].address, - specs[5].address, - specs[6].address, - ], - [ - ORACLE_CONTRACT_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - KEYLESS_DEPLOY_ADDRESS, - ACCESS_CONTROL_ADDRESS, - LIMIT_CONTROL_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - CREATE2_FACTORY_ADDRESS, - ] - ); - assert_eq!( - [ - specs[0].code_hash, - specs[1].code_hash, - specs[2].code_hash, - specs[3].code_hash, - specs[4].code_hash, - specs[5].code_hash, - specs[6].code_hash, - ], - [ - ORACLE_CONTRACT_CODE_HASH, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - KEYLESS_DEPLOY_CODE_HASH, - ACCESS_CONTROL_CODE_HASH, - LIMIT_CONTROL_CODE_HASH, - SEQUENCER_REGISTRY_CODE_HASH, - CREATE2_FACTORY_CODE_HASH, - ] - ); - for spec in &specs { - assert_eq!(spec.nonce, 1, "{} starts at nonce 1", spec.address); - assert_eq!(keccak256(&spec.code), spec.code_hash); - } - assert!(specs[..6].iter().all(|spec| !spec.require_nonzero_nonce)); - assert!(specs[6].require_nonzero_nonce, "EIP-7997 requires a nonzero factory nonce"); - assert!(specs[..5].iter().all(|spec| spec.seed.is_empty())); - assert!(specs[6].seed.is_empty(), "the factory has no storage"); - assert_eq!(specs[5].seed.len(), 7, "the registry seeds the seven bootstrap slots"); -} - -/// A fresh deploy creates the account, installs the code and seeds every slot. -#[test] -fn test_a_fresh_deploy_creates_the_account_and_seeds_storage() { - let mut db = MemoryDatabase::default(); - let specs = system_contract_specs(&config()); - let registry = &specs[5]; - let factory = &specs[6]; - - let state = transact_deploy(&mut db, registry).expect("the registry deploys"); - let account = state.get(&SEQUENCER_REGISTRY_ADDRESS).expect("the registry is in the witness"); - assert!(account.is_touched()); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(account.info.nonce, 1); - assert_eq!(account.storage.len(), 7); - assert_eq!( - account.storage.get(&CURRENT_SYSTEM_ADDRESS).unwrap().present_value, - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0) - ); - assert_eq!( - account.storage.get(&CURRENT_SEQUENCER).unwrap().present_value, - U256::from_be_bytes(SEQUENCER.into_word().0) - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value, - U256::from_be_bytes(ADMIN_ADDR.into_word().0) - ); - assert_eq!( - account.storage.get(&INITIAL_SYSTEM_ADDRESS).unwrap().present_value, - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0) - ); - assert_eq!( - account.storage.get(&INITIAL_SEQUENCER).unwrap().present_value, - U256::from_be_bytes(SEQUENCER.into_word().0) - ); - assert_eq!(account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value, U256::from(7)); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value, - U256::from(config().min_rotation_delay) - ); - db.commit(state); - - let state = transact_deploy(&mut db, factory).expect("the factory deploys"); - let account = state.get(&CREATE2_FACTORY_ADDRESS).expect("the factory is in the witness"); - assert!(account.is_created()); - assert_eq!(account.info.nonce, CREATE2_FACTORY_NONCE); - assert!(account.storage.is_empty()); -} - -/// Already deployed with the matching code hash is a read-only witness entry. -#[test] -fn test_a_matching_deploy_is_a_read_only_witness_entry() { - let mut db = MemoryDatabase::default(); - let spec = oracle_spec(); - let deployed = transact_deploy(&mut db, &spec).unwrap(); - db.commit(deployed); - - let state = transact_deploy(&mut db, &spec).expect("the second deploy is a no-op"); - let account = state.get(&ORACLE_CONTRACT_ADDRESS).expect("the read is in the witness"); - assert!(!account.is_touched(), "a matching deploy does not touch"); - assert!(!account.is_created(), "a matching deploy does not create"); - assert!(account.storage.is_empty(), "a matching deploy does not seed"); - assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH); -} - -/// Present with different code is an error, not an overwrite. -#[test] -fn test_foreign_code_at_a_system_address_is_an_error() { - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0xfe])); - - let error = transact_deploy(&mut db, &oracle_spec()).expect_err("foreign code must fail"); - let message = error.to_string(); - assert!(message.contains("refusing to overwrite"), "the error names the refusal: {message}"); - match error { - SystemContractDeployError::ForeignCode { address, expected, found } => { - assert_eq!(address, ORACLE_CONTRACT_ADDRESS); - assert_eq!(expected, ORACLE_CONTRACT_CODE_HASH); - assert_eq!(found, keccak256([0xfe])); - assert_ne!(found, KECCAK_EMPTY); - } - other => panic!("expected ForeignCode, got {other}"), - } -} - -/// Matching factory code at nonce 0 is an error: EIP-7997 requires a nonzero nonce, and the -/// matching-code path does not rewrite one. -#[test] -fn test_matching_factory_code_at_nonce_zero_is_an_error() { - let mut db = MemoryDatabase::default(); - db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); - db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 0); - let factory = &system_contract_specs(&config())[6]; - assert!(factory.require_nonzero_nonce); - - let error = transact_deploy(&mut db, factory).expect_err("nonce 0 is invalid for the factory"); - match error { - SystemContractDeployError::ZeroFactoryNonce { address } => { - assert_eq!(address, CREATE2_FACTORY_ADDRESS); - } - other => panic!("expected ZeroFactoryNonce, got {other}"), - } - assert!(error.to_string().contains("nonce 0")); -} - -/// Matching factory code at nonce 7 is accepted as it is: the helper does not rewrite a valid -/// existing nonce down to 1. -#[test] -fn test_matching_factory_code_keeps_a_nonce_greater_than_one() { - let mut db = MemoryDatabase::default(); - db.set_account_code(CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE); - db.set_account_nonce(CREATE2_FACTORY_ADDRESS, 7); - let factory = &system_contract_specs(&config())[6]; - - let state = transact_deploy(&mut db, factory).expect("nonce 7 is a valid factory"); - let account = state.get(&CREATE2_FACTORY_ADDRESS).unwrap(); - assert!(!account.is_touched()); - assert!(!account.is_created()); - assert_eq!(account.info.nonce, 7); - assert_eq!(account.info.code_hash, CREATE2_FACTORY_CODE_HASH); -} - -/// The six `MegaETH` contracts are not EIP-7997: matching code at nonce 0 is a read-only entry, -/// not an error. Rewriting the nonce would be a state change the matching-code path exists to -/// avoid. -#[test] -fn test_matching_megaeth_code_at_nonce_zero_is_accepted() { - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); - db.set_account_nonce(ORACLE_CONTRACT_ADDRESS, 0); - - let state = - transact_deploy(&mut db, &oracle_spec()).expect("MegaETH contracts are not EIP-7997"); - let account = state.get(&ORACLE_CONTRACT_ADDRESS).unwrap(); - assert!(!account.is_touched()); - assert_eq!(account.info.nonce, 0); -} - -/// An account that exists with empty code and nonce 0 (an EOA that received value) is a fresh -/// deploy: the balance is kept, the slots are seeded, and marking the account created clears -/// any storage it had. That is the accepted bootstrap path. -#[test] -fn test_an_empty_account_at_the_address_is_a_fresh_deploy() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1_000)); - - let spec = system_contract_specs(&config()) - .into_iter() - .find(|spec| spec.address == SEQUENCER_REGISTRY_ADDRESS) - .unwrap(); - let state = transact_deploy(&mut db, &spec).expect("empty code is a fresh deploy"); - let account = state.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created(), "the bootstrap path marks created, which clears storage"); - assert_eq!(account.info.balance, U256::from(1_000)); - assert_eq!(account.info.nonce, 1); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(account.storage.len(), 7); -} - -/// An empty-code account with nonce 42 is a used account, not a prefunded EOA: refusing it -/// avoids resetting the nonce and dropping storage under a `created` mark. -#[test] -fn test_an_empty_account_with_a_used_nonce_is_an_error() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1_000)); - db.set_account_nonce(SEQUENCER_REGISTRY_ADDRESS, 42); - - let spec = system_contract_specs(&config()) - .into_iter() - .find(|spec| spec.address == SEQUENCER_REGISTRY_ADDRESS) - .unwrap(); - let error = transact_deploy(&mut db, &spec).expect_err("a used empty account must fail"); - match error { - SystemContractDeployError::UsedEmptyAccount { address, nonce } => { - assert_eq!(address, SEQUENCER_REGISTRY_ADDRESS); - assert_eq!(nonce, 42); - } - other => panic!("expected UsedEmptyAccount, got {other}"), - } - assert!(error.to_string().contains("nonce 42")); -} - -/// Zero addresses in the registry config fail at load, not at the first block. -#[test] -fn test_registry_config_rejects_a_zero_address() { - let mut config = config(); - config.initial_system_address = Address::ZERO; - let err = config.validate().expect_err("zero system address"); - assert!(err.message.contains("initial_system_address must not be zero")); - - config = self::config(); - config.initial_sequencer = Address::ZERO; - let err = config.validate().expect_err("zero sequencer"); - assert!(err.message.contains("initial_sequencer must not be zero")); - - config = self::config(); - config.initial_admin = Address::ZERO; - let err = config.validate().expect_err("zero admin"); - assert!(err.message.contains("initial_admin must not be zero")); - - config = self::config(); - config.min_rotation_delay = 0; - let err = config.validate().expect_err("zero min rotation delay"); - assert!(err.message.contains("min_rotation_delay must not be zero")); -} - -/// The seeded current-system-address slot is slot 0, which is the slot a later rotation read -/// consults. -#[test] -fn test_the_seeded_system_address_slot_is_the_current_one() { - assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::ZERO); -} - -/// A failed account load is [`SystemContractDeployError::Database`], and that inner error is -/// the `source` of the deploy error. -#[test] -fn test_a_database_error_is_the_source_of_the_deploy_error() { - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(ORACLE_CONTRACT_ADDRESS); - let err = transact_deploy(&mut db, &oracle_spec()).expect_err("the load fails"); - match &err { - SystemContractDeployError::Database(_) => {} - other => panic!("expected Database, got {other}"), - } - assert!( - core::error::Error::source(&err).is_some(), - "the database error is the source of the deploy error" - ); -} diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index bcb331e23..0817418b4 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -149,16 +149,17 @@ fn test_a_failed_deployment_gives_the_created_account_back() { } /// 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, 32,000, and EIP-3860's 2 gas per word of +/// 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 itself spends nothing, and every other charge of the call is -/// state and history gas. +/// 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), 32_000 + 2); - assert_eq!(create_regular(33), 32_000 + 4); - assert_eq!(create_regular(MAX_INITCODE_SIZE), 32_000 + 65_536); - let state = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_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 @@ -174,12 +175,8 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { 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, 2 * record(), "{len} bytes at {gas_limit}"); - assert_eq!( - total, - regular_expected + state + 2 * record(), - "{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}"); } } } @@ -287,17 +284,32 @@ fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { /// 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 deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); - for gas_limit in GAS_LIMITS { + 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; - let outcome = MegaEvm::new(context(system_db())) - .execute_transaction(tx) - .expect("a valid transaction"); + 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); @@ -305,4 +317,31 @@ fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { 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 index 548680449..2fd93df66 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -1,7 +1,7 @@ //! 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, B256}; +use alloy_primitives::{address, hex, B256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ system::{ @@ -21,7 +21,8 @@ use mega_evm::{ use revm::{ bytecode::opcode::{ CALL, CREATE, DELEGATECALL, GAS, GASPRICE, INVALID, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, - ORIGIN, POP, PUSH0, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + ORIGIN, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SHR, SSTORE, + STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -111,30 +112,6 @@ fn test_a_deployment_survives_a_commit() { } } -/// A successful deployment spends the signer's nonce, from 0 to 1. -#[test] -fn test_keyless_deploy_increments_nonce_from_zero() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&runtime(1))); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - -/// A signer at nonce 1 still deploys at its Nick's-Method address, which is its first creation's -/// and not its nonce's, and stays at nonce 1: the creation's bump from 1 is taken back. -#[test] -fn test_a_signer_at_nonce_one_deploys_at_the_same_address() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&runtime(1))); - let db = system_db().account_nonce(deployment.signer, 1); - let outcome = deploy(db, &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 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] @@ -234,6 +211,104 @@ fn test_keyless_deploy_empty_initcode() { } } +/// 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] @@ -431,10 +506,10 @@ fn test_keyless_deploy_emits_logs() { } } -/// Init code that logs and deploys nothing keeps its log: the call reports `EmptyCodeDeployed` -/// and the receipt carries the log, because the creation succeeded — it just left no code. +/// 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_its_logs() { +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() @@ -448,10 +523,7 @@ fn test_an_empty_code_deployment_keeps_its_logs() { let deployment = Deployment::new(init_code); let outcome = deploy(system_db(), &deployment, gas_limit); assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - let logs = outcome.result.logs(); - assert_eq!(logs.len(), 1); - assert_eq!(logs[0].topics(), [topic]); - assert_eq!(logs[0].data.data, Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef])); + assert!(outcome.result.logs().is_empty()); assert_eq!(nonce(&outcome, deployment.signer), 1); } } @@ -575,12 +647,24 @@ fn test_keyless_deploy_not_intercepted_for_inner_calls() { } /// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: -/// not dispatched. The outer deployment deploys; the inner one does not. +/// 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) @@ -592,13 +676,27 @@ fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { .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 status = - outcome.state[&outer.address].storage.get(&U256::ZERO).map(|slot| slot.present_value); - assert_eq!(status, Some(U256::ZERO), "the inner call failed"); + 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); } @@ -697,42 +795,6 @@ fn test_a_retry_does_not_pay_for_the_signer_again() { } } -/// A deployment that fails at run time spends the signer's nonce and pays for its account, as a -/// successful one does. -#[test] -fn test_a_deployment_that_fails_still_spends_the_nonce_and_pays_for_the_signer() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!(nonce(&outcome, deployment.signer), 1); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); - } -} - -/// A successful deployment spends the nonce too, and pays for the signer's account, the -/// contract's account and its code. -#[test] -fn test_a_deployment_that_succeeds_spends_the_nonce_and_pays_for_three_accounts() { - 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()); - assert_eq!(returned(&outcome).deployedAddress, CREATE2_FACTORY_CONTRACT); - assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 1); - let code_len = outcome.state[&CREATE2_FACTORY_CONTRACT] - .info - .code - .as_ref() - .map_or(0, |code| code.original_bytes().len()); - assert_eq!( - outcome.gas.state, - entry(GasId::new_account_state_gas()) + - entry(GasId::create_state_gas()) + - satin_gas_params().code_deposit_state_gas(code_len), - ); - } -} - /// 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] @@ -822,26 +884,6 @@ fn test_a_deployment_carrying_value_logs_the_move() { } } -/// A `keylessDeploy` call carrying value is refused before anything moves: it logs nothing and -/// counts what a transaction carrying the same calldata to an account with no code counts, its -/// body alone. -#[test] -fn test_a_call_carrying_value_moves_and_logs_nothing() { - let deployment = Deployment::new(deploying(&runtime(1))); - for gas_limit in GAS_LIMITS { - let mut tx = - call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::from(1)); - tx.0.base.gas_limit = gas_limit; - let refused = MegaEvm::new(context(system_db())) - .execute_transaction(tx) - .expect("a valid transaction"); - assert_eq!(refusal(&refused), KeylessDeployError::NoEtherTransfer); - assert!(refused.result.logs().is_empty()); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - assert_eq!(refused.usage, reference.usage, "the body alone, at {gas_limit}"); - } -} - /// 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 diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index c4c9d005e..f6afb2d1f 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -4,9 +4,10 @@ //! 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, a crossing stops the transaction with the deployment taken back -//! whole, and the control contracts and the Oracle answer its constructor as they answer any -//! frame. +//! 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`]). @@ -30,14 +31,13 @@ use revm::{ STOP, SUB, SWAP1, TIMESTAMP, }, context::{BlockEnv, TxEnv}, - context_interface::cfg::GasId, interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, primitives::KECCAK_EMPTY, Inspector, }; use super::*; -use crate::common::{call_tx, context, state_is_free, CALLER as RELAYER}; +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"); @@ -45,13 +45,6 @@ const BENEFICIARY: Address = address!("0x0000000000000000000000000000000000beef0 /// The cap a read of the block environment sets, by default. const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; -/// What a transaction did, and what gas detention made of it. -struct Run { - outcome: MegaTransactionOutcome, - limit: Option, - accessed: VolatileDataAccess, -} - /// 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) @@ -66,13 +59,6 @@ fn context_in( context(db).with_block(BlockEnv { beneficiary, ..block() }).with_tx_runtime_limits(limits) } -/// The `keylessDeploy` transaction `data` from the relayer at `gas_limit`. -fn keyless_tx(data: Bytes, gas_limit: u64) -> MegaTransaction { - let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); - tx.0.base.gas_limit = gas_limit; - tx -} - /// Runs `tx` in `ctx`, through an inspector when `inspected`. fn run_tx( ctx: MegaContext, @@ -198,6 +184,31 @@ fn refused_read(outcome: &MegaTransactionOutcome) -> VolatileDataAccess { 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 @@ -240,9 +251,9 @@ fn test_a_signer_that_is_the_beneficiary_detains_its_deployment() { /// 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 reverts -/// with the stop, and the deployment is taken back whole. Plain and inspected, below and above the -/// execution cap. +/// 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); @@ -264,7 +275,7 @@ fn test_a_constructor_that_reads_volatile_data_is_held_to_the_cap() { // 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_stopped(&stopped, &reads, gas_limit, left); + 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); } @@ -273,7 +284,8 @@ fn test_a_constructor_that_reads_volatile_data_is_held_to_the_cap() { /// 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 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); @@ -293,7 +305,7 @@ fn test_a_sender_that_is_the_beneficiary_holds_the_whole_deployment_to_the_cap() 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_stopped(&short, &deployment, gas_limit, 6 - 1); + assert_creation_stopped(&short, &deployment, gas_limit, 6 - 1); } } @@ -371,28 +383,6 @@ fn test_a_constructor_that_switches_volatile_access_off_is_refused_its_own_read( } } -/// Records every answer `remainingComputeGas()` gives, next to the spendable regular gas its -/// caller resumes with: what a regular charge of the caller could draw at its next instruction. -#[derive(Debug, Default)] -struct AnswerAndResume { - pending: Option, - 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::()); - } - } -} - /// `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 @@ -435,6 +425,54 @@ fn test_remaining_compute_gas_answers_a_constructor_its_allowance() { } } +/// 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 @@ -471,7 +509,7 @@ fn reads_the_oracle(rounds: u16) -> Bytes { /// 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 deployment is taken back whole. +/// 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)); @@ -518,7 +556,7 @@ fn test_a_constructor_reads_the_oracle_as_any_frame_does() { 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_stopped(&stopped, &deployment, gas_limit, left); + assert_creation_stopped(&stopped, &deployment, gas_limit, left); assert_eq!(stopped.accessed, VolatileDataAccess::ORACLE); } } @@ -622,30 +660,27 @@ fn test_a_failed_deployment_keeps_the_reads_its_creation_made() { } /// 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 state-gas limit has no -/// room for stops the transaction on state growth, not on compute. +/// 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() { - // A deployment that adds no state gas has no state-gas limit to cross. - if state_is_free() { - return; - } let prefix = BytecodeBuilder::default().append_many([TIMESTAMP, POP]).sstore(U256::ZERO, U256::ONE); let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); - let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); - let limit = upfront + entry(GasId::sstore_set_state_gas()) - 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_state_gas_limit(limit)); - let ExecutionResult::Revert { output, .. } = &run.outcome.result else { - panic!("expected the state-gas stop, got {:?}", run.outcome.result); + 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::StateGrowth.as_u8(), limit }, + 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), 0, "the deployment is taken back"); + 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 index 88b424e7c..a0fff80aa 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -5,16 +5,19 @@ //! the stop, what gas detention made of the transaction, and every event the inspector saw with //! the journal depth it saw it at. //! -//! The record is the way to hold a change to the engine's frame lifecycle to what it changes: -//! when `MEGA_KEYLESS_RECORD` names a file, the record is written there, and the records of two -//! builds can be compared line by line. The test itself holds every scenario's recorded run to its -//! plain one, on everything but the events. +//! 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 -//! latched body; a system call; and the calls that are not dispatched. Each at a gas limit below +//! 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 _; @@ -34,8 +37,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLER, CREATE, GAS, INVALID, LOG0, POP, PUSH0, REVERT, SELFDESTRUCT, STATICCALL, - STOP, TIMESTAMP, + CALL, CALLER, CREATE, GAS, INVALID, POP, PUSH0, REVERT, SELFDESTRUCT, STATICCALL, STOP, + TIMESTAMP, }, context::{BlockEnv, CfgEnv, ContextTr, JournalTr}, interpreter::{ @@ -47,17 +50,19 @@ use revm::{ }; use super::{detention::reads_then_burns, *}; -use crate::common::{context, state_is_free, CALLER as RELAYER}; +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, and the record is -/// written where `MEGA_KEYLESS_RECORD` says. +/// 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!( @@ -77,10 +82,24 @@ fn test_keyless_differential_record() { 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"); + 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 ---------- */ @@ -255,13 +274,6 @@ impl Mode { } } -/// Init code that logs `len` bytes of data and deploys a one-byte runtime. -fn logging(len: u64) -> Bytes { - let prefix = - BytecodeBuilder::default().push_number(len).push_number(0_u64).append(LOG0).build_vec(); - constructor(&prefix, &runtime(1)) -} - /// 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(); @@ -528,7 +540,6 @@ 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; - let slot = Deployment::new(filling_a_slot()); 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); @@ -541,22 +552,6 @@ fn scenarios() -> Vec { ) .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 80 + 100)), ); - let signer = if nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; - let used = - signer + entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()); - // A deployment that adds no state gas, where a state byte is free, crosses no - // state-gas limit. - if !state_is_free() { - all.push( - Scenario::deploying( - format!("limit: state gas, nonce {nonce}"), - db(&slot), - &slot, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(used - 1)), - ); - } all.push( Scenario::deploying( format!("limit: compute, nonce {nonce}"), @@ -586,24 +581,6 @@ fn scenarios() -> Vec { ) .limits(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39)), ); - all.push( - Scenario::deploying( - format!("limit: tx KV, nonce {nonce}"), - db(&slot), - &slot, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2)), - ); - all.push( - Scenario::deploying( - format!("limit: frame KV, nonce {nonce}"), - db(&slot), - &slot, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(3)), - ); all.push( Scenario::deploying( format!("limit: the creation's start, nonce {nonce}"), @@ -613,21 +590,9 @@ fn scenarios() -> Vec { ) .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 40)), ); - let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); - if !state_is_free() { - all.push( - Scenario::deploying( - format!("limit: upfront state gas, nonce {nonce}"), - db(&small), - &small, - gas_limit, - ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1)), - ); - } } all.push( - Scenario::deploying("limit: a latched body", system_db(), &small, gas_limit) + 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( diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index d9d232e3c..554ac26eb 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -3,8 +3,10 @@ //! 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, MegaTransaction, + system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, LimitKind, + MegaLimitExceeded, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{LOG0, PUSH0, REVERT}, @@ -13,12 +15,13 @@ use revm::{ 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, CALLER}; +use crate::common::{context, keyless_tx, CALLER}; /// What an inspector was told, in order. #[derive(Debug, Clone, PartialEq, Eq)] @@ -85,17 +88,12 @@ impl Inspector, EthInterpreter> for Recorder { } } -/// The `keylessDeploy` transaction of `deployment` at `gas_limit`. -fn keyless_tx(deployment: &Deployment, gas_limit: u64) -> MegaTransaction { - let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); - tx.0.base.gas_limit = gas_limit; - tx -} - /// 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, gas_limit)).expect("valid"); + 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, @@ -149,19 +147,6 @@ fn test_the_inspector_sees_the_call_and_the_creation_it_starts() { } } -/// The traced run and the plain run agree to the gas. -#[test] -fn test_an_inspected_deployment_costs_what_a_plain_one_does() { - let deployment = Deployment::new(deploying(&runtime(3))); - for gas_limit in GAS_LIMITS { - let (inspected, _) = inspect(&deployment, Recorder::default(), gas_limit); - let plain = deploy(system_db(), &deployment, gas_limit); - assert_eq!(inspected.result, plain.result, "at {gas_limit}"); - assert_eq!(inspected.gas, plain.gas); - assert_eq!(inspected.usage, plain.usage); - } -} - /// A call the rules refuse is reported as the call it is, its start and end paired around the /// refusal; no creation starts. #[test] @@ -232,22 +217,21 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { } } -/// A transaction the latch stopped before its first frame is not dispatched on the inspected path -/// either: the inspector sees the call and its stop, and no creation. +/// 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_latched_transaction_is_seen_as_the_call_it_is() { +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 outcome = evm.execute_transaction(keyless_tx(&deployment, gas_limit)).expect("valid"); - assert!(outcome.limit_exceeded.is_some(), "at {gas_limit}"); - assert_eq!( - evm.inspector().events, - [Event::Call(KEYLESS_DEPLOY_ADDRESS), Event::CallEnd(InstructionResult::Revert)], - ); - assert!(!outcome.state.contains_key(&deployment.signer)); + 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}"); } } @@ -264,7 +248,9 @@ fn test_a_tracer_sees_the_call_and_the_creation_it_starts() { 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, gas_limit)).expect("valid"); + 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(); @@ -336,3 +322,99 @@ fn test_a_tracer_sees_the_call_and_the_creation_it_starts() { 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 index d1a7c7837..90a8b9a40 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -1,16 +1,17 @@ //! 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 and KV budgets, the transaction's limits, -//! the state-gas limit. A frame budget reverts the creation alone, and the call answers -//! `ExecutionReverted` with the stop's revert data, the signer's nonce spent. A transaction limit -//! stops the transaction: the call reverts with the stop and 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. +//! 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 stop is pinned as a column of the matrix: every transaction-level 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 rewrites every frame result into a success. +//! 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 @@ -22,11 +23,12 @@ use mega_evm::{ LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{LOG0, PUSH0, REVERT, TIMESTAMP}, + bytecode::opcode::{PUSH0, REVERT, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, }, + primitives::KECCAK_EMPTY, Database, Inspector, }; @@ -34,17 +36,7 @@ use super::{ detention::{crossing_left, reads_then_burns}, *, }; -use crate::common::{context, state_is_free}; - -/// Init code that logs `len` bytes of data and deploys a one-byte runtime. -fn logging(len: u64) -> Bytes { - let prefix = mega_evm::test_utils::BytecodeBuilder::default() - .push_number(len) - .push_number(0_u64) - .append(LOG0) - .build_vec(); - constructor(&prefix, &runtime(1)) -} +use crate::common::context; /// Init code that fills a fresh slot and deploys a one-byte runtime. fn filling_a_slot() -> Bytes { @@ -120,58 +112,6 @@ fn assert_nothing_kept( } } -/// A transaction whose body alone crosses its data-size limit is stopped before its first frame, -/// and that frame is not a deployment: the call is answered with the stop, and no rule reads the -/// signer. -#[test] -fn test_a_transaction_latched_by_its_body_deploys_nothing() { - let deployment = Deployment::new(deploying(&runtime(1))); - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100), - ); - assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit: 100 }, "at {gas_limit}"); - assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); - let [total, ..] = - beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!(total, 0, "not even the overhead is charged"); - } -} - -/// A log that crosses the transaction's data-size limit stops the transaction. The limit holds the -/// body, the two records of the creation's start and 100 bytes more, so the body passes and the -/// creation starts, and the constructor's `LOG0` of 2,000 bytes is what crosses: the stop reports -/// the body, the two records and the whole log as used, the call reverts with the stop, and the -/// deployment is taken back whole. -#[test] -fn test_a_deployment_crossing_the_transaction_data_size_limit_stops_it() { - let deployment = Deployment::new(logging(2_000)); - let start = body_bytes(&deployment) + 2 * WRITE_RECORD_SIZE; - let limit = start + 100; - let used = start + LOG_BASE_SIZE + 2_000; - 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, - frame_local: false - }), - "at {gas_limit}: the constructor's log crosses" - ); - assert_stopped_whole(&outcome, &deployment, gas_limit); - } -} - /// 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. @@ -193,9 +133,11 @@ 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 deployment before its init code runs. +/// 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_transaction() { +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 { @@ -204,14 +146,24 @@ fn test_the_creations_start_crossing_the_limit_stops_the_transaction() { gas_limit, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); - assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit }); - assert_stopped_whole(&outcome, &deployment, gas_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 transaction is not latched. +/// 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))); @@ -222,7 +174,16 @@ fn test_the_signers_record_can_put_the_call_over_its_budget() { EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39), ); assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); - assert_eq!(outcome.limit_exceeded, None, "a budget, not the transaction's limit"); + 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); } } @@ -248,130 +209,14 @@ fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { } } -/// A transaction KV limit reaches the creation as its share: 98% of what the call has left, -/// rounded down. A limit of two leaves the creation one, and the two records its start makes cross -/// it: the creation is stopped before its init code runs, alone, and the signer's nonce is spent. -/// Records come one at a time, so inside the creation its share always binds before the -/// transaction's limit does. -#[test] -fn test_a_kv_limit_below_the_creations_start_stops_the_creation_at_its_start() { - let deployment = Deployment::new(filling_a_slot()); - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2), - ); - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); - let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { - unreachable!() - }; - assert_eq!(gas_used, 0, "the init code never ran"); - assert_eq!(outcome.limit_exceeded, None); - assert_eq!(nonce(&outcome, deployment.signer), 1, "a stopped creation spends the nonce"); - assert_eq!(outcome.usage.write_records, 1); - } -} - -/// And a KV budget of three gives the creation two records — its start's — so the slot it fills -/// reverts it alone. -#[test] -fn test_a_deployment_crossing_its_kv_budget_reverts_alone() { - let deployment = Deployment::new(filling_a_slot()); - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_frame_kv_update_limit(3), - ); - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 2 }); - assert_eq!(outcome.limit_exceeded, None); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - -/// The state gas of the creation's start — the signer's account and the created account — is held -/// once the creation is built, as a `CREATE`'s upfront charge is: a limit below it stops the -/// transaction before the init code runs. -#[test] -fn test_the_upfront_state_gas_is_held_to_the_state_gas_limit() { - // A deployment that adds no state gas has no state-gas limit to cross. - if state_is_free() { - return; - } - let deployment = Deployment::new(deploying(&runtime(1))); - let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(upfront - 1), - ); - assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit: upfront - 1 }); - assert_stopped_whole(&outcome, &deployment, gas_limit); - } -} - -/// A slot the constructor fills counts on top of the upfront state gas. -#[test] -fn test_a_deployment_crossing_the_state_gas_limit_stops_it() { - // A deployment that adds no state gas has no state-gas limit to cross. - if state_is_free() { - return; - } - let deployment = Deployment::new(filling_a_slot()); - let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); - let limit = upfront + entry(GasId::sstore_set_state_gas()) - 1; - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit), - ); - assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit }); - assert_stopped_whole(&outcome, &deployment, gas_limit); - } -} - -/// And so does the code it deposits: a limit one short of it stops the transaction before the -/// code is written. -#[test] -fn test_the_deposited_code_is_held_to_the_state_gas_limit() { - // A deployment that adds no state gas has no state-gas limit to cross. - if state_is_free() { - return; - } - let deployment = Deployment::new(deploying(&runtime(5))); - let limit = entry(GasId::new_account_state_gas()) + - entry(GasId::create_state_gas()) + - satin_gas_params().code_deposit_state_gas(5) - - 1; - for gas_limit in GAS_LIMITS { - let outcome = limited( - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit), - ); - assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 3, limit }); - assert_stopped_whole(&outcome, &deployment, 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()); - let upfront = entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()); // The creation gets 98% of what the call has left, rounded down: room for its three records - // and its byte of code, and 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) - .with_tx_kv_update_limit(4) - .with_tx_state_gas_limit( - upfront + - entry(GasId::sstore_set_state_gas()) + - satin_gas_params().code_deposit_state_gas(1), - ); + .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}"); @@ -483,13 +328,11 @@ fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { /* ---------- the stop, as a column of the matrix ---------- */ -/// A transaction-level limit a deployment's creation crosses. +/// 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 slot the constructor fills crosses the state-gas limit. - StateGas, /// The constructor reads the block's timestamp, then computes past the cap. Compute, } @@ -498,21 +341,20 @@ enum Crossing { const COMPUTE_CAP: u64 = 1_000; impl Crossing { - const ALL: [Self; 3] = [Self::DataSize, Self::StateGas, Self::Compute]; + 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::StateGas => filling_a_slot(), Self::Compute => reads_then_burns(TIMESTAMP, 1_000), } } - /// The limits under which a deployment of `deployment`, by a signer at `signer_nonce`, - /// crosses the limit, with the stop it reports: its kind, its limit, and what it counts as + /// 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, signer_nonce: u64) -> (EvmTxRuntimeLimits, Crossed) { + fn limits(self, deployment: &Deployment) -> (EvmTxRuntimeLimits, Crossed) { let limits = EvmTxRuntimeLimits::no_limits(); match self { Self::DataSize => { @@ -526,18 +368,6 @@ impl Crossing { Crossed::new(LimitKind::DataSize, limit, used), ) } - Self::StateGas => { - // The signer's account when the bump creates it, the created account, and the - // slot, which crosses a limit one gas short of it. - let signer = - if signer_nonce == 0 { entry(GasId::new_account_state_gas()) } else { 0 }; - let used = signer + - entry(GasId::create_state_gas()) + - entry(GasId::sstore_set_state_gas()); - let limit = used - 1; - let stop = Crossed::new(LimitKind::StateGrowth, limit, used); - (limits.with_tx_state_gas_limit(limit), stop) - } 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 @@ -566,50 +396,33 @@ impl Crossed { const fn new(kind: LimitKind, limit: u64, used: u64) -> Self { Self { kind, limit, used } } - - /// The limit check the transaction's outcome reports for the stop. - const fn check(self) -> LimitCheck { - LimitCheck::ExceedsLimit { - kind: self.kind, - limit: self.limit, - used: self.used, - frame_local: false, - } - } } -/// Records the result of every frame it sees end, then rewrites it into a success with no output -/// — a creation's too, whose address it revives: a tool's inspector the stop must see through. +/// Records the result of every frame it sees end, and rewrites nothing. #[derive(Default)] -struct Rewriter { - /// The frames that ended, deepest first: whether each was a creation, and its result before - /// the rewrite. +struct Recorder { + /// The frames that ended, deepest first: whether each was a creation, and its result. ended: Vec<(bool, InstructionResult)>, } -impl Inspector, EthInterpreter> for Rewriter { +impl Inspector, EthInterpreter> for Recorder { fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { self.ended.push((false, outcome.result.result)); - outcome.result.result = InstructionResult::Stop; - outcome.result.output = Bytes::new(); } fn create_end( &mut self, _: &mut MegaContext, - inputs: &CreateInputs, + _: &CreateInputs, outcome: &mut CreateOutcome, ) { self.ended.push((true, outcome.result.result)); - outcome.result.result = InstructionResult::Return; - outcome.result.output = Bytes::new(); - outcome.address = Some(inputs.created_address(1)); } } /// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit` under `limits`, without an -/// inspector and under a [`Rewriter`]: both outcomes, and the frames the rewriter saw end. -fn plain_and_rewritten( +/// 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, @@ -619,36 +432,32 @@ fn plain_and_rewritten( 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(Rewriter::default()); - let rewritten = evm.execute_transaction(tx).expect("the transaction is valid"); + .with_inspector(Recorder::default()); + let recorded = evm.execute_transaction(tx).expect("the transaction is valid"); let ended = evm.inspector().ended.clone(); - (plain, rewritten, ended) + (plain, recorded, ended) } -/// The stop, as a column of the matrix: each transaction-level limit a deployment's creation can -/// cross — data size, state gas, 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 rewrites every frame result into a success and revives the creation. +/// 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. /// -/// Every run reverts with the stop, and the stop counts as used what the constructor's crossing -/// brings the transaction to: the body, the start's two records and the whole log; the accounts -/// the deployment adds and the slot; the compute up to the limit. So the crossing is the -/// constructor's, not the creation's start or the call's charges. Every run keeps nothing of the -/// deployment: the signer's nonce is where it was, neither spent from 0 nor left at 2 from 1; no -/// code, no record, and no state or history gas beyond the transaction's body; above the cap the -/// reservoir comes back. 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. The -/// inspector sees the creation end with the stop, then the call, and changes nothing the -/// transaction reports. +/// 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() { - // A deployment that adds no state gas, where a state byte is free, crosses no state-gas limit. - let free = state_is_free(); - for crossing in Crossing::ALL.into_iter().filter(|c| !(free && matches!(c, Crossing::StateGas))) - { + for crossing in Crossing::ALL { let deployment = Deployment::new(crossing.init_code()); for signer_nonce in [0, 1] { - let (limits, expected) = crossing.limits(&deployment, signer_nonce); + let (limits, expected) = crossing.limits(&deployment); let Crossed { kind, limit, used } = expected; let db = match signer_nonce { 0 => system_db(), @@ -656,36 +465,39 @@ fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { }; for gas_limit in GAS_LIMITS { let row = format!("{crossing:?}, signer at {signer_nonce}, gas limit {gas_limit}"); - let (plain, rewritten, ended) = - plain_and_rewritten(db.clone(), &deployment, gas_limit, limits); - for (column, outcome) in [("plain", &plain), ("rewritten", &rewritten)] { + 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!( - stop(outcome), + creation_stop(outcome), MegaLimitExceeded { kind: kind.as_u8(), limit }, "{cell}" ); - assert_eq!( - outcome.limit_exceeded, - Some(expected.check()), - "{cell}: the constructor crosses" + 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" ); - assert_nothing_kept(outcome, &deployment, gas_limit, signer_nonce, &cell); 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::Revert)], - "{row}: the creation, then the call, each ended with the stop", + [(true, InstructionResult::Revert), (false, InstructionResult::Return)], + "{row}: the creation ended with the stop, then the call returned its answer", ); - assert_eq!(rewritten.result_and_state, plain.result_and_state, "{row}"); - assert_eq!(rewritten.gas, plain.gas, "{row}"); - assert_eq!(rewritten.usage, plain.usage, "{row}"); - assert_eq!(rewritten.limit_exceeded, plain.limit_exceeded, "{row}"); + 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}"); } } } @@ -711,76 +523,3 @@ fn test_a_deployment_is_counted_but_not_stopped_under_the_exemption() { let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()).unwrap(); assert_eq!(ret.deployedAddress, deployment.address); } - -use revm::primitives::KECCAK_EMPTY; - -/// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit` under `limits`, with the -/// signer's SALT bucket at `m_signer` times the minimum and the deploy address's at `m_address`. -fn crowded_run( - db: MemoryDatabase, - deployment: &Deployment, - gas_limit: u64, - limits: EvmTxRuntimeLimits, - (m_signer, m_address): (u64, u64), -) -> Outcome { - let envs = crowded(TestExternalEnvs::new(), deployment.signer, m_signer); - let envs = crowded(envs, deployment.address, m_address); - 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()) - .with_tx_runtime_limits(limits); - 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 state-gas limit holds each upfront charge of a deployment once, at the price its bucket -/// sets: the signer's account the call pays for, and the created account the creation's start -/// holds, as the frame-start hold holds any `CREATE`'s. With the signer's bucket at twice the -/// minimum and the deploy address's at four times, a deployment holds `2 ×` the new account, `4 ×` -/// the created account and `4 ×` its deposited byte. A limit of exactly that deploys, as without a -/// limit; one gas less stops the transaction. A signer that has an account pays for none, and the -/// limit that holds the rest deploys it. -#[test] -fn test_the_upfront_charges_are_held_once_at_their_bucket_prices() { - // A deployment that adds no state gas has no state-gas limit to cross. - if state_is_free() { - return; - } - let deployment = Deployment::new(deploying(&runtime(1))); - assert_ne!(bucket(deployment.signer), bucket(deployment.address)); - let created = entry(GasId::create_state_gas()) + satin_gas_params().code_deposit_state_gas(1); - let held = 2 * entry(GasId::new_account_state_gas()) + 4 * created; - let limited = |db: MemoryDatabase, gas_limit, limit| { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_gas_limit(limit); - crowded_run(db, &deployment, gas_limit, limits, (2, 4)) - }; - for gas_limit in GAS_LIMITS { - let unlimited = crowded_run( - system_db(), - &deployment, - gas_limit, - EvmTxRuntimeLimits::no_limits(), - (2, 4), - ); - assert_eq!(unlimited.gas.state, held, "at {gas_limit}"); - - let exact = limited(system_db(), gas_limit, held); - assert_eq!(returned(&exact).deployedAddress, deployment.address, "at {gas_limit}"); - assert_eq!(exact.gas, unlimited.gas); - let short = limited(system_db(), gas_limit, held - 1); - assert_eq!(stop(&short), MegaLimitExceeded { kind: 3, limit: held - 1 }); - assert_stopped_whole(&short, &deployment, gas_limit); - - let funded = db_for(&deployment, U256::from(1)); - let exact = limited(funded.clone(), gas_limit, 4 * created); - assert_eq!(returned(&exact).deployedAddress, deployment.address, "at {gas_limit}"); - assert_eq!(exact.gas.state, 4 * created); - let short = limited(funded, gas_limit, 4 * created - 1); - assert_eq!(stop(&short), MegaLimitExceeded { kind: 3, limit: 4 * created - 1 }); - } -} diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index 1e854e3bc..1c369b637 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -13,6 +13,7 @@ mod differential; mod dispatch; mod frame; mod inspector; +mod interface; mod limits; mod precedence; mod rules; @@ -27,8 +28,8 @@ use mega_evm::{ decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, }, test_utils::MemoryDatabase, - write_record_history_gas, BucketId, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, - MegaSpecId, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, + BucketId, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, + MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, }; use revm::{ bytecode::opcode::{CODECOPY, PUSH0, RETURN}, @@ -147,6 +148,15 @@ 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 { @@ -265,14 +275,23 @@ 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. +/// The history gas of one write record, `WRITE_RECORD_SIZE` bytes, by hand. pub(crate) fn record() -> u64 { - write_record_history_gas(1).expect("a record has a price") + history(mega_evm::WRITE_RECORD_SIZE) } -/// The history gas of `bytes` bytes. +/// The history gas of `bytes` bytes, by hand. pub(crate) fn history(bytes: u64) -> u64 { - mega_evm::history_gas(bytes).expect("a byte count has a price") + 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`. diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 4578bd339..46db0ffa9 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -339,3 +339,43 @@ fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { ]; 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 index 43ddd429e..52a5b414a 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -69,23 +69,6 @@ fn small() -> Deployment { Deployment::new(deploying(&runtime(1))) } -/// Rule 1: the call carries no value. A deployment is made by its signer, and the contract holds -/// no balance. -#[test] -fn test_keyless_deploy_rejects_ether_transfer() { - let deployment = small(); - for gas_limit in GAS_LIMITS { - let mut tx = - call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ONE); - 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), KeylessDeployError::NoEtherTransfer, "at {gas_limit}"); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. #[test] fn test_keyless_deploy_gas_limit_too_low() { @@ -437,31 +420,6 @@ fn test_keyless_deploy_signer_nonce_too_high() { } } -/// Rule 4 counts real nonces, and a deployment that fails takes its signer from 0 to 1 and no -/// further: a signer at nonce 1 stays there however often its deployment fails. -#[test] -fn test_a_signer_at_nonce_one_stays_there_however_often_it_fails() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - for gas_limit in GAS_LIMITS { - let mut db = system_db().account_nonce(deployment.signer, 1); - for attempt in 0..10 { - let outcome = run_nth( - db.clone(), - deployment.call_data(LARGE_OVERRIDE), - gas_limit, - EvmTxRuntimeLimits::no_limits(), - attempt, - ); - assert!( - matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. }), - "attempt {attempt} at {gas_limit}", - ); - assert_eq!(nonce(&outcome, deployment.signer), 1, "attempt {attempt} at {gas_limit}"); - db.commit(outcome.result_and_state.state); - } - } -} - /// 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 @@ -623,13 +581,14 @@ fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { /// 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. -/// The record stays only when a creation that deployed no code moved value out of the signer's -/// account: the record then stands for that write. A deployment that deployed no code keeps the -/// record of the account it created. +/// 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; - let kv_share_of_one = EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(2); + // 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", @@ -643,14 +602,19 @@ fn test_every_way_a_deployment_from_nonce_one_fails_leaves_the_nonce_at_one() { EvmTxRuntimeLimits::no_limits(), 0, ), - ("no code", Deployment::new(Bytes::new()), EvmTxRuntimeLimits::no_limits(), 1), + ("no code", Deployment::new(Bytes::new()), EvmTxRuntimeLimits::no_limits(), 0), ( "no code carrying value", Deployment::with_value(Bytes::new(), one), EvmTxRuntimeLimits::no_limits(), - 2, + 0, + ), + ( + "stopped at its start", + Deployment::new(deploying(&runtime(1))), + a_share_short_of_the_start, + 0, ), - ("stopped at its start", Deployment::new(deploying(&runtime(1))), kv_share_of_one, 0), ]; for gas_limit in GAS_LIMITS { for (name, deployment, limits, records) in &cases { @@ -780,8 +744,9 @@ fn test_a_delegated_signer_deploys() { /// 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: 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. +/// 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"); @@ -792,7 +757,7 @@ fn test_nonces_a_delegated_signer_spends_in_its_deployment_stay_spent() { 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]), 4), + ("deploys nothing", with_suffix(&[STOP]), 1), ("reverts", with_suffix(&[PUSH0, PUSH0, REVERT]), 1), ]; for gas_limit in GAS_LIMITS { @@ -831,10 +796,12 @@ fn test_nonces_a_delegated_signer_spends_in_its_deployment_stay_spent() { ); } else { let error = failure(&again); - assert!( - matches!(error, KeylessDeployError::ExecutionReverted { .. }), - "{name}: resubmitted at {gas_limit}: {error:?}", - ); + 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"); @@ -912,7 +879,9 @@ fn test_a_delegated_signer_whose_creation_reverts_keeps_every_bump() { } } -/// Rule 5: the deploy address holds no code. +/// 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])); @@ -920,20 +889,10 @@ fn test_keyless_deploy_contract_already_exists() { 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); - } -} - -/// 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_deploy_address_in_witness_rex6() { - for gas_limit in GAS_LIMITS { - let db = - system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - let outcome = submit(db, CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); - assert!(outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT)); + assert!( + outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT), + "the occupancy read is in the witness, at {gas_limit}", + ); } } @@ -963,7 +922,7 @@ fn test_keyless_deploy_insufficient_balance_zero() { } } -/// A signer holding part of the value is refused too. +/// 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 { @@ -971,6 +930,7 @@ fn test_keyless_deploy_insufficient_balance_partial() { 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); } } @@ -1003,18 +963,6 @@ fn test_a_signer_with_nothing_deploys_what_carries_no_value() { } } -/// The value is real, so it must be funded. -#[test] -fn test_the_value_must_be_funded() { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1_000)); - for gas_limit in GAS_LIMITS { - let db = db_for(&deployment, U256::from(999)); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance, "at {gas_limit}"); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// 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. /// 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 9b8176197..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. @@ -45,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 12c331d16..51a97c9fa 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -4,11 +4,13 @@ mod access_control; mod common; mod control; -mod deploy; 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 7490f6aad..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); @@ -52,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, @@ -293,18 +295,21 @@ fn test_a_reverting_frame_does_not_take_the_hint_bytes_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); - // The body already counts the calldata. The hint counts it again, and that second copy is - // the byte that crosses. - let counted = top_level_hint(data.len() as u64); - let limit = counted - 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, U256::ZERO), @@ -313,17 +318,19 @@ 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.data_size, counted, - "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: counted, + used: reached, frame_local: false, }), + "the stop reports the usage the hint would have reached", ); assert_eq!( outcome.result.output().cloned().unwrap_or_default(), @@ -375,19 +382,9 @@ fn return_status(code: BytecodeBuilder) -> Bytes { code.append_many([PUSH0, MSTORE]).push_number(32_u8).append_many([PUSH0, RETURN]).build() } -/// Appends a `CALL` of `MegaAccessControl` with `selector`, discarding its status. -fn steer(code: BytecodeBuilder, selector: [u8; 4]) -> BytecodeBuilder { - use mega_evm::system::ACCESS_CONTROL_ADDRESS; - use revm::bytecode::opcode::POP; - code.mstore(0x0, selector) - .push_number(0_u8) - .push_number(0_u8) - .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]) +/// 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] = @@ -455,49 +452,10 @@ fn test_hints_reach_the_service_in_the_order_they_were_sent() { ); } -/// A transaction that sends value with its `sendHint` forwards nothing: the method is not payable, -/// so the transaction reverts in the bytecode, and its hint would be one it never sent. -#[test] -fn test_a_value_bearing_hint_transaction_forwards_nothing() { - let (result, hints, usage) = run_with_oracle( - system_db(), - call_tx(ORACLE_CONTRACT_ADDRESS, send_hint(b"paid"), U256::ONE), - ); - assert!(!result.result.is_success(), "{:?}", result.result); - assert!(hints.is_empty()); - assert_eq!( - usage.data_size, - mega_evm::TX_BODY_SIZE + send_hint(b"paid").len() as u64, - "the calldata alone: no hint was counted", - ); -} - -/// A hint sent with gas is forwarded, its payload whole, and the calldata of the call is counted -/// on the transaction. -#[test] -fn test_a_hint_with_gas_forwards_and_is_counted() { - let data = send_hint(&[0_u8; 128]); - let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 100_000)); - let (_, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert_eq!(hints.len(), 1); - assert_eq!(hints[0].data.len(), 128); - assert_eq!(usage.data_size, nested_hint(data.len() as u64)); -} - -/// A call of the Oracle with a selector that is not `sendHint` is not a hint, whatever it -/// carries: nothing is forwarded or counted. -#[test] -fn test_an_unknown_selector_to_the_oracle_counts_no_hint() { - let data: Vec = [0xde, 0xad, 0xbe, 0xef].into_iter().chain([0_u8; 256]).collect(); - let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); - let (_, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert!(hints.is_empty()); - assert_eq!(usage.data_size, nested_hint(0)); -} - /// 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. +/// 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 @@ -528,20 +486,15 @@ fn test_a_malformed_or_padded_hint_is_counted_whole() { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); assert!(hints.is_empty(), "a hint past the limit is not forwarded"); - assert_eq!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit, - used: nested_hint(total), - frame_local: false, - }), - ); + 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 stops the transaction. +/// 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; @@ -557,20 +510,22 @@ fn test_consecutive_hints_add_up_on_the_transaction() { EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); assert_eq!(hints.len(), 1, "the first hint was forwarded, the second was not"); - assert!(matches!( - outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }) - )); + 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 transaction with a revert carrying the stop, not a halt: the contract -/// never runs on to return its call's status, and the transaction is billed what ran rather than -/// its gas limit. +/// 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_transaction() { - use revm::context::result::ExecutionResult; - +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); @@ -581,29 +536,25 @@ fn test_data_size_overflow_blocks_forwarding_and_stops_the_transaction() { ); assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: LIMIT, - used: nested_hint(data.len() as u64), - frame_local: false, - }; - assert_eq!(outcome.limit_exceeded, Some(stop)); - assert!( - matches!(&outcome.result, ExecutionResult::Revert { output, .. } - if output == &stop.revert_data()), - "the stop, not the status: {:?}", - outcome.result + 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 up to its call, which the stop answered at the Oracle's - // start, handing back what it forwarded: the same code stopping after a call to an Oracle with - // no code, without limits, runs exactly that. + // 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(call().stop().build()).account_code(ORACLE_CONTRACT_ADDRESS, Bytes::new()), + 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"); } diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 00ec6f37e..728123a12 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -10,11 +10,13 @@ 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, ORACLE_CONTRACT_CODE}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + 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, VolatileDataAccess, + MegaTransactionOutcome, OracleEnv, OracleRead, VolatileDataAccess, }; use revm::{ bytecode::opcode::{ @@ -86,11 +88,13 @@ impl OracleEnv for Service { type Envs = (EmptyExternalEnv, Service); -/// What a transaction did, and what gas detention made of its reads. +/// 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`. @@ -109,7 +113,12 @@ fn run_under( 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() } + 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. @@ -418,6 +427,7 @@ fn test_a_read_the_frame_cannot_pay_for_asks_nothing() { "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()); } @@ -441,22 +451,127 @@ fn test_a_refused_read_asks_nothing() { 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()); } -/// The Oracle's own code answers `getSlot` from the service too: the read is the `SLOAD` in its -/// frame, whatever code runs there. +/// 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_deployed_oracle_reads_through_the_service() { - let service = Service::holding(SLOT, SERVICE_VALUE); - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); - let run = run(db, &service, call_tx(ORACLE_CONTRACT_ADDRESS, get_slot(SLOT), U256::ZERO)); +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!( - IOracle::getSlotCall::abi_decode_returns(run.outcome.result.output().unwrap()).unwrap(), - B256::from(SERVICE_VALUE), + 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 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 index cbd768b03..f20ffb471 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -7,24 +7,18 @@ //! 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_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +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::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionOutcome, }; -use revm::{ - bytecode::opcode::*, - context::{BlockEnv, TxEnv}, - interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, - Inspector, -}; +use revm::{bytecode::opcode::*, context::BlockEnv}; -use crate::common::{body_history, system_db, CALLER}; +use crate::common::{body_history, call_tx_with_gas, system_db, AnswerAndResume, CALLER}; const CONTRACT: Address = address!("0x0000000000000000000000000000000000300001"); const CONTRACT2: Address = address!("0x0000000000000000000000000000000000300002"); @@ -51,13 +45,7 @@ fn block(beneficiary: Address) -> BlockEnv { /// A transaction from [`CALLER`] to `to` with `data`, carrying `gas_limit`. fn tx(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() - })) + 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, @@ -370,28 +358,6 @@ fn test_a_childs_read_binds_its_callers_answer() { /* ---------- the answer is what the caller can spend when it resumes ---------- */ -/// Records every answer a query returns, next to the spendable regular gas its caller resumes -/// with: what a regular charge of the caller could draw at its next instruction. -#[derive(Debug, Default)] -struct AnswerAndResume { - pending: Option, - 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::()); - } - } -} - /// 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( diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 91030d477..84ab99255 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -1,32 +1,34 @@ //! 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, ErrorInjectingDatabase, GasInspector, MemoryDatabase}, - EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + 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::{ bytecode::opcode::{SLOAD, STOP}, context::{ - result::{EVMError, ExecutionResult}, + result::{EVMError, ExecutionResult, InvalidTransaction}, transaction::{AccessList, AccessListItem}, CfgEnv, TxEnv, }, - database::State, + database::{states::bundle_state::BundleRetention, State}, DatabaseCommit, }; use crate::common::{ - account_state_gas, block, body_history, context, state_is_free, system_db, CALLER, GAS_LIMIT, + account_state_gas, block, context, state_is_free, system_db, CALLER, GAS_LIMIT, }; /// The chain the tests run on. @@ -154,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!( @@ -191,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() { @@ -247,69 +241,77 @@ fn other_shapes(caller: Address) -> [(&'static str, MegaTransaction); 4] { ] } -/// A transaction from the system address that does not have the system shape — off the -/// whitelist, a creation, another type than legacy — is an ordinary transaction: it is not -/// promoted, so an empty system address cannot pay its fee, and a funded one pays its fee and -/// its history like any sender. +/// 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_another_shape_from_the_system_address_is_an_ordinary_transaction() { +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) { - let refused = rejection(db(), tx.clone()); - assert!(refused.contains("LackOfFundForMaxFee"), "{shape}: {refused}"); - - let mut evm = MegaEvm::new(chain_context( - db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS)), - )); - let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); - assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); - assert!(!evm.ctx().is_system_originated(), "{shape}"); - assert!(outcome.state[&MEGA_SYSTEM_ADDRESS].info.balance < U256::from(FUNDS), "{shape}"); - assert!(outcome.gas.history >= body_history(0), "{shape} pays history"); + 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}"); + } } } -/// A transaction without the system shape never reads the registry, whoever sends it: a database -/// that cannot serve the registry's account does not stop it, and its state holds nothing of the -/// registry. A legacy call to the Oracle has the shape, and its validation reads the registry, -/// here into the database's error. +/// 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_a_transaction_of_another_shape_never_reads_the_registry() { - let db = || { - let mut db = ErrorInjectingDatabase::new( - chain_db() - .account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])) - .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS)) - .account_balance(CALLER, U256::from(FUNDS)), - ); - db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); - db +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)) }; - for caller in [MEGA_SYSTEM_ADDRESS, CALLER] { - for (shape, tx) in other_shapes(caller) { - let outcome = MegaEvm::new(chain_context(db())) - .execute_transaction(tx) - .expect("the registry is never read"); - assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); - assert!(!outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "{shape}"); + 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:?}"); } } +} - let shaped = legacy_tx(CALLER, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 0); - let error = MegaEvm::new(chain_context(db())) - .execute_transaction(shaped) - .expect_err("the shaped transaction reads the registry"); - assert!(matches!(error, EVMError::Database(_)), "{error:?}"); -} - -/// The read of the live system address warms nothing. A user's legacy call to the Oracle's -/// `setSlots` has the system shape, so its validation reads the registry's slot and finds the -/// caller is not the system address; the Oracle then asks the registry for the system address -/// itself, and that `SLOAD` pays the cold price, as it does for the same call as an EIP-2930 -/// transaction, which reads nothing at validation: the two spend the same gas on every ledger. -/// Only an access list that names the slot makes the `SLOAD` warm. +/// 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_the_read_leaves_the_slot_and_the_registry_cold() { +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)))) @@ -336,22 +338,55 @@ fn test_the_read_leaves_the_slot_and_the_registry_cold() { ) }; - let (shaped, cold) = run(write()); - assert!( - shaped.state[&SEQUENCER_REGISTRY_ADDRESS].storage.contains_key(&CURRENT_SYSTEM_ADDRESS), - "the shaped transaction read the slot", - ); - let (unshaped, unread) = run(typed(write(), 1)); - assert_eq!(cold, unread, "the SLOAD after the read costs what it costs without one"); - assert_eq!(shaped.gas, unshaped.gas, "and so does the whole transaction"); + 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 warmed = typed(write(), 1); - warmed.0.base.access_list = AccessList(vec![AccessListItem { + 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 (_, warm) = run(warmed); - assert!(warm < cold, "a warm SLOAD ({warm}) is cheaper than the cold one ({cold})"); + 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_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 @@ -379,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); @@ -477,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)) @@ -514,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()); @@ -579,23 +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_eq!( - fresh, - existing + account_state_gas(), - "{fresh} is not one account 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] @@ -633,40 +671,50 @@ fn test_a_deposit_that_creates_two_accounts_pays_for_both() { /// 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. +/// 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 { - let deposit = || deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); - // A transaction without calldata has its intrinsic gas as its floor; run with its caller in - // place, the deposit creates no account. - let intrinsic = - run_outcome(chain_db().account_balance(sender, U256::from(1)), deposit()).gas.floor; - let mut tx = deposit(); - tx.0.base.gas_limit = intrinsic + account_state_gas() - 1; + 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 = INTRINSIC + account_state_gas() - 1; tx } -/// 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. +/// 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_halts() { +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 outcome = run_outcome(chain_db(), deposit_one_short_of_its_caller(sender)); + 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 exists whatever the deposit does, so a stop the -/// deposit's body latched does not waive its charge: a deposit that cannot pay for it is still an -/// out-of-gas halt, and the halt is not a data-size stop. +/// 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_halts() { +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; @@ -675,15 +723,21 @@ fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_halts( 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(deposit_one_short_of_its_caller(sender)) + .execute_transaction(tx) .expect("the deposit is included"); 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.limit_exceeded, None, "the halt is not a data-size stop"); + 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 }, @@ -691,8 +745,8 @@ fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_halts( ); } -/// 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(); @@ -789,22 +843,26 @@ fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { } /// A transaction that already carries the system source hash is a deposit by type, so it does -/// not have the system shape: it reads nothing of the registry and runs as the deposit it is, as -/// one carrying the hash from any other caller does (see -/// `test_a_deposit_from_another_caller_is_untouched`). No promotion is made for it, so none of the -/// promotion's checks runs: its nonce is not the system address's. +/// 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_runs_as_a_deposit() { +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 mut db = ErrorInjectingDatabase::new(chain_db()); - db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); - let outcome = MegaEvm::new(chain_context(db)) + let outcome = MegaEvm::new(chain_context(chain_db())) .execute_transaction(tx) - .expect("validation reads nothing of the registry"); - assert!(outcome.result.is_success(), "{:?}", outcome.result); + .expect("a deposit is not refused"); + assert!( + 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 2a50a71c2..a1c80cc18 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## OVERVIEW -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 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. `README.md` says what the two modes are and how a test is judged. @@ -14,7 +14,11 @@ The `state-test` CLI (`crates/state-test`) is a thin front end over this crate. - `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`. @@ -23,6 +27,8 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty - 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 accept any error for an expected exception; map the error in `src/exceptions.rs`. @@ -34,4 +40,6 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty - 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 a42a01862..2aa2624aa 100644 --- a/crates/mega-state-test/Cargo.toml +++ b/crates/mega-state-test/Cargo.toml @@ -25,11 +25,15 @@ alloy-trie = { workspace = true, features = ["std", "ethereum"] } # misc serde = { workspace = true, features = ["derive", "std"] } -serde_json = { workspace = true, features = ["std"] } +serde_json = { workspace = true, features = ["raw_value", "std"] } thiserror = { workspace = true, features = ["std"] } walkdir.workspace = true [dev-dependencies] +# alloy +alloy-eips.workspace = true + +# misc tempfile.workspace = true # Published as `mega-state-test`; the library keeps the `state_test` import name. diff --git a/crates/mega-state-test/DEVIATIONS.md b/crates/mega-state-test/DEVIATIONS.md index c43706ef2..aff8790d1 100644 --- a/crates/mega-state-test/DEVIATIONS.md +++ b/crates/mega-state-test/DEVIATIONS.md @@ -24,6 +24,57 @@ With the four entries taken back out of the table, every Osaka fixture passes. - `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. diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index dd0c46d64..18bc0aa3f 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -3,6 +3,7 @@ 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 @@ -11,7 +12,7 @@ The library keeps the `state_test` import name. 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, history and the access entries it pressed back on purpose, 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. + 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. @@ -57,6 +58,83 @@ 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. +## 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. 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 index 80f777726..0310ba950 100644 --- a/crates/mega-state-test/src/deviations.rs +++ b/crates/mega-state-test/src/deviations.rs @@ -20,6 +20,7 @@ use revm::primitives::b256; use serde::Serialize; use crate::{ + blockchain, runner::{Produced, TestId}, Fork, }; @@ -38,6 +39,62 @@ pub struct Deviation { /// 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. @@ -63,6 +120,11 @@ impl Deviation { } } + /// 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 { @@ -72,14 +134,48 @@ impl Deviation { } } +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 && { - let path = id.path.replace('\\', "/"); - path.strip_suffix(self.path).is_some_and(|dir| dir.is_empty() || dir.ends_with('/')) - } + id.name == self.name && id.indexes == self.indexes && path_ends_with(&id.path, self.path) } } @@ -104,6 +200,660 @@ pub const AMSTERDAM_OPCODES_ON_OSAKA: Deviation = Deviation { 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", @@ -140,6 +890,7 @@ pub const SELFDESTRUCT_BURNS_ON_OSAKA: Deviation = Deviation { 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", @@ -511,6 +1262,48 @@ pub fn render_markdown() -> String { 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 } @@ -569,6 +1362,72 @@ mod tests { } } + /// 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] diff --git a/crates/mega-state-test/src/exceptions.rs b/crates/mega-state-test/src/exceptions.rs index 8a232b9ec..3c8b04618 100644 --- a/crates/mega-state-test/src/exceptions.rs +++ b/crates/mega-state-test/src/exceptions.rs @@ -123,7 +123,7 @@ pub fn check_unbuildable( } /// Whether `got`, the names an error satisfies, includes one of the ones `expected` names. -fn check_names(expected: &str, got: &'static [&'static str]) -> Result<(), Mismatch> { +pub(crate) fn check_names(expected: &str, got: &'static [&'static str]) -> Result<(), Mismatch> { if got.is_empty() { return Err(Mismatch::Unnamed); } diff --git a/crates/mega-state-test/src/lib.rs b/crates/mega-state-test/src/lib.rs index 0af1e7131..0f65f5c73 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -9,15 +9,21 @@ //! 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, history and the access entries it pressed back on purpose, so -//! almost every stateful fixture differs, and the count is what is worth watching. +//! 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 blockchain; pub mod deviations; pub mod exceptions; mod fork; @@ -25,6 +31,7 @@ mod mode; pub mod roots; pub mod runner; pub mod skips; +pub mod witness; pub use fork::*; pub use mode::*; diff --git a/crates/mega-state-test/src/mode.rs b/crates/mega-state-test/src/mode.rs index 7861c65ec..a4eb2685d 100644 --- a/crates/mega-state-test/src/mode.rs +++ b/crates/mega-state-test/src/mode.rs @@ -9,7 +9,7 @@ use mega_evm::{ inspector::NoOpInspector, }, test_utils::{neutral_cfg, neutralize_evm, zero_fee_l1_block_info}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, + EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, }; use serde::Serialize; @@ -33,9 +33,9 @@ pub enum Mode { 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 — - /// gas detention at the spec's caps and nothing else — not the protocol's defaults, so the - /// transaction data-size limit is not held. + /// 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, } @@ -75,7 +75,20 @@ impl Mode { block: BlockEnv, chain_id: u64, ) -> MegaContext { - let ctx = MegaContext::new(db, MegaSpecId::SATIN); + 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 => { @@ -97,7 +110,19 @@ impl Mode { block: BlockEnv, chain_id: u64, ) -> MegaEvm { - let mut evm = MegaEvm::new(self.context(fork, db, block, chain_id)); + 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"); diff --git a/crates/mega-state-test/src/roots.rs b/crates/mega-state-test/src/roots.rs index 1bd046caa..acff5f35a 100644 --- a/crates/mega-state-test/src/roots.rs +++ b/crates/mega-state-test/src/roots.rs @@ -1,10 +1,16 @@ -//! The two roots a state test's expectation is written in: the post-state root and the hash of -//! the logs, computed the way the reference runner computes them. +//! 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::revm::{ - database::PlainAccount, - primitives::{keccak256, Address, Log, B256}, +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. @@ -14,7 +20,25 @@ pub fn logs_hash(logs: &[Log]) -> B256 { keccak256(&out) } -/// The state root over `accounts`: a state test's `hash` field. +/// 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. @@ -53,11 +77,58 @@ pub fn state_root<'a>(accounts: impl IntoIterator Result { +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")) @@ -598,13 +598,54 @@ fn execute_and_check( 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)), + }; + + 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 { + 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)?; - // The block is 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. let mut eth_cfg = CfgEnv::new(); eth_cfg.chain_id = chain_id; - eth_cfg.set_spec_and_mainnet_gas_params(config.fork.spec_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); @@ -612,7 +653,7 @@ fn execute_and_check( (Ok(tx), _) => tx, (Err(error), Some(expected)) => { return match exceptions::check_unbuildable(expected, &error, unit) { - Ok(()) => Ok(Some(SkipReason::UnbuildableInvalidTransaction)), + Ok(()) => Ok(Err(SkipReason::UnbuildableInvalidTransaction)), Err(_) => Err(Failure::new( FailureKind::WrongException, format!("expected {expected}, the transaction cannot be built: {error}"), @@ -625,23 +666,7 @@ fn execute_and_check( }; let tx = OpTx(OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() }); - - 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 { - 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) + Ok(Ok(Ready { chain_id, block, tx })) } /// Takes back out of `state` the base-fee vault account Satin's fee routing created, where 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/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/runner.rs b/crates/mega-state-test/tests/runner.rs index 26208b50c..3f71fc110 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -377,6 +377,7 @@ fn registry_of(report: &Report, path: &'static str) -> &'static [Deviation] { reason: "the reason", fork: Fork::Osaka, entries: entries.leak(), + blockchain_entries: &[], }])) } 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 014893022..64a348c84 100644 --- a/crates/state-test/AGENTS.md +++ b/crates/state-test/AGENTS.md @@ -6,8 +6,9 @@ This crate is not published; the runner, the modes, the deviation registry and t ## STRUCTURE - `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, the summary or the exit codes: `src/main.rs`. +- 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 8a8fdbda7..f425e3029 100644 --- a/crates/state-test/Cargo.toml +++ b/crates/state-test/Cargo.toml @@ -28,4 +28,10 @@ clap = { workspace = true, features = ["default"] } 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 96db52850..7f573970d 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -12,4 +12,14 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--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. -What the two modes are, how a test is judged and the deviation registry are described in the `mega-state-test` crate's `README.md` and `DEVIATIONS.md`. +```bash +state-test btest [options] ... +``` + +`btest` imports the execution-spec blockchain tests through Satin's block executor: the Osaka tests of the main release's `blockchain_tests`. + +- 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/main.rs b/crates/state-test/src/main.rs index befe9a898..7c24e0cdd 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -4,9 +4,14 @@ //! 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))] +mod btest; + use std::{path::PathBuf, process::ExitCode}; use clap::Parser; @@ -21,7 +26,11 @@ const LISTED_FAILURES: usize = 50; /// Command-line arguments. #[derive(Parser, Debug)] -#[command(name = "state-test", about = "Runs execution-spec state tests on the Satin engine")] +#[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..)] @@ -57,6 +66,12 @@ struct Cmd { } 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 { diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index aadc9f52c..d9d3348d9 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -1,14 +1,23 @@ //! 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. +//! 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, }; @@ -149,3 +158,165 @@ fn test_bad_arguments_exit_non_zero() { 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/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 f78c870c5..cf7682795 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -43,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. @@ -54,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. @@ -89,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. @@ -130,21 +138,11 @@ 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 +# 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. ``` -## 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 -``` - -`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, and which of the two engines runs it (see [Engines](../configuration/chain-and-spec.md#engines)). @@ -158,29 +156,31 @@ On these chains a block runs on Satin from the timestamp the chain's schedule ac 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 runs Satin from genesis, the rung the Satin engine pins for an unrecognized chain. +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. -Use `--override.spec` below to replay a chain that runs a legacy spec. + +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. +`--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 deploys, which MegaETH mainnet and testnet reach at `Rex6`. -On an older block Satin's own deploy check refuses to overwrite them, and the replay fails with an error naming the contract. +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 the chain's, a counterfactual: the fields the JSON object names replace the chain's, and every other stays. -Without it, a Satin replay of a block its chain does not run on Satin runs on Satin's default limits. -The object's shape, the defaults and what is refused are in [Protocol limits](../configuration/chain-and-spec.md#protocol-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. @@ -196,16 +196,25 @@ Each block runs on the engine its spec names: the one `--override.spec` forces, 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. +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. -| 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`, `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 | +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. @@ -243,10 +252,10 @@ The exit code is 0, 1 when a block could not be replayed, or 2 when `--verify` i ### 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 default protocol limits, or those `--override.limits` gives, with no building policy of a block builder applied. +`--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. -Satin's pre-block changes deploy the EIP-7997 factory at `0x4e59b44847b379578588920cA78FbF26c0B4956C`, which no legacy spec reads, so a block cached from a legacy replay does not hold it; the first Satin replay of the block reads it over RPC and adds it to the cache. +`--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 @@ -281,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 diff --git a/docs/mega-evme/commands/run.md b/docs/mega-evme/commands/run.md index efe2be5ef..0c7c59929 100644 --- a/docs/mega-evme/commands/run.md +++ b/docs/mega-evme/commands/run.md @@ -62,7 +62,7 @@ Each group is documented on its own page. | Option | Default | | ------------ | -------------------------------------------- | -| `--spec` | `Rex6` | +| `--spec` | `Rex6`; `Satin` under `--genesis` | | `--gas` | `10000000` | | `--sender` | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` | | `--receiver` | `0x0000000000000000000000000000000000000000` | @@ -328,7 +328,7 @@ RPC Options: Chain Options: --spec - 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) + 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: Rex6] @@ -336,7 +336,7 @@ Chain Options: Chain ID [default: 6342] [aliases: --chainid] --override.limits - Satin only: run under these protocol limits instead of the chain's, a counterfactual. A JSON object in the shape a chain configuration carries `ProtocolLimits` in (camelCase, per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names replace the chain's, every other stays. Refused when it names an unknown field or a value no chain may carry + 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] diff --git a/docs/mega-evme/commands/tx.md b/docs/mega-evme/commands/tx.md index 333dbb068..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 @@ -85,6 +86,18 @@ The output includes the same fields as [`run --json`](run.md#json-output) (with | --------- | ---------------- | --------------------------------------------------------------------------- | | `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,7 +226,7 @@ RPC Options: --rpc.rate-limit Retry-layer compute-units-per-second budget [default: 660] Chain Options: - --spec Spec: `Satin`, or a legacy spec `Equivalence` to `Rex6` [default: Rex6] + --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 diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index c77f6301a..d7ae2e73a 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -10,11 +10,12 @@ The `replay` command auto-detects the spec from the chain ID and block timestamp ## Options -| Flag | Default | Aliases | Description | -| -------------------------------- | ----------- | ----------- | ----------------------------------------------------------------------------------------- | -| `--spec ` | `Rex6` | — | MegaETH spec to use | -| `--chain-id ` | `6342` | `--chainid` | Chain ID | -| `--override.limits ` | the chain's | — | Satin only: protocol limits to run under instead, see [Protocol limits](#protocol-limits) | +| 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 @@ -62,7 +63,7 @@ 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`, `kv_update`, `compute_gas`, `state_growth`), `limit`, `used` | +| `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 ===`. @@ -70,52 +71,65 @@ A legacy run has no `satin` field. ### Protocol limits -A Satin run is held to the protocol limits of the chain it names, read from the chain's schedule at the block's timestamp, as a node holds a block of that chain. -On a chain whose schedule runs Satin at that timestamp, these are the chain's own limits. -Any other Satin run is a counterfactual: MegaETH mainnet and testnet, which do not schedule Satin yet, the default chain `6342`, and any chain the tool does not know run on Satin's default 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 | Default | +| 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 | -| Every other limit | unlimited | +| A frame's data size beyond its share (`frameDataSizeLimit`) | unlimited | -The defaults are provisional, as Satin is. -A chain whose schedule runs Satin but does not carry its limits is refused: the tool does not guess a chain's limits. +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 shape a chain configuration carries the limits in, inline or as the path of a file. -The fields it names replace the chain's, and every other stays. -The whole shape, at the defaults: +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, - "txKvUpdateLimit": 18446744073709551615, - "frameKvUpdateLimit": 18446744073709551615, - "txStateGasLimit": 18446744073709551615, "blockEnvAccessComputeGasLimit": 20000000, "oracleAccessComputeGasLimit": 20000000 }, - "blockExecutionGasLimit": 18446744073709551615, - "blockStateGasLimit": 18446744073709551615, - "blockTxsDataLimit": 13107200, - "blockKvUpdateLimit": 18446744073709551615 + "blockTxsDataLimit": 13107200 } ``` -`18446744073709551615` (`u64::MAX`) leaves a limit unlimited. -The limits an override leaves are held to what a chain configuration is: an unknown field, a zero limit, a transaction data-size limit below the 310 bytes every transaction's body counts, or a compute cap no transaction reaches is refused. +`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; for `state_growth`, the state gas held there, so a deposit whose created caller alone crosses the limit reports that account, even where its first frame would add another. +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 ```bash @@ -131,6 +145,12 @@ 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 one write record -mega-evme run 0x600160005260... --spec Satin --override.limits '{"txRuntimeLimits":{"txKvUpdateLimit":1}}' +# 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 20da454c5..d0c842fe6 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -69,7 +69,7 @@ mega-evme replay --block 26400000..26400099 \ ``` 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 EIP-7997 factory its pre-block changes deploy) and adds it to the cache; later runs of the same blocks can drop `--rpc`: +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 \ diff --git a/docs/mega-evme/overview.md b/docs/mega-evme/overview.md index ddf5b4f7b..05b52fedc 100644 --- a/docs/mega-evme/overview.md +++ b/docs/mega-evme/overview.md @@ -100,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/glossary.md b/docs/spec/glossary.md index c1bb69faf..359d3df64 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -135,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). diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index b53ba9e67..3c1e25f79 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -54,7 +54,7 @@ Protocol-level changes outside the verifiable execution layer (e.g., networking, 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)). 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. @@ -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, KV updates and state gas per transaction, with no separate compute-gas limit; every transaction-level limit stops a transaction with a revert carrying `MegaLimitExceeded`. +- **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; the pre-block calls, the system-contract deploys and the EIP-7997 factory run before every block. -- **Live system address** — a system-shaped transaction reads the [SequencerRegistry](system-contracts/sequencer-registry.md) itself. -- **Block limits** — execution gas, state gas, data size and KV updates are packing budgets that never refuse a deposit. +- **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 b6de2b08e..3854c1540 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -50,7 +50,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 pays history gas, so no transaction behaves identically to Optimism under Satin. +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). 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 2f2e568b8..588768154 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, per-transaction limits that stop a transaction 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, block limits as packing budgets, 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, 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/satin.md b/docs/spec/upgrades/satin.md index b682b1d2c..43fb960ee 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1,11 +1,11 @@ --- -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, per-transaction limits that stop a transaction 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, and block limits as packing budgets. +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 an informative summary of the Satin specification. -For the full normative definition, see the Satin spec in the mega-evm repository. +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. @@ -19,11 +19,11 @@ 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 KV updates, measure state growth in state gas, and drop the separate compute-gas limit: compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md). -Every transaction-level limit — data size, KV updates, state gas, and detention's compute limit — now stops a transaction with a revert carrying `MegaLimitExceeded(kind, limit)` instead of a halt, and the sender pays only for what ran. +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 every block-level execution limit a packing budget that never refuses a deposit. +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. @@ -34,13 +34,13 @@ The changes, in the order this page records them: 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 and EIP-2780 intrinsic cost, with the EIP-8038 repricing left at Osaka's values. +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 and KV updates over a byte table and write records, state growth as a state-gas limit, and no compute-gas limit. -11. **The revert-class stop.** Every transaction-level limit stops the transaction with a revert. +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.** @@ -51,6 +51,7 @@ The changes, in the order this page records them: 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 @@ -68,13 +69,20 @@ The changes, in the order this page records them: - 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 as the node supplies it, and zero for a block that carries none. + `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 from Jovian onward activates, MUST contain only deposit transactions; a non-deposit transaction in it makes the block invalid. + - 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 @@ -99,8 +107,9 @@ The precompile set MUST be Karst's, with KZG point evaluation at MegaETH's price | 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. -KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 gas fails with `OutOfGas`, and a successful call is charged exactly 100,000. +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 @@ -112,14 +121,17 @@ KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 ga - 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 check their operands, the static context and the initcode size in the inherited order: Satin charges nothing ahead of those checks. +- 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, a limit that halts the transaction. +- 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 @@ -151,6 +163,7 @@ A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amster - **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`; @@ -158,14 +171,21 @@ A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amster - _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 towards its execution-gas limit is `max(regular, floor)`, with history gas taken out of the regular ledger before the floor applies. + 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 @@ -179,67 +199,75 @@ Satin has no separate compute-gas limit: compute is regular gas, bounded by the #### New behavior -The gas schedule MUST be Amsterdam's — including [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 three changes: +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 seventeen regular-gas entries below, which Amsterdam repriced for [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) (four of them because EIP-8037 moved the cost of creating state onto the state dimension), MUST keep their Osaka values; - 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, including 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. - -Regular-gas entries that keep their Osaka value: - -| Entry | Satin | -| ---------------------------------------------- | ------ | -| Warm storage read | 100 | -| Cold account access, additional | 2,500 | -| Cold storage access, additional | 2,000 | -| Cold `SLOAD` | 2,100 | -| Value transfer of a call | 9,000 | -| New account of a call | 25,000 | -| New account of `SELFDESTRUCT` | 25,000 | -| `SSTORE` static cost | 100 | -| `SSTORE` of a fresh slot, before the load cost | 19,900 | -| `SSTORE` reset, before the cold load | 2,800 | -| `SSTORE` refund of a restored fresh slot | 19,900 | -| `SSTORE` refund of a restored reset | 2,800 | -| `SSTORE` refund of a cleared slot | 4,800 | -| `CREATE` and `CREATE2` | 32,000 | -| Creation transaction (unused under EIP-2780) | 32,000 | -| Access-list address | 2,400 | -| Access-list storage key | 1,900 | - -Entries that differ from Osaka: - -| Entry | Osaka | Satin | -| --------------------------------------------- | ------ | ------- | -| 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 | - -Under EIP-2780 the floor's base is the transaction's own decomposed intrinsic base (below), not the 12,000 entry. +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, access-list addresses and the block beneficiary — as warm, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) has it: Rex6's cold charge on the first `CALL`-family touch of such an address does not apply. +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 @@ -266,9 +294,10 @@ Every EIP-8037 state charge MUST be `entry × m`: - 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, MUST fail the transaction; it MUST NOT be priced at any multiplier. +- 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. @@ -296,24 +325,29 @@ The bytes MUST be those of the byte table below, which is also the table the dat | 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 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. +- `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 it does not count against the execution cap. +- 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: @@ -321,10 +355,12 @@ 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 is zero too. + 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 a receipt's gas used, because the history gas of the same bytes is higher; it does bind the figure a block counts towards its execution-gas limit, `max(regular, floor)` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +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 @@ -359,90 +395,106 @@ At these prices it never raises a receipt's gas used, because the history gas of - 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 transaction crossing a limit halts; a frame crossing its budget reverts alone. +- 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 -Three dimensions are limited per transaction; compute is not one of them (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +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 unless the chain sets another | Yes | -| KV updates | Write records | Unlimited unless the chain sets one | Yes | -| State gas | EIP-8037 state gas the transaction holds | Unlimited unless the chain sets one | No | +| 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. - A deposit's data size is counted like any transaction's. + 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 own account and the four fee accounts are part of the body and MUST NOT be counted as records; a frame running as the sender records nothing for the sender's account. - Records MUST be deduplicated per frame: a frame records an account once. + 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_SHARE_NUMERATOR / FRAME_SHARE_DENOMINATOR` = 98/100 of what its parent has left, rounded down, in each of data size and write records, under an optional per-frame cap. + 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. -- **State gas** is the net EIP-8037 state gas the transaction holds: what it was charged before the first frame, plus what every frame on the call stack holds, net of refills and of failed frames. - It MUST be checked wherever state gas is charged, after the charge: a charge the frame cannot pay is an out-of-gas whatever the limit. - The sites are the applied authorities and the account a deposit-like transaction creates for its caller, before the first frame (the authorities are taken back on a crossing), a fresh slot, a `SELFDESTRUCT`'s new beneficiary, a new account a frame's start adds — the first frame's recipient or created account, and the account a `CALL`, `CREATE` or `CREATE2` adds — (held once the frame is decided: a frame refused on its caller's account, or answered with a failure, gives the charge back and is not held for it), and deployed code (at the deposit, before the creation commits). - Because it is a limit on gas, a slot or an account in a bucket `m` times the minimum reaches it `m` times sooner. + 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.** - Where the state gas and a count cross at the same site, the state gas is the dimension reported; between the counts, data size is checked before write records, and a transaction limit before a frame budget. - A frame start is the exception: its records and transfer log are held before the frame is built, and the state gas charged upfront for the account it adds — by its opcode, or, for the first frame, by EIP-2780 — only once the frame is decided; a start the records stop adds no account, so its upfront state gas is given back rather than held, and the data-size or KV stop is the one reported. + 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 per-transaction limits and the per-frame caps are protocol values: the chain configuration carries them as parameters of the Satin hardfork, together with the detention caps and the block limits, and a node MUST hold every transaction to the values the chain configures, never to values it is handed with a block. - The values above are the defaults. - A chain configuration that activates Satin without these parameters MUST be refused when it is loaded, and so MUST one that sets a limit to zero, a transaction data-size limit below `TX_BODY_SIZE`, or a detention cap no transaction's compute reaches (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). - The 98/100 share is not a parameter. - At the default data-size limit a transaction keeps fewer than 327,680 write records (13,107,200 / 40), so a KV limit binds only below that. +- **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 halts: it produces a failed receipt, its remaining gas is preserved and refunded to the sender, and it is included in the block. +- 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 transaction-level limit — data size, KV updates, state gas, and gas detention's compute limit — MUST stop the transaction with a revert, never a halt: - -1. The frame that crosses the limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. -2. From then on no frame runs another instruction: a caller receiving that result MUST return the same revert instead of resuming, a frame about to start MUST be answered with it, and every result returned upward MUST be rewritten to it, whatever produced the result. -3. 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. -4. 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 later stop MUST NOT revert it, as a revert of the first frame does not: +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. - The one exception is the state gas charged upfront for the account the frame adds — by the calling opcode, or, for the first frame, by EIP-2780: it is held once the frame is decided, so a frame built by then returns the stop before its first instruction, a frame answered without running is rewritten to the stop, and what the start moved is reverted with the frames the stop reverts — for the first frame, which no frame's revert follows, with its answer. -- A body over the data-size limit MUST stop the transaction before it runs: no authorization is applied, no record made outside a frame is charged, the first frame's start is charged nothing, and the first frame is answered with the stop. -- EIP-7702 authorities whose state gas or records would cross a limit MUST be taken back before the first frame, with their writes and the state gas applying them charged; the first frame is then answered with the stop. - Authorities admitted there are kept through a later stop, as above. +- 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 frame budget MUST revert its frame alone, with the same revert data, and its caller continues. 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 | -| 1 | KV updates | The limit or frame budget crossed, in write records | -| 2 | Compute (gas detention) | The compute the transaction may reach: its compute at the binding read plus the cap, in gas | -| 3 | State growth | The transaction's state-gas limit, in gas | +| `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. -Kind 3 changes unit: Rex6 reported it in new accounts and slots, Satin in state gas. -A contract can revert with the same bytes, so the revert data alone does not identify a stop. +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 @@ -458,24 +510,33 @@ A contract can revert with the same bytes, so the revert data alone does not ide 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 the chain configuration carries with the other limits (see [Resource Limits](#10-resource-limits)), 20,000,000 each by default. - A chain's caps MUST be 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. + 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`), and a withheld part, the rest. + 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 refund at the end of the transaction. + 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 transaction MUST be stopped with `MegaLimitExceeded(2, limit)` (see [The Revert-Class Stop](#11-the-revert-class-stop)). - The transaction is billed what it spent before that charge, less than one charge short of the limit, and the sender gets back everything the frames had, the withheld part included. + 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. @@ -483,7 +544,8 @@ A contract can revert with the same bytes, so the revert data alone does not ide 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 MUST be the crossing. + 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.** @@ -504,8 +566,14 @@ The reference implementation has no price for one, so it runs such a precompile #### 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. -- 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. + 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 | @@ -528,7 +596,7 @@ The reference implementation has no price for one, so it runs such a precompile - `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). + 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 @@ -544,10 +612,12 @@ A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): - 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. -- A `SELFDESTRUCT` to itself of an account created in the same transaction burns the balance without a log. +- 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 @@ -555,12 +625,13 @@ A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): - 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 nothing; a sandbox preflight failure reverts with `ParentBudgetExceeded`; a failed read reverts with `InternalError()`. +- 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. @@ -575,19 +646,27 @@ An out-of-gas step halts the call, consuming its regular gas. | 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 | `InvalidSignature()` | +| 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: 32,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 | +| 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 the legacy engine's order, so a call several rules refuse reports the Rex6 error. -- The deploy-address read of step 12 MUST NOT warm the deploy address and MUST NOT load its code. -- A signer that is the block beneficiary MUST be detained as a read of the beneficiary's account. +- 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. @@ -595,18 +674,21 @@ An out-of-gas step halts the call, consuming its regular gas. 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 succeeded and moved value out of the signer, whose account then keeps a write of its own. + 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 also for a constructor that destroyed its own account. - `gasUsed` MUST be what the creation spent from both pools, before refunds, with no intrinsic gas. + 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 frame budget the creation crosses reverts the creation, and the call answers `ExecutionReverted` with the stop's revert data. - A transaction-level limit stops the transaction: the call 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 its own frame budget, the call reverts with that stop and the deployment, the nonce included, is taken back without stopping the transaction. -- Of the contract's errors, `ParentBudgetExceeded(uint8,uint64,uint64)`, `InvalidTransaction()`, `InsufficientComputeGas(uint64,uint64)` and `InternalError()` MUST NOT be produced: a failed database read or SALT lookup fails the transaction with its cause. + 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. -- The `KeylessDeploy` contract, its interface and its errors are unchanged. + [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 @@ -618,13 +700,23 @@ An out-of-gas step halts the call, consuming its regular gas. #### 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 hint that would cross the transaction's data-size limit is not forwarded, and the limit stops the transaction. + 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 @@ -632,19 +724,29 @@ An out-of-gas step halts the call, consuming its regular gas. - 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. +- 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 -- A transaction MUST be tested for the system shape on its own fields first: type `0x0`, a call (not a creation) to an address on `MEGA_SYSTEM_TX_WHITELIST` (the Oracle). -- Only a transaction with that shape MUST read the registry: when the registry holds the code this spec deploys, the node reads `_currentSystemAddress` from the transaction's own state, cold, without the registry's code, and compares it with the caller. - The registry account (without code) and that slot are part of the transaction's state and witness, not the pre-block witness. -- A registry that is absent, holds other code, or names the zero address MUST make no transaction a Mega System Transaction. -- A transaction of any other shape reads nothing and is never a Mega System Transaction, whoever sent it. - A transaction from the system address without the shape is an ordinary transaction, validated and charged as a user's. - The Oracle authorizes writes on the sender alone, so such a transaction to the Oracle succeeds as a user transaction: it pays fees, is held to every per-transaction limit, is detained, is priced by bucket, and pays history gas. -- A Mega System Transaction is validated (chain id, nonce, EIP-3607) and promoted to a deposit exactly as in Rex6. -- Because a role change can only be scheduled for a later block 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. +- 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 @@ -652,6 +754,7 @@ An out-of-gas step halts the call, consuming its regular gas. - 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 @@ -661,20 +764,31 @@ An out-of-gas step halts the call, consuming its regular gas. 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 (neither call runs in the genesis block, and a block without a parent beacon block root is invalid, as EIP-2935 and EIP-4788 define); - 3. deploy 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` with nonce 1; - 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`. -- **Deploys.** - Each deploy is idempotent: an address already holding the expected code is only read (its nonce kept). - An absent account, or one with empty code and nonce 0, MUST get the code, nonce 1 and the registry's seed slots; it keeps any balance it has, and any storage it had is cleared. - There is one version of each contract (the Oracle and the SequencerRegistry at version 2.0.0): an address holding other code, an address with empty code and a non-zero nonce, and a factory with the expected code and nonce 0 MUST make the block invalid. + 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 a deploy or in the due-change read is always an internal error. + 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 @@ -684,6 +798,10 @@ An out-of-gas step halts the call, consuming its regular gas. #### 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; @@ -694,7 +812,7 @@ A system-originated transaction and every system call: 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, but a user's deposit is not system-originated: it is held to every per-transaction limit, detained, and priced by bucket. +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 @@ -706,25 +824,30 @@ A deposit pays no history gas either, but a user's deposit is not system-origina #### 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. -Four of those counts can be limited: - -| Block limit | Counted | Checked | Default | -| ------------- | ------------------------------------- | -------------------------------- | ---------------- | -| Execution gas | `max(regular, floor)` per transaction | Before the next transaction runs | Unlimited | -| State gas | State gas per transaction | After the next transaction runs | Unlimited | -| Data size | Data-size bytes per transaction | Before the next transaction runs | 13,107,200 bytes | -| KV updates | Write records per transaction | Before the next transaction runs | Unlimited | - -- These are packing budgets: the transaction that reaches a limit MUST be included, and later transactions MUST be skipped — for state gas, only a later transaction that adds state gas. -- A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by any of the four, and MUST count towards all four. - A Mega System Transaction is a legacy transaction in the block, so at block level it is held to these budgets and to the data-availability limits like any non-deposit transaction. -- History gas has no block limit; the block's history bytes are reported, not limited. +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 four limits are protocol values the chain configuration carries as parameters of the Satin hardfork, with the per-transaction limits (see [Resource Limits](#10-resource-limits)); the defaults are the table's. - A node validating a block MUST hold it to the chain's 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 four limits below the chain's value, never above it. +- 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. - A deposit counts towards the block's encoded size and not towards its data-availability size; the block gas limit holds it as it holds every transaction. + 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. @@ -733,71 +856,234 @@ Four of those counts can be limited: #### 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; -- the block has reached the chain's execution-gas, data-size or KV limit; -- the block has reached the chain's state-gas limit and the transaction adds state gas; -- it is not a deposit and the block activates Satin or an Optimism fork from Jovian onward. +- 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 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 one of the four block limits held below the chain'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 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 is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). -A failed bucket-capacity read or database read MUST fail the transaction with its cause rather than settle it at any price. +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)); -- a system-contract address holds foreign code or has empty code and a used nonce, or the factory's address holds the factory's code at nonce 0; +- 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` 165,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 267,240 (183,600 of it state gas); the last two move by a few gas with the code that sets them up. +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 transaction stopped by a resource limit or by gas detention now reverts rather than halting, with `MegaLimitExceeded(kind, limit)` as its output, and its sender pays only for what ran. -Kind 3 now reports the state-gas limit in gas. -A transaction that reads volatile data is still stopped at its compute at the read plus 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. +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 failed attempts by anyone cannot make its address undeployable; only a delegated signer whose own code spends a nonce during the creation moves past it. +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; the Satin deploy step refuses, rather than upgrades, any other code at their addresses. -A system-address transaction without the system shape is now executed as a user transaction instead of being refused; only the holder of the system key can send one. +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: the chain configuration carries them as parameters of the Satin hardfork, so every node executing a chain holds its blocks to the same ones, and a configuration that activates Satin without them does not load. -By default the KV-update and state-gas limits and the block's execution-gas limit are unlimited, the data-size limits are 13,107,200 bytes, and the detention caps are 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: 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. @@ -806,6 +1092,7 @@ Satin is unstable and not scheduled on any network: its prices, limits and rules - [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`. diff --git a/mutants/README.md b/mutants/README.md index a53211a97..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 | @@ -162,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/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 1aeb3b89c..1ea725151 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -30,7 +30,8 @@ report saying why, when the results cannot be scored. orphans --suppressions --universe - Flag suppressions that match no live mutant. + 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 @@ -306,15 +307,41 @@ def cmd_note_empty(args: argparse.Namespace) -> int: 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. """ - _, line_supp = load_suppressions(Path(path)) if path else ([], []) - return {e["mutant"].strip() for e in line_supp if "mutant" in e} + 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: @@ -366,6 +393,21 @@ def cmd_report(args: argparse.Namespace) -> int: write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) return 0 + 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: @@ -384,7 +426,7 @@ def cmd_report(args: argparse.Namespace) -> int: else: timeout = list(run.timeout) - supp = suppressed_names(args.suppressions) + 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 = [], [] @@ -511,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 diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 3324cc9ae..5de5b115e 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -51,7 +51,8 @@ SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" # `:(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' -JOBS="${JOBS:-$(nproc)}" +# 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=() diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh index 4f6920a54..c1df50c0f 100755 --- a/scripts/price_grid.sh +++ b/scripts/price_grid.sh @@ -13,9 +13,11 @@ # `--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 -# tests a price guard held back at it (`note_price_guard`) in _.guards, one per line. A -# summary line per point, with how many passed, were guarded and failed, goes to stdout and, when -# $GITHUB_STEP_SUMMARY is set, a table to the step summary. Exits 1 if any point fails. +# 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 @@ -34,6 +36,9 @@ EXTRA_POINTS="0.001/0.001" 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}" @@ -52,7 +57,7 @@ case "${1:-}" in points="$points $EXTRA_POINTS" ;; "" | -h | --help) - sed -n '2,24p' "$0" | sed 's/^# \{0,1\}//' + sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//' exit 2 ;; *) @@ -71,7 +76,7 @@ if ! cargo test -p mega-evm --features "$FEATURES" --locked --no-run; then exit 1 fi -summary="| CPSB | CPHB | result | passed | guarded | failed |"$'\n'"|---|---|---|---:|---:|---:|" +summary="| CPSB | CPHB | result | passed | guarded | snapshot skips | failed |"$'\n'"|---|---|---|---:|---:|---:|---:|" failed_points="" for point in $points; do cpsb="${point%/*}" @@ -92,21 +97,25 @@ for point in $points; do 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 - [ -f "$guards" ] && guarded=$(wc -l <"$guards" | tr -d ' ') + 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 failed %4ss %s\n' \ - "$point" "$result" "$passed" "$guarded" "$failed" "$seconds" "$log" + 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 | $failed |" + summary="$summary"$'\n'"| $cpsb | $cphb | $result | $passed | $guarded | $snapshot_skips | $failed |" done if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index b3d8bf1c2..d329a767e 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -321,6 +321,24 @@ def test_a_suppressed_survivor_passes(self) -> None: 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"))) @@ -623,5 +641,31 @@ def test_an_old_bash_is_refused(self) -> None: 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() From 2f353be7aee96235ee8975b999e8fb0052caef3d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 10:26:48 +0800 Subject: [PATCH 391/458] feat: detention and frame-start rules from the review follow-ups, rebased onto the squashed W7 These seven commits were made on the review follow-ups before W7's last commits; they are squashed here so that the series sits on #400's squash merge without replaying W7's old history. The tree is the one their merge with W7's head produced. - refactor: detention keeps the frames' figures from the first frame, with no lazy rebuild - feat: detention counts what a callee runs on a value call's stipend as compute - feat: frame-start records are held to the limits once revm decided the start, with no refusal prediction - test: a priced and an unpriced precompile part as a failed call and a crossing under detention - test: the check of a kept frame start trips on a transfer log counted and not journaled - fix: gas detention's funding check before a priced precompile compares only a value the call moves - refactor: clearer names for the frame-start holds, the stipend read from the schedule in tests, and the docs the stipend rule left stale --- AGENTS.md | 53 +- crates/mega-evm/src/access/detention.rs | 459 +++++-------- crates/mega-evm/src/access/mod.rs | 11 +- crates/mega-evm/src/evm/execution.rs | 607 ++++++++---------- crates/mega-evm/src/evm/instructions.rs | 30 +- crates/mega-evm/src/limit/limit.rs | 180 +++--- crates/mega-evm/src/limit/mod.rs | 43 +- .../mega-evm/src/system/keyless/dispatch.rs | 2 +- crates/mega-evm/src/system/limit_control.rs | 6 +- crates/mega-evm/tests/satin/data_size.rs | 2 +- .../tests/satin/detained_transfers.rs | 51 +- crates/mega-evm/tests/satin/detention.rs | 151 ++++- crates/mega-evm/tests/satin/stops.rs | 10 +- crates/mega-evm/tests/satin/transfer_logs.rs | 296 ++++----- crates/mega-evm/tests/satin/withheld_gas.rs | 63 ++ .../mega-evm/tests/system/keyless/deploy.rs | 9 +- ...erential__keyless_differential_record.snap | 18 +- .../tests/system/remaining_compute_gas.rs | 9 +- crates/mega-evm/tests/tracers/scenarios.rs | 6 +- docs/spec/upgrades/satin.md | 25 +- 20 files changed, 983 insertions(+), 1048 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eb470a8c2..c0fe3e472 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,17 +123,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 | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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 @@ -180,13 +180,15 @@ 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 lane of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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 as the frame starts, before revm decides it, and held to the limits once revm has, in `MegaEvm::frame_init` (`AdditionalLimit::hold_built_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start (`journal_position`): a frame revm built returns the stop on its first run, before any instruction, 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` is held to nothing and its lane goes with its failure, and a creation it answers before bumping its creator's nonce, read off the journal since the mark, has its count withdrawn (`AdditionalLimit::withdraw_refused_start`); either gets back the history its caller paid at the opcode, which charged it before revm decided, so a caller that cannot pay that charge runs out of gas even where revm would have refused the start. + 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 lands on the creator, which is held to its limits with it. + 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 debug build asserts at every start revm made and kept that it 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). + 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 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). @@ -315,10 +317,11 @@ Detention caps how much a transaction may still compute once it read such data ( 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. + 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, and the gas run after a read is at most the cap, but for what halting frames leave. + 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.** @@ -333,12 +336,12 @@ Detention caps how much a transaction may still compute once it read such data ( 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, 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. + 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. 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. @@ -394,15 +397,15 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 frame returns a stop before running another instruction in two cases (`AdditionalLimit::stop_before_run`, `before_frame_run`): on its first run, when its own start crossed a limit once revm built it; and on a resume, when a child left it one — 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). + 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`). 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index c013d8c30..2b19ef2b7 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -18,7 +18,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 +28,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 +72,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.child_stipend = stipend; } } @@ -93,28 +95,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 +111,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, so the gas run after a read is at most the cap, but for what halting frames leave +/// (below). 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,10 +146,11 @@ 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. +/// 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 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 @@ -175,14 +162,9 @@ impl FrameFigures { /// /// # 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 /// @@ -223,16 +205,8 @@ pub struct Detention { 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 { @@ -262,9 +236,6 @@ impl Detention { 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 @@ -362,11 +333,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 +344,6 @@ impl Detention { &mut self, observed: VolatileDataAccess, gas: &mut Gas, - depth: usize, forwarded: u64, ) { self.accessed |= observed; @@ -382,9 +351,6 @@ 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 limit = self.lower_limit(compute.saturating_add(cap)); gas.limit_spendable(limit.saturating_sub(compute)); @@ -429,112 +395,40 @@ impl Detention { /// 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); } - /// 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, stipend); } - 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 + /// 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); } } @@ -559,13 +453,7 @@ impl Detention { 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); - } + self.figures.on_frame_end(depth); if let Some(limit) = self.stop(gas) { return Some(ComputeStop { limit, used: self.compute(gas) }); } @@ -729,12 +617,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()); @@ -782,15 +670,22 @@ impl Detention { /// 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) + 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) } @@ -890,7 +785,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 +801,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,7 +815,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_state_cost(1_000_000)); detention.hold(&mut frame); assert_eq!(detention.compute(&frame), 0); @@ -938,7 +833,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 { @@ -960,10 +855,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,7 +878,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(100_000_001)); detention.note_halt(frame.remaining()); frame.spend_all(); @@ -994,44 +889,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), 9_000); + assert!(child.record_regular_cost(spent)); + assert_eq!(detention.compute(&child), 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), 9_000 + spent - 2_300, "{spent}"); + detention.on_frame_run(&mut caller, 0); + assert_eq!(detention.compute(&caller), 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 +941,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,25 +954,24 @@ 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; + let compute = 2_000 + 1_000 + 9_000 + 4_000 + 500; assert_eq!(detention.compute(&grandchild), compute); assert_eq!(detention.compute_limit(), Some(compute + CAP)); assert_eq!(grandchild.spendable(), CAP); @@ -1088,37 +986,17 @@ mod tests { 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,42 +1006,15 @@ 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. @@ -1174,7 +1025,7 @@ 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)); @@ -1203,9 +1054,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); @@ -1253,9 +1104,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 +1142,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,7 +1199,7 @@ 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"); @@ -1364,14 +1215,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 +1233,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); @@ -1505,11 +1356,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..a27cdb20e 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -48,11 +48,12 @@ //! 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. +//! 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, so the gas run after a read +//! is at most the cap, but for what halting frames leave. 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 diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 0db00ef6f..e07e1fc8b 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -24,7 +24,7 @@ use revm::{ }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, + journaled_state::{entry::JournalEntry, JournalCheckpoint}, Host, }, handler::{ @@ -39,10 +39,10 @@ use revm::{ InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, Gas, InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, }, - primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, Inspector, Journal, }; @@ -55,7 +55,7 @@ use crate::{ }, history_gas, synthetic_frame_result, system::keyless, - Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, + Detention, ExternalEnvTypes, LimitKind, MegaContext, MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; @@ -450,15 +450,15 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm { @@ -545,6 +522,9 @@ impl EvmTr for MegaEvm { @@ -552,20 +532,16 @@ impl EvmTr for MegaEvm 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" - ), - } + take_back_a_stopped_answer(ctx, start.position, 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 + /// Runs the frame on top of the stack, unless it has a stop to return: its own start's, when + /// it crossed a limit once revm built the frame, or the one a child left it, when what the /// 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`]). @@ -680,14 +656,15 @@ where /// 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. + /// + /// A frame whose start crossed a limit returns the stop before it runs: the inspector sees it + /// start and end with the stop, and is told neither of an interpreter nor of the logs its + /// start journaled, which the stop takes back — what it sees of a call answered with the stop. #[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. @@ -724,10 +701,13 @@ where 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 { + // A frame whose start crossed a limit returns the stop before it runs, which takes back + // what its start journaled, as for a call answered with the stop. + let stopped = ctx.additional_limit.has_stop_before_run(); + if !stopped && ctx.journal().logs().len() != logs_i { inspect_logs(ctx, inspector, logs_i); } - if !keyless::runs(ctx, frame) { + if !keyless::runs(ctx, frame) && !stopped { inspector.initialize_interp(&mut frame.interpreter, ctx); } Ok(ItemOrResult::Item(frame)) @@ -771,10 +751,12 @@ where /// 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. A stop on a first run +/// is the frame's own start, which crossed a limit once revm built the frame: its revert takes +/// back what the start moved. A stop on a resume is the child's doing: 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. /// /// 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 @@ -795,7 +777,8 @@ fn before_frame_run( } /// 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. +/// for the child's start to add to the transaction's, with the stipend revm gives a value call's +/// child, which the frame did not forward; 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 @@ -814,8 +797,9 @@ fn after_frame_run( next: &mut Result>, E>, ) { match next { - Ok(ItemOrResult::Item(_)) => { - ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); + Ok(ItemOrResult::Item(child)) => { + let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); + ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth, stipend); } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); @@ -829,20 +813,6 @@ fn after_frame_run( } } -/// 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. /// @@ -895,7 +865,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 +879,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 +893,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 +911,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 +938,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 +946,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 +962,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, @@ -1070,23 +1059,138 @@ where 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. +/// What holding a frame's start to the limits needs of it once revm consumed its input: where the +/// start began 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. + position: JournalCheckpoint, + /// The frame's depth. + depth: usize, + /// The account a creation is made by; `None` for a call. + creator: Option
, + /// 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, + /// Whether the start counted an EIP-7708 transfer log, for a debug build to hold to the one + /// revm journaled. + #[cfg(debug_assertions)] + transfer_log: bool, +} + +impl FrameStart { + /// The start of the frame `frame_init` asks for, about to be decided by revm. + fn of( + ctx: &mut MegaContext, + frame_init: &FrameInit, + ) -> Self { + let input = &frame_init.frame_input; + let (creator, reservoir) = match input { + FrameInput::Call(inputs) => (None, inputs.reservoir), + FrameInput::Create(inputs) => (Some(inputs.caller()), inputs.reservoir()), + FrameInput::Empty => (None, 0), + }; + Self { + position: journal_position(ctx), + depth: frame_init.depth, + creator, + gas_limit: input_gas_limit(input), + reservoir, + #[cfg(debug_assertions)] + transfer_log: ctx.additional_limit.frame_start_transfer_log(input), + } + } + + /// Asserts that revm journaled the transfer log the start counted, once it made the start and + /// kept it: the rule the count follows is the one revm journals the log by. Only transfer logs + /// are compared: a precompile may journal logs of its own. + #[cfg(debug_assertions)] + fn assert_transfer_log_journaled( + &self, + ctx: &MegaContext, + ) { + let journaled = ctx.journal_ref().logs()[self.position.log_i..] + .iter() + .filter(|log| log.address == revm::primitives::eip7708::ETH_TRANSFER_LOG_ADDRESS) + .count(); + debug_assert_eq!( + journaled, + usize::from(self.transfer_log), + "the transfer log counted is the one revm journaled" + ); + } +} + +/// Holds `start`, the start of a frame revm answered without building it, to the limits, now that +/// revm decided it: `answer` is revm's answer, or gas detention's to a precompile whose price +/// crosses the compute limit, given without running it. +/// +/// A call revm refused to move value for — a value its caller cannot fund — moved nothing and is +/// held to nothing: its lane goes with its failure. Any other call's start moved its value, +/// whatever the answer made of it then, and is held to the limits, before gas detention holds the +/// answer: a crossing is the stop, which the answer gives way to, on the gas its caller forwarded, +/// untouched, as a frame stopped before it ran. 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. /// -/// 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( +/// A creation revm answers moved nothing and kept no account. It bumped its creator's nonce +/// unless it refused the creation on the creator's account — an endowment it cannot fund, a nonce +/// it cannot bump — which then counts nothing ([`withdraw_refused_start`](crate::AdditionalLimit)); +/// a creation it fails after the bump, onto an occupied address, is held to nothing at its start: +/// its failure takes the created account's record and the transfer log back, and the nonce record, +/// which outlives it, lands on the creator, which is held to its limits with it. +fn hold_answered_start( 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(); + start: &FrameStart, + answer: &mut FrameResult, +) { + let Some(creator) = start.creator else { + if matches!( + answer.instruction_result(), + InstructionResult::OutOfFunds | InstructionResult::OverflowPayment + ) { + return; + } + #[cfg(debug_assertions)] + if answer.instruction_result().is_ok() { + start.assert_transfer_log_journaled(ctx); + } + let check = ctx.additional_limit.check_start(); + if check.exceeded_limit() { + let output = ctx.additional_limit.note_frame_stop(&check); + stop_the_answer(answer, start, output); + } + return; + }; + let bumped = ctx.journal_ref().journal()[start.position.journal_i..] + .iter() + .any(|entry| matches!(entry, JournalEntry::NonceBump { address } if *address == creator)); + if bumped { + return; } - let output = ctx.additional_limit.note_frame_stop(check); - Ok(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) + ctx.additional_limit.withdraw_refused_start(); + // revm answers a creation whose creator's nonce cannot be bumped with a success. The + // transaction's own frame, refused so, makes none of the records charged before execution for + // it, and the history they cost comes back with the answer, as for a frame that kept nothing. + if start.depth == 0 && answer.instruction_result().is_ok() { + answer.gas_mut().refill_history(ctx.additional_limit.top_level_write_record_gas()); + } +} + +/// 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 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 gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + outcome.result = InterpreterResult::new(InstructionResult::Revert, output, gas); + outcome.was_precompile_called = false; + outcome.precompile_call_logs.clear(); } /// The depth guard: a frame past the call-stack limit, of any call scheme or a creation, answered @@ -1095,9 +1199,9 @@ 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 @@ -1112,60 +1216,6 @@ 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)] @@ -1216,82 +1266,6 @@ 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 /// nonce once, so the distinct authorities other than the sender are the accounts written. The @@ -1332,11 +1306,10 @@ fn record_applied_authorities( /// 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. +/// frame revm refuses to start on its sender's account makes no record, and the charge comes back +/// once revm refused it ([`hold_answered_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. /// `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, @@ -1355,17 +1328,13 @@ fn charge_records_made_outside_a_frame( !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 records = u64::from(writes_a_record); + let Some((top_level, _)) = charge_write_records_history(gas, records, 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.stage_top_level_records(records); true } @@ -1374,11 +1343,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"); @@ -1402,20 +1370,15 @@ mod tests { })) } - /// 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 @@ -1451,9 +1414,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 +1426,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 +1445,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 +1522,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 +1590,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"); @@ -1640,74 +1619,22 @@ mod tests { } } - /// The guard trips on a transfer log the data size counted for a frame revm built and did not - /// journal. + /// The check of a start revm made and kept trips on a transfer log the start counted and revm + /// 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)); + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let position = journal_position(&mut ctx); + let start = FrameStart { + position, + depth: 1, + creator: None, + gas_limit: 0, + reservoir: 0, + transfer_log: true, + }; + start.assert_transfer_log_journaled(&ctx); } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 7494f5e2c..01ab40c82 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -88,7 +88,7 @@ use crate::{ 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>; @@ -278,12 +278,12 @@ fn selfdestruct( /// 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`]). +/// is charged nothing. Every frame an opcode starts is charged, revm deciding the start only once +/// the frame's init asks it: a start revm then refuses — a value the caller cannot fund, a frame +/// past the call-stack limit — makes no records, and gives the charge back when it returns. 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`]), even where revm would have refused the +/// start. /// /// 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. @@ -302,11 +302,6 @@ fn charge_frame_start( // 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), @@ -471,7 +466,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 +495,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 — diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6cc04a504..6bc6775f2 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -54,9 +54,12 @@ pub struct AdditionalLimit { /// 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 stop the frame about to run must return instead of running: the one a frame revm built + /// returns on its first run when its start crossed a limit + /// ([`hold_built_start`](Self::hold_built_start)), or the one a frame a child returned into + /// returns when what the child left it put it over a limit + /// ([`on_frame_return`](Self::on_frame_return)). + pending_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. @@ -95,11 +98,6 @@ pub struct AdditionalLimit { /// 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. @@ -130,7 +128,7 @@ impl AdditionalLimit { self.tracker.reset(); self.staged = None; self.exempt = false; - self.resume_stop = None; + self.pending_stop = None; self.frame_stop = None; self.limit_exceeded = None; self.target_is_authority = false; @@ -142,7 +140,6 @@ impl AdditionalLimit { 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; @@ -241,11 +238,18 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// The stop the running frame returns instead of running another instruction: the one + /// The stop the running frame returns instead of running another instruction: the one its own + /// start left it ([`hold_built_start`](Self::hold_built_start)), or 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() + self.pending_stop.take() + } + + /// Whether the running frame has a stop to return before it runs another instruction + /// ([`stop_before_run`](Self::stop_before_run)). + pub(crate) const fn has_stop_before_run(&self) -> bool { + self.pending_stop.is_some() } /// What the transaction keeps so far: its data-size bytes and write records, with every @@ -355,31 +359,6 @@ impl AdditionalLimit { 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; @@ -548,30 +527,58 @@ impl AdditionalLimit { /// 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. + /// revm journals for the move, on the frame's own lane. The lane follows the frame's journal + /// checkpoint: 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 { + /// The count is made as the frame starts, before revm decides the start, and nothing is held + /// to a limit until revm has: a start revm builds the frame for is held to the limits before + /// the frame runs ([`hold_built_start`](Self::hold_built_start)), and one revm answers once + /// the answer is known ([`check_start`](Self::check_start)); a start revm refuses on its + /// caller's account made nothing, and its lane is popped with its failure, or stands for + /// nothing ([`withdraw_refused_start`](Self::withdraw_refused_start)). A start past the + /// call-stack limit, which the depth guard answers before it reaches here, gets an empty + /// lane ([`push_empty_frame`](Self::push_empty_frame)). + pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) { self.frame_began = true; self.push_lane(input, depth); if self.frame_start_transfer_log(input) { self.tracker.record(TRANSFER_LOG); } + } + + /// Holds the start of the frame revm just built to the limits: a crossing is the stop the + /// frame returns on its first run, before any instruction ([`stop_before_run`]). revm moved + /// the value, journaled the transfer log and, for a creation, bumped its creator's nonce; the + /// stop is a revert of the frame, so its journal checkpoint takes the move and the log back, + /// and the nonce, bumped before the checkpoint, stays, with its record on the creator. + /// + /// [`stop_before_run`]: Self::stop_before_run + #[inline] + pub(crate) fn hold_built_start(&mut self) { + let check = self.check(); + if check.exceeded_limit() { + debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); + self.pending_stop = Some(check); + } + } + + /// The verdict on the start of the frame revm just answered without building it, the + /// writes its start made counted: a crossing means the answer must give way to the stop. + pub(crate) fn check_start(&self) -> LimitCheck { self.check() } + /// Withdraws the count of the start of the frame revm just answered, a creation revm refused + /// on its creator's account before it wrote anything: an empty lane stands in for the + /// frame's, so the creation counts no record, its creator's account is no more recorded than + /// before, and its caller gets back, when the lane is popped, all it paid for the records. + pub(crate) fn withdraw_refused_start(&mut self) { + if let Some(lane) = self.tracker.current_mut() { + lane.creator_record = false; + } + self.tracker.discard_running_lane(); + } + /// 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. /// @@ -767,14 +774,7 @@ impl AdditionalLimit { /// 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); @@ -797,7 +797,7 @@ impl AdditionalLimit { return false; } let check = self.check(); - self.resume_stop = check.exceeded_limit().then_some(check); + self.pending_stop = check.exceeded_limit().then_some(check); true } @@ -865,7 +865,7 @@ impl AdditionalLimit { 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 { + self.pending_stop = if unchecked { let check = self.check(); check.exceeded_limit().then_some(check) } else { @@ -1096,6 +1096,28 @@ mod tests { ); } + /// A creation revm refused on its creator's account counts nothing once its count is + /// withdrawn: whatever revm answered — `OutOfFunds`, or the success with no address it gives a + /// creator whose nonce cannot be bumped — its records are not kept, its creator's account is + /// not recorded, and its caller gets back all it paid, the nonce record's charge included. + #[test] + fn test_a_refused_start_counts_nothing_and_gives_its_charge_back() { + for answered in [InstructionResult::OutOfFunds, InstructionResult::Return] { + let mut limit = with_the_transactions_frame(); + let input = creation(CALLEE, U256::from(1)); + let records = limit.frame_start_records(&input); + assert_eq!(records, FrameStartRecords { on_lane: 1, caller: true }); + limit.stage_frame_charge(records, 3, 4); + limit.on_frame_init(&input, 1); + limit.withdraw_refused_start(); + assert_eq!(limit.usage(), LimitUsage::ZERO, "{answered:?}"); + let result = crate::synthetic_frame_result(&input, answered, Bytes::new()); + assert_eq!(limit.on_frame_return(&result), 3 + 4, "{answered:?}: the whole charge"); + assert!(!limit.tracker.current().unwrap().account_recorded, "{answered:?}"); + assert_eq!(limit.usage(), LimitUsage::ZERO, "{answered:?}"); + } + } + /// 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. @@ -1294,29 +1316,6 @@ mod tests { 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) @@ -1326,9 +1325,10 @@ mod tests { /// 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] + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let first = limit.check_start(); + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + [first, limit.check_start()] } /// A transaction that is not exempt is stopped wherever it crosses a limit: counting the @@ -1584,7 +1584,8 @@ mod tests { 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); + limit.on_frame_init(&inner, 1); + let check = limit.check_start(); if fits { assert_eq!(check, LimitCheck::WithinLimit, "exactly the budget"); } else { @@ -1606,7 +1607,8 @@ mod tests { 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); + limit.on_frame_init(&first, 0); + let check = limit.check_start(); if fits { assert_eq!(check, LimitCheck::WithinLimit, "exactly the limit"); continue; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 226bf53c8..59144fdb9 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -45,27 +45,27 @@ //! - 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. +//! 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 +//! 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 frame start is counted as the frame starts and held to the limits once revm decided it, on +//! what revm then did. 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, gets back what its caller paid for +//! its records, and no limit stops it. A creation revm fails after it bumped its creator's nonce, +//! onto an occupied address, is held to nothing at its start: its failure discards its records and +//! transfer log, but for the nonce record, which lands on the creator. //! //! 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 @@ -430,11 +430,12 @@ 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, 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, diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ccc65c088..4681f21fe 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -381,7 +381,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 }); diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 10276934a..228f194df 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -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/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 8188ca906..cd830bf67 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -589,7 +589,7 @@ fn test_a_storage_write_one_byte_over_stops_on_the_write() { /// 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 = || { diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 4b0a209e6..99e42a71f 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 +//! 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. +//! 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, 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,7 +236,16 @@ 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 }); @@ -274,11 +283,11 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { /* ---------- 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] = [ @@ -567,7 +576,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..1e7fab848 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -84,6 +84,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 +213,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 +241,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 +258,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 +282,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 +383,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. @@ -951,13 +986,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 +1000,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 +1011,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 +1031,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. diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 781397192..18498699a 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1378,7 +1378,7 @@ enum Answered { /// 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, } @@ -1625,11 +1625,11 @@ fn test_an_answer_three_calls_down_is_the_stop_its_caller_catches_at_either_tier } /// 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. #[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); } diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index fd026b07a..ddc91c99d 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -6,8 +6,8 @@ //! 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; +//! 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 the beneficiary's record, once the //! opcode completed, and a crossing stops the destructing frame, which takes the move back. //! @@ -18,10 +18,11 @@ //! 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. +//! 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 +41,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}, @@ -416,8 +417,8 @@ 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 +/// that moves the value, which keeps nothing of the move, 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. /// @@ -549,6 +550,61 @@ 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" + ); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + 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. @@ -745,12 +801,14 @@ 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 the history of the records it would make at its +/// opcode, as every start is, before revm decides it, and gets the charge back once revm refused +/// it: given room for the charge, the caller runs on past the refused call, billed its body's +/// history alone and counting nothing more. A caller that keeps less than those records cost, +/// once it has forwarded all it can, runs out of gas at the opcode, as it does when it can fund the +/// value. #[test] -fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { +fn test_a_value_call_its_caller_cannot_fund_gets_its_charge_back() { let actor = BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).append(POP).stop().build(); let db = |held: u64| { @@ -768,23 +826,10 @@ 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 }, @@ -795,128 +840,26 @@ 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 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 { + 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; + } + assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); + let gas_limit = 21_000 + history_gas(body).unwrap() + actor_gas; + for held in [VALUE - 1, VALUE] { + let short = execute_under(db(held), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(short.result.is_halt(), "holding {held}: {:?}", short.result); + assert_eq!(short.gas.gas_used, gas_limit, "holding {held}: the halt used the gas limit"); } -} - -/// 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 @@ -936,12 +879,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() @@ -976,16 +919,15 @@ fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { 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 +948,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); @@ -1019,15 +968,18 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() "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 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); 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"); + 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 }); } /// A deposit's value moves in its first frame and is logged there, from the depositor to the diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index d50e617d9..1aa1b80d3 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1538,6 +1538,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 diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 2fd93df66..b2efce301 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -884,11 +884,10 @@ 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 two +/// records 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)); 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..dd4b0ab81 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 @@ -47,13 +47,13 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "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: the call's budget, nonce 0 @ 50000000 | keccak256=0x563c2538189232c42fe596a21c5f2b9e2bd0ba5b074ee1b208bc3d4e88c181cf", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x86c98b3191b04ec2645753e17e62a1888a4f8c42aaf9cce7256af3727a7c25c0", "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: the call's budget, nonce 1 @ 50000000 | keccak256=0xbf76a42ed427e64d62ab6c0ea96b20181bd7f1a7918642bd895c44dd33d429ab", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x13a7db43ef62af595ed78f1c233c9ea743d8b2bdf1b227b4bade5112932931e0", "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", @@ -112,13 +112,13 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "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: the call's budget, nonce 0 @ 400000000 | keccak256=0x5b79812ff316d7436d9c98fcdf3e7491afc928032cb26fe7901ca534b0f0a968", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xdb08fbc4f6bcb751a845c920299f5b3fdb7ee2b1176a53e3b4cd2ead628ba76f", "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 call's budget, nonce 1 @ 400000000 | keccak256=0x49182fdae5b1b8ee2aca9ddc7090e8111d754a062b514bb30d76e3c9ff12e75f", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x7b58cb388000f0a13245b90261bc7de760860180921c122862110ad3574029db", "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", @@ -145,7 +145,7 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "rule: init code over the limit @ 2000000000 | keccak256=0x8e0e07266b270414f4eb958872388f1a26baf80ff2262daba5da7553b7435e8e" ], "summary": { - "bytes": 2392466, + "bytes": 2393338, "cases": 139, "lines": 11444, "runs": 556 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/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs index 1f1935d75..6803e89a4 100644 --- a/crates/mega-evm/tests/tracers/scenarios.rs +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -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; diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 43fb960ee..941b0dddc 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -349,6 +349,7 @@ When each charge is made: 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. +The opcode pays for them whether or not the start then happens: a start refused on its caller's account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — makes no record and MUST give the charge back when its failed frame returns, and a caller that cannot pay the charge MUST halt with out-of-gas at the opcode though the start would have been refused. These MUST NOT pay history gas: @@ -429,9 +430,9 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw 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. +- **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 and be stopped by no limit; its caller is charged for the records at its opcode and gets the charge back (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, lands on the creator, which MUST be held to its limits with it. - **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. @@ -475,10 +476,11 @@ What was applied before the first frame is not the frames' doing, and a stop of 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. + A stopped creation keeps its creator's nonce bump, 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)). @@ -513,9 +515,12 @@ A contract can revert with the same bytes, and so can a caller that re-raises th `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. + 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 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 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)). @@ -614,10 +619,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 From 7c09935c903754ac8c69eef1a9973107f722b624 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:24:39 +0800 Subject: [PATCH 392/458] feat(state-test): print a digest of every transaction's whole outcome --- AGENTS.md | 2 + crates/mega-state-test/AGENTS.md | 1 + crates/mega-state-test/README.md | 17 ++ crates/mega-state-test/src/digest.rs | 349 +++++++++++++++++++++++++ crates/mega-state-test/src/lib.rs | 1 + crates/mega-state-test/src/runner.rs | 126 ++++++++- crates/mega-state-test/tests/runner.rs | 82 +++++- crates/state-test/README.md | 3 + crates/state-test/src/main.rs | 16 +- crates/state-test/tests/cli.rs | 28 ++ 10 files changed, 609 insertions(+), 16 deletions(-) create mode 100644 crates/mega-state-test/src/digest.rs diff --git a/AGENTS.md b/AGENTS.md index c0fe3e472..7d21317ee 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 diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index a1c80cc18..feb1f9dbd 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -38,6 +38,7 @@ 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. - 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..3d1dd1689 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -58,6 +58,23 @@ 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. + +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..09c5012e4 --- /dev/null +++ b/crates/mega-state-test/src/digest.rs @@ -0,0 +1,349 @@ +//! 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())) +} + +fn result_gas(gas: &ResultGas) -> 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", gas.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 { + fields([("data_size", usage.data_size.into()), ("write_records", usage.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) -> 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)), + ("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)), + ("logs", logs(l)), + ("output", hex(output)), + ("status", "revert".into()), + ]), + ExecutionResult::Halt { reason, gas, logs: l } => fields([ + ("gas", result_gas(gas)), + ("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)), + ("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) + .with_reservoir_remaining(5_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), + usage: LimitUsage { data_size: 500, write_records: 3 }, + 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; + assert_ne!(digest(&base), digest(&data)); + assert_ne!(digest(&base), digest(&records)); + } + + /// 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..069c1e9b1 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; diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index f8966439d..cd6731f57 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, }, + 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,22 @@ 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, /// 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 +241,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 +513,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 +591,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 +643,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 +663,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 +673,12 @@ 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); 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 +687,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..bd019753b 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -31,7 +31,15 @@ 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, + deviations: DEVIATIONS, + } } /// A unit calling `CONTRACT` with `transaction` fields over the defaults, and one entry per fork @@ -499,3 +507,75 @@ 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(|record| state_test::digest::hash(record)).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")); +} diff --git a/crates/state-test/README.md b/crates/state-test/README.md index 7f573970d..8f5205dae 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -10,6 +10,9 @@ 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. - `--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..1ec5444c5 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -17,7 +17,7 @@ use std::{path::PathBuf, process::ExitCode}; use clap::Parser; use state_test::{ deviations, - runner::{find_json_files, run, Config, Outcome, Report, Summary, TestResult}, + runner::{find_json_files, run, Config, DigestForm, Outcome, Report, Summary, TestResult}, Fork, Mode, }; @@ -47,6 +47,14 @@ 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, /// Trace every test with an EIP-3155 tracer on standard error; runs on one thread. #[arg(long)] trace: bool, @@ -92,12 +100,18 @@ fn main() -> ExitCode { } else { cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())) }; + 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, deviations: deviations::DEVIATIONS, }; let report = run(&files, config); diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index d9d3348d9..152ab79d7 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -159,6 +159,34 @@ 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"); +} + /// 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, From 8c35ae912555aacff3faea7c85d79e3a4a0bf0d4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:30:39 +0800 Subject: [PATCH 393/458] feat(state-test): run the fixtures under tighter Satin limits --- crates/mega-state-test/AGENTS.md | 1 + crates/mega-state-test/README.md | 8 +++++ crates/mega-state-test/src/lib.rs | 2 ++ crates/mega-state-test/src/runner.rs | 8 ++++- crates/mega-state-test/tests/runner.rs | 32 ++++++++++++++++- crates/state-test/README.md | 2 ++ crates/state-test/src/main.rs | 49 +++++++++++++++++++++++++- crates/state-test/tests/cli.rs | 21 +++++++++++ 8 files changed, 120 insertions(+), 3 deletions(-) diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index feb1f9dbd..fd9b08fad 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -39,6 +39,7 @@ 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 3d1dd1689..93cc7e53e 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -69,6 +69,14 @@ The record holds the status with its halt or revert reason, the output, the crea 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-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 diff --git a/crates/mega-state-test/src/lib.rs b/crates/mega-state-test/src/lib.rs index 069c1e9b1..d25456f3d 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -35,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 cd6731f57..2dadd11af 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -52,7 +52,7 @@ use mega_evm::{ primitives::{Bytes, B256, KECCAK_EMPTY, U256}, DatabaseCommit, ExecuteCommitEvm, }, - MegaContext, MegaEvm, + EvmTxRuntimeLimits, MegaContext, MegaEvm, }; use serde::{ de::{Error as _, MapAccess, Visitor}, @@ -86,6 +86,9 @@ pub struct Config { 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], @@ -674,6 +677,9 @@ fn execute_and_check( let mut state = State::builder().with_cached_prestate(unit.state()).with_bundle_update().build(); 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()); execute_and_commit(&mut evm, tx, executed) diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index bd019753b..fab80241e 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"; @@ -38,6 +38,7 @@ fn config(mode: Mode, fork: Fork) -> Config { json_outcome: false, trace: false, digest: None, + limits: None, deviations: DEVIATIONS, } } @@ -579,3 +580,32 @@ fn test_the_digest_covers_failed_and_rejected_tests() { .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"); + assert_eq!(tight["limit_exceeded"]["limit"], 400); + 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 8f5205dae..dafbb2c97 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -13,6 +13,8 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--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` 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 1ec5444c5..2361f838d 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -18,7 +18,7 @@ use clap::Parser; use state_test::{ deviations, runner::{find_json_files, run, Config, DigestForm, Outcome, Report, Summary, TestResult}, - Fork, Mode, + EvmTxRuntimeLimits, Fork, Mode, }; /// How many unattributed failures, and how many unreproduced entries, the summary lists. @@ -55,6 +55,17 @@ struct Cmd { /// 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, /// Trace every test with an EIP-3155 tracer on standard error; runs on one thread. #[arg(long)] trace: bool, @@ -100,6 +111,13 @@ 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), @@ -112,6 +130,7 @@ fn main() -> ExitCode { json_outcome: cmd.json_outcome, trace: cmd.trace, digest, + limits, deviations: deviations::DEVIATIONS, }; let report = run(&files, config); @@ -149,6 +168,34 @@ 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() + { + 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); + } + 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 152ab79d7..c0ae26e32 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -187,6 +187,27 @@ fn test_the_digest_options_print_a_line_per_transaction() { 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"], + ] { + 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, From 109976274f424e85629ecbb8c8d7984fa070ab86 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:56:38 +0800 Subject: [PATCH 394/458] style(state-test): pass the digest hash as a function --- crates/mega-state-test/tests/runner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index fab80241e..d280c0df7 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -542,7 +542,7 @@ fn test_the_digest_is_stable_across_runs_and_thread_counts() { assert_eq!(one, run_with(4)); assert_eq!(one, run_with(4)); let hashes: std::collections::BTreeSet<_> = - one.iter().flatten().map(|record| state_test::digest::hash(record)).collect(); + one.iter().flatten().map(state_test::digest::hash).collect(); assert_eq!(hashes.len(), 6, "six distinct values, two files of each"); } From 855ee9145cd8a2ed2e7c154a096214d421c0e156 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 00:49:39 +0800 Subject: [PATCH 395/458] build: pin the revm fork at the mega.6 release commit Pin every fork crate at 7bc0c664 (megaeth-labs/revm#75); the lock moves only the fork's entries. mega.6 drops ResultGas::reservoir_remaining and the system-call state-gas margin switch, so mega-evm takes both over: - MegaHandler::tx_gas splits a system call's gas at SYSTEM_CALL_REGULAR_GAS_LIMIT, whatever the configuration; the neutral configuration leaves it whole, as revm's runner does. - The handler reads the reservoir where revm builds the result's gas and reports it on the layer (AdditionalLimit::reservoir_remaining); MegaGasUsage takes it as an argument. - The op-revm baselines run op-revm through a shared reference handler with the same split, reading op-revm's reservoir beside its result. The execution-spec workflows read the pin from the lock as a tag or a rev. The state-test digest keeps its encoding, the reservoir now read off the outcome. The keyless differential's digest moves with the two Debug renderings that changed (ResultGas, GasTracker); the record, normalized, is unchanged but for the system calls' reservoir, now written apart. --- .github/workflows/exec-spec-satin.yml | 15 +- .github/workflows/exec-spec.yml | 15 +- Cargo.lock | 26 +- Cargo.toml | 26 +- crates/mega-evm/src/block/eips.rs | 11 +- crates/mega-evm/src/evm/context.rs | 53 +++- crates/mega-evm/src/evm/execution.rs | 50 +++- crates/mega-evm/src/evm/mod.rs | 15 +- crates/mega-evm/src/evm/result.rs | 24 +- crates/mega-evm/src/lib.rs | 1 + crates/mega-evm/src/limit/limit.rs | 16 + .../mega-evm/src/system/sequencer_registry.rs | 13 +- crates/mega-evm/src/test_utils/neutral.rs | 23 +- crates/mega-evm/tests/block/eips.rs | 42 +-- crates/mega-evm/tests/block/main.rs | 5 + crates/mega-evm/tests/fuzz/regressions.rs | 5 +- crates/mega-evm/tests/satin/equivalence.rs | 115 ++++---- crates/mega-evm/tests/satin/main.rs | 2 + crates/mega-evm/tests/satin/spec_numbers.rs | 5 +- crates/mega-evm/tests/satin/strategic_stop.rs | 12 +- .../tests/satin/synthetic_frame_gas.rs | 20 +- crates/mega-evm/tests/satin/system_call.rs | 124 +++----- crates/mega-evm/tests/shared/op_reference.rs | 221 ++++++++++++++ .../tests/system/keyless/differential.rs | 14 +- .../mega-evm/tests/system/keyless/limits.rs | 13 +- ...erential__keyless_differential_record.snap | 278 +++++++++--------- crates/mega-state-test/src/digest.rs | 19 +- 27 files changed, 722 insertions(+), 441 deletions(-) create mode 100644 crates/mega-evm/tests/shared/op_reference.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/Cargo.lock b/Cargo.lock index b50a95875..6ad95fe3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index ae3ba2ae5..4f7e429fa 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 = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } [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. +# against the revm pin above. op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.3" } diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 54531548f..205ceb9f4 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -30,15 +30,12 @@ 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}; +use crate::{ExternalEnvTypes, MegaEvm, SYSTEM_CALL_REGULAR_GAS_LIMIT}; /// The caller every pre-block system call runs as. pub use alloy_eips::eip4788::SYSTEM_ADDRESS; diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 03d3fe786..01229ebcd 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -133,9 +133,8 @@ 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 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 { @@ -162,6 +161,8 @@ impl MegaContext { /// 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. + /// - 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 @@ -424,6 +425,20 @@ 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 + } + /// Prepares the common execution layer for a transaction or a system call that is, or is not, /// `system_originated`. /// @@ -550,14 +565,6 @@ 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 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. @@ -568,7 +575,6 @@ 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); @@ -675,7 +681,6 @@ 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"); @@ -690,7 +695,6 @@ mod tests { cap: Option, eip7708: bool, eip7708_disabled: bool, - margin: bool, chain_id_check: bool, code_size: Option, initcode_size: Option, @@ -705,7 +709,6 @@ 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, @@ -756,7 +759,6 @@ 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); @@ -903,6 +905,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] diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index e07e1fc8b..3fccd1ddf 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -59,6 +59,10 @@ use crate::{ PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; +/// 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. @@ -71,12 +75,20 @@ pub struct MegaHandler { /// 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 + /// reported once the result is built ([`execution_result`](Handler::execution_result)). + 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(), + deposit_creates_caller: Cell::new(false), + settled_reservoir: Cell::new(None), + } } } @@ -269,6 +281,26 @@ where Ok(gas) } + /// revm's transaction-level gas, with 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. + /// + /// revm builds a system call's gas here, on no intrinsic gas, and so 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); + 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, 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. @@ -333,6 +365,10 @@ where /// 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. + /// + /// The reservoir the transaction leaves unspent is 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,6 +376,7 @@ where init_and_floor_gas: InitialAndFloorGas, eip7702_gas_refund: i64, ) -> Result { + self.settled_reservoir.set(Some(exec_result.gas().reservoir())); 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); @@ -371,13 +408,22 @@ 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. 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.get().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 diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8893e7efc..c6cdfe522 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -303,6 +303,7 @@ where result_and_state.result.gas(), layer.history_gas_spent(), layer.history_bytes(), + layer.reservoir_remaining(), ); Ok(MegaTransactionOutcome { result_and_state, @@ -429,10 +430,12 @@ impl MegaEvm { /// 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. + /// and never the regular budget. The block's pre-block calls run through it. What the call + /// left of its reservoir is + /// [`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining). /// /// [`SYSTEM_CALL_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_GAS_LIMIT - /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_REGULAR_GAS_LIMIT + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: crate::SYSTEM_CALL_REGULAR_GAS_LIMIT pub fn transact_system_call_with_gas_limit( &mut self, caller: Address, @@ -553,7 +556,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}; @@ -747,7 +750,7 @@ mod tests { assert!(result.result.is_success()); assert_eq!(evm.ctx().tx().gas_limit(), 123_456_789); assert_eq!( - result.result.gas().reservoir_remaining(), + evm.ctx().additional_limit().reservoir_remaining(), 123_456_789 - SYSTEM_CALL_REGULAR_GAS_LIMIT, "an empty callee draws nothing from the reservoir", ); @@ -757,7 +760,7 @@ mod tests { .unwrap(); assert!(result.result.is_success()); assert_eq!(evm.ctx().tx().gas_limit(), 1_000_000); - assert_eq!(result.result.gas().reservoir_remaining(), 0); + assert_eq!(evm.ctx().additional_limit().reservoir_remaining(), 0); } /// The default system-call entry point runs on revm's system-call gas limit whatever the @@ -777,7 +780,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/result.rs b/crates/mega-evm/src/evm/result.rs index b3873f90d..3758e2f83 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -117,18 +117,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 +167,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 +187,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/lib.rs b/crates/mega-evm/src/lib.rs index 28f859579..7c05ab07f 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -56,6 +56,7 @@ pub use evm::{ 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, + SYSTEM_CALL_REGULAR_GAS_LIMIT, }; #[cfg(any(test, feature = "test-utils"))] pub use external::{ diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6bc6775f2..f9ad7e98a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -102,6 +102,8 @@ pub struct AdditionalLimit { history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, + /// The EIP-8037 reservoir the settled transaction left unspent. + reservoir_remaining: 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, @@ -142,6 +144,7 @@ impl AdditionalLimit { self.pending_frame_charge = FrameCharge::NONE; self.history_gas_spent = 0; self.history_bytes = 0; + self.reservoir_remaining = 0; self.transfer_logs = false; } @@ -263,6 +266,19 @@ impl AdditionalLimit { self.history_gas_spent } + /// 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 + } + + /// 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; + } + /// 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. /// diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index f7cda377b..16c9c3ba9 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -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, }; @@ -382,10 +383,10 @@ mod tests { 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"); + 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(), + evm.ctx().additional_limit().reservoir_remaining(), 250_000_000 - SYSTEM_CALL_REGULAR_GAS_LIMIT ); } @@ -395,9 +396,9 @@ mod tests { 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"); + 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); + assert_eq!(evm.ctx().additional_limit().reservoir_remaining(), 0); } /// 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/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/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 6a72eb556..452c09a25 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -24,12 +24,11 @@ use mega_evm::{ pre_block_call_gas_limit, 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}, database::State, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, Database, }; @@ -531,28 +530,19 @@ 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 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 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 +559,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(250_000_000), + ) + .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/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/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 518c5f445..3d0614db0 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -114,7 +114,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}"); diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 39e1dc3dc..35cc2d91b 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -40,39 +40,28 @@ 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, 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 +73,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 +92,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 +103,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 +117,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 +134,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 +144,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 +169,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 +184,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 +198,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 +216,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 +430,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()), @@ -823,13 +818,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 +875,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/main.rs b/crates/mega-evm/tests/satin/main.rs index dd2ee96c2..f5b755c7a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -28,6 +28,8 @@ mod intrinsic; mod limit_exemption; mod limit_stop; mod neutral; +#[path = "../shared/op_reference.rs"] +mod op_reference; mod outcome; mod pool_validation; mod precompile_gas; diff --git a/crates/mega-evm/tests/satin/spec_numbers.rs b/crates/mega-evm/tests/satin/spec_numbers.rs index 38551315b..8a998115a 100644 --- a/crates/mega-evm/tests/satin/spec_numbers.rs +++ b/crates/mega-evm/tests/satin/spec_numbers.rs @@ -23,7 +23,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::{ @@ -46,8 +45,8 @@ use mega_evm::{ 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, + 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"); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index c33ef7f6d..07daad02a 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -214,18 +214,18 @@ 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() + 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 @@ -440,7 +440,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), ); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index cfcbec37c..7126fb0da 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -232,11 +232,11 @@ 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()); } @@ -330,7 +330,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 +349,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 +365,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", ); } diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 5a077f0a1..d65fa3ed5 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -2,17 +2,17 @@ //! 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. +//! `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}; @@ -29,31 +29,22 @@ use mega_evm::{ 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, + 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 +61,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 +93,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,23 +102,6 @@ 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. fn run_both( (mut mega, mut op): (MegaEvm, Op), @@ -147,21 +109,23 @@ fn run_both( contract: Address, data: Bytes, gas_limit: u64, -) -> (Outcome, Outcome) { - let mega_outcome = mega +) -> (Settled, Settled) { + let result_and_state = 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) + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let op_outcome = op_reference::system_call(&mut op, caller, contract, data, 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 +142,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::() } @@ -202,7 +166,7 @@ fn test_a_system_call_within_30m_has_no_reservoir() { 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.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); @@ -222,7 +186,7 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { 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(), + mega.reservoir_remaining, gas_limit - SYSTEM_CALL_REGULAR_GAS_LIMIT - slot(), "the excess, less the one slot it paid for", ); @@ -262,7 +226,7 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { 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()) + (reading.to::(), mega.reservoir_remaining) }; // The most slots the reservoir holds, and what the one after them spills. @@ -297,7 +261,7 @@ fn test_reservoir_remaining_is_what_the_writes_left() { SYSTEM_CALL_GAS_LIMIT, ); assert_eq!( - mega.result.gas().reservoir_remaining(), + mega.reservoir_remaining, DEFAULT_RESERVOIR - writes * slot(), "{writes} writes", ); @@ -319,7 +283,7 @@ fn test_a_failing_system_call_settles_like_op_revm() { 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.reservoir_remaining, DEFAULT_RESERVOIR, "nothing kept"); assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); @@ -332,7 +296,7 @@ fn test_a_failing_system_call_settles_like_op_revm() { SYSTEM_CALL_GAS_LIMIT, ); 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, @@ -402,7 +366,7 @@ fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { SYSTEM_CALL_REGULAR_GAS_LIMIT, ); assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), 0); + assert_eq!(mega.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(); @@ -432,23 +396,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 +459,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/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/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index a0fff80aa..ebb4e7171 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())) }; @@ -1031,11 +1031,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/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 90a8b9a40..8ad2ef057 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -105,8 +105,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", ); } @@ -240,10 +239,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 +277,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 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 dd4b0ab81..d142aee16 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=0x563c2538189232c42fe596a21c5f2b9e2bd0ba5b074ee1b208bc3d4e88c181cf", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x86c98b3191b04ec2645753e17e62a1888a4f8c42aaf9cce7256af3727a7c25c0", - "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=0xbf76a42ed427e64d62ab6c0ea96b20181bd7f1a7918642bd895c44dd33d429ab", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x13a7db43ef62af595ed78f1c233c9ea743d8b2bdf1b227b4bade5112932931e0", + "rule: value @ 50000000 | keccak256=0x32e127d6c4c3d862e527382016152b78430a70faf7ef66fc3b89e8db19fe7fc2", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x5ec2c3380c7c50550621e8e3f4e6184b97627f59e8e0e84ea03f0ead8e756fd9", + "rule: arguments that do not decode @ 50000000 | keccak256=0xfabc9647b618b9b871176f5c368ca06fe88ea60ddfce3d7921dda7513b5b5f70", + "rule: malformed transaction @ 50000000 | keccak256=0x3d7b7cf2cb58e065fd0a393f5964819cfd0bcb223f276326af65b87333fdded2", + "rule: a trailing byte @ 50000000 | keccak256=0x9d8d5b538965ca6ce930be14c371d3fd73c29bbedfccd649bf9a43052588f656", + "rule: not a creation @ 50000000 | keccak256=0x753b01095b0e6b82fe69268face02fc174caec81c4288265db8c10457a0acd4e", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0xbd17be82c15a65317e5b31383d1c191b036d274d42d7078b4986fa8cdc8c734f", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x6513b47dc3fa557c390ade0b18a47021e5ce37e427fba7189fe84f089b650b1b", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xc939cb81da1cbeb80d33d107388f70a052abd126014d6b94da4fd52a7ae0155e", + "rule: invalid signature @ 50000000 | keccak256=0x12f095dd420797ce04e8721d211eb6a7cee720572f81cdc5050fc95077e56e47", + "rule: signer nonce 2 @ 50000000 | keccak256=0xe83367f1d2d95fef8714a65b741ec03ebebcd833d654aef385940d0bc77a5fbc", + "rule: signer with code @ 50000000 | keccak256=0xe76e29fa53120706fc1f14b796fa2178fa403c5defc66ea993db43cf0411d837", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x72cdec61618a4e0459014006d0acfc7928ded0ad2135024f331b90fca368e47b", + "rule: occupied address @ 50000000 | keccak256=0x1cc9153e4cb8f8dd82197405914df3ad6adc78995b6c31e3702425823075195c", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x56876ba1a9dbe188ad837037460c926af84fb67a3ce2b490f7ccc7fb996c29e8", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xbbc37a434deaf690a8998cbdc7645c9b679e79615c43b1201793164a7d4a9e78", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x794a655eaa2553e7894c47c6c02a377ddc5c3d1d1f5ed294a43c8af67b204c30", + "deploys from nonce 1 @ 50000000 | keccak256=0xf6dfd5ad051c64c637309e77da7fb370dee24c6a569b8fef131152767682fed8", + "the address already has a balance @ 50000000 | keccak256=0xe6350edd3c01f3cc5507ef7227d03444d6640add5a7d9ab454ce04ba9c9d677f", + "moves value @ 50000000 | keccak256=0xb7ca4d8f5aac293ab7b4f16bc2821fd0a2ccad360aba7ec815eab6300ec782a0", + "moves value from nonce 1 @ 50000000 | keccak256=0xa508e116c8525b81c4c27cdcd6de310b7261d86beb8e5a61c92c810d5168dfa8", + "the CREATE2 factory @ 50000000 | keccak256=0x9defc54fcea8addd1b41ef5ce2a01b6064a012f2e769f12f051dcbe9e9739c1b", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x20363fe8b2ac7c8a27262c342109378581f998ec6d11b552962e528cc3848fe3", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x7658acefecdb9e68eb1edc8ee3e0a352e729d9d03095e0a8413f0311f371805f", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0x88f6e7d3a3a0e23aca47cc250c88042cc6c9ee2b7f5951fd692a156d0a9daac9", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x8a994094dcc131c0cb43fea37cbcafebb13c49da83c5988206eff35563f2fcff", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x9edeb46f45a2b9ba4bc505e6788a3d316ed5be4ddb3f29fad7ea7c8eb1dab899", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x6ee8ef7bd6a030c1ec50a295a3f2825dc9f5b22166840a645ad29169d3d33cf8", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x090e600aadd82297b31263d204dfc6b8e715890cb6b2085f7c51468eeaf1c34f", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x0646f099491c9d3429c1b22772b70ec343121d4209d18db2d223794b31e92d6e", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0xe4f3abec05741d8c9fa83fac86523bf7f36dde48f26d344e5ac70084647c5a4d", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x0b5a5aa504cd3254a6294f30869b6a8617b8d32430417ca8d5d3302e37161da2", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xecdf635bd46b7552f5f4003d689038426081a6656d4cf6f70fba84f041513c4e", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x81e50cb977f473cebe6189fda1dad77e5451cf084b8e00cb32ba39c1c2acc0eb", + "a constructor out of gas @ 50000000 | keccak256=0x4a2b0a5a139dc4f2deac9cef3c81d0c5dcf1cf16f395723ee1ac2e169027e20c", + "the signer sends it @ 50000000 | keccak256=0xf4b217ee909a34fa24eb33e69e22d991934921666a4b7c09575b408d26a8b649", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x68fc6964cb808234a2d1d33f585fb4c9657f484b0d356ffd331bf6397d41128d", + "a delegated signer @ 50000000 | keccak256=0x7330f3b25240cd042d903a307ceebd468712ab0e0c9bc53956b352a836793277", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xdd703fa6882916d0ca48e3fd6471a71950ba478f7d2efd69c8e3801c81dbe3b2", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x41ee8ae476e6201aaa92cdd797aaff01b27948cf491fa6c3c56cdc0424fd1724", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x37a162d66e66eaef26783bc9561e06aba6dce9824835444dfc73e7034f404684", + "limit: compute, nonce 0 @ 50000000 | keccak256=0xc2631c368e7d21e89e7323514c180d9b25e176ed5f9670dbd34913cd5187eff7", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xa65b39c137245c46091e529c2f7944aa2e62cf30dcbc9a73becaf82c0896fb43", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x0ceeaf101b1fee07554f6921d6569826a7ec2c3a3cf0536aa0aa2ac3bba5f861", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x16ef5657b25cfc98fde279c24028149997b65d743364890fdcc5f2a6ededeac6", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfc3ec81976944e9a9a74e281b679e51cb8fa90dd35d22e93d9a7b87051e6be8c", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x2ec14b4f0383ea6b0f12d50f0cd563bc00fa9092e50d22a156ca442852284686", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x519591ff76aad51fcf7b46f3f07b43680648bb0fe64308d600dc7ae0fd10d477", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x8f1596f86a5a6443ee8242b11d986b0a2d525485d2f579b0373cc2c44d12f4d1", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xe3e92aa87207f7c32e09845c17a80c911567cfd6938857c8f39e41ec2ceee873", "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=0x5b79812ff316d7436d9c98fcdf3e7491afc928032cb26fe7901ca534b0f0a968", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xdb08fbc4f6bcb751a845c920299f5b3fdb7ee2b1176a53e3b4cd2ead628ba76f", - "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=0x49182fdae5b1b8ee2aca9ddc7090e8111d754a062b514bb30d76e3c9ff12e75f", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x7b58cb388000f0a13245b90261bc7de760860180921c122862110ad3574029db", + "limit: the default limits @ 50000000 | keccak256=0xd8fc1b80ef6e59850a033311e764a0c0b324711ab87b7e9f228d81fef2b6e862", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x9d754342c40b514543e0f20d22761b08fb573db9e47e5ab0c37002f08247ffae", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x4b09c30811e005f448c0b99dacb90ed0c821bb69819563758e3835e5950efd80", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xc290bda4152920c918e83ea5e3f59ea87b95b4c38276173fe493e8f3c5e7a55b", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x5bf4131809cf73d80be4dc42e7444e40d52a2216e54fbc9ce64a93dd2cbb2750", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x213fa7e0cf47df7801303f285ad4f1d2671c77850a1acfbb418c0a73581001f8", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xfb0daf3fff5b193acf10c5c4c6e07f56103f8e34bba116c02e0b19816e97d0d7", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x67b1800a5d3d0a89ece8785d2ecbd1440c2f4c2233cbedd130130528a24995e1", + "not dispatched: version() @ 50000000 | keccak256=0x012db0dd4056435f91b578f704d89b2403e5ee8aa546bf5938ee2c8b29302db8", + "not dispatched: no selector @ 50000000 | keccak256=0xa2dd7ce0ac78254d620a50f31df1359066dc31453b857f3f141e02f85dcd495e", + "not dispatched: from a contract @ 50000000 | keccak256=0x9a6219ff6a37c8d7f15944cfa621aecc9ee887836e7c6095d79fe7fa27377ebb", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x7c9e8aba2966417968663ad8a0cf8fe425d1cf768ff2c7d01eb1533c5a302b42", + "no contract code @ 50000000 | keccak256=0xa781ab3fb45d2eb3ce305104a970b9f37e9696b53b9116ceadcf8d2a5dbccc44", + "a system call @ 50000000 | keccak256=0x0c6827dd67a583c406d822bb6be663e1f2181d7169031b788689b69f4df1368d", + "rule: value @ 400000000 | keccak256=0xbf8b1ec960298877fdb19bd98d81c5d12e468e5f0f1ea4b6f6211f056182cf86", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xa5b782b90fe088899e5f64da600964352b0c15127d5bbcd4b6f0615cd57a7872", + "rule: arguments that do not decode @ 400000000 | keccak256=0x4f62b297a17843c8efb18ca1db2085bc21d5214f1533207bd4b1822cc17383dd", + "rule: malformed transaction @ 400000000 | keccak256=0xbe95f76f8f3110c158bb566e06703c619ce372604ed92edf26566831a7af207a", + "rule: a trailing byte @ 400000000 | keccak256=0xb34fab993aa8b36d8a797878da1efffcd1bbc250e2a61a3d06efa9a4bf11dd3d", + "rule: not a creation @ 400000000 | keccak256=0x7513600f734e60c577538bc669aed90e20c921cf6647399a9cd2cd0da7dfc902", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x48cedb3705954bed9029105fe9f1533547d5fc2906f0622291b9f0fed393b2a2", + "rule: signed at nonce 1 @ 400000000 | keccak256=0xbfa3e0ca7a0b001efdb1984f96db0dc71e000721ef128f3ab1b934906a225885", + "rule: override below the signed gas limit @ 400000000 | keccak256=0xd88431eade0790516f127cc0a1a0708f0e47957eab688073ed4e7ff31f2e9e19", + "rule: invalid signature @ 400000000 | keccak256=0x9f9efe417c783be1664401bef0de138ceffc6153507b0196d2fdc5beb3e06dcc", + "rule: signer nonce 2 @ 400000000 | keccak256=0x52850f08a7f8b5ccbac2abcc15927231eef0c7a5ea1885b6d69a083e2f66f7c4", + "rule: signer with code @ 400000000 | keccak256=0xb43427299f42b4ee56254bdb857544d23ba4da7cf93f1bbd7e7a0659c91d77a3", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xacdcac30a6ec827840cd9af82403d36f904fa6a13c82f1d12eb3c0f0fa5b0e19", + "rule: occupied address @ 400000000 | keccak256=0xbc0dc0d08f77077e23fdf5928ab179afdc08c204dc12f87d4f9fc8f11de63d8f", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x0b3e4a7a6caa16e6dad6eb8bd6073ab811264470bf2ac4d3dbf16247e51e6756", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x9eef5c415b054097f2b05ea81a705f3cc8e2bf63e0c709996c73f8f18fc4448f", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x9d61f6180375c5390d6a20cc1e18e394b83248708835e87f3369bc1dd1413454", + "deploys from nonce 1 @ 400000000 | keccak256=0xd05aad7c48c761c24f143ff3c6ad8e018dadb04aa974c848a3f4f4e74e7b73b9", + "the address already has a balance @ 400000000 | keccak256=0xa46e4d68f4852cdbaa6855f65385a4d74e80cf13294da3a07c9aa5db565f5727", + "moves value @ 400000000 | keccak256=0x14184a1d8be28567f143bfd50f0cffc340514459531a659cbe61da1aa9d374aa", + "moves value from nonce 1 @ 400000000 | keccak256=0xc1f491c7c65cfdac3e955bda5d0e109ae973724214ce10dcbd86d8ab987c42bd", + "the CREATE2 factory @ 400000000 | keccak256=0x593d3f328f4e1c8a5405be9652ce2681c99d7f69bfe578d63f6739fb862ba7a9", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xeaf9df1c39ec19aa926968308c6d4bcf1078c00e15ff55c6ad053b2472bc425a", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x7fccd4eb3f4d9e7d089443c00fd60aef0b5a3156067ea0d9fda1fc6be09dc00b", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0xab285f069bad22c980214cc6f0c48e0905397a307b623adbe0e27d30876d48aa", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xb563c73f2becdd16d894f7b7c365ed2456dd81e49bc53401ae17cbfe8adb7ac9", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x54819c71d7208cd779a459870e9ca6fbb3b4ac15141af5b1a443848479d62b3b", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x98e21e5b40eb07ef81ad46a2bda808a2fbf79a4f2bcf736b2fd9f864ba85510a", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x9f4a7808e3bf06652a83f5b6df4e762a85e6bc4564ef7192f6535fcebfca3aaf", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xf0b3c5d9d151c0add55bd1454d71d0b3d181014e0f6e69167e75b1b177ed7ade", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x3da6beb7b1b7d27328bda18af075c6d6f23dfbe5bc0dcd17078c00c8fd8502ad", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x487530c68a0a31093a7161d5e51b7c044abc39bfaa39619da4080bfb1ae8c10e", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x6d1221ed777d1119fd2cc83e6de1c3e03e8f813d97d6cb3b88cceeb09eddcc58", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x7d102dc0c3d0bea4c3384044a69ddd139229040a72968a7bbef7ea70c86af005", + "a constructor out of gas @ 400000000 | keccak256=0x60db547a068a7d4b1c666aeb6fa67279eb75f6e684083861aa18ee2f5896f77b", + "the signer sends it @ 400000000 | keccak256=0x23d3e43c0591e50bead0e091db67aef632a77f7b789a26ab426cfc7a69814e21", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xa530a2b24e4f4c977e1a73999e343d6230c3372f7467d49901451ab310e9df54", + "a delegated signer @ 400000000 | keccak256=0xe0d591f3e38dda862488a1009602e3f3b24a7ba333a9fbda56fc2f8c0caaa7a7", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x0b7d568b7270ccde9eb252f3a60aef197c80f4e4720c9f673d6b09da8538aa6c", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xa2c3e89c11a418a2ad592b75dbf3ba4ef19f95e5634dbdd9a2552f4cbbb223b9", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x3fda5141c92c11c841821a4754de70393a313b6384e6e0bf8d2606dbe6d03f02", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x02f6f21cfc59e30ec997eaf750e39eba6a2b2cce4844e781dbcf118e2be5a1f1", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xa3d35dab98f17e60684b7fbcdb827fe82f004950301da26d87e78d7ba5125ec1", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xdb5e2d786cf84bd8c57d844f9d33c074735b0c7457e6cbf68c3fb66a9a88aabf", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x97e3915f1b9d2e3fe4c473a182b1dd5262fd8143ad765da63a3d20aa6ed5beb6", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x9482d4309b67ed34e4a9cd81480f3ac412dc428b4f8be119c8ce6da847650bf0", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x51b12b6471b58aae1bf288e49fc96363dabad62935fed9e53d5e988f1714f280", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xbe7a4b9b28f7b381c4889456ad8396f07fff0bc465722d021db69769e81852f3", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x79c1c1a6ba7f1d66e3e10cd3f5a19d706963fce44e18365bc61ddb2a56aaf830", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xed059de9072084c0cb48a30e520a4cbe621eb6e181f487dda43010e8a4b8e3a8", "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=0xb30a667ac091db1a3cd9ec446b4a07a89c5708d5ef2828142a56116ec8a9b532", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xf1e5506faa79785026d6a61d955ddf0fec8b18266c9b30291b2223e024a8a88a", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x0ba0cd288c2eea3f4dae0aaa76f88e09f30aa3675a76c85b775f7db167cf9305", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xf967b7846d165534ebbba8b4f557549c3428a802ea2d3f6645ba8a11b82df13d", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xd0ba998a740373b278c9758023bf74f6a8c14b8d78e83c3a29b9f237954c6ff8", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0xbc23f753100b78da4dffbb4179682ffde30965fd467c0fa5fff882e8ce492084", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0xacacfe1a26f8f2f960a9a874f882f86efa99ccd93d81052ebe9c3882be7dcdc3", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x93e270afa02f2c36c7ca2c590c8c0b375f276ef56fba8a46749926c956ec96d5", + "not dispatched: version() @ 400000000 | keccak256=0x076ebe076e73f9c816e4a087c552db1c0958aade9e9c8bde0e4f3259ff4d4528", + "not dispatched: no selector @ 400000000 | keccak256=0x9af766c263638d7bda8a38853ace3da20e67197f235f9d046540b219feff51a6", + "not dispatched: from a contract @ 400000000 | keccak256=0xa92e8257fe6dd27b5654ae3784dbea6b76f2a299b5f595c0d858c6a6dcc83de6", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x7c6d8d153d7e970248fd2cfcb8ecbff2fd52176274902baaa905fd52150a83e3", + "no contract code @ 400000000 | keccak256=0x591cbcfdfc6f20a914d9eb7a784d14abdc3fdcbb00598d638b54022fc0500379", + "a system call @ 400000000 | keccak256=0xe64d8b07830e675c4c49f01bbbad5c5d39f6d53fafe9410746d57b83d3caba0d", + "out of gas: the overhead @ 161535 | keccak256=0xc72abadf5209f0081056bed175cc07e3e83a3af77cd91e35c31b2d18eb63502d", + "out of gas: the signer's account @ 162536 | keccak256=0x740a42ebfde771dc0c2e9ed8722599b1bd40e509bf43e7d4e33e45d41e2ffcce", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x1075d3e85809cee95fc0c6aed52a5b240cd70b3981b024a0aa838d9d781a5552", + "out of gas: the creation's charges @ 163024 | keccak256=0xad8555a91355f30b8e442d1701cf3b26b5485feccc9423dfbe73424d1f443715", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x3254c59dbccad8c83e235ff4ff302475c879f1c821be6b5a6ccd5841f952a538", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x396c7588a13a4c29413037de16e518f10a44b17f8abed0de97303b0c39ff51fc", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x6a1dd7d98b6bf1e7765a8650149bf565dfb0a4a10eea6a2c5120207073419150", + "rule: init code over the limit @ 150000000 | keccak256=0x960eb6e8c4e829af439106007ece5846551074beb2cc3eaac307207d9b40c860", + "rule: init code over the limit @ 2000000000 | keccak256=0x58da5d395d2b47867b957a47072721843bc4fd359f62379c21e38c78965b156c" ], "summary": { - "bytes": 2393338, + "bytes": 2407322, "cases": 139, - "lines": 11444, + "lines": 11452, "runs": 556 } } diff --git a/crates/mega-state-test/src/digest.rs b/crates/mega-state-test/src/digest.rs index 09c5012e4..3faf44271 100644 --- a/crates/mega-state-test/src/digest.rs +++ b/crates/mega-state-test/src/digest.rs @@ -66,14 +66,16 @@ fn address(address: &Address) -> String { format!("0x{}", to_hex(address.as_slice())) } -fn result_gas(gas: &ResultGas) -> Value { +/// 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", gas.reservoir_remaining().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()), @@ -161,24 +163,24 @@ fn state(state: &EvmState) -> Value { object(state.iter().map(|(addr, account_)| (address(addr), account(account_)))) } -fn result(result: &ExecutionResult) -> Value { +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)), + ("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)), + ("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)), + ("gas", result_gas(gas, reservoir_remaining)), ("logs", logs(l)), ("reason", format!("{reason:?}").into()), ("status", "halt".into()), @@ -193,7 +195,7 @@ pub fn canonical(executed: Executed<'_>) -> Value { ("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)), + ("result", result(&outcome.result, outcome.gas.reservoir_remaining)), ("state", state(&outcome.state)), ("usage", usage(&outcome.usage)), ]), @@ -231,7 +233,6 @@ mod tests { .with_state_gas_spent(30_000) .with_refunded(4_000) .with_floor_gas(21_000) - .with_reservoir_remaining(5_000) } fn outcome() -> MegaTransactionOutcome { @@ -254,7 +255,7 @@ mod tests { }, state, ), - gas: MegaGasUsage::new(&gas(), 10_000, 125), + gas: MegaGasUsage::new(&gas(), 10_000, 125, 5_000), usage: LimitUsage { data_size: 500, write_records: 3 }, limit_exceeded: None, oracle_reads: vec![OracleRead { slot: U256::from(4), answer: Some(U256::from(5)) }], From 9b2ba4e886bcb545e1bbfef5c78dc2af5268aca2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 00:51:00 +0800 Subject: [PATCH 396/458] fix(evm): keep the fork's legacy journal switch off whatever the configuration says The revm fork carries a switch back to revm 40.0.3's journal semantics for the engine that reproduces that version. Satin's journal runs the fork's semantics: the spec configuration fixes the switch off, as it fixes the other fork switches, so a configuration carrying it (the legacy engine exports it on) changes neither the configuration nor the journal's copy. The neutral configuration keeps it off as well: the journal's semantics are the machinery under test, not a price. --- crates/mega-evm/src/evm/context.rs | 57 ++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 01229ebcd..974fb3572 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -133,7 +133,8 @@ 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 chain-id check and the two code-size limits. Every other field (chain + /// 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. @@ -158,7 +159,9 @@ 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 @@ -173,7 +176,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; @@ -565,6 +570,12 @@ 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). /// +/// 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 /// transactions a chain accepts is the chain's rule, not a caller's choice. @@ -578,6 +589,7 @@ pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { 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 } @@ -685,7 +697,17 @@ mod tests { 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. @@ -699,6 +721,7 @@ mod tests { code_size: Option, initcode_size: Option, gas_params: &'a GasParams, + legacy: bool, } impl<'a> Fixed<'a> { @@ -713,6 +736,7 @@ mod tests { code_size: cfg.limit_contract_code_size, initcode_size: cfg.limit_contract_initcode_size, gas_params: &cfg.gas_params, + legacy: cfg.legacy_journal_semantics, } } } @@ -763,6 +787,7 @@ mod tests { 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); @@ -770,6 +795,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() { From b8bdc5bba641e5f9410b52aae21a173ba8c8d71b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 00:55:51 +0800 Subject: [PATCH 397/458] fix(evm): keep the failed-charge record to the frame's own charges The revm fork records the regular gas a frame had before every failed charge, never clears it, and records a later halt only when no record is there. Two writers are not the frame's own failure: - A callback's refused charge: StepGuard puts the record back, with the crossing, around step, step_end and log_full, and around initialize_interp, which a frame's start now calls through it, so a halt the interpreter refuses before any charge records what the frame has then; a record an opcode's failure left before the callback stays. - abandon_frame: the failed records charge recorded the gas left after the forward was taken, so the record is written again once the forward is back; a price that cannot be computed fails before any charge and is recorded the same way. --- crates/mega-evm/src/evm/execution.rs | 7 +- crates/mega-evm/src/evm/inspector.rs | 138 +++++++++++++++--- crates/mega-evm/src/evm/instructions.rs | 6 + .../mega-evm/tests/satin/inspector_limits.rs | 86 +++++++++-- 4 files changed, 200 insertions(+), 37 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 3fccd1ddf..5ac2774e3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -754,7 +754,7 @@ where inspect_logs(ctx, inspector, logs_i); } if !keyless::runs(ctx, frame) && !stopped { - inspector.initialize_interp(&mut frame.interpreter, ctx); + StepGuard(&mut *inspector).initialize_interp(&mut frame.interpreter, ctx); } Ok(ItemOrResult::Item(frame)) } @@ -763,8 +763,9 @@ where /// 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. + /// The step callbacks run through [`StepGuard`], as `initialize_interp` does at the frame's + /// start, 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, diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 88d30da55..103162664 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -90,13 +90,16 @@ //! 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`]). +//! crossing, and an opcode's failed charge records what the frame had, which detention reads as +//! what its halt burned; the refusal of an inspector's charge is neither, 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. +//! until detention next sets it. Only the two records of a refused charge are 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 @@ -110,8 +113,8 @@ use revm::{ handler::FrameResult, inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ - CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, - Interpreter, InterpreterTypes, + gas::WithheldCrossing, CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, + Gas, InstructionResult, Interpreter, InterpreterTypes, }, primitives::{Address, Bytes, Log, U256}, Database, Inspector, @@ -304,19 +307,23 @@ 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 +/// A regular charge the frame's spendable gas cannot pay is refused, and leaves two records: the +/// regular gas the frame had before it, which gas detention reads as what a halting frame burned, +/// and, when the part detention withholds would have paid it, 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. +/// frame at once, so its records are the frame's end. An inspector's does not: the interpreter +/// never sees it fail and the frame runs on, and a halt that no failed charge records — a cold +/// access the frame cannot pay — keeps a record already there. So both records a callback leaves +/// are put back to what they were before the callback, and the frame ends on the charges it made +/// itself; a record an opcode's own failure left before the callback stays. /// -/// 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. +/// It stands in for the inspector in revm's instruction loop (`inspect_instructions`), which makes +/// four of the callbacks forwarded here and no other, and for the one callback a frame's start +/// hands the interpreter to before the loop, `initialize_interp`; the rest of 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> @@ -324,25 +331,32 @@ where I: Inspector, INTR: InterpreterTypes, { + #[inline] + fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let records = gas_records(&interp.gas); + self.0.initialize_interp(interp, context); + restore_gas_records(&mut interp.gas, records); + } + #[inline] fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); + let records = gas_records(&interp.gas); self.0.step(interp, context); - interp.gas.set_withheld_crossing(crossing); + restore_gas_records(&mut interp.gas, records); } #[inline] fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); + let records = gas_records(&interp.gas); self.0.step_end(interp, context); - interp.gas.set_withheld_crossing(crossing); + restore_gas_records(&mut interp.gas, records); } #[inline] fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let crossing = interp.gas.withheld_crossing(); + let records = gas_records(&interp.gas); self.0.log_full(interp, context, log); - interp.gas.set_withheld_crossing(crossing); + restore_gas_records(&mut interp.gas, records); } #[inline] @@ -351,6 +365,23 @@ where } } +/// A frame's two records of a refused regular charge: the crossing of its withheld gas and the +/// regular gas it had before the charge. +type GasRecords = (Option, Option); + +/// The records of a refused charge `gas` holds before a callback runs. +#[inline] +const fn gas_records(gas: &Gas) -> GasRecords { + (gas.withheld_crossing(), gas.failed_charge_remaining()) +} + +/// Puts the records [`gas_records`] read back on `gas`, over whatever the callback left. +#[inline] +const fn restore_gas_records(gas: &mut Gas, (crossing, failed): GasRecords) { + gas.set_withheld_crossing(crossing); + gas.set_failed_charge_remaining(failed); +} + /// The journal's entry and log counts, for the debug-build proof. `None` in release builds. type JournalSnapshot = Option<(usize, usize)>; @@ -668,3 +699,68 @@ fn upfront_charge(input: &FrameInput) -> Option { synthetic_frame_result(input, InstructionResult::Revert, Bytes::new()) .refundable_state_gas_charge() } + +#[cfg(test)] +mod tests { + use super::*; + use revm::interpreter::interpreter::EthInterpreter; + + /// Charges `amount` of regular gas from every callback that holds the interpreter, and + /// ignores whether the frame could pay it. + struct Charges(u64); + + impl Inspector<(), EthInterpreter> for Charges { + fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut ()) { + let _ = interp.gas.record_regular_cost(self.0); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut ()) { + let _ = interp.gas.record_regular_cost(self.0); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut ()) { + let _ = interp.gas.record_regular_cost(self.0); + } + + fn log_full(&mut self, interp: &mut Interpreter, _: &mut (), _: Log) { + let _ = interp.gas.record_regular_cost(self.0); + } + } + + /// Runs `callback` of [`StepGuard`] around `inspector` on `interp`. + fn guarded(callback: &str, inspector: &mut Charges, interp: &mut Interpreter) { + let mut guard = StepGuard(inspector); + match callback { + "initialize_interp" => guard.initialize_interp(interp, &mut ()), + "step" => guard.step(interp, &mut ()), + "step_end" => guard.step_end(interp, &mut ()), + "log_full" => guard.log_full(interp, &mut (), Log::default()), + _ => unreachable!(), + } + } + + /// A charge a callback cannot pay is refused and leaves no failed-charge record behind: the + /// frame did not fail, and a record left there would be read as what the frame had when a + /// later halt that records nothing of its own ended it. A record an opcode's own failed charge + /// left before the callback stays as it was, whatever the callback's charge did. + #[test] + fn test_a_callback_leaves_the_failed_charge_record_as_it_was() { + for callback in ["initialize_interp", "step", "step_end", "log_full"] { + let mut interp = Interpreter { gas: Gas::new(1_000), ..Default::default() }; + guarded(callback, &mut Charges(1_001), &mut interp); + assert_eq!(interp.gas.remaining(), 1_000, "{callback}: the charge took nothing"); + assert_eq!(interp.gas.failed_charge_remaining(), None, "{callback}: no record"); + + // An opcode's charge failed with 1,000 left, and its halt zeroed the frame's gas: a + // callback after it fails its own charge on nothing left. + assert!(!interp.gas.record_regular_cost(1_500)); + interp.gas.spend_all(); + guarded(callback, &mut Charges(1), &mut interp); + assert_eq!( + interp.gas.failed_charge_remaining(), + Some(1_000), + "{callback}: the opcode's record" + ); + } + } +} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 01ab40c82..4c6da2a4f 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -331,6 +331,11 @@ fn charge_frame_start( /// 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. +/// +/// The halt's record of what the frame had — the regular gas the revm fork records before a +/// failed charge, which detention reads where the frame ends — is written again once the forward +/// is back: the failed charge recorded the gas left after the forward was taken, and a price that +/// could not be computed failed before any charge. #[cold] #[inline(never)] fn abandon_frame( @@ -340,6 +345,7 @@ fn abandon_frame( if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); } + interpreter.gas.set_failed_charge_remaining(Some(interpreter.gas.remaining())); note_halt(interpreter, host, Err(InstructionResult::OutOfGas)) } diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 86c7d8fef..d21832ff4 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -5,7 +5,8 @@ //! 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. +//! even under gas detention, where the same refusal of an opcode's charge is the crossing, nor +//! for what a later halt of the frame burns. //! - 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. @@ -17,7 +18,7 @@ use mega_evm::{ MegaTransactionOutcome, }; use revm::{ - bytecode::opcode::{LOG0, POP, PUSH0, TIMESTAMP}, + bytecode::opcode::{BALANCE, CALL, JUMP, JUMPDEST, LOG0, POP, PUSH0, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, InterpreterAction, InterpreterResult, @@ -30,6 +31,8 @@ use crate::common::{call, context}; 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 +143,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 +190,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 +228,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 +248,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 +256,42 @@ fn test_an_inspector_cannot_overdraw_a_frame() { } } +/// A charge an inspector's callback could not pay leaves nothing behind for what the frame burns +/// when it halts. `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 records what `B` had. What `B` burns is what it had at that +/// halt, not at the refused charge: counted as compute, the difference would leave `A` a longer +/// run to the limit, and a larger bill, than the transaction no inspector runs. +#[test] +fn test_a_refused_charge_leaves_nothing_for_a_later_halt() { + 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); + for from in [Callback::InitializeInterp, Callback::Step, Callback::StepEnd] { + 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"); + assert_eq!(overdrawn.limit_exceeded, plain.limit_exceeded, "{from:?}: the same stop"); + assert_eq!(overdrawn.result, plain.result, "{from:?}"); + assert_eq!(overdrawn.gas, plain.gas, "{from:?}: the same run to the limit"); + } +} + /// How [`AnswersB`] builds the gas of its answer. #[derive(Clone, Copy, Debug)] enum AnswerGas { From 9245e82d0491e75d7dedde39944893fe3866ceb3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 01:03:32 +0800 Subject: [PATCH 398/458] feat(evm): read what a halting frame burned off the fork's failed-charge record The revm fork records the regular gas a frame had before every deduction that fails and before a halt on a cold access it cannot pay. Gas detention reads that record where the frame ends, so the halt-noting machinery goes: the unbounded-charge wrappers (KECCAK256, the four copies into memory, EXP), every note_halt site, Detention::note_halt and left_at_halt. The detention bound is now exact, an opcode's static gas included: a frame that halts because it cannot pay its opcode's static gas burns what it had, where it counted as compute before. The two tests that pinned that over-count now pin the exact bound on the same programs. --- crates/mega-evm/src/access/detention.rs | 46 ++--- crates/mega-evm/src/access/mod.rs | 18 +- crates/mega-evm/src/evm/instructions.rs | 89 ++------- crates/mega-evm/src/limit/mod.rs | 3 +- crates/mega-evm/tests/satin/withheld_gas.rs | 198 +++++++------------- 5 files changed, 107 insertions(+), 247 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 2b19ef2b7..effe4e8f9 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -134,9 +134,9 @@ impl FrameFigures { /// ``` /// /// Every regular charge an instruction makes counts, the ones a callee pays out of a stipend -/// included, so the gas run after a read is at most the cap, but for what halting frames leave -/// (below). The regular ledger bills the transaction its compute less the stipends, which no pool -/// of the transaction's gas paid. +/// 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 @@ -148,17 +148,11 @@ impl FrameFigures { /// 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: 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 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. +/// 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 that drops the frame its opcode was +/// starting records what it has once the forward is back. /// /// # Keeping the figure /// @@ -203,8 +197,6 @@ 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, for a transaction detention holds. figures: FrameFigures, } @@ -234,7 +226,6 @@ impl Detention { self.accessed = VolatileDataAccess::empty(); self.limit = None; self.burned = 0; - self.left_at_halt = None; self.figures.clear(); } @@ -383,13 +374,6 @@ impl Detention { } } - /// 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 @@ -433,7 +417,11 @@ impl Detention { } /// 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 /// would have paid ([`stop`](Self::stop)): the frame crossed the limit, and must revert with @@ -446,7 +434,6 @@ 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; } @@ -459,7 +446,7 @@ impl Detention { } 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()); + 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 @@ -880,7 +867,6 @@ mod tests { detention.on_frame_run(&mut frame, 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); @@ -1017,7 +1003,7 @@ mod tests { /// 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] { @@ -1031,7 +1017,7 @@ mod tests { 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 { diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index a27cdb20e..1b3f15dad 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -44,16 +44,14 @@ //! //! 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. -//! 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, so the gas run after a read -//! is at most the cap, but for what halting frames leave. 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. +//! 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 diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 4c6da2a4f..9a9d15f1e 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -47,11 +47,12 @@ //! 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. +//! 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 wrapper that writes the record is the one that drops a frame its opcode was +//! starting: it hands the frame's forward back to its 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,16 +65,16 @@ 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, CREATE, CREATE2, + DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, LOG0, LOG1, + LOG2, LOG3, LOG4, NUMBER, SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, 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, @@ -105,7 +106,7 @@ pub(crate) fn mega_instructions( 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] = [ + let wrappers: [(u8, InstructionFn); 28] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -134,12 +135,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]; @@ -173,17 +168,14 @@ fn commit_after(interpreter, host, history); - if settled.is_err() { - return note_halt(interpreter, host, settled); - } + settle_history::(interpreter, host, history)?; } result } @@ -304,7 +296,7 @@ fn charge_frame_start( Some(InterpreterAction::NewFrame(input)) => { host.additional_limit.frame_start_records(input) } - _ => return note_halt(interpreter, host, result), + _ => return result, }; if !host.prices_history() { return result; @@ -340,31 +332,13 @@ fn charge_frame_start( #[inline(never)] fn abandon_frame( interpreter: &mut Interpreter, - host: &mut MegaContext, + host: &MegaContext, ) -> InstructionExecResult { if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); } interpreter.gas.set_failed_charge_remaining(Some(interpreter.gas.remaining())); - 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 + Err(InstructionResult::OutOfGas) } /// Hands the frame the running opcode is suspending on the reservoir its caller has now. @@ -437,7 +411,7 @@ fn read_volatile( 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); + return result; } settle_reads(interpreter, host, result, gas) } @@ -462,7 +436,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. @@ -548,31 +522,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/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 59144fdb9..adc4dec84 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -434,8 +434,7 @@ pub enum LimitCheck { /// 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, unless a halting frame's leftover, counted as compute, took the transaction past - /// it before the charge. + /// limit. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 1aa1b80d3..e1fb2514a 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -610,73 +610,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 +660,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 +746,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" ); } } From 276e3c535460d9799e03b9cbb013b85dde9d3d44 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 01:05:51 +0800 Subject: [PATCH 399/458] docs: the exact detention bound and the mega.6 fork Satin's spec states the bound gas detention now holds: what a halting frame burns is never compute, an opcode's static gas included, so no halt takes a transaction's compute past the limit; the overshoot rule and kind 2's note on it go. The overview names the fork release. AGENTS.md records what Satin takes over from the fork (the system-call split, the reservoir report), the failed-charge record detention reads, the legacy journal switch fixed off, and the shared op-revm reference. --- AGENTS.md | 52 ++++++++++++++++------------ crates/mega-evm/README.md | 3 +- crates/mega-evm/src/evm/context.rs | 4 +-- crates/mega-evm/src/evm/execution.rs | 6 ++-- docs/spec/overview.md | 2 +- docs/spec/upgrades/satin.md | 11 +++--- 6 files changed, 40 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7d21317ee..5b24c549d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,7 +104,10 @@ 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. +- The fork pins at the commit of its mega.6 release (megaeth-labs/revm#75, `7bc0c664`), until the tag is cut. + mega.6 no longer splits a system call's gas or reports 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. @@ -125,23 +128,23 @@ 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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 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, 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 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 record of what a frame that drops the frame its opcode was starting has, 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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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, and the settled transaction's history gas, history bytes and unspent reservoir; `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 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. @@ -282,8 +285,9 @@ 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: @@ -320,7 +324,7 @@ Detention caps how much a transaction may still compute once it read such data ( - **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 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, and the gas run after a read is at most the cap, but for what halting frames leave. + 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. 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. @@ -338,7 +342,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 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, 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. 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`). @@ -359,9 +363,10 @@ Detention caps how much a transaction may still compute once it read such data ( 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 that cannot pay its records hands the dropped frame's forward back before it fails, and records what the frame has then (`abandon_frame`): the failed charge recorded the gas left after the forward was taken. + An inspector's refused charge is not the frame's: `StepGuard` puts the record back around each callback, so a later halt that records nothing of its own is not 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`. @@ -397,7 +402,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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 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 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. A frame returns a stop before running another instruction in two cases (`AdditionalLimit::stop_before_run`, `before_frame_run`): on its first run, when its own start crossed a limit once revm built it; and on a resume, when a child left it one — 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. @@ -436,7 +441,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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. + A charge the frame cannot pay is refused and takes nothing, and the frame runs on; revm's instruction loop, and `initialize_interp` at a frame's start, see the inspector through `StepGuard`, which puts back the withheld-part crossing and the failed-charge record such a refusal leaves, 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. @@ -458,6 +463,7 @@ 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/`) @@ -465,7 +471,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - `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;`. +- `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`. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 9bb86423e..0ef6b341a 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -140,8 +140,7 @@ The transaction's KV count is in its outcome's usage and the block's in its resu 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. +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. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 974fb3572..ea022e037 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -134,8 +134,8 @@ 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 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`. + /// 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 { diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 5ac2774e3..f5744e1c9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -286,9 +286,9 @@ where /// reads inside it, and the rest is its state-gas reservoir, which the state it writes draws /// first. /// - /// revm builds a system call's gas here, on no intrinsic gas, and so 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 + /// 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 { diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 3854c1540..3e98d1c88 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 (`v40.0.3-mega.6`; until that tag is cut, its release commit `7bc0c664`), 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).
diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 941b0dddc..4faa323ad 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -495,7 +495,7 @@ The revert data: 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)). +Kind 2 names the 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 @@ -519,7 +519,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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 is not compute, with one exception: when an opcode's static gas cannot be paid, what the halting frame had left counts as compute. + 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. @@ -536,12 +536,9 @@ A contract can revert with the same bytes, and so can a caller that re-raises th - **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. + A frame that halts adds nothing to the compute (see Compute, above), so no halt takes the transaction's compute past the limit: the compute after a read is at most the 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.** 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. From 0149deb26617378bd07c923a022bfaac5c160e3c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 02:23:52 +0800 Subject: [PATCH 400/458] build: pin the revm fork at the local commit with the instruction hooks Every fork crate moves from the mega.6 commit (7bc0c664) to 6147a76d, which adds `Host::write_completed` and `Host::frame_starting` on top of mega.6. The lock moves the fork crates' source alone. The pin is local only (file:///Users/cz/work/mega-revm): it moves to the pushed commit or the mega.7 tag before this branch is pushed. --- Cargo.lock | 26 +++++++++++++------------- Cargo.toml | 24 ++++++++++++------------ 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6ad95fe3c..3b4105d0e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" 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=7bc0c664b89ff7fe2e80651893838193ba151e35#7bc0c664b89ff7fe2e80651893838193ba151e35" +source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index 4f7e429fa..e8505c0a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,18 +232,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", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "7bc0c664b89ff7fe2e80651893838193ba151e35" } +revm = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-primitives = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-interpreter = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-context = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-context-interface = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-handler = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-database = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-database-interface = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-state = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-bytecode = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-precompile = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm-inspector = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } [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 cf8277eee2044791f09b5b7a737887ba8f5f2ee2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 02:26:10 +0800 Subject: [PATCH 401/458] refactor(access): hold a frame and read its compute off its GasTracker --- crates/mega-evm/src/access/detention.rs | 45 ++++++++++--------- crates/mega-evm/src/evm/instructions.rs | 2 +- .../mega-evm/src/system/keyless/dispatch.rs | 2 +- 3 files changed, 26 insertions(+), 23 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index effe4e8f9..cb68b7064 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; @@ -83,7 +86,7 @@ impl FrameFigures { /// 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; } } @@ -342,7 +345,7 @@ impl Detention { if cap == u64::MAX { return; } - 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)); } @@ -368,7 +371,7 @@ 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))); } @@ -392,7 +395,7 @@ impl Detention { return; } self.figures.on_frame_run(gas.limit(), depth); - self.hold(gas); + self.hold(gas.tracker_mut()); } /// The frame at `depth`, whose gas is `gas`, suspended to start a child, to which revm gives @@ -442,7 +445,7 @@ impl Detention { } self.figures.on_frame_end(depth); if let Some(limit) = self.stop(gas) { - return Some(ComputeStop { limit, used: self.compute(gas) }); + return Some(ComputeStop { limit, used: self.compute(gas.tracker()) }); } if result.is_halt() { // The settlement rolls the spill back into regular gas and burns it all. @@ -564,7 +567,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) }) } @@ -656,7 +659,7 @@ impl Detention { /* Helpers */ /// The transaction's compute while the running frame has `gas`. - fn compute(&self, gas: &Gas) -> u64 { + fn compute(&self, gas: &GasTracker) -> u64 { let figures = &self.figures; figures .suspended @@ -731,7 +734,7 @@ pub fn decode_volatile_data_access_disabled(revert_data: &[u8]) -> Option u64 { +pub(crate) const fn regular_spent(gas: &GasTracker) -> u64 { gas.limit().saturating_sub(gas.remaining()).saturating_sub(gas.state_gas_spilled()) } @@ -804,8 +807,8 @@ mod tests { detention.on_frame_run(&mut frame, 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); } @@ -831,7 +834,7 @@ 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"); } } @@ -899,15 +902,15 @@ mod tests { let mut child = gas(60_000 + 2_300, 0); detention.on_frame_run(&mut child, 1); - assert_eq!(detention.compute(&child), 9_000); + assert_eq!(detention.compute(child.tracker()), 9_000); assert!(child.record_regular_cost(spent)); - assert_eq!(detention.compute(&child), 9_000 + spent, "{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()); - assert_eq!(regular_spent(&caller), 9_000 + spent - 2_300, "{spent}"); + assert_eq!(regular_spent(caller.tracker()), 9_000 + spent - 2_300, "{spent}"); detention.on_frame_run(&mut caller, 0); - assert_eq!(detention.compute(&caller), 9_000 + spent, "{spent}"); + assert_eq!(detention.compute(caller.tracker()), 9_000 + spent, "{spent}"); assert_eq!(detention.figures.suspended, 0); } } @@ -958,7 +961,7 @@ mod tests { 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 + 4_000 + 500; - assert_eq!(detention.compute(&grandchild), compute); + assert_eq!(detention.compute(grandchild.tracker()), compute); assert_eq!(detention.compute_limit(), Some(compute + CAP)); assert_eq!(grandchild.spendable(), CAP); @@ -968,7 +971,7 @@ 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); } @@ -1027,7 +1030,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); } } @@ -1077,7 +1080,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); } } @@ -1188,7 +1191,7 @@ mod tests { 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)); } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 9a9d15f1e..45c29052e 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -245,7 +245,7 @@ fn 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); + host.detention.hold(interpreter.gas.tracker_mut()); result } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 4681f21fe..d494a7e56 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -119,7 +119,7 @@ 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") }; From 1eac47cf602b2f55070a51bd5e3d13d6a9efe3cf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 02:32:09 +0800 Subject: [PATCH 402/458] feat(evm): count and charge completed writes in the Host's write hook revm's SSTORE, LOG0..LOG4 and SELFDESTRUCT call `Host::write_completed` once the write is in the journal and every charge the opcode makes is made. The hook commits the write's record to the running frame, holds it to the limits (a crossing reverts the frame with the stop), charges its history, a log drawing on the frame's allowance first, refills a taken-back record's history, and holds the frame to the compute limit again after an SSTORE. The SSTORE and LOG wrappers, `commit_after`, `settle_history` and `stop_frame` go, and so does the Host's staging: `StagedRecord`, `staged_record`, `stage_record` and `discard_staged_record`. The Host's write methods only write, so a tool's write through the Host counts nothing. SELFDESTRUCT keeps its wrapper for its volatile read alone. --- crates/mega-evm/src/evm/host.rs | 193 ++++++++-------- crates/mega-evm/src/evm/instructions.rs | 184 ++------------- crates/mega-evm/src/lib.rs | 2 +- crates/mega-evm/src/limit/limit.rs | 85 +++---- crates/mega-evm/src/limit/mod.rs | 6 +- crates/mega-evm/src/limit/record.rs | 226 +++++++++---------- crates/mega-evm/tests/satin/history_gas.rs | 2 +- crates/mega-evm/tests/satin/write_records.rs | 62 ++--- 8 files changed, 290 insertions(+), 470 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index cade09497..736e2abbc 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. @@ -63,9 +64,9 @@ use delegate::delegate; use revm::{ context::ContextTr, context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, + cfg::{gas::GasTracker, GasId, GasParams, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, - host::LoadError, + host::{CompletedWrite, LoadError, WriteVerdict}, journaled_state::AccountInfoLoad, }, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, @@ -73,8 +74,8 @@ use revm::{ }; use crate::{ - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, StagedRecord, - VolatileDataAccess, + history_gas, limit::HistoryBytes, system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, + MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -93,6 +94,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); } } @@ -249,46 +266,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,13 +284,64 @@ 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) } + + /// Commits the record of a write an opcode completed, 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 ([`storage_call_stipend`](crate::storage_call_stipend)): a write record is the + /// frame's own to pay for, and a record taken back — a slot written back to its original value + /// — 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 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 (check, history) = self.additional_limit.commit_write(&write); + if check.exceeded_limit() { + return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); + } + if self.prices_history() { + match history { + HistoryBytes::None => {} + HistoryBytes::Appended(bytes) => { + let Some(cost) = history_gas(bytes) else { return WriteVerdict::OutOfGas }; + let drawn = if from_allowance { + self.additional_limit.try_consume_stipend(cost) + } else { + 0 + }; + if !gas.record_history_cost(cost - drawn) { + return WriteVerdict::OutOfGas; + } + } + HistoryBytes::Taken(bytes) => gas.refill_history(history_gas(bytes).unwrap_or(0)), + } + } + if holds_again { + self.detention.hold(gas); + } + WriteVerdict::Continue + } } impl MegaContext { @@ -395,11 +425,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 +440,26 @@ 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.additional_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. + 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" + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }, ); } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 45c29052e..6e0070707 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,31 +1,19 @@ //! 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 four that write state the resource limits +//! count by starting a frame — `CALL`, `CALLCODE`, `CREATE` and `CREATE2` — and 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: +//! The opcodes that write state themselves — `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` — are +//! revm's own: revm calls the Host's completed-write hook at the end of each, once the write is in +//! the journal and every charge the opcode makes has been made, and the Host counts the write, +//! holds it to the limits and charges the history it costs there (see the `host` module). A failed +//! opcode never reaches the hook, so it counts nothing. `SELFDESTRUCT` is wrapped for the volatile +//! read it can make alone. //! -//! 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 +//! The four that start a frame 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 @@ -43,9 +31,6 @@ //! `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. -//! //! 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. The revm fork records that gas first, before //! every deduction that fails — an opcode's static gas, which the interpreter's step loop charges @@ -66,9 +51,8 @@ use revm::{ bytecode::opcode::{ BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, CREATE, CREATE2, - DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, LOG0, LOG1, - LOG2, LOG3, LOG4, NUMBER, SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, - TIMESTAMP, + DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, NUMBER, + SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, STATICCALL, TIMESTAMP, }, context_interface::Host, handler::instructions::EthInstructions, @@ -80,13 +64,13 @@ use revm::{ 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, + charge_write_records_history, volatile_data_access_disabled_revert_data, ExternalEnvTypes, + MegaContext, VolatileDataAccess, }; use super::{input_gas_limit, satin_gas_table, value_call_stipend, MegaInstructions}; @@ -98,21 +82,15 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth 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 opcodes that start a frame whose start 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, satin_gas_table(), spec); - let wrappers: [(u8, InstructionFn); 28] = [ - (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); 22] = [ (SELFDESTRUCT, selfdestruct::), (CALL, call::), (CALLCODE, call::), @@ -143,127 +121,6 @@ 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 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() { - settle_history::(interpreter, host, history)?; - } - 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(interpreter.gas.tracker_mut()); - 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. /// @@ -506,6 +363,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. diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 7c05ab07f..7afe7cef7 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -68,7 +68,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, diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index f9ad7e98a..92c307749 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -2,26 +2,26 @@ use alloy_primitives::{Address, Bytes}; use revm::{ - context_interface::context::CodeDeposit, + context_interface::{context::CodeDeposit, host::CompletedWrite}, handler::FrameResult, interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; use super::{ frame_limit::{FrameLimitTracker, Lane}, - record::{HistoryBytes, RecordEffect, StagedRecord}, + record::{write_effect, write_moves_value, HistoryBytes, RecordEffect}, 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, the stops -/// its frames return, and whether it is exempt from every limit. +/// data-size bytes and write records, 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, stops). +/// system call, and is driven by the Host's instruction hooks (the records of completed writes and +/// the charge of a frame's start) and the frame lifecycle (lanes, stops). /// /// # The stop /// @@ -49,7 +49,6 @@ use crate::storage_call_stipend; #[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). @@ -128,7 +127,6 @@ impl AdditionalLimit { /// 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.pending_stop = None; self.frame_stop = None; @@ -380,22 +378,12 @@ impl AdditionalLimit { self.history_gas_spent = history_gas_spent; } - /* Observe, stage, commit */ + /* Completed writes */ - /// 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, 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. + /// Commits the record of `write`, which the running opcode completed, to the running frame's + /// lane, and reports the history bytes it appends or takes back. Called by the Host's + /// completed-write hook, which revm calls only once the opcode made every charge; a crossed + /// limit in the verdict stops the opcode's frame, and the hook 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 @@ -403,16 +391,12 @@ impl AdditionalLimit { /// 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); + pub(crate) fn commit_write( + &mut self, + write: &CompletedWrite<'_>, + ) -> (LimitCheck, HistoryBytes) { + let effect = write_effect(write, 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, @@ -421,7 +405,12 @@ impl AdditionalLimit { return (LimitCheck::WithinLimit, history); } }; - let counted = if self.transfer_logs && record.moves_value() { + match write { + // A log's bytes are history beside the write records; a record's are counted as one. + CompletedWrite::Log { .. } => self.tracker.record_log_and_code_bytes(counted.data_size), + CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => {} + } + let counted = if self.transfer_logs && write_moves_value(write) { counted.saturating_add(TRANSFER_LOG) } else { counted @@ -433,14 +422,6 @@ impl AdditionalLimit { (self.check(), history) } - /// 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; - } - /* Transaction-level records */ /// Counts the transaction's body: its envelope, the writes its inclusion makes, its calldata, @@ -1005,7 +986,10 @@ mod tests { use super::*; use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; use alloy_primitives::{address, Address, Bytes, U256}; - use revm::interpreter::{CallInput, CallValue}; + use revm::{ + context_interface::context::SelfDestructResult, + interpreter::{CallInput, CallValue}, + }; const SENDER: Address = address!("00000000000000000000000000000000000f0001"); const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); @@ -1646,15 +1630,12 @@ mod tests { /// 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 moved = SelfDestructResult { had_value: true, ..Default::default() }; + let destruction = + |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; 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(); + let (check, history) = limit.commit_write(&destruction(TARGET)); assert_eq!(check, LimitCheck::WithinLimit); assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); assert_eq!( @@ -1665,8 +1646,7 @@ mod tests { 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(); + let (check, history) = limit.commit_write(&destruction(SENDER)); assert_eq!(history, HistoryBytes::None); assert_eq!( check, @@ -1681,8 +1661,7 @@ mod tests { 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(); + let _ = limit.commit_write(&destruction(TARGET)); assert_eq!(limit.usage(), WRITE_RECORD, "no log, no bytes"); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index adc4dec84..2949b4244 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -13,8 +13,9 @@ //! ([`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. +//! bytes and write records, on a lane per frame ([`AdditionalLimit`]). A write an opcode makes is +//! counted once the opcode completed, in the Host's completed-write hook, which revm calls after +//! every charge the opcode makes. //! //! # The data-size limit //! @@ -136,7 +137,6 @@ 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; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index fe980e280..d022e5a94 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -1,39 +1,15 @@ -//! The facts the Host observes for the opcode that is running. +//! What a write an opcode completed counts. +//! +//! revm hands the Host the facts of every write `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` +//! complete, once the write is in the journal and every charge the opcode makes has been made +//! ([`Host::write_completed`](revm::context_interface::Host::write_completed)). A failed opcode +//! offers nothing, so nothing here is counted for a write its failure takes back. use alloy_primitives::Address; -use revm::interpreter::SStoreResult; +use revm::context_interface::host::CompletedWrite; use super::{log_history_bytes, LimitUsage, 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 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 { @@ -72,50 +48,52 @@ impl RecordEffect { } } -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 { +/// What committing the write `write` 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 write_effect(write: &CompletedWrite<'_>, sender: Address) -> RecordEffect { + match *write { + CompletedWrite::Sstore { result: slot, .. } => { + if slot.is_original_eq_present() { + if slot.is_original_eq_new() { RecordEffect::None - } - } - 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 + RecordEffect::Record(WRITE_RECORD) } + } else if slot.is_original_eq_new() { + RecordEffect::Refund(WRITE_RECORD) + } else { + RecordEffect::None + } + } + CompletedWrite::Log { topics, data_len, .. } => RecordEffect::Record(LimitUsage { + data_size: log_history_bytes(u64::from(topics), data_len), + write_records: 0, + }), + CompletedWrite::SelfDestruct { address, target, result } => { + if result.had_value && target != address && target != sender { + RecordEffect::Record(WRITE_RECORD) + } else { + RecordEffect::None } } } +} - /// 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, .. }) +/// Whether the write 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) fn write_moves_value(write: &CompletedWrite<'_>) -> bool { + match *write { + CompletedWrite::SelfDestruct { address, target, result } => { + result.had_value && target != address + } + CompletedWrite::Sstore { .. } | CompletedWrite::Log { .. } => false, } } @@ -124,41 +102,64 @@ mod tests { use super::*; use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; use alloy_primitives::{address, U256}; + use revm::context_interface::context::{SStoreResult, SelfDestructResult}; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); const OTHER: Address = address!("0000000000000000000000000000000000000077"); + const DESTRUCTED: Address = address!("0000000000000000000000000000000000000d00"); - 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), - }) + } + } + + fn sstore(slot: &SStoreResult) -> CompletedWrite<'_> { + CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: slot } + } + + const fn log(topics: u8, data_len: u64) -> CompletedWrite<'static> { + CompletedWrite::Log { address: OTHER, topics, data_len } + } + + fn destruction(had_value: bool) -> SelfDestructResult { + SelfDestructResult { had_value, target_exists: true, previously_destroyed: false } + } + + fn selfdestruct(result: &SelfDestructResult, target: Address) -> CompletedWrite<'_> { + CompletedWrite::SelfDestruct { address: DESTRUCTED, target, result } } /// 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 effect = + |original, present, new| write_effect(&sstore(&slot(original, present, new)), SENDER); + assert_eq!(effect(0, 0, 1), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(effect(5, 5, 0), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(effect(0, 1, 0), RecordEffect::Refund(WRITE_RECORD)); + assert_eq!(effect(0, 1, 2), RecordEffect::None); + assert_eq!(effect(3, 3, 3), RecordEffect::None); + assert_eq!(effect(3, 4, 4), 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 })); + let effect = |topics, data_len| write_effect(&log(topics, data_len), SENDER); + assert_eq!( + effect(0, 0), + RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 }) + ); assert_eq!( - log(4, 100), + effect(4, 100), RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) ); assert_eq!( - log(1, u64::MAX), + effect(1, u64::MAX), RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) ); } @@ -167,26 +168,16 @@ mod tests { /// record's forty, and nothing for a write that leaves no record. #[test] fn test_history_bytes_are_the_records_data_size() { + let history = |write: &CompletedWrite<'_>| write_effect(write, SENDER).history_bytes(); + assert_eq!(history(&sstore(&slot(0, 0, 1))), HistoryBytes::Appended(WRITE_RECORD_SIZE)); + assert_eq!(history(&sstore(&slot(0, 1, 0))), HistoryBytes::Taken(WRITE_RECORD_SIZE)); + assert_eq!(history(&sstore(&slot(3, 3, 3))), HistoryBytes::None); 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(), + history(&log(3, 32)), 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(), + history(&selfdestruct(&destruction(true), OTHER)), HistoryBytes::Appended(WRITE_RECORD_SIZE) ); } @@ -194,37 +185,28 @@ mod tests { /// 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, to_other_account, beneficiary }.effect(SENDER) + let effect = |had_value, target| { + write_effect(&selfdestruct(&destruction(had_value), target), 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, - to_other_account: true, - beneficiary: SENDER, - }; - assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); + assert_eq!(effect(true, OTHER), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(effect(true, DESTRUCTED), RecordEffect::None); + assert_eq!(effect(false, OTHER), RecordEffect::None); + assert_eq!(effect(false, DESTRUCTED), RecordEffect::None); + assert_eq!(effect(true, 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()); + let moves = + |had_value, target| write_moves_value(&selfdestruct(&destruction(had_value), target)); + assert!(moves(true, OTHER)); + assert!(moves(true, SENDER), "the body's record is not the log"); + assert!(!moves(true, DESTRUCTED), "a destruction to itself burns"); + assert!(!moves(false, OTHER), "nothing to move"); + assert!(!write_moves_value(&sstore(&slot(0, 0, 1)))); + assert!(!write_moves_value(&log(3, 32))); } /// A transfer log counts what a `LOG3` carrying one word counts: the same rule, not a number @@ -232,7 +214,7 @@ mod tests { #[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), + write_effect(&log(3, 32), SENDER), RecordEffect::Record(crate::limit::TRANSFER_LOG) ); } diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 0012dc7aa..f9d026169 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -104,7 +104,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. diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index f2aac4aba..023184c45 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1,4 +1,4 @@ -//! 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 @@ -19,8 +19,7 @@ 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::{ @@ -528,26 +527,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.additional_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.additional_limit().usage(), before, "a tool's log counts nothing"); } } @@ -556,40 +553,31 @@ 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.additional_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)); + assert_eq!(after_sstore(&steps), 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. +/// 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() { // CALLEE calls CONTRACT with 5,000 gas: past the EIP-2200 stipend check, so the Host call @@ -604,20 +592,16 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { .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"); + 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"); + assert_eq!(after_sstore(&steps), records(1), "the SSTORE's record, and not the tool's log"); } /* ---------- applied EIP-7702 authorities ---------- */ From e4bfb06257e0c45b74fa14ccc72c2d1a38915ad3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 02:36:27 +0800 Subject: [PATCH 403/458] feat(evm): charge a frame start's write records in the Host's start hook revm's CALL, CALLCODE, DELEGATECALL, STATICCALL, CREATE and CREATE2 call `Host::frame_starting` once they took the forward and before they build the frame's input. The hook charges the caller the history of the records the start makes and leaves the charge for the frame's lane; revm then copies the reservoir the charge left into the input, so a built frame and an answered start both inherit it. A charge the caller cannot pay, or a price that overflows, gives the forward back, re-records what the frame has for gas detention, and fails the opcode out of gas without starting a frame. `charge_frame_start`, `abandon_frame` and `inherit_reservoir` go, and with them the CREATE and CREATE2 wrappers; the four calls keep one wrapper for their volatile reads. The records a start makes are one rule over caller, target and value, asked at the opcode and as the frame starts. The debug check that the records a caller paid for are the ones its frame counts runs on the plain and the observed path only: an inspector that may rewrite a frame's input runs between the two. --- crates/mega-evm/src/evm/execution.rs | 5 + crates/mega-evm/src/evm/host.rs | 44 +++++- crates/mega-evm/src/evm/instructions.rs | 179 ++++-------------------- crates/mega-evm/src/limit/limit.rs | 103 ++++++++++---- 4 files changed, 150 insertions(+), 181 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index f5744e1c9..21434b23d 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -711,6 +711,7 @@ where &mut self, mut frame_init: FrameInit, ) -> Result, ContextDbError> { + let rewriting = self.has_rewriting_inspector(); let (ctx, inspector) = self.ctx_inspector(); // What the calling opcode charged upfront, before the inspector's hooks can rewrite the // call it charged for. @@ -719,6 +720,10 @@ where let output = answered_by_inspector(ctx, inspector, &frame_init, output, upfront); return Ok(ItemOrResult::Result(output)); } + if rewriting { + // The start the calling opcode paid for may not be the one the inspector lets start. + ctx.additional_limit.waive_start_check(); + } 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 diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 736e2abbc..582475ca7 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -66,7 +66,7 @@ use revm::{ context_interface::{ cfg::{gas::GasTracker, GasId, GasParams, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, - host::{CompletedWrite, LoadError, WriteVerdict}, + host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, journaled_state::AccountInfoLoad, }, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, @@ -74,8 +74,8 @@ use revm::{ }; use crate::{ - history_gas, limit::HistoryBytes, system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, - MegaContext, OracleEnv, VolatileDataAccess, + charge_write_records_history, history_gas, limit::HistoryBytes, + system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -342,6 +342,44 @@ impl revm::context_interface::Host } WriteVerdict::Continue } + + /// Charges the running frame the history of the write records the frame it is starting makes + /// — a value transfer's sender and recipient, a creation's creator nonce and created account. + /// 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. + /// + /// 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. 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. 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: &FrameStart, gas: &mut GasTracker) -> bool { + let records = self.additional_limit.opcode_start_records(start); + if !self.prices_history() { + return true; + } + let charged = charge_write_records_history(gas, records.on_lane, u64::from(records.caller)); + let Some((on_lane, caller)) = charged else { + gas.erase_cost(start.forward); + gas.set_failed_charge_remaining(Some(gas.remaining())); + return false; + }; + self.additional_limit.stage_frame_charge(records, on_lane, caller); + true + } } impl MegaContext { diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 6e0070707..7872e7fe7 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,24 +1,17 @@ //! The instruction table of the Satin engine. //! -//! Every opcode runs revm's own instruction, except the four that write state the resource limits -//! count by starting a frame — `CALL`, `CALLCODE`, `CREATE` and `CREATE2` — and the ones that can -//! read volatile data. +//! Every opcode runs revm's own instruction, except the ones that can read volatile data. //! -//! The opcodes that write state themselves — `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` — are -//! revm's own: revm calls the Host's completed-write hook at the end of each, once the write is in -//! the journal and every charge the opcode makes has been made, and the Host counts the write, -//! holds it to the limits and charges the history it costs there (see the `host` module). A failed -//! opcode never reaches the hook, so it counts nothing. `SELFDESTRUCT` is wrapped for the volatile -//! read it can make alone. -//! -//! The four that start a frame 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 @@ -26,7 +19,7 @@ //! //! 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; +//! 3. run revm's instruction, 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. @@ -36,8 +29,8 @@ //! 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 wrapper that writes the record is the one that drops a frame its opcode was -//! starting: it hands the frame's forward back to its caller first. +//! 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`]). @@ -50,9 +43,9 @@ use revm::{ bytecode::opcode::{ - BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, CREATE, CREATE2, - DELEGATECALL, DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, NUMBER, - SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, 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, @@ -69,8 +62,7 @@ use revm::{ }; use crate::{ - charge_write_records_history, volatile_data_access_disabled_revert_data, ExternalEnvTypes, - MegaContext, VolatileDataAccess, + volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; use super::{input_gas_limit, satin_gas_table, value_call_stipend, MegaInstructions}; @@ -81,23 +73,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 start a frame whose start 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); 22] = [ + 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::), @@ -121,132 +110,14 @@ pub(crate) fn mega_instructions( instructions } -/// 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. Every frame an opcode starts is charged, revm deciding the start only once -/// the frame's init asks it: a start revm then refuses — a value the caller cannot fund, a frame -/// past the call-stack limit — makes no records, and gives the charge back when it returns. 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`]), even where revm would have refused the -/// start. -/// -/// 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)) => { - host.additional_limit.frame_start_records(input) - } - _ => return 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. -/// -/// The halt's record of what the frame had — the regular gas the revm fork records before a -/// failed charge, which detention reads where the frame ends — is written again once the forward -/// is back: the failed charge recorded the gas left after the forward was taken, and a price that -/// could not be computed failed before any charge. -#[cold] -#[inline(never)] -fn abandon_frame( - interpreter: &mut Interpreter, - host: &MegaContext, -) -> InstructionExecResult { - if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { - interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); - } - interpreter.gas.set_failed_charge_remaining(Some(interpreter.gas.remaining())); - Err(InstructionResult::OutOfGas) -} - -/// 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. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 92c307749..efa2edafa 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -2,7 +2,10 @@ use alloy_primitives::{Address, Bytes}; use revm::{ - context_interface::{context::CodeDeposit, host::CompletedWrite}, + context_interface::{ + context::CodeDeposit, + host::{CompletedWrite, FrameStart, FrameStartKind}, + }, handler::FrameResult, interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; @@ -373,6 +376,13 @@ impl AdditionalLimit { self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; } + /// Leaves the frame about to start unchecked against the answer its caller's charge was + /// computed from ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)): an + /// inspector that may rewrite the frame's input ran between the charge and the count. + pub(crate) const fn waive_start_check(&mut self) { + self.pending_frame_charge.records = None; + } + /// 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; @@ -692,12 +702,16 @@ impl AdditionalLimit { /// 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. + /// opcode, on the facts revm's instruction hands the frame-start hook, 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 the input revm builds carries the caller, target and value + /// the hook was handed, and nothing between the two changes it: 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. + /// + /// An inspector that may rewrite the input runs between the two, and can split them: under one + /// the frame is not checked ([`waive_start_check`](Self::waive_start_check)). fn records_the_caller_paid_for( &self, input: &FrameInput, @@ -735,29 +749,70 @@ impl AdditionalLimit { } } - /// 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. + /// The write records starting `input` makes at a depth above the transaction's own frame, + /// counted as the frame starts ([`start_records`](Self::start_records)). 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::Call(inputs) => self.start_records( + inputs.caller, + Some(inputs.target_address), + inputs.transfers_value(), + ), + FrameInput::Create(inputs) => self.start_records(inputs.caller(), None, true), FrameInput::Empty => FrameStartRecords::NONE, } } + /// The write records the frame `start` describes makes, for the opcode about to start it, + /// which pays for them ([`start_records`](Self::start_records)). + pub(crate) fn opcode_start_records(&self, start: &FrameStart) -> FrameStartRecords { + let transfers_value = !start.value.is_zero(); + match start.kind { + FrameStartKind::Create | FrameStartKind::Create2 => { + self.start_records(start.caller, None, true) + } + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => { + self.start_records(start.caller, start.target, transfers_value) + } + } + } + + /// The write records a frame's start makes at a depth above the transaction's own frame: a + /// call from `caller` to `target` that transfers value or not, or a creation (`target` is + /// `None`). `on_lane` are the records the frame's failure discards, `caller` whether its start + /// also writes the caller's own account. + /// + /// A call that moves no value writes nothing. A value call writes its recipient, unless that is + /// the caller itself or the transaction's sender, whose account the body counts. A creation + /// writes the account it creates. Either writes the caller's account — a transfer's sender, a + /// creation's creator nonce — unless the caller's frame already recorded it. + /// + /// The opcode that starts the frame pays for all of them, after the gas it forwards was taken, + /// 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. The answer is asked twice, at the opcode + /// ([`opcode_start_records`](Self::opcode_start_records)) and as the frame starts + /// ([`frame_start_records`](Self::frame_start_records)), and the two are checked against each + /// other ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). + fn start_records( + &self, + caller: Address, + target: Option
, + transfers_value: bool, + ) -> FrameStartRecords { + let caller_recorded = self.tracker.current().is_some_and(|lane| lane.account_recorded); + let Some(target) = target else { + return FrameStartRecords { on_lane: 1, caller: !caller_recorded }; + }; + if !transfers_value { + return FrameStartRecords::NONE; + } + let writes_target = target != caller && target != self.sender; + FrameStartRecords { on_lane: u64::from(writes_target), caller: !caller_recorded } + } + /// 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() { From cc0ce79816b4bf16baa64744ba61e66fafbdd46b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 02:45:15 +0800 Subject: [PATCH 404/458] docs: writes and frame starts are metered in the fork's instruction hooks --- .claude/skills/satin-review/SKILL.md | 5 ++- AGENTS.md | 57 ++++++++++++++++------------ 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5b40e67ff..ee29909c7 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -76,7 +76,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ### 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`. +- **Where:** `src/limit/` (byte table, `LimitKind`, `AdditionalLimit`, `FrameLimitTracker`, `Lane`, the effect of a completed write in `record.rs`), `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. @@ -94,7 +94,8 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **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. + - A write is counted in the Host's completed-write hook, 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 frame start's records are charged in the Host's frame-start hook, after the forward and before revm builds the frame's input; a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - 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. diff --git a/AGENTS.md b/AGENTS.md index 5b24c549d..142fe49d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,7 +105,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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`), 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. -- The fork pins at the commit of its mega.6 release (megaeth-labs/revm#75, `7bc0c664`), until the tag is cut. +- 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 fork pins at the commit that adds the instruction hooks on top of its mega.6 release (megaeth-labs/revm#75), until the mega.7 tag is cut. mega.6 no longer splits a system call's gas or reports 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. @@ -128,17 +130,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 | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `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, 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 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 record of what a frame that drops the frame its opcode was starting has, 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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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, and the settled transaction's history gas, history bytes and unspent reservoir; `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 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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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, 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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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`; `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`), what a completed write counts (`record.rs`), 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, and the settled transaction's history gas, history bytes and unspent reservoir; `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 @@ -159,7 +161,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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, 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. - 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. @@ -172,7 +174,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. + Every other charge is made where the record is: the completed-write hook charges a storage write's, a log's and a `SELFDESTRUCT`'s record 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. 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. @@ -333,7 +335,7 @@ Detention caps how much a transaction may still compute once it read such data ( - **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. + 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`, 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.** @@ -365,7 +367,7 @@ Detention caps how much a transaction may still compute once it read such data ( - **What a halt burns.** 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 that cannot pay its records hands the dropped frame's forward back before it fails, and records what the frame has then (`abandon_frame`): the failed charge recorded the gas left after the forward was taken. + 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 is not the frame's: `StepGuard` puts the record back around each callback, so a later halt that records nothing of its own is not 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. @@ -380,16 +382,21 @@ 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. +- **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 commits the record to the running frame's lane and holds it to the limits first — 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 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). + 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge for the frame's lane, which gives back on return what the start did not keep. + revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. + 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, asked at the opcode and as the frame starts; a debug build checks the two agree, except under an inspector that may rewrite the frame's input between them. +- **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. From f21cfc429efe68fc6e29f8764969718fc02e334d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 03:01:15 +0800 Subject: [PATCH 405/458] test(satin): pin the hooks' boundaries: allowance, refill, failed starts, creation shares - an event larger than the history allowance draws all of it and pays the rest, or runs out of gas one gas short of the rest; - a history-only refill after a read does not lift detention's cap; - a start whose records its caller cannot pay, for every kind that makes records and an explicit forward one gas short, counts none of its forward or a value call's stipend as compute, and one gas more starts the frame; - every call kind reaches its start charge after its forward, below the execution cap and above it with the reservoir paying first; - a creation is held to its share from its start: 81 bytes left stop it, 82 start it, and 100 leave room for 18 deployed bytes (with an endowment, the same rule with the transfer log). --- crates/mega-evm/tests/satin/data_size.rs | 97 ++++++++++ crates/mega-evm/tests/satin/detention.rs | 176 +++++++++++++++++- crates/mega-evm/tests/satin/history_gas.rs | 99 +++++++++- .../tests/satin/storage_call_stipend.rs | 57 +++++- 4 files changed, 425 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index cd830bf67..95211050b 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -399,6 +399,103 @@ 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 — the created account's record and its creator's nonce record, the creator not having +/// recorded its account, and with an endowment the transfer log. 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, which +/// keeps its creator's nonce record: 81 without an endowment, a share of 79 against 80 bytes. One +/// byte more, a share of 80, starts it. With 100 left the share is 98, so the creation may deposit +/// the 18 bytes beyond its start, and the 19th stops it at its deposit; with an endowment, 260 +/// left leave room for 14. A stopped creation keeps nothing of its own, and its creator resumes +/// with the nonce record alone. +#[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)); + run_at(db, call(CALLER, A, U256::ZERO, GAS_LIMIT), 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, + }; + let nonce_record_alone = usage(WRITE_RECORD_SIZE, 1); + 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!( + outcome.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty()), + "{case}: nothing was created", + ); + }; + + for endowment in [0, 1] { + let log = if endowment == 0 { 0 } else { TRANSFER_LOG_SIZE }; + let at_start = 2 * 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), share(starts - 1), &case); + + let case = format!("endowment {endowment}, {starts} left"); + let started = run(starts, 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, usage(at_start, 2), "{case}: both records and the log"); + + let left = 100 + log; + let room = share(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, usage(share(left), 2), "{case}: exactly its share"); + 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), share(left), &case); + + if endowment == 0 { + assert_eq!((starts - 1, share(starts - 1), starts), (81, 79, 82)); + assert_eq!((share(left), room), (98, 18)); + } else { + assert_eq!((share(left), room), (254, 14)); + } + } +} + /// 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 { diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 1e7fab848..5367e04e6 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -18,7 +18,9 @@ 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}, + 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, @@ -1825,6 +1827,178 @@ 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 a 64th of what it holds, a +/// 64th 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. +#[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 + /// 64 times the price less one, which leaves it a 64th 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, + }, + Start { + name: "a value CALLCODE", + code: value_call(CALLCODE, None), + charges: value_call_charges(false), + price: price(1), + 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 64 times the price less one, forwards + // all but a 64th of it less the price's 64th, and keeps the price less one. + let charges = value_call_charges(true); + let given = charges.iter().sum::() + 64 * (price(2) - 1); + let forward = 63 * (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(64 * price - 1); + if given <= spent + spilled { + note_price_guard("a new account's state gas outweighs 64 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/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index f9d026169..5c2815df7 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -11,7 +11,10 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STOP}, + bytecode::opcode::{ + CALL, CALLCODE, CREATE, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STATICCALL, + STOP, + }, context_interface::cfg::GasId, }; @@ -225,6 +228,100 @@ 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); } +/// 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 makes no records: from the same gas it 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), (CALLCODE, 1)] { + 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 is spent, and a forward that leaves + // it one gas less than that, the most the 63/64 rule lets it forward. + let spill = price - reservoir.unwrap_or(0); + let forward = 63 * (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"); + if reservoir.is_some() { + assert_eq!(exact.gas.reservoir_remaining, 0, "{case}: the reservoir paid first"); + } + + for scheme in [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 diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 0629017e7..675db36b0 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -27,8 +27,8 @@ use mega_evm::{ 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, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, LOG_BASE_SIZE, + LOG_TOPIC_SIZE, 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, @@ -275,6 +275,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]) From d4443cc86cd64b3bcd3332043464d3643da36218 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 03:33:02 +0800 Subject: [PATCH 406/458] docs: the review checklist and the bench notes name the instruction hooks --- REVIEW.md | 6 +++--- crates/mega-evm/benches/transact.rs | 13 +++++++------ crates/mega-evm/src/access/mod.rs | 4 ++-- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 8451aeeb4..09251868f 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,10 +24,10 @@ 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. + 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. 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. diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 1acddffa6..4e245fad3 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 lanes 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 diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 1b3f15dad..5d5e53f80 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -37,8 +37,8 @@ //! (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. //! //! # The cap //! From edf9cfafdfc6eda80d2b56da69a92861966083ed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 03:41:35 +0800 Subject: [PATCH 407/458] fix(limit): keep both charged-versus-counted checks off a rewriting inspector's frames A rewriting inspector can change a start's input after its history was charged, for the transaction's own frame as for one an opcode starts. Both debug checks that the records counted are the ones charged now step aside under such an inspector, as decided for the plain, non-rewriting path only; the transaction's own frame's check did not. --- crates/mega-evm/src/evm/execution.rs | 3 ++- crates/mega-evm/src/limit/limit.rs | 20 ++++++++------ crates/mega-evm/tests/satin/inspector.rs | 33 +++++++++++++++++++++++- 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 21434b23d..540753131 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -721,7 +721,8 @@ where return Ok(ItemOrResult::Result(output)); } if rewriting { - // The start the calling opcode paid for may not be the one the inspector lets start. + // The start its charge paid for — the calling opcode's, or the transaction's for its + // own frame — may not be the one the inspector lets start. ctx.additional_limit.waive_start_check(); } let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index efa2edafa..181d34a00 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -376,11 +376,15 @@ impl AdditionalLimit { self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; } - /// Leaves the frame about to start unchecked against the answer its caller's charge was - /// computed from ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)): an - /// inspector that may rewrite the frame's input ran between the charge and the count. + /// Leaves the frame about to start unchecked against the answer its charge was computed from + /// — its caller's at the opcode + /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)), + /// or the transaction's before execution for the transaction's own frame + /// ([`check_top_level_records`](Self::check_top_level_records)): an inspector that may rewrite + /// the frame's input ran between the charge and the count. pub(crate) const fn waive_start_check(&mut self) { self.pending_frame_charge.records = None; + self.pending_top_level_records = None; } /// Records the history gas the settled transaction spent. @@ -736,9 +740,10 @@ impl AdditionalLimit { /// 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. + /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)), and under one the + /// frame is not checked ([`waive_start_check`](Self::waive_start_check)). A divergence trips + /// here in every other 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!( @@ -766,7 +771,6 @@ impl AdditionalLimit { /// The write records the frame `start` describes makes, for the opcode about to start it, /// which pays for them ([`start_records`](Self::start_records)). pub(crate) fn opcode_start_records(&self, start: &FrameStart) -> FrameStartRecords { - let transfers_value = !start.value.is_zero(); match start.kind { FrameStartKind::Create | FrameStartKind::Create2 => { self.start_records(start.caller, None, true) @@ -775,7 +779,7 @@ impl AdditionalLimit { FrameStartKind::CallCode | FrameStartKind::DelegateCall | FrameStartKind::StaticCall => { - self.start_records(start.caller, start.target, transfers_value) + self.start_records(start.caller, start.target, !start.value.is_zero()) } } } diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index bfe002245..a3a9c706d 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -12,7 +12,7 @@ use revm::{ 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, @@ -771,3 +771,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"); +} From cdb4ba54e6f3e51cfece35562a52bd2031f8e18e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 03:42:04 +0800 Subject: [PATCH 408/458] docs: the context, detention and table notes name the hooks; the out-of-gas SSTORE test names what it pins --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 4 ++-- crates/mega-evm/src/evm/context.rs | 5 +++-- crates/mega-evm/tests/satin/write_records.rs | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 142fe49d9..f4eeb93d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -158,7 +158,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index cb68b7064..9bf30e498 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -154,8 +154,8 @@ impl FrameFigures { /// 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 that drops the frame its opcode was -/// starting records what it has once the forward is back. +/// 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 /// diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index ea022e037..72506d0ec 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -46,8 +46,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 diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 023184c45..c3d6a2b65 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -579,7 +579,7 @@ fn test_completed_sstore_commits_its_record() { /// 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(); From 410c1a888e49ccd1df9a42918ce6251221a6cf37 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:01:26 +0800 Subject: [PATCH 409/458] feat(evm): the context's journal is MegaJournal, a delegating wrapper of revm's MegaContext runs on MegaJournal, which owns revm's Journal and implements JournalTr by delegating every method (clippy::missing_trait_methods denied), forwards JournalExt::journal and dereferences to revm's journal read-only. alloy-evm's precompile provider is implemented for revm's journal only, so the Satin provider runs alloy-evm's run over the new journal, with a differential test against alloy-evm's. --- crates/mega-evm/src/evm/context.rs | 20 +- crates/mega-evm/src/evm/execution.rs | 12 +- crates/mega-evm/src/evm/journal.rs | 275 +++++++++++++++++++++++++ crates/mega-evm/src/evm/mod.rs | 2 + crates/mega-evm/src/evm/precompiles.rs | 119 ++++++++++- crates/mega-evm/src/lib.rs | 10 +- 6 files changed, 406 insertions(+), 32 deletions(-) create mode 100644 crates/mega-evm/src/evm/journal.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 72506d0ec..18184cb81 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -13,7 +13,7 @@ use revm::{ }, context_interface::{cfg::GasId, context::CodeDeposit}, primitives::{Address, Bytes, StorageKey}, - Database, Journal, + Database, }; use crate::{ @@ -29,13 +29,14 @@ use crate::{ }, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, VolatileDataAccess, + MegaJournal, 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 and the Satin journal. pub(crate) type MegaInnerContext = - Context, DB, Journal, L1BlockInfo>; + Context, DB, MegaJournal, L1BlockInfo>; /// Execution context of the Satin engine. /// @@ -107,7 +108,8 @@ 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 inner: MegaInnerContext = + Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); Self { inner, cfg, @@ -544,7 +546,7 @@ impl MegaContext { /// 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) + (journaled_state.into_revm().database, self.cfg, block) } } @@ -614,7 +616,7 @@ impl ContextTr for MegaContext; type Db = DB; - type Journal = Journal; + type Journal = MegaJournal; type Chain = L1BlockInfo; type Local = LocalContext; @@ -627,7 +629,7 @@ impl ContextTr for MegaContext, &DB, - &Journal, + &MegaJournal, &L1BlockInfo, &LocalContext, ); @@ -637,7 +639,7 @@ impl ContextTr for MegaContext, - &mut Journal, + &mut MegaJournal, &mut L1BlockInfo, &mut LocalContext, ); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 540753131..2beb1cc00 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -43,7 +43,7 @@ use revm::{ InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, - Inspector, Journal, + Inspector, }; use crate::{ @@ -55,7 +55,7 @@ use crate::{ }, history_gas, synthetic_frame_result, system::keyless, - Detention, ExternalEnvTypes, LimitKind, MegaContext, MegaEvm, MegaInstructions, + Detention, ExternalEnvTypes, LimitKind, MegaContext, MegaEvm, MegaInstructions, MegaJournal, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; @@ -444,15 +444,15 @@ impl InspectorHandler for MegaHandler: ContextTr>, - Journal: JournalExt, + MegaContext: ContextTr>, + MegaJournal: 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`. + // 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> diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs new file mode 100644 index 000000000..8473d1694 --- /dev/null +++ b/crates/mega-evm/src/evm/journal.rs @@ -0,0 +1,275 @@ +//! The journal of the Satin engine: revm's journal behind a wrapper of the engine's own. +//! +//! [`MegaJournal`] owns revm's [`Journal`] and implements [`JournalTr`] by delegating every method +//! to it, the configuration switches included: a switch kept at the trait's no-op default would +//! silently turn a journal feature off. The one default kept is `clear`'s, which finalizes through +//! `finalize`. The impl denies `clippy::missing_trait_methods`, so a method `JournalTr` gains is a +//! lint error here until it is given its rule. +//! +//! [`JournalExt::journal`] hands out revm's own entries, and the journal dereferences to revm's +//! [`Journal`] read-only, so code that reads revm's journal state keeps reading it. There is no +//! mutable dereference: a write goes through [`JournalTr`], where the wrapper sees it. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::ops::Deref; +use std::vec::Vec; + +use delegate::delegate; +use revm::{ + context::{ + journaled_state::{ + account::JournaledAccount, AccountInfoLoad, AccountLoad, JournalCheckpoint, + JournalLoadError, TransferError, + }, + JournalTr, + }, + context_interface::context::{SStoreResult, SelfDestructResult, StateLoad}, + inspector::JournalExt, + primitives::{ + hardfork::SpecId, Address, AddressMap, AddressSet, Bytes, HashSet, Log, StorageKey, + StorageValue, B256, U256, + }, + state::{Account, Bytecode, EvmState}, + Database, Journal, JournalEntry, +}; + +/// The journal of the Satin engine: revm's journal behind a wrapper of the engine's own. See the +/// module documentation. +/// +/// It is the journal of every [`MegaContext`](crate::MegaContext). A node that names the +/// context's journal type names this one; one that reads revm's journal state reads it through the +/// dereference, and one that writes to it does so through [`JournalTr`]. +#[derive(Clone, Debug)] +pub struct MegaJournal { + /// revm's journal, which holds the state. + revm: Journal, +} + +impl MegaJournal { + /// Consumes the journal and returns revm's. + pub fn into_revm(self) -> Journal { + self.revm + } +} + +impl Deref for MegaJournal { + type Target = Journal; + + fn deref(&self) -> &Journal { + &self.revm + } +} + +#[deny(clippy::missing_trait_methods)] +impl JournalTr for MegaJournal { + type Database = DB; + type State = EvmState; + type JournaledAccount<'a> + = JournaledAccount<'a, DB, JournalEntry> + where + DB: 'a; + + fn new(database: DB) -> Self { + Self { revm: Journal::new(database) } + } + + delegate! { + to self.revm { + fn db_mut(&mut self) -> &mut DB; + fn db(&self) -> &DB; + fn evm_state_mut(&mut self) -> &mut EvmState; + fn evm_state(&self) -> &EvmState; + fn db_and_state(&self) -> (&DB, &EvmState); + fn db_and_state_mut(&mut self) -> (&mut DB, &mut EvmState); + fn sload( + &mut self, + address: Address, + key: StorageKey, + ) -> Result, DB::Error>; + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, JournalLoadError>; + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Result, DB::Error>; + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, JournalLoadError>; + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); + fn log(&mut self, log: Log); + fn take_logs(&mut self) -> Vec; + fn logs(&self) -> &[Log]; + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, JournalLoadError>; + fn warm_access_list(&mut self, access_list: AddressMap>); + fn warm_coinbase_account(&mut self, address: Address); + fn warm_precompiles(&mut self, addresses: &AddressSet); + fn precompile_addresses(&self) -> &AddressSet; + fn set_spec_id(&mut self, spec_id: SpecId); + fn set_eip7708_config(&mut self, disabled: bool, eip8246_delayed_clear_disabled: bool); + fn set_amsterdam_eip7708_enabled(&mut self, enabled: bool); + fn set_legacy_journal_semantics(&mut self, enabled: bool); + fn touch_account(&mut self, address: Address); + fn transfer( + &mut self, + from: Address, + to: Address, + balance: U256, + ) -> Result, DB::Error>; + #[allow(deprecated)] + fn caller_accounting_journal_entry( + &mut self, + address: Address, + old_balance: U256, + bump_nonce: bool, + ); + fn balance_incr(&mut self, address: Address, balance: U256) -> Result<(), DB::Error>; + #[allow(deprecated)] + fn nonce_bump_journal_entry(&mut self, address: Address); + fn load_account(&mut self, address: Address) -> Result, DB::Error>; + #[allow(deprecated)] + fn load_account_code( + &mut self, + address: Address, + ) -> Result, DB::Error>; + fn load_account_with_code( + &mut self, + address: Address, + ) -> Result, DB::Error>; + fn load_account_delegated( + &mut self, + address: Address, + ) -> Result, DB::Error>; + fn load_account_mut( + &mut self, + address: Address, + ) -> Result>, DB::Error>; + fn load_account_mut_skip_cold_load( + &mut self, + address: Address, + skip_cold_load: bool, + ) -> Result>, JournalLoadError>; + fn load_account_with_code_mut( + &mut self, + address: Address, + ) -> Result>, DB::Error>; + fn load_account_mut_optional_code( + &mut self, + address: Address, + load_code: bool, + ) -> Result>, DB::Error>; + fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256); + fn set_code(&mut self, address: Address, code: Bytecode); + fn code(&mut self, address: Address) -> Result, DB::Error>; + fn code_hash(&mut self, address: Address) -> Result, DB::Error>; + fn depth(&self) -> usize; + fn transfer_loaded( + &mut self, + from: Address, + to: Address, + balance: U256, + ) -> Option; + fn create_account_checkpoint( + &mut self, + caller: Address, + address: Address, + balance: U256, + spec_id: SpecId, + ) -> Result; + fn checkpoint(&mut self) -> JournalCheckpoint; + fn checkpoint_commit(&mut self); + fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint); + fn commit_tx(&mut self); + fn discard_tx(&mut self); + fn finalize(&mut self) -> EvmState; + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, JournalLoadError>; + } + } + + /// The trait's own default: it finalizes through `finalize`. + fn clear(&mut self) { + let _ = self.finalize(); + } +} + +impl JournalExt for MegaJournal { + /// revm's own journal entries. + #[inline] + fn journal(&self) -> &[JournalEntry] { + JournalExt::journal(&self.revm) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::MemoryDatabase; + use alloy_primitives::address; + + const A: Address = address!("00000000000000000000000000000000000a0002"); + const B: Address = address!("00000000000000000000000000000000000a0003"); + const C: Address = address!("00000000000000000000000000000000000a0004"); + + /// Every configuration switch reaches revm's journal: a switch kept at the trait's no-op + /// default would turn a journal feature off without a word. + #[test] + fn test_the_switches_reach_revms_journal() { + let mut mega = MegaJournal::new(MemoryDatabase::default()); + let mut plain: Journal = Journal::new(MemoryDatabase::default()); + let precompiles = AddressSet::from_iter([A]); + let access_list = AddressMap::from_iter([(B, HashSet::from_iter([U256::from(1)]))]); + for (spec, flag) in [(SpecId::OSAKA, true), (SpecId::CANCUN, false)] { + mega.set_spec_id(spec); + plain.set_spec_id(spec); + mega.set_eip7708_config(flag, !flag); + plain.set_eip7708_config(flag, !flag); + mega.set_amsterdam_eip7708_enabled(flag); + plain.set_amsterdam_eip7708_enabled(flag); + mega.set_legacy_journal_semantics(flag); + plain.set_legacy_journal_semantics(flag); + mega.warm_coinbase_account(C); + plain.warm_coinbase_account(C); + mega.warm_precompiles(&precompiles); + plain.warm_precompiles(&precompiles); + mega.warm_access_list(access_list.clone()); + plain.warm_access_list(access_list.clone()); + assert_eq!(mega.inner.cfg, plain.inner.cfg, "{spec:?}"); + assert_eq!(mega.inner.warm_addresses, plain.inner.warm_addresses, "{spec:?}"); + assert_eq!(mega.precompile_addresses(), plain.precompile_addresses()); + } + } + + /// `JournalExt::journal` hands out revm's own entries, the ones an inspector reads after a + /// write. + #[test] + fn test_the_journal_extension_hands_out_revms_entries() { + let mut journal = MegaJournal::new(MemoryDatabase::default()); + journal.set_spec_id(SpecId::OSAKA); + journal.load_account(A).unwrap(); + journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); + let entries = JournalExt::journal(&journal); + assert!(!entries.is_empty()); + assert_eq!(entries, JournalExt::journal(&*journal), "revm's own"); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index c6cdfe522..824e3e4cd 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -13,6 +13,7 @@ mod history; mod host; mod inspector; mod instructions; +mod journal; mod precompiles; mod prices; mod result; @@ -27,6 +28,7 @@ pub use factory::*; pub use frame::*; pub use history::*; pub use inspector::*; +pub use journal::*; pub use precompiles::*; pub use prices::*; pub use result::*; diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 1ebe4fddb..0e8c6bddb 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -46,20 +46,26 @@ #[cfg(not(feature = "std"))] use alloc as std; -use std::{string::String, sync::Arc}; +use std::{ + string::{String, ToString}, + sync::Arc, +}; use alloy_evm::{ - precompiles::{DynPrecompile, Precompile as _, PrecompilesMap}, - Database, + precompiles::{DynPrecompile, Precompile as _, PrecompileInput, PrecompilesMap}, + Database, EvmInternals, }; +use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ - handler::PrecompileProvider, + context::{BlockEnv, CfgEnv, ContextTr}, + handler::{precompile_output_to_interpreter_result, 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 +191,18 @@ pub mod kzg_point_evaluation { .with_required_gas(required_gas); } +/// The plain revm context over revm's own journal, the one alloy-evm implements the provider for. +type RevmJournalContext = + Context, DB, Journal, L1BlockInfo>; + /// 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. +/// alloy-evm implements the provider for revm's plain context over revm's own journal, and the +/// context [`MegaContext`] wraps runs on the Satin journal ([`MegaJournal`](crate::MegaJournal)), +/// so `run` is alloy-evm's own, on that journal: the precompile gets the call's input and an +/// [`EvmInternals`] over the journal, and its output is turned into the call's result the way +/// revm turns any precompile's. A precompile's writes through [`EvmInternals`] reach the journal +/// as any tool's do, and the journal counts none of them. impl PrecompileProvider> for PrecompilesMap { @@ -197,7 +211,7 @@ impl PrecompileProvider bool { + fn set_spec(&mut self, _spec: OpSpecId) -> bool { false } @@ -207,17 +221,35 @@ impl PrecompileProvider, inputs: &CallInputs, ) -> Result, String> { - PrecompileProvider::>::run(self, &mut context.inner, inputs) + let Some(precompile) = self.get(&inputs.bytecode_address) else { + return Ok(None); + }; + let (block, tx, cfg, journal, _, local) = context.inner.all_mut(); + let output = precompile + .call(PrecompileInput { + data: inputs.input.as_bytes_local(local).as_ref(), + gas: inputs.gas_limit, + reservoir: inputs.reservoir, + caller: inputs.caller, + value: inputs.call_value(), + is_static: inputs.is_static, + internals: EvmInternals::new(journal, block, cfg, tx), + target_address: inputs.target_address, + bytecode_address: inputs.bytecode_address, + }) + .map_err(|error| error.to_string())?; + Ok(Some(precompile_output_to_interpreter_result(output, inputs.gas_limit))) } + /// 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) } #[inline] fn contains(&self, address: &Address) -> bool { - PrecompileProvider::>::contains(self, address) + self.get(address).is_some() } } @@ -286,6 +318,71 @@ mod tests { .expect("the address is a precompile") } + /// The provider on the Satin journal runs a precompile as alloy-evm's provider runs it on + /// revm's own journal: for every entry of the Satin set, and for a node's own precompiles that + /// succeed, log, write through `EvmInternals`, revert and fail fatally, and for an address with + /// no precompile, the two give the same answer and leave the same logs and the same state. + #[test] + fn test_the_provider_runs_a_precompile_as_alloy_evms_does() { + use alloy_primitives::{address, Log, LogData}; + use revm::{context::JournalTr, precompile::PrecompileError}; + const SUCCEEDS: Address = address!("00000000000000000000000000000000000e0001"); + const LOGS: Address = address!("00000000000000000000000000000000000e0002"); + const WRITES: Address = address!("00000000000000000000000000000000000e0003"); + const REVERTS: Address = address!("00000000000000000000000000000000000e0004"); + const FATAL: Address = address!("00000000000000000000000000000000000e0005"); + const MISSING: Address = address!("00000000000000000000000000000000000e00ff"); + let own = |address: Address| { + DynPrecompile::new(PrecompileId::Custom("own".into()), move |mut input| { + let ok = |gas| Ok(PrecompileOutput::new(gas, Bytes::from_static(b"ok"), 0)); + match address { + SUCCEEDS => ok(10), + LOGS => { + let data = LogData::new_unchecked(Vec::new(), input.data.to_vec().into()); + input.internals.log(Log { address, data }); + ok(20) + } + WRITES => { + input.internals.sstore(address, U256::from(1), U256::from(2)).unwrap(); + ok(30) + } + REVERTS => Ok(PrecompileOutput::revert(5, Bytes::from_static(b"no"), 0)), + _ => Err(PrecompileError::Fatal("broken".into())), + } + }) + }; + let mut map = satin_precompiles_map(); + for address in [SUCCEEDS, LOGS, WRITES, REVERTS, FATAL] { + map.apply_precompile(&address, |_| Some(own(address))); + } + let addresses = satin_precompiles() + .addresses() + .copied() + .chain([SUCCEEDS, LOGS, WRITES, REVERTS, FATAL, MISSING]); + for address in addresses { + for input in [Bytes::new(), Bytes::from(std::vec![1; 192])] { + let inputs = inputs(address, input, 1_000_000); + let mut mega = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let mut plain: RevmJournalContext = + Context::new(MemoryDatabase::default(), OpSpecId::KARST) + .with_cfg(mega.cfg().clone()); + let ours = map.clone().run(&mut mega, &inputs); + let theirs = PrecompileProvider::>::run( + &mut map.clone(), + &mut plain, + &inputs, + ); + assert_eq!(ours, theirs, "{address}: the answer"); + assert_eq!(mega.journal_ref().logs(), plain.journal_ref().logs(), "{address}"); + assert_eq!(mega.journal_ref().state, plain.journal_ref().state, "{address}"); + } + } + assert_eq!( + PrecompileProvider::>::warm_addresses(&map), + PrecompileProvider::>::warm_addresses(&map), + ); + } + /// A valid proof costs the `MegaETH` price and returns the field parameters. #[test] fn test_kzg_precompile_sufficient_gas() { diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 7afe7cef7..c66b3f2d7 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -53,9 +53,9 @@ pub use evm::{ 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, + MegaJournal, 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, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; #[cfg(any(test, feature = "test-utils"))] @@ -79,9 +79,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, -}; +pub(crate) use evm::{charge_write_records_history, MegaInstructions, PricedPrecompiles}; /* Re-export of upstream crates, so consumers build against the exact versions used here */ pub use alloy_consensus; From ba76fb7fa46e1ebd184a835f64893bcad6406d84 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:05:14 +0800 Subject: [PATCH 410/458] feat(limit): the journal's ledger, a shadow of the lanes fed from every input MegaJournal keeps a ledger of what the transaction's own execution keeps: one level per open checkpoint, frame levels opened only inside the start window around revm's frame start (a call's first checkpoint, a creation's account checkpoint, budgeted from before its creator's nonce record), rollback levels for every other checkpoint, start reports, marks for Satin's own reverts and a frame side with the refund formula. The journal's own write methods count nothing; the completed-write hook, the code deposit, hints, authorities and keyless feed the ledger beside the lanes, which still take every decision. The ledger-shadow feature compares the two at normalised points (totals, budgets and usage at built starts, start verdicts and the crossing hypothetical, refunds, caller checks) and asserts frame identity; mismatches panic. The state-test crates pass the feature on. --- crates/mega-evm/Cargo.toml | 3 + crates/mega-evm/src/evm/context.rs | 58 +- crates/mega-evm/src/evm/execution.rs | 274 +++++- crates/mega-evm/src/evm/host.rs | 17 +- crates/mega-evm/src/evm/inspector.rs | 41 +- crates/mega-evm/src/evm/journal.rs | 464 ++++++++- crates/mega-evm/src/evm/mod.rs | 2 +- crates/mega-evm/src/limit/ledger.rs | 930 ++++++++++++++++++ crates/mega-evm/src/limit/limit.rs | 248 ++++- crates/mega-evm/src/limit/mod.rs | 11 + crates/mega-evm/src/limit/record.rs | 18 + crates/mega-evm/src/limit/shadow.rs | 94 ++ .../mega-evm/src/system/keyless/dispatch.rs | 1 + crates/mega-evm/src/system/keyless/settle.rs | 24 +- crates/mega-evm/src/system/oracle.rs | 10 + crates/mega-state-test/Cargo.toml | 5 + crates/state-test/Cargo.toml | 5 + 17 files changed, 2041 insertions(+), 164 deletions(-) create mode 100644 crates/mega-evm/src/limit/ledger.rs create mode 100644 crates/mega-evm/src/limit/shadow.rs diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index b92d1b6cd..087230849 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -68,6 +68,9 @@ test-utils = ["dep:derive_more"] # `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"] +# Verification-only: compares the journal's ledger with the lanes wherever the two must agree, and +# panics on a mismatch. Off by default; without it the comparison compiles out. +ledger-shadow = [] # 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 diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 18184cb81..1ea6b622b 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -108,15 +108,15 @@ impl MegaContext { external_envs: ExternalEnvs, ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); - let inner: MegaInnerContext = + let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; + let mut inner: MegaInnerContext = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); + inner.journaled_state.ledger_mut().set_limits(limits); 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(), @@ -250,10 +250,17 @@ 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`, on the lanes and in the journal's + /// ledger alike. + pub(crate) const fn set_tx_runtime_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.additional_limit.set_limits(limits); + self.inner.journaled_state.ledger_mut().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 @@ -448,7 +455,8 @@ impl MegaContext { } /// Prepares the common execution layer for a transaction or a system call that is, or is not, - /// `system_originated`. + /// `system_originated`: the lanes and the journal's ledger begin it together, held to the same + /// limits and counting the same 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. @@ -460,7 +468,8 @@ impl MegaContext { /// 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.additional_limit.set_transfer_logs(transfer_logs); self.bucket_multipliers.reset(); self.oracle_reads.clear(); // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call @@ -474,7 +483,13 @@ impl MegaContext { } // 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.record_tx_body(body); + self.inner.journaled_state.ledger_mut().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( @@ -648,9 +663,10 @@ impl ContextTr for MegaContext ContextTr for MegaContext Result<(), Self::Error> { - evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); + let ctx = evm.ctx_mut(); + ctx.additional_limit.on_last_frame_return(frame_result); + // The transaction's own frame, answered without returning through `frame_return_result`. + if ctx.additional_limit.starts_open() != 0 { + on_start_return(ctx, 0); + } 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()); + let top_level = evm.ctx_ref().additional_limit.top_level_write_record_gas(); + #[cfg(feature = "ledger-shadow")] + evm.ctx_mut().additional_limit.shadow_note_top_level_refund(top_level); + parent_gas.refill_history(top_level); if instruction_result.is_halt() { parent_gas.spend_all(); } @@ -359,6 +368,22 @@ where .saturating_add_signed(frame_result.gas().history_gas_spent()); layer.set_history_gas_spent(history); layer.settle_history_bytes(priced); + #[cfg(feature = "ledger-shadow")] + { + let ctx = evm.ctx_ref(); + let ledger = ctx.journal_ref().ledger(); + if !ledger.diverged() { + let (lanes, formula) = ctx.additional_limit.shadow_top_level_refunds(); + if let Some(formula) = formula { + assert_eq!( + lanes, formula, + "ledger shadow mismatch at the transaction's settlement: the own frame's \ + record refund" + ); + } + } + shadow::agree(&ctx.additional_limit, ledger, "the transaction's settlement"); + } Ok(()) } @@ -531,6 +556,7 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), ItemOrResult::Result(result) => Err(result), - } + }); + let report = self.inner.ctx.journal_mut().close_start(); + (decided?, report) }; let ctx = &mut self.inner.ctx; debug_assert!(!keyless || outcome.is_ok(), "revm builds a keylessDeploy call's frame"); @@ -569,8 +607,19 @@ impl EvmTr for MegaEvm { @@ -578,9 +627,10 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { let refund = self.inner.ctx.additional_limit.on_frame_return(&result); + on_start_return(&mut self.inner.ctx, refund); 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 @@ -729,8 +784,8 @@ where // 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; + let start = ctx.journal_mut().mark(); + let logs_i = start.position.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 @@ -788,10 +843,14 @@ where instructions.gas_table(), ), }; + if action.is_return() { + // revm closes the frame's level as it processes its return. + ctx.journal_mut().ledger_mut().frame_returning(); + } 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 source = ResultSource::Engine(built_frame_mark(ctx, frame)); 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); @@ -1060,14 +1119,15 @@ impl MegaEvm { 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(); + self.inner.ctx.additional_limit.push_empty_frame(frame_init.depth); } answer } } -/// 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. +/// Takes the journal, and its ledger, 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 @@ -1077,12 +1137,12 @@ impl MegaEvm { /// is all that takes them back. The journal's depth is left as it is. fn take_back_a_stopped_answer( ctx: &mut MegaContext, - start: JournalCheckpoint, + start: &Mark, succeeded: bool, result: &FrameResult, ) { if succeeded && !result.instruction_result().is_ok() { - revert_journal_to(ctx, start); + ctx.journal_mut().revert_to(start); } } @@ -1104,7 +1164,7 @@ where INSP: Inspector, EthInterpreter>, { let mut output = call_too_deep(frame_init).unwrap_or(output); - ctx.additional_limit.push_empty_frame(); + ctx.additional_limit.push_empty_frame(frame_init.depth); 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); @@ -1115,10 +1175,10 @@ where /// What holding a frame's start to the limits needs of it once revm consumed its input: where the /// start began 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. - position: JournalCheckpoint, + /// Where the journal and its ledger 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: Mark, /// The frame's depth. depth: usize, /// The account a creation is made by; `None` for a call. @@ -1131,6 +1191,10 @@ struct FrameStart { /// revm journaled. #[cfg(debug_assertions)] transfer_log: bool, + /// The account the start moves value from, and the call's target, which a creation learns + /// when revm builds it: the two ends of the start's own transfer log. + #[cfg(debug_assertions)] + ends: (Address, Option
), } impl FrameStart { @@ -1146,27 +1210,39 @@ impl FrameStart { FrameInput::Empty => (None, 0), }; Self { - position: journal_position(ctx), + mark: ctx.journal_mut().mark(), depth: frame_init.depth, creator, gas_limit: input_gas_limit(input), reservoir, #[cfg(debug_assertions)] transfer_log: ctx.additional_limit.frame_start_transfer_log(input), + #[cfg(debug_assertions)] + ends: match input { + FrameInput::Call(inputs) => (inputs.caller, Some(inputs.target_address)), + FrameInput::Create(inputs) => (inputs.caller(), None), + FrameInput::Empty => (Address::ZERO, None), + }, } } /// Asserts that revm journaled the transfer log the start counted, once it made the start and - /// kept it: the rule the count follows is the one revm journals the log by. Only transfer logs - /// are compared: a precompile may journal logs of its own. + /// kept it: the rule the count follows is the one revm journals the log by. Only the transfer + /// logs of the start's own move are compared, from its caller to the frame it starts — for a + /// creation, the account revm `created` — a precompile may journal logs of its own, transfer + /// logs of the value it moves through `EvmInternals` among them. #[cfg(debug_assertions)] fn assert_transfer_log_journaled( &self, ctx: &MegaContext, + created: Option
, ) { - let journaled = ctx.journal_ref().logs()[self.position.log_i..] + use revm::primitives::eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}; + let (from, to) = (self.ends.0, self.ends.1.or(created).unwrap_or_default()); + let ends = [ETH_TRANSFER_LOG_TOPIC, from.into_word(), to.into_word()]; + let journaled = ctx.journal_ref().logs()[self.mark.position.log_i..] .iter() - .filter(|log| log.address == revm::primitives::eip7708::ETH_TRANSFER_LOG_ADDRESS) + .filter(|log| log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics() == ends) .count(); debug_assert_eq!( journaled, @@ -1196,29 +1272,42 @@ impl FrameStart { fn hold_answered_start( ctx: &mut MegaContext, start: &FrameStart, + report: &StartReport, answer: &mut FrameResult, ) { + #[cfg(feature = "ledger-shadow")] + let held = |ctx: &MegaContext, lanes: Option| { + shadow::verdict(lanes, report.verdict, ctx.journal_ref().ledger(), "an answered start"); + }; + #[cfg(not(feature = "ledger-shadow"))] + let _ = report; let Some(creator) = start.creator else { if matches!( answer.instruction_result(), InstructionResult::OutOfFunds | InstructionResult::OverflowPayment ) { + #[cfg(feature = "ledger-shadow")] + held(ctx, None); return; } #[cfg(debug_assertions)] if answer.instruction_result().is_ok() { - start.assert_transfer_log_journaled(ctx); + start.assert_transfer_log_journaled(ctx, None); } let check = ctx.additional_limit.check_start(); + #[cfg(feature = "ledger-shadow")] + held(ctx, Some(check)); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); stop_the_answer(answer, start, output); } return; }; - let bumped = ctx.journal_ref().journal()[start.position.journal_i..] + let bumped = ctx.journal_ref().journal()[start.mark.position.journal_i..] .iter() .any(|entry| matches!(entry, JournalEntry::NonceBump { address } if *address == creator)); + #[cfg(feature = "ledger-shadow")] + held(ctx, None); if bumped { return; } @@ -1227,7 +1316,10 @@ fn hold_answered_start( // transaction's own frame, refused so, makes none of the records charged before execution for // it, and the history they cost comes back with the answer, as for a frame that kept nothing. if start.depth == 0 && answer.instruction_result().is_ok() { - answer.gas_mut().refill_history(ctx.additional_limit.top_level_write_record_gas()); + let top_level = ctx.additional_limit.top_level_write_record_gas(); + #[cfg(feature = "ledger-shadow")] + ctx.additional_limit.shadow_note_top_level_refund(top_level); + answer.gas_mut().refill_history(top_level); } } @@ -1285,6 +1377,101 @@ fn inspect_logs( } } +/// The mark the built frame `frame` is taken back to when an inspector rewrites its success into a +/// failure: the one its start's side kept, which is the frame's own checkpoint, with the counts its +/// level opened with. +fn built_frame_mark( + ctx: &MegaContext, + frame: &EthFrame, +) -> Mark { + let kept = ctx.additional_limit.running_start().and_then(|side| side.mark()).copied(); + ledger_assert!( + kept.is_some_and(|mark| mark.position == frame.checkpoint), + "a built frame's start side keeps the mark of its own checkpoint" + ); + kept.unwrap_or_else(|| ctx.journal_ref().ledger().mark(frame.checkpoint)) +} + +/// What the ledger is told about the start `frame_init` asks revm for. +fn start_facts(frame_init: &FrameInit) -> StartFacts { + let depth = frame_init.depth; + match &frame_init.frame_input { + FrameInput::Call(inputs) => StartFacts { + depth, + caller: inputs.caller, + target: Some(inputs.target_address), + transfers_value: inputs.transfers_value(), + }, + FrameInput::Create(inputs) => StartFacts { + depth, + caller: inputs.caller(), + target: None, + transfers_value: !inputs.value().is_zero(), + }, + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), + } +} + +/// Asserts, as a frame at `depth` starts, that the journal's nearest frame level is the running +/// frame's own: the one its start opened, at the depth above. The frame levels of every frame +/// that started and returned since are closed, whatever rollback levels a tool holds open around +/// them. +fn assert_running_frame( + ctx: &MegaContext, + depth: usize, +) { + let running = ctx.additional_limit.running_start().and_then(|side| side.seq()); + ledger_assert!( + ctx.journal_ref().ledger().running_frame() == depth.checked_sub(1).zip(running), + "a frame starts from the running frame's own level" + ); +} + +/// Pops the side of the start of the frame returning now, once the lanes popped its lane and gave +/// its caller back `refund` of the history it paid for the start's records, and asserts the frame's +/// own level, and every level opened inside it, closed: the journal's nearest frame level is the +/// caller's. +/// +/// Under the shadow, the ledger is held to the lanes: the refund by the formula, the check of the +/// caller the frame returns into, and what the two hold the transaction to. The transaction's own +/// frame has no caller to refund or check: its record's refund is held at the settlement. +fn on_start_return( + ctx: &mut MegaContext, + refund: u64, +) { + let Some(side) = ctx.additional_limit.pop_start() else { return }; + let caller = ctx.additional_limit.running_start().and_then(|side| side.seq()); + ledger_assert!( + ctx.journal_ref().ledger().running_frame() == side.depth().checked_sub(1).zip(caller), + "a frame returns with its own level closed, into its caller's" + ); + #[cfg(feature = "ledger-shadow")] + { + let ledger = ctx.journal_ref().ledger(); + if side.depth() == 0 { + if side.comparable() { + let formula = side.refund(ledger); + ctx.additional_limit.shadow_set_top_level_refund(formula); + } + } else { + shadow::refund(refund, &side, ledger, "a frame's return"); + let check = ledger.check(); + let lanes = ctx.additional_limit.shadow_pending_stop(); + shadow::verdict( + lanes, + check.exceeded_limit().then_some(check), + ledger, + "a caller's check", + ); + } + shadow::agree(&ctx.additional_limit, ctx.journal_ref().ledger(), "a frame's return"); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = refund; +} + /// 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. @@ -1345,6 +1532,7 @@ fn record_applied_authorities( 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); + ctx.journal_mut().ledger_mut().count_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); @@ -1662,11 +1850,11 @@ 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 = ctx.journal_mut().mark(); // 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); + 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}"); } @@ -1679,15 +1867,15 @@ mod tests { #[should_panic(expected = "the transfer log counted is the one revm journaled")] fn test_a_transfer_log_counted_and_not_journaled_trips() { let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let position = journal_position(&mut ctx); let start = FrameStart { - position, + mark: ctx.journal_mut().mark(), depth: 1, creator: None, gas_limit: 0, reservoir: 0, transfer_log: true, + ends: (CALLER, Some(TARGET)), }; - start.assert_transfer_log_journaled(&ctx); + start.assert_transfer_log_journaled(&ctx, None); } } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 582475ca7..3a1ff03c2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -287,7 +287,8 @@ impl revm::context_interface::Host Ok(load) } - /// Commits the record of a write an opcode completed, holds it to the limits, and charges the + /// Commits the record of a write an opcode completed — to the running frame's lane, and to the + /// running frame's level of the journal's ledger — 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. @@ -316,7 +317,19 @@ impl revm::context_interface::Host CompletedWrite::Log { .. } => (true, false), CompletedWrite::SelfDestruct { .. } => (false, false), }; - let (check, history) = self.additional_limit.commit_write(&write); + // One count, committed to the lanes, which decide, and to the journal's ledger. + let (count, history) = self.additional_limit.write_count(&write); + let check = self.additional_limit.commit_count(&count); + let journaled = self.inner.journaled_state.ledger_mut().count_write(&count); + #[cfg(feature = "ledger-shadow")] + { + use crate::limit::shadow; + let ledger = self.inner.journaled_state.ledger(); + shadow::verdict(Some(check), Some(journaled), ledger, "a completed write"); + shadow::agree(&self.additional_limit, ledger, "a completed write"); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = journaled; if check.exceeded_limit() { return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 103162664..53003b0b4 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -109,7 +109,7 @@ use revm::{ context::{ContextTr, JournalTr}, - context_interface::{cfg::StateGasCharge, journaled_state::JournalCheckpoint, Host}, + context_interface::{cfg::StateGasCharge, Host}, handler::FrameResult, inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ @@ -120,7 +120,7 @@ use revm::{ Database, Inspector, }; -use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; +use crate::{limit::Mark, 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 @@ -523,9 +523,10 @@ pub(crate) enum ResultSource { /// 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), + /// building a frame — and what the frame journaled begins at the mark: the frame's own + /// checkpoint, or where the journal stood when the start began, with the ledger as it stood + /// there. + Engine(Mark), } /// Hands a frame's end to the inspector, then settles what its rewrite does not change. @@ -569,9 +570,9 @@ pub(crate) fn frame_end_checked( } let answered = match source { ResultSource::Inspector => true, - ResultSource::Engine(checkpoint) => { + ResultSource::Engine(mark) => { if before.is_ok() && !frame_result.instruction_result().is_ok() { - revert_journal_to(context, checkpoint); + context.journal_mut().revert_to(&mark); } false } @@ -638,36 +639,14 @@ fn settle_kept_nothing( 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 }; + #[cfg(feature = "ledger-shadow")] + context.additional_limit.shadow_note_top_level_refund(history); 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) { diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 8473d1694..9f0ba3f40 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -1,14 +1,29 @@ -//! The journal of the Satin engine: revm's journal behind a wrapper of the engine's own. +//! The journal of the Satin engine: revm's journal, with the ledger of what the transaction's own +//! execution keeps beside it. //! //! [`MegaJournal`] owns revm's [`Journal`] and implements [`JournalTr`] by delegating every method -//! to it, the configuration switches included: a switch kept at the trait's no-op default would -//! silently turn a journal feature off. The one default kept is `clear`'s, which finalizes through -//! `finalize`. The impl denies `clippy::missing_trait_methods`, so a method `JournalTr` gains is a -//! lint error here until it is given its rule. +//! to it. A handful of methods also tell the ledger what they did, under one rule: +//! +//! - **Counted writes.** A call's value transfer (`transfer_loaded`) and a creation's account +//! checkpoint (`create_account_checkpoint`) are counted when revm makes them for a frame start, +//! inside the start window the engine opens around revm's frame start, and only there. Every +//! other write — `sstore`, `log`, `selfdestruct`, a `transfer`, anything through an account +//! handle — is forwarded and counts nothing: a write an opcode completed reaches the ledger from +//! the Host's completed-write hook, and a write a tool or a precompile makes is not the +//! transaction's own execution. +//! - **Levels and the transaction's end.** `checkpoint`, `checkpoint_commit` and +//! `checkpoint_revert` open and close the ledger's levels with revm's checkpoints; `commit_tx`, +//! `discard_tx` and `finalize` close them all. +//! - **Everything else is forwarded**, the configuration switches included: a switch kept at the +//! trait's no-op default would silently turn a journal feature off. The one default kept is +//! `clear`'s, which finalizes through the hooked `finalize`. +//! +//! The impl denies `clippy::missing_trait_methods`, so a method `JournalTr` gains is a lint error +//! here until it is given its rule. //! //! [`JournalExt::journal`] hands out revm's own entries, and the journal dereferences to revm's //! [`Journal`] read-only, so code that reads revm's journal state keeps reading it. There is no -//! mutable dereference: a write goes through [`JournalTr`], where the wrapper sees it. +//! mutable dereference: a write that bypassed the methods above could not be seen by the ledger. #[cfg(not(feature = "std"))] use alloc as std; @@ -34,8 +49,13 @@ use revm::{ Database, Journal, JournalEntry, }; -/// The journal of the Satin engine: revm's journal behind a wrapper of the engine's own. See the -/// module documentation. +use crate::{ + limit::{ledger_assert, Ledger, Mark, StartFacts, StartReport}, + LimitUsage, +}; + +/// The journal of the Satin engine: revm's journal, and the ledger of what the transaction's own +/// execution keeps. See the module documentation. /// /// It is the journal of every [`MegaContext`](crate::MegaContext). A node that names the /// context's journal type names this one; one that reads revm's journal state reads it through the @@ -44,13 +64,75 @@ use revm::{ pub struct MegaJournal { /// revm's journal, which holds the state. revm: Journal, + /// The ledger, kept in step with `revm`'s checkpoints. + ledger: Ledger, } impl MegaJournal { + /// What the journal's ledger holds the running (or last) transaction to keep: its data-size + /// bytes and write records. + /// + /// The engine's decisions are taken on + /// [`AdditionalLimit::usage`](crate::AdditionalLimit::usage), which counts the same writes; the + /// two agree wherever the transaction's own execution, rather than a tool, took its state back. + pub fn ledger_usage(&self) -> LimitUsage { + self.ledger.usage() + } + + /// The ledger. + pub(crate) const fn ledger(&self) -> &Ledger { + &self.ledger + } + + /// The ledger, mutably. + pub(crate) const fn ledger_mut(&mut self) -> &mut Ledger { + &mut self.ledger + } + /// Consumes the journal and returns revm's. pub fn into_revm(self) -> Journal { self.revm } + + /// Opens the start window for the frame start `facts` describes, which revm decides next. + pub(crate) fn open_start(&mut self, facts: StartFacts) { + self.ledger.open_start(facts); + } + + /// Closes the start window, and reports what the start counted. + pub(crate) fn close_start(&mut self) -> StartReport { + self.ledger.close_start() + } + + /// Marks where the journal and the ledger stand, without changing the journal's depth. + pub(crate) fn mark(&mut self) -> Mark { + let position = self.revm.checkpoint(); + self.revm.checkpoint_commit(); + self.ledger.mark(position) + } + + /// The mark the frame revm just built is taken back to when it is rewritten into a failure + /// ([`Ledger::frame_start_mark`]). + pub(crate) fn frame_start_mark(&self) -> Option { + self.ledger.frame_start_mark() + } + + /// Takes back every journal entry, log and self-destruct made since `mark`, as revm takes back + /// a frame that fails, and the ledger with them; the journal's depth is left as it is. + pub(crate) fn revert_to(&mut self, mark: &Mark) { + let _ = self.revm.checkpoint(); + self.revm.checkpoint_revert(mark.position); + self.ledger.revert_to(mark); + } + + /// Asserts the ledger holds a level for every checkpoint revm's journal holds open. + #[inline] + fn assert_levels(&self) { + ledger_assert!( + self.ledger.depth() == self.revm.depth, + "the ledger holds one level per open checkpoint" + ); + } } impl Deref for MegaJournal { @@ -71,9 +153,12 @@ impl JournalTr for MegaJournal { DB: 'a; fn new(database: DB) -> Self { - Self { revm: Journal::new(database) } + Self { revm: Journal::new(database), ledger: Ledger::default() } } + // Forwarded: reads, transient storage, the switches, account handles, and the writes the + // ledger does not count here. A write an opcode completed is counted by the Host's + // completed-write hook; any other is not the transaction's own execution. delegate! { to self.revm { fn db_mut(&mut self) -> &mut DB; @@ -126,6 +211,7 @@ impl JournalTr for MegaJournal { fn set_amsterdam_eip7708_enabled(&mut self, enabled: bool); fn set_legacy_journal_semantics(&mut self, enabled: bool); fn touch_account(&mut self, address: Address); + // A transfer that is not a frame start's: revm starts frames with `transfer_loaded`. fn transfer( &mut self, from: Address, @@ -179,25 +265,6 @@ impl JournalTr for MegaJournal { fn code(&mut self, address: Address) -> Result, DB::Error>; fn code_hash(&mut self, address: Address) -> Result, DB::Error>; fn depth(&self) -> usize; - fn transfer_loaded( - &mut self, - from: Address, - to: Address, - balance: U256, - ) -> Option; - fn create_account_checkpoint( - &mut self, - caller: Address, - address: Address, - balance: U256, - spec_id: SpecId, - ) -> Result; - fn checkpoint(&mut self) -> JournalCheckpoint; - fn checkpoint_commit(&mut self); - fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint); - fn commit_tx(&mut self); - fn discard_tx(&mut self); - fn finalize(&mut self) -> EvmState; fn load_account_info_skip_cold_load( &mut self, address: Address, @@ -207,7 +274,74 @@ impl JournalTr for MegaJournal { } } - /// The trait's own default: it finalizes through `finalize`. + /// Counted inside a call's start window: the records the transfer makes and its transfer log. + fn transfer_loaded( + &mut self, + from: Address, + to: Address, + balance: U256, + ) -> Option { + let logs = self.revm.logs().len(); + let refused = self.revm.transfer_loaded(from, to, balance); + let logged = self.revm.logs().len() > logs; + self.ledger.on_transfer(from, to, balance, refused.is_some(), logged); + refused + } + + /// Counted inside a creation's start window: the creator's nonce record before the creation's + /// level opens, then the created account and the transfer log on it. + fn create_account_checkpoint( + &mut self, + caller: Address, + address: Address, + balance: U256, + spec_id: SpecId, + ) -> Result { + let start = self.ledger.before_creation(); + let logs = self.revm.logs().len(); + let opened = self.revm.create_account_checkpoint(caller, address, balance, spec_id); + let logged = self.revm.logs().len() > logs; + self.ledger.after_creation(start, address, opened.ok(), logged); + self.assert_levels(); + opened + } + + fn checkpoint(&mut self) -> JournalCheckpoint { + let checkpoint = self.revm.checkpoint(); + self.ledger.on_checkpoint(checkpoint); + self.assert_levels(); + checkpoint + } + + fn checkpoint_commit(&mut self) { + self.revm.checkpoint_commit(); + self.ledger.on_commit(); + self.assert_levels(); + } + + fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) { + self.revm.checkpoint_revert(checkpoint); + self.ledger.on_revert(checkpoint); + self.assert_levels(); + } + + fn commit_tx(&mut self) { + self.revm.commit_tx(); + self.ledger.on_transaction_end(); + } + + fn discard_tx(&mut self) { + self.revm.discard_tx(); + self.ledger.on_transaction_end(); + } + + fn finalize(&mut self) -> EvmState { + let state = self.revm.finalize(); + self.ledger.on_transaction_end(); + state + } + + /// The trait's own default: it finalizes through the hooked `finalize`. fn clear(&mut self) { let _ = self.finalize(); } @@ -224,12 +358,121 @@ impl JournalExt for MegaJournal { #[cfg(test)] mod tests { use super::*; - use crate::test_utils::MemoryDatabase; + use crate::{ + limit::{Mark, StartSide}, + test_utils::MemoryDatabase, + EvmTxRuntimeLimits, LimitCheck, LimitKind, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + }; use alloy_primitives::address; + use revm::{ + context_interface::journaled_state::account::JournaledAccountTr, + primitives::Log as PrimitiveLog, + }; + const SENDER: Address = address!("00000000000000000000000000000000000a0001"); + /// The transaction's own frame. const A: Address = address!("00000000000000000000000000000000000a0002"); const B: Address = address!("00000000000000000000000000000000000a0003"); const C: Address = address!("00000000000000000000000000000000000a0004"); + /// The account a creation from [`A`] makes. + const CREATED: Address = address!("00000000000000000000000000000000000a0005"); + const BODY: u64 = 310; + + /// The transaction's bytes before any frame: the body. + fn body() -> LimitUsage { + LimitUsage { data_size: BODY, write_records: 0 } + } + + /// `n` write records and `logs` transfer logs on top of the body. + fn kept(records: u64, logs: u64) -> LimitUsage { + LimitUsage { + data_size: BODY + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, + write_records: records, + } + } + + /// A journal on Satin's base spec, with transfer logs, every account funded, holding a + /// transaction from [`SENDER`] under `limits`. + fn journal(limits: EvmTxRuntimeLimits) -> MegaJournal { + let db = [SENDER, A, B, C].into_iter().fold(MemoryDatabase::default(), |db, account| { + db.account_balance(account, U256::from(10)) + }); + let mut journal = MegaJournal::new(db); + journal.set_spec_id(SpecId::OSAKA); + journal.set_amsterdam_eip7708_enabled(true); + for account in [SENDER, A, B, C, CREATED] { + journal.load_account(account).unwrap(); + } + journal.ledger_mut().set_limits(limits); + journal.ledger_mut().begin_transaction(false, true, BODY); + journal + } + + /// Starts a call from `caller` to `target` at `depth` as revm starts one: its checkpoint, then + /// its value transfer. Returns the frame's checkpoint and what the start counted. + fn start_call( + journal: &mut MegaJournal, + depth: usize, + caller: Address, + target: Address, + value: u64, + ) -> (JournalCheckpoint, StartReport) { + let value = U256::from(value); + let facts = + StartFacts { depth, caller, target: Some(target), transfers_value: !value.is_zero() }; + journal.open_start(facts); + let checkpoint = journal.checkpoint(); + assert!(journal.transfer_loaded(caller, target, value).is_none()); + (checkpoint, journal.close_start()) + } + + /// Starts a creation from `creator` at `depth` as revm starts one: the nonce bump, then the + /// account checkpoint. + fn start_creation( + journal: &mut MegaJournal, + depth: usize, + creator: Address, + value: u64, + ) -> (JournalCheckpoint, StartReport) { + let value = U256::from(value); + let facts = + StartFacts { depth, caller: creator, target: None, transfers_value: !value.is_zero() }; + journal.open_start(facts); + let _ = journal.load_account_mut(creator).unwrap().data.bump_nonce(); + let checkpoint = + journal.create_account_checkpoint(creator, CREATED, value, SpecId::OSAKA).unwrap(); + (checkpoint, journal.close_start()) + } + + /// The journal's own write methods count nothing, inside a frame start's window and outside + /// it: a write an opcode completed is counted by the Host's completed-write hook, and any other + /// is not the transaction's own execution. + #[test] + fn test_the_journals_own_writes_count_nothing() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let writes = |journal: &mut MegaJournal| { + journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); + journal.sstore_skip_cold_load(A, U256::from(2), U256::from(1), false).unwrap(); + journal.log(PrimitiveLog::new_unchecked(A, Vec::new(), Bytes::new())); + assert_eq!(journal.transfer(A, B, U256::from(1)).unwrap(), None); + journal.selfdestruct(C, B, false).unwrap(); + }; + let _ = start_call(&mut journal, 0, SENDER, A, 0); + writes(&mut journal); + assert_eq!(journal.ledger_usage(), body(), "outside a start's window"); + + journal.open_start(StartFacts { + depth: 1, + caller: A, + target: Some(B), + transfers_value: false, + }); + let _ = journal.checkpoint(); + writes(&mut journal); + let _ = journal.close_start(); + assert_eq!(journal.ledger_usage(), body(), "inside a start's window"); + assert!(!journal.logs().is_empty(), "the writes reached revm's journal"); + } /// Every configuration switch reaches revm's journal: a switch kept at the trait's no-op /// default would turn a journal feature off without a word. @@ -264,12 +507,167 @@ mod tests { /// write. #[test] fn test_the_journal_extension_hands_out_revms_entries() { - let mut journal = MegaJournal::new(MemoryDatabase::default()); - journal.set_spec_id(SpecId::OSAKA); - journal.load_account(A).unwrap(); + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); let entries = JournalExt::journal(&journal); assert!(!entries.is_empty()); assert_eq!(entries, JournalExt::journal(&*journal), "revm's own"); } + + /// The ledger holds a level for every checkpoint revm's journal holds open: a commit closes + /// one and keeps what was counted inside it, a revert closes one and takes it back, and + /// `clear`, the trait's default, closes them all through `finalize`. + #[test] + fn test_the_levels_follow_revms_checkpoints() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let (checkpoint, _) = start_call(&mut journal, 1, A, B, 1); + assert_eq!((journal.ledger().depth(), journal.depth()), (2, 2)); + assert_eq!(journal.ledger_usage(), kept(2, 1), "B's record, A's, and the transfer log"); + journal.ledger_mut().frame_returning(); + journal.checkpoint_revert(checkpoint); + assert_eq!((journal.ledger().depth(), journal.depth()), (1, 1)); + assert_eq!(journal.ledger_usage(), body(), "the revert takes the start back"); + + let _ = start_call(&mut journal, 1, A, B, 1); + journal.ledger_mut().frame_returning(); + journal.checkpoint_commit(); + assert_eq!(journal.ledger_usage(), kept(2, 1), "the commit keeps it"); + let _ = journal.checkpoint(); + journal.clear(); + assert_eq!((journal.ledger().depth(), journal.depth()), (0, 0)); + assert_eq!(journal.ledger_usage(), kept(2, 1), "readable until the next transaction"); + } + + /// A tool's checkpoint around a frame start — opened before the start, closed after the frame + /// returned — is a rollback level the frame's level sits above. Committed, it changes nothing: + /// the frame's records stand, its refund is none, and its caller's account stays recorded, so + /// a later value call from it records only its recipient. Reverted, it takes back what the + /// frame kept: the records, the caller's flag and the frame's refund all go back to before + /// the start, and the later call records the caller again. + #[test] + fn test_a_tool_checkpoint_around_a_frame_start_closes_in_order() { + for reverted in [false, true] { + let case = if reverted { "reverted" } else { "committed" }; + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let tool = journal.checkpoint(); + let (_, report) = start_call(&mut journal, 1, A, B, 1); + assert_eq!( + (report.on_level, report.caller_on_level, report.transfer_log), + (1, true, true), + "{case}: B's record, A's, and the log" + ); + journal.ledger_mut().frame_returning(); + journal.checkpoint_commit(); + let mut side = StartSide::new(1, 7, 11); + side.attach(report, None); + if reverted { + journal.checkpoint_revert(tool); + } else { + journal.checkpoint_commit(); + } + let refund = if reverted { 7 + 11 } else { 0 }; + assert_eq!(side.refund(journal.ledger()), refund, "{case}: B's refund"); + assert_eq!(journal.ledger_usage(), if reverted { body() } else { kept(2, 1) }); + + let (_, later) = start_call(&mut journal, 1, A, C, 1); + assert_eq!(later.caller_on_level, reverted, "{case}: A's flag"); + journal.ledger_mut().frame_returning(); + journal.checkpoint_commit(); + let records = if reverted { 2 } else { 3 }; + assert_eq!( + journal.ledger_usage(), + kept(records, if reverted { 1 } else { 2 }), + "{case}" + ); + } + } + + /// A revert that would close a level from below — a checkpoint taken before a frame started, + /// reverted while the frame still runs — is not supported, and trips. + #[test] + #[cfg(any(debug_assertions, feature = "ledger-shadow"))] + #[should_panic(expected = "a revert closes the latest level")] + fn test_a_revert_below_a_running_frame_trips() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let tool = journal.checkpoint(); + let _ = start_call(&mut journal, 1, A, B, 1); + journal.checkpoint_revert(tool); + } + + /// A creation's budget and usage are measured from before its creator's nonce record, and its + /// level opens after it: with `R` bytes left to an unrecorded creator, the creation gets + /// `R − ⌈R / 50⌉` and starts with the created account's record and the creator's, 80 bytes. + /// At 81 bytes that is a budget of 79, which the start crosses; at 100, a budget of 98, which + /// leaves the creation 18 bytes. An endowment adds its transfer log to the start. + #[test] + fn test_a_creation_is_budgeted_from_before_its_creators_record() { + for (left, value, budget, start) in + [(81, 0, 79, 80), (100, 0, 98, 80), (81 + 160, 1, 236, 240), (100 + 160, 1, 254, 240)] + { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(BODY + left); + let mut journal = journal(limits); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let (_, report) = start_creation(&mut journal, 1, A, value); + let case = format!("{left} bytes left, value {value}"); + assert!(report.creator, "{case}: the creator's record is the start's"); + let used = LimitUsage { data_size: start, write_records: 2 }; + assert_eq!(journal.ledger().running_budget(), Some((budget, used)), "{case}"); + let verdict = if start > budget { + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: budget, + used: start, + frame_local: true, + } + } else { + LimitCheck::WithinLimit + }; + assert_eq!(report.verdict, Some(verdict), "{case}"); + } + } + + /// A creation's start mark is its level's opening — after the creator's record — never where + /// its usage is measured from: a creation rewritten into a failure is taken back to it, and + /// keeps its creator's record and flag, as a creation that fails does. + #[test] + fn test_a_creations_start_mark_keeps_its_creators_record() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let (checkpoint, _) = start_creation(&mut journal, 1, A, 1); + let mark: Mark = journal.frame_start_mark().expect("the creation's level is open"); + assert_eq!(mark.position, checkpoint, "the creation's own checkpoint"); + journal.ledger_mut().frame_returning(); + journal.checkpoint_commit(); + assert_eq!(journal.ledger_usage(), kept(2, 1)); + + journal.revert_to(&mark); + assert_eq!(journal.ledger_usage(), kept(1, 0), "the creator's record stays"); + let (_, later) = start_creation(&mut journal, 1, A, 0); + assert!(!later.creator, "A stays recorded"); + } + + /// The hypothetical start a call gas detention answers without running is held to the limits + /// as the start revm would have made: the same records, the transfer log of the value it moves, + /// the same budget. + #[test] + fn test_a_hypothetical_start_is_held_as_the_start_revm_makes() { + for (depth, value, limit) in [(1, 1, 239), (1, 1, 240), (1, 0, 0), (0, 1, 199), (0, 1, 200)] + { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(BODY + limit); + let mut journal = journal(limits); + let caller = if depth == 0 { + SENDER + } else { + let _ = start_call(&mut journal, 0, SENDER, A, 0); + A + }; + let facts = StartFacts { depth, caller, target: Some(B), transfers_value: value != 0 }; + let hypothetical = journal.ledger().hypothetical_start(&facts); + let (_, report) = start_call(&mut journal, depth, caller, B, value); + assert_eq!(Some(hypothetical), report.verdict, "depth {depth}, value {value}, {limit}"); + } + } } diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 824e3e4cd..d475917aa 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -223,7 +223,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. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs new file mode 100644 index 000000000..e8fd19ddc --- /dev/null +++ b/crates/mega-evm/src/limit/ledger.rs @@ -0,0 +1,930 @@ +//! The journal's ledger: what the transaction's own execution keeps, counted at the journal's +//! writes and rewound with the journal's checkpoints. +//! +//! The ledger lives in [`MegaJournal`](crate::MegaJournal), beside revm's journal, and keeps one +//! level per checkpoint revm's journal holds open. A revert restores the counts the level saw when +//! it opened, so what the ledger holds is what the journal keeps, whoever reverted what: revm for a +//! frame that fails, Satin for a stop, a tool for a checkpoint of its own. +//! +//! # Frame levels and rollback levels +//! +//! A checkpoint opens one of two kinds of level: +//! +//! - a **frame level**, for each frame revm starts: the first checkpoint revm opens while it +//! decides a call's start, or the one a creation's account checkpoint returns. Only the engine's +//! start window ([`open_start`](Ledger::open_start)) opens one. It carries the frame's data-size +//! budget, the account the frame runs as and whether that account is already recorded; +//! - a **rollback level**, for every other checkpoint: the pre-execution phase's, a system call's, +//! a precompile's, a tool's. It carries what its revert restores and nothing else. +//! +//! Budgets, the per-frame dedup of a frame's own account and the running frame's check use the +//! nearest frame level. A rollback level may enclose a frame start (a tool's checkpoint opened +//! before a call and closed after it) as long as the two close in order. A revert that would close +//! a level from below — a checkpoint reverted while a level opened after it is still open — is not +//! supported, and trips in debug builds. +//! +//! # What is counted where +//! +//! - the body and the Oracle hints, as the ledger's base, which no revert takes back; +//! - the records of the applied EIP-7702 authorities, inside the pre-execution level; +//! - a frame start's records and its transfer log, inside the start window, at the two writes revm +//! makes for the start: a call's value transfer, and a creation's account checkpoint. A +//! creation's creator nonce record is counted before the creation's level opens, so the +//! creation's failure leaves it with the creator, and the creation's budget and usage are +//! measured from before it; +//! - a completed write's record, on the running frame's level, fed by the Host's completed-write +//! hook; +//! - deployed code, on the creation's level before revm commits it. +//! +//! Nothing a tool or a precompile writes through the journal is counted: the journal's own write +//! methods count nothing, and the start window is open only while revm decides a start. +//! +//! The lanes ([`AdditionalLimit`](crate::AdditionalLimit)) count the same quantities and stay the +//! ones every decision is taken on; under the `ledger-shadow` feature the two are compared where +//! they must agree. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +use alloy_primitives::{Address, U256}; +use revm::context_interface::journaled_state::JournalCheckpoint; + +use super::{ + limit::share_of_remaining, record::WriteCount, EvmTxRuntimeLimits, LimitCheck, LimitKind, + LimitUsage, TRANSFER_LOG, WRITE_RECORD, +}; + +/// Asserts an invariant of the ledger's levels in debug builds and in `ledger-shadow` builds; in +/// any other build the check is type-checked and compiled out, as `debug_assert!`'s is. +macro_rules! ledger_assert { + ($($arg:tt)*) => { + if cfg!(any(debug_assertions, feature = "ledger-shadow")) { + assert!($($arg)*); + } + }; +} +pub(crate) use ledger_assert; + +/// What the ledger counts that the journal rewinds: additions and refunds, kept apart as the lanes +/// keep them, so that a frame's own usage saturates as a lane's does, and the log and code bytes +/// history counts beside the write records. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// What was counted. + used: LimitUsage, + /// What was taken back: a slot written back to its original value. + refund: LimitUsage, + /// The log and code bytes among [`used`](Self::used). + log_and_code_bytes: u64, +} + +impl Counts { + /// What was counted since `base`, an earlier snapshot of the same count, net of what was taken + /// back since: a frame's usage when `base` is where the frame began. + const fn usage_since(&self, base: &Self) -> LimitUsage { + self.used.saturating_sub(base.used).saturating_sub(self.refund.saturating_sub(base.refund)) + } +} + +/// A frame level's frame: who it is, and what it may keep. +#[derive(Clone, Copy, Debug)] +struct FrameLevel { + /// The frame's start, numbered in the order starts opened their levels in the transaction. + seq: u64, + /// The frame's depth. + depth: usize, + /// Where the frame's usage is measured from: where its level opened, or, for a creation, + /// before its creator's nonce record. + at_base: Counts, + /// The most data-size bytes the frame may keep. + budget: u64, + /// The account the frame runs as. + account: 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. + recorded: bool, + /// Whether the frame is returning, so revm may close its level. + returning: bool, +} + +impl FrameLevel { + /// What the frame keeps so far, the children it kept included. + const fn usage(&self, counts: &Counts) -> LimitUsage { + counts.usage_since(&self.at_base) + } + + /// The data-size bytes the frame may still keep. + const fn remaining(&self, counts: &Counts) -> u64 { + self.budget.saturating_sub(self.usage(counts).data_size) + } +} + +/// One open checkpoint of revm's journal. +#[derive(Clone, Copy, Debug)] +struct Level { + /// The checkpoint revm's journal opened it at, which its revert reverts to. + opened_at: JournalCheckpoint, + /// The counts its revert restores. + at_open: Counts, + /// The flag of the nearest frame level below it as it stood when it opened, which its revert + /// restores. + flag_at_open: bool, + /// The number the next frame start would get when it opened: a frame level numbered at or + /// above it opened inside it. + seq_at_open: u64, + /// The frame, for a frame level; `None` for a rollback level. + frame: Option, +} + +/// What the engine tells the ledger about a frame start it is about to hand revm. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct StartFacts { + /// The frame's depth. + pub(crate) depth: usize, + /// The account starting the frame. + pub(crate) caller: Address, + /// The call's target; `None` for a creation. + pub(crate) target: Option
, + /// Whether the start transfers value: a call carrying a non-zero transfer, or a creation with + /// an endowment. + pub(crate) transfers_value: bool, +} + +/// The start window, open while revm decides one frame start. +#[derive(Clone, Copy, Debug)] +struct Window { + facts: StartFacts, + /// Whether the start's frame level opened. + opened: bool, + /// Whether the start's write — a call's transfer, a creation's account checkpoint — was seen. + counted: bool, +} + +/// What a frame start counted, as the ledger saw it while revm decided the start. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct StartReport { + /// The number of the frame level the start opened; `None` when revm opened none. + pub(crate) seq: Option, + /// The records counted on the start's own level: a value call's recipient, a creation's + /// account. + pub(crate) on_level: u64, + /// Whether the start counted its caller's record on its own level: a value transfer's sender. + pub(crate) caller_on_level: bool, + /// Whether the start counted its creator's nonce record, below its own level, where the + /// creation's failure leaves it. + pub(crate) creator: bool, + /// Whether the start counted the transfer log revm journaled for it. + pub(crate) transfer_log: bool, + /// Whether revm refused the start's value transfer. + pub(crate) refused: bool, + /// The verdict on the start, held to the limits while its level was open; `None` when nothing + /// was held: a refused transfer, a creation that failed before its level opened, a start revm + /// never decided. + pub(crate) verdict: Option, +} + +/// A point the ledger and revm's journal can be taken back to together +/// ([`MegaJournal::revert_to`](crate::MegaJournal)). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Mark { + /// Where revm's journal stood. + pub(crate) position: JournalCheckpoint, + /// The counts. + counts: Counts, + /// The flag of the nearest frame level; `None` when there is none. + flag: Option, + /// The number the next frame start would get: a frame level numbered at or above it is taken + /// back with the mark. + seq: u64, + /// The number of levels open: a revert to the mark finds at most these. + levels: usize, +} + +/// The facts of a creation's start, taken before anything of it is counted. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CreationStart { + /// The creation's budget, from what its creator had left before its nonce record. + budget: u64, + /// Where the creation's usage is measured from: before its creator's nonce record. + at_base: Counts, + /// Whether the creator's nonce record was counted. + creator: bool, + /// The creation's depth. + depth: usize, +} + +/// The ledger. See the module documentation. +#[derive(Clone, Debug, Default)] +pub(crate) struct Ledger { + counts: Counts, + /// The body's data-size bytes. + body: u64, + /// The Oracle hints' data-size bytes. + hints: u64, + /// One level per checkpoint revm's journal holds open, the latest last. + levels: Vec, + /// The start window, while one is open. + window: Option, + /// What the last start counted. + last_start: Option, + /// The last frame level closed, and whether it was kept: committed, and not taken back since. + last_closed: Option<(u64, bool)>, + /// The number the next frame level gets. + next_seq: u64, + /// The transaction's sender, whose account the body counts. + sender: Address, + /// Whether the transaction's call target is an applied EIP-7702 authority, whose record the + /// authorities' records hold. + target_is_authority: bool, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, + limits: EvmTxRuntimeLimits, + /// Whether the transaction is held to no limit. + exempt: bool, + /// Whether a tool's checkpoint that enclosed a frame start was reverted: the lanes do not + /// follow it, and the shadow stops comparing for the transaction. + #[cfg(feature = "ledger-shadow")] + diverged: bool, +} + +impl Ledger { + /// Holds every transaction from the next one on to `limits`. + pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.limits = limits; + } + + /// Starts a transaction, held to the limits or to none when `exempt`, whose body weighs `body` + /// bytes and whose value movements journal transfer logs or not. + pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { + self.counts = Counts::default(); + self.body = body; + self.hints = 0; + self.levels.clear(); + self.window = None; + self.last_start = None; + self.last_closed = None; + self.next_seq = 0; + self.sender = Address::ZERO; + self.target_is_authority = false; + self.transfer_logs = transfer_logs; + self.exempt = exempt; + #[cfg(feature = "ledger-shadow")] + { + self.diverged = false; + } + } + + /* What the ledger holds */ + + /// What the transaction keeps so far: its data-size bytes and write records. + pub(crate) fn usage(&self) -> LimitUsage { + LimitUsage { data_size: self.body.saturating_add(self.hints), write_records: 0 } + .saturating_add(self.counts.used) + .saturating_sub(self.counts.refund) + } + + /// The history bytes the transaction keeps beside its write records: its logs and the code it + /// deposited. + #[cfg(feature = "ledger-shadow")] + pub(crate) fn log_and_code_bytes(&self) -> u64 { + self.counts.log_and_code_bytes + } + + /// The number of levels open, which is revm's journal depth. + pub(crate) fn depth(&self) -> usize { + self.levels.len() + } + + /// The number of frame levels open: the frames on the call stack. + #[cfg(feature = "ledger-shadow")] + pub(crate) fn frame_levels(&self) -> usize { + self.levels.iter().filter(|level| level.frame.is_some()).count() + } + + /// The running frame's level: the nearest frame level. + fn frame_level(&self) -> Option<&FrameLevel> { + self.levels.iter().rev().find_map(|level| level.frame.as_ref()) + } + + /// The running frame's level, mutably. + fn frame_level_mut(&mut self) -> Option<&mut FrameLevel> { + self.levels.iter_mut().rev().find_map(|level| level.frame.as_mut()) + } + + /// The level of the frame below the running one: the one that started it. + fn calling_level_mut(&mut self) -> Option<&mut FrameLevel> { + self.levels.iter_mut().rev().filter_map(|level| level.frame.as_mut()).nth(1) + } + + /// The running frame's depth and number, the identity its level was opened with. + pub(crate) fn running_frame(&self) -> Option<(usize, u64)> { + self.frame_level().map(|level| (level.depth, level.seq)) + } + + /// The running frame's budget and what it keeps so far. + #[cfg(any(test, feature = "ledger-shadow"))] + pub(crate) fn running_budget(&self) -> Option<(u64, LimitUsage)> { + self.frame_level().map(|level| (level.budget, level.usage(&self.counts))) + } + + /// Whether the frame level numbered `seq` is the last one closed, and was kept: committed, and + /// not taken back since. + pub(crate) fn kept(&self, seq: u64) -> bool { + self.last_closed == Some((seq, true)) + } + + /// Whether a tool's checkpoint that enclosed a frame start was reverted in the transaction. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn diverged(&self) -> bool { + self.diverged + } + + /* Verdicts */ + + /// The verdict on `used` crossing `kind`'s `limit`: within, whatever it crossed, for an exempt + /// transaction. + const fn crossed(&self, limit: u64, used: u64, frame_local: bool) -> LimitCheck { + if self.exempt { + return LimitCheck::WithinLimit; + } + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local } + } + + /// Holds what the transaction keeps to its limit, then what the running frame keeps to its + /// budget. + pub(crate) fn check(&self) -> LimitCheck { + let (kept, limit) = (self.usage(), self.limits.tx_data_size_limit); + if kept.exceeds_data_size(limit) { + return self.crossed(limit, kept.data_size, false); + } + if let Some(level) = self.frame_level() { + let used = level.usage(&self.counts); + if used.exceeds_data_size(level.budget) { + return self.crossed(level.budget, used.data_size, true); + } + } + LimitCheck::WithinLimit + } + + /// The budget of a frame starting now: a share of what the running frame has left, or, for + /// the transaction's own frame, what the transaction has left, under the frame cap. + fn child_budget(&self) -> u64 { + let forwarded = match self.frame_level() { + Some(parent) => share_of_remaining(parent.remaining(&self.counts)), + None => self.limits.tx_data_size_limit.saturating_sub(self.usage().data_size), + }; + forwarded.min(self.limits.frame_data_size_limit) + } + + /// 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: the records it would count and the + /// transfer log of the value it would move, held to the transaction's limit and to the budget + /// its frame would get. Nothing is counted. + pub(crate) fn hypothetical_start(&self, facts: &StartFacts) -> LimitCheck { + let Some(target) = facts.target else { + unreachable!("only a call is answered without revm deciding its start") + }; + let mut counted = LimitUsage::ZERO; + if facts.transfers_value { + let (on_level, caller) = if facts.depth == 0 { + (target != facts.caller && !self.target_is_authority, false) + } else { + let caller = !self.frame_level().is_some_and(|level| level.recorded); + (target != facts.caller && target != self.sender, caller) + }; + counted = WRITE_RECORD.times(u64::from(on_level) + u64::from(caller)); + if self.transfer_logs && target != facts.caller { + counted = counted.saturating_add(TRANSFER_LOG); + } + } + let (kept, limit) = (self.usage().saturating_add(counted), self.limits.tx_data_size_limit); + if kept.exceeds_data_size(limit) { + return self.crossed(limit, kept.data_size, false); + } + let budget = self.child_budget(); + if counted.exceeds_data_size(budget) { + return self.crossed(budget, counted.data_size, true); + } + LimitCheck::WithinLimit + } + + /* What the transaction counts outside the journal's writes */ + + /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts + /// other than the transaction's `sender`, `target_is_authority` if the call target is one. + /// Inside the pre-execution level, whose revert takes them back. + pub(crate) fn count_authorities( + &mut self, + sender: Address, + authorities: u64, + target_is_authority: bool, + ) { + self.sender = sender; + self.target_is_authority = target_is_authority; + self.counts.used = self.counts.used.saturating_add(WRITE_RECORD.times(authorities)); + } + + /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and + /// never taken back once counted. + pub(crate) fn admit_hint(&mut self, bytes: u64) -> LimitCheck { + let hint = LimitUsage { data_size: bytes, write_records: 0 }; + let (reached, limit) = (self.usage().saturating_add(hint), self.limits.tx_data_size_limit); + if reached.exceeds_data_size(limit) { + let stop = self.crossed(limit, reached.data_size, false); + if stop.exceeded_limit() { + return stop; + } + } + self.hints = self.hints.saturating_add(bytes); + LimitCheck::WithinLimit + } + + /// Counts what a completed write keeps on the running frame's level: what it adds, or what it + /// takes back. The verdict is the check after an addition; a record taken back holds nothing. + pub(crate) fn count_write(&mut self, count: &WriteCount) -> LimitCheck { + if count.taken != LimitUsage::ZERO { + self.counts.refund = self.counts.refund.saturating_add(count.taken); + return LimitCheck::WithinLimit; + } + self.counts.log_and_code_bytes = + self.counts.log_and_code_bytes.saturating_add(count.log_bytes); + if count.added == LimitUsage::ZERO { + return LimitCheck::WithinLimit; + } + self.counts.used = self.counts.used.saturating_add(count.added); + self.check() + } + + /// Counts `bytes` of code a creation deposits, on the creation's level before revm commits it. + pub(crate) fn count_code(&mut self, bytes: u64) -> LimitCheck { + if bytes == 0 { + return LimitCheck::WithinLimit; + } + let code = LimitUsage { data_size: bytes, write_records: 0 }; + self.counts.used = self.counts.used.saturating_add(code); + self.counts.log_and_code_bytes = self.counts.log_and_code_bytes.saturating_add(bytes); + self.check() + } + + /// Runs the running frame — a `keylessDeploy` call's — as `creator`, whose nonce the creation + /// it starts writes: recorded already when the creator is the transaction's sender. + pub(crate) fn set_frame_creator(&mut self, creator: Address) { + let sender = self.sender; + if let Some(level) = self.frame_level_mut() { + level.account = Some(creator); + level.recorded = creator == sender; + } + } + + /// Takes back the nonce record a creation left the running frame, a `keylessDeploy` call's, + /// when its nonce bump is taken back. `false` when there was none to take. + pub(crate) fn take_back_creator_record(&mut self) -> bool { + let sender = self.sender; + let Some(level) = self.frame_level_mut() else { return false }; + if level.account == Some(sender) || !level.recorded { + return false; + } + level.recorded = false; + self.counts.used = self.counts.used.saturating_sub(WRITE_RECORD); + true + } + + /* The start window */ + + /// Opens the start window for the start `facts` describes, which revm decides next. + pub(crate) fn open_start(&mut self, facts: StartFacts) { + ledger_assert!(self.window.is_none(), "start windows do not nest"); + if facts.depth == 0 { + self.sender = facts.caller; + } + self.last_start = None; + self.window = Some(Window { facts, opened: false, counted: false }); + } + + /// Closes the start window once revm decided the start, and reports what the start counted. + pub(crate) fn close_start(&mut self) -> StartReport { + self.window = None; + self.last_start.take().unwrap_or_default() + } + + /// The start report of the open window. + fn report_mut(&mut self) -> &mut StartReport { + self.last_start.get_or_insert_with(StartReport::default) + } + + /* Levels */ + + /// Opens a level at `opened_at`, a frame level when `frame` is given. + fn open_level(&mut self, opened_at: JournalCheckpoint, frame: Option) { + let flag_at_open = self.frame_level().is_some_and(|level| level.recorded); + self.levels.push(Level { + opened_at, + at_open: self.counts, + flag_at_open, + seq_at_open: self.next_seq, + frame, + }); + } + + /// The number of the next frame level, taken. + const fn take_seq(&mut self) -> u64 { + let seq = self.next_seq; + self.next_seq += 1; + seq + } + + /// revm's journal opened a checkpoint at `opened_at`: the frame level of a call whose start the + /// window is open for, when it is the first checkpoint of the window; a rollback level + /// otherwise. + pub(crate) fn on_checkpoint(&mut self, opened_at: JournalCheckpoint) { + let Some(window) = self.window.filter(|window| !window.opened) else { + return self.open_level(opened_at, None); + }; + let StartFacts { depth, caller, target, transfers_value } = window.facts; + let Some(target) = target else { + // A creation's frame level is the one its account checkpoint opens. + return self.open_level(opened_at, None); + }; + // The one start rule that stays an interpretation of the input: whether the frame's own + // account is recorded before anything of the frame is counted. + let recorded = if depth == 0 { + target == caller || self.target_is_authority || transfers_value + } else { + let inherited = self + .frame_level() + .is_some_and(|parent| parent.account == Some(target) && parent.recorded); + inherited || target == self.sender || transfers_value + }; + let frame = FrameLevel { + seq: self.take_seq(), + depth, + at_base: self.counts, + budget: self.child_budget(), + account: Some(target), + recorded, + returning: false, + }; + self.open_level(opened_at, Some(frame)); + if let Some(window) = &mut self.window { + window.opened = true; + } + let verdict = self.check(); + *self.report_mut() = + StartReport { seq: Some(frame.seq), verdict: Some(verdict), ..Default::default() }; + } + + /// revm moved `value` from `from` to `to` for the call whose start the window is open for + /// (`refused` when it could not), and journaled a transfer log or not (`logged`): counts the + /// records the transfer makes on the call's level, then holds the start to the limits. + /// + /// The transaction's own frame records the recipient unless it is the sender or an applied + /// authority. Any other records the recipient unless it is the caller or the sender, and the + /// caller's own account once per frame; a `CALLCODE` or a call to itself records the caller + /// although revm moves nothing. + pub(crate) fn on_transfer( + &mut self, + from: Address, + to: Address, + value: U256, + refused: bool, + logged: bool, + ) { + let Some(window) = &mut self.window else { return }; + if window.counted || !window.opened || window.facts.target.is_none() { + return; + } + window.counted = true; + let depth = window.facts.depth; + if refused { + let report = self.report_mut(); + report.refused = true; + report.verdict = None; + return; + } + if value.is_zero() { + return; + } + let mut caller_on_level = false; + let on_level = if depth == 0 { + u64::from(to != from && !self.target_is_authority) + } else { + if let Some(caller) = self.calling_level_mut() { + caller_on_level = !caller.recorded; + caller.recorded = true; + } + u64::from(to != from && to != self.sender) + }; + let mut counted = WRITE_RECORD.times(on_level + u64::from(caller_on_level)); + if logged { + counted = counted.saturating_add(TRANSFER_LOG); + } + self.counts.used = self.counts.used.saturating_add(counted); + let verdict = self.check(); + let report = self.report_mut(); + report.on_level = on_level; + report.caller_on_level = caller_on_level; + report.transfer_log = logged; + report.verdict = Some(verdict); + } + + /// revm is about to open a creation's account checkpoint for `creator`'s start: takes the + /// creation's budget and base, then counts the creator's nonce record, before anything of the + /// creation. `None` outside a creation's start window. + pub(crate) fn before_creation(&mut self) -> Option { + let window = self.window.as_mut()?; + if window.counted || window.facts.target.is_some() { + return None; + } + window.counted = true; + let depth = window.facts.depth; + let (budget, at_base) = (self.child_budget(), self.counts); + let mut creator = false; + if depth > 0 { + if let Some(level) = self.frame_level_mut() { + creator = !level.recorded; + level.recorded = true; + } + } + if creator { + self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); + } + Some(CreationStart { budget, at_base, creator, depth }) + } + + /// revm opened (`Ok`) or failed to open (`Err`) the account checkpoint of a creation at + /// `address`, and journaled a transfer log or not (`logged`): opens the creation's frame level, + /// counts the created account and the log on it, then holds the start to the limits. The + /// creation's usage includes its creator's nonce record; its revert keeps it. + /// + /// A checkpoint opened outside a creation's start window opens a rollback level. + pub(crate) fn after_creation( + &mut self, + start: Option, + address: Address, + opened: Option, + logged: bool, + ) { + let Some(start) = start else { + if let Some(opened_at) = opened { + self.open_level(opened_at, None); + } + return; + }; + let Some(opened_at) = opened else { + *self.report_mut() = StartReport { creator: start.creator, ..Default::default() }; + return; + }; + let frame = FrameLevel { + seq: self.take_seq(), + depth: start.depth, + at_base: start.at_base, + budget: start.budget, + account: Some(address), + recorded: true, + returning: false, + }; + self.open_level(opened_at, Some(frame)); + if let Some(window) = &mut self.window { + window.opened = true; + } + let mut counted = WRITE_RECORD; + if logged { + counted = counted.saturating_add(TRANSFER_LOG); + } + self.counts.used = self.counts.used.saturating_add(counted); + let verdict = self.check(); + *self.report_mut() = StartReport { + seq: Some(frame.seq), + on_level: 1, + creator: start.creator, + transfer_log: logged, + verdict: Some(verdict), + ..Default::default() + }; + } + + /// The running frame is returning: revm closes its level next, committing or reverting it. + pub(crate) fn frame_returning(&mut self) { + if let Some(level) = self.frame_level_mut() { + level.returning = true; + } + } + + /// Asserts a frame level closes as revm closes one: while its start is being decided, or once + /// its frame is returning. A frame level any other checkpoint closes — a tool's checkpoint + /// reverted while a frame opened after it still runs — would leave the frame running without + /// its level. + fn assert_frame_closes(&self, frame: &FrameLevel) { + ledger_assert!( + self.window.is_some() || frame.returning, + "a revert closes the latest level: a frame's level closes only when the frame returns" + ); + } + + /// revm's journal committed its latest checkpoint: the level closes, and a frame level hands + /// its frame's flag to a caller running as the same account. + pub(crate) fn on_commit(&mut self) { + let Some(level) = self.levels.pop() else { return }; + let Some(frame) = level.frame else { return }; + self.assert_frame_closes(&frame); + if let Some(caller) = self.frame_level_mut() { + if frame.account.is_some() && frame.account == caller.account { + caller.recorded |= frame.recorded; + } + } + self.last_closed = Some((frame.seq, true)); + } + + /// revm's journal reverted to `checkpoint`: the latest level, which must be the one opened + /// there, closes, and the counts and the flag of the nearest frame level below it are what they + /// were when it opened. + pub(crate) fn on_revert(&mut self, checkpoint: JournalCheckpoint) { + let Some(level) = self.levels.pop() else { return }; + ledger_assert!( + level.opened_at == checkpoint, + "a revert closes the latest level: a revert below a level still open is not supported" + ); + self.counts = level.at_open; + if let Some(caller) = self.frame_level_mut() { + caller.recorded = level.flag_at_open; + } + match level.frame { + Some(frame) => { + self.assert_frame_closes(&frame); + self.last_closed = Some((frame.seq, false)); + } + // A rollback level a frame started inside — a tool's checkpoint around a call — takes + // back what the frame kept, so the frame's level is no longer kept either. + None => { + self.take_back_closed_from(level.seq_at_open); + #[cfg(feature = "ledger-shadow")] + if self.next_seq > level.seq_at_open { + self.diverged = true; + } + } + } + } + + /// Notes that the last frame level closed is taken back when it is numbered `seq` or above. + const fn take_back_closed_from(&mut self, seq: u64) { + if let Some((closed, kept)) = &mut self.last_closed { + if *closed >= seq { + *kept = false; + } + } + } + + /// revm's journal ended the transaction: every level closes. What was counted stays readable + /// until the next transaction begins. + pub(crate) fn on_transaction_end(&mut self) { + self.levels.clear(); + self.window = None; + } + + /* Marks */ + + /// A mark at `position`, where revm's journal stands now. + pub(crate) fn mark(&self, position: JournalCheckpoint) -> Mark { + Mark { + position, + counts: self.counts, + flag: self.frame_level().map(|level| level.recorded), + seq: self.next_seq, + levels: self.levels.len(), + } + } + + /// The mark a frame revm just built is taken back to when it is rewritten into a failure: its + /// own checkpoint, the counts its level opened with — after a creation's creator record — and + /// the flag of the frame below as it stood then. Never where the frame's usage is measured + /// from, which for a creation is before the creator's record. + pub(crate) fn frame_start_mark(&self) -> Option { + let level = self.levels.last()?; + let frame = level.frame?; + let below = self.levels.len() - 1; + let caller = self.levels[..below].iter().rev().any(|level| level.frame.is_some()); + Some(Mark { + position: level.opened_at, + counts: level.at_open, + flag: caller.then_some(level.flag_at_open), + seq: frame.seq, + levels: below, + }) + } + + /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, the + /// running frame's flag, and whether the last frame level closed is kept. + pub(crate) fn revert_to(&mut self, mark: &Mark) { + ledger_assert!( + self.levels.len() <= mark.levels, + "a revert to a mark finds every level opened since closed" + ); + self.counts = mark.counts; + if let (Some(flag), Some(level)) = (mark.flag, self.frame_level_mut()) { + level.recorded = flag; + } + self.take_back_closed_from(mark.seq); + } +} + +/// Satin's side of one frame start: what its caller paid for the records it makes, what the +/// ledger saw it count, and, for a frame revm built, the mark it is taken back to when it is +/// rewritten into a failure. One per frame result revm will return, as the lanes are. +#[derive(Clone, Copy, Debug)] +pub(crate) struct StartSide { + /// The frame's depth. + depth: usize, + /// What the caller paid for the records on the frame's own level. + on_level_charge: u64, + /// What the caller paid for the record of its own account. + caller_charge: u64, + /// What the ledger saw the start count; the default for a start answered before revm decided + /// it, which counted nothing. + report: StartReport, + /// The mark of a frame revm built. + mark: Option, + /// Whether the records the lanes counted for the start are those its charge paid for. + #[cfg(feature = "ledger-shadow")] + comparable: bool, +} + +impl StartSide { + /// The side of a start at `depth` whose caller paid `on_level_charge` and `caller_charge`. + pub(crate) const fn new(depth: usize, on_level_charge: u64, caller_charge: u64) -> Self { + Self { + depth, + on_level_charge, + caller_charge, + report: StartReport { + seq: None, + on_level: 0, + caller_on_level: false, + creator: false, + transfer_log: false, + refused: false, + verdict: None, + }, + mark: None, + #[cfg(feature = "ledger-shadow")] + comparable: true, + } + } + + /// Attaches what the ledger saw the start count and the built frame's mark. + pub(crate) const fn attach(&mut self, report: StartReport, mark: Option) { + self.report = report; + self.mark = mark; + } + + /// Notes whether the records the lanes counted are those the charge paid for. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn set_comparable(&mut self, comparable: bool) { + self.comparable = comparable; + } + + /// Whether the shadow compares the refund: the records the lanes counted are those the charge + /// paid for. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn comparable(&self) -> bool { + self.comparable + } + + /// The frame's depth. + pub(crate) const fn depth(&self) -> usize { + self.depth + } + + /// The number of the frame level the start opened. + pub(crate) const fn seq(&self) -> Option { + self.report.seq + } + + /// The mark of a frame revm built. + pub(crate) const fn mark(&self) -> Option<&Mark> { + self.mark.as_ref() + } + + /// The history gas the caller gets back once the frame returned: what it paid less the price + /// of the start's records `ledger` holds. + /// + /// The records on the start's own level are held when that level was kept — committed, and not + /// taken back since; a creator's nonce record, counted below the creation's level, whenever it + /// was counted. So a start answered before revm decided it, or refused before its writes, gets + /// everything back; a call answered with a success keeps its records; a failed precompile, and + /// a frame that fails, give theirs back, a creator's surviving record aside. + #[cfg_attr(not(feature = "ledger-shadow"), allow(dead_code))] + pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { + let kept = self.report.seq.is_some_and(|seq| ledger.kept(seq)); + let on_level = kept && self.report.on_level > 0; + let caller = (kept && self.report.caller_on_level) || self.report.creator; + let mut refund = 0; + if !on_level { + refund += self.on_level_charge; + } + if !caller { + refund += self.caller_charge; + } + refund + } +} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 181d34a00..90f7edb5c 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -10,11 +10,17 @@ use revm::{ interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + use super::{ frame_limit::{FrameLimitTracker, Lane}, - record::{write_effect, write_moves_value, HistoryBytes, RecordEffect}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, + ledger::{Mark, StartSide}, + record::{write_effect, write_moves_value, HistoryBytes, RecordEffect, WriteCount}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, StartReport, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, + WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -109,6 +115,23 @@ pub struct AdditionalLimit { /// 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, + /// Satin's side of every frame start, one per frame result revm will return, as the lanes + /// are: what the start's caller paid for its records, what the journal's ledger saw the start + /// count, and the mark a frame revm built is taken back to when it is rewritten into a + /// failure. + starts: Vec, + /// The write records the transaction's own frame makes, as the charge of their history before + /// execution found them, kept whatever an inspector does: what the shadow holds the frame's + /// refund to. + #[cfg(feature = "ledger-shadow")] + top_level_paid_for: Option, + /// The history gas given back for the transaction's own frame's write record, at whichever of + /// the three sites gave it back: what the shadow holds the journal's formula to. + #[cfg(feature = "ledger-shadow")] + top_level_refunded: u64, + /// The journal's formula's answer to the same, once the transaction's own frame returned. + #[cfg(feature = "ledger-shadow")] + top_level_refund: Option, } impl AdditionalLimit { @@ -147,6 +170,13 @@ impl AdditionalLimit { self.history_bytes = 0; self.reservoir_remaining = 0; self.transfer_logs = false; + self.starts.clear(); + #[cfg(feature = "ledger-shadow")] + { + self.top_level_paid_for = None; + self.top_level_refunded = 0; + self.top_level_refund = None; + } } /// Records whether the running transaction's value movements journal EIP-7708 transfer logs. @@ -340,6 +370,10 @@ impl AdditionalLimit { /// 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); + #[cfg(feature = "ledger-shadow")] + { + self.top_level_paid_for = Some(records); + } } /// Draws up to `amount` from the running frame's history allowance and reports what it gave; @@ -373,7 +407,13 @@ impl AdditionalLimit { on_lane: u64, caller: u64, ) { - self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; + self.pending_frame_charge = FrameCharge { + records: Some(records), + on_lane, + caller, + #[cfg(feature = "ledger-shadow")] + paid_for: Some(records), + }; } /// Leaves the frame about to start unchecked against the answer its charge was computed from @@ -394,46 +434,56 @@ impl AdditionalLimit { /* Completed writes */ - /// Commits the record of `write`, which the running opcode completed, to the running frame's - /// lane, and reports the history bytes it appends or takes back. Called by the Host's - /// completed-write hook, which revm calls only once the opcode made every charge; a crossed - /// limit in the verdict stops the opcode's frame, and the hook charges the history. + /// What `write`, which the running opcode completed, keeps, and the history bytes it appends or + /// takes back: one answer, which the Host's completed-write hook commits to the running frame's + /// lane ([`commit_count`](Self::commit_count)) and to the journal's ledger. /// - /// 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. + /// A `SELFDESTRUCT` that moved value to another account also keeps the EIP-7708 transfer log + /// revm journaled for the move, with the beneficiary's record. 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_write( - &mut self, - write: &CompletedWrite<'_>, - ) -> (LimitCheck, HistoryBytes) { + pub(crate) fn write_count(&self, write: &CompletedWrite<'_>) -> (WriteCount, HistoryBytes) { let effect = write_effect(write, self.sender); let history = effect.history_bytes(); - let counted = match effect { + let added = match effect { RecordEffect::None => LimitUsage::ZERO, RecordEffect::Record(usage) => usage, RecordEffect::Refund(usage) => { - self.tracker.refund(usage); - return (LimitCheck::WithinLimit, history); + return (WriteCount { taken: usage, ..WriteCount::NONE }, history); } }; - match write { - // A log's bytes are history beside the write records; a record's are counted as one. - CompletedWrite::Log { .. } => self.tracker.record_log_and_code_bytes(counted.data_size), - CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => {} - } - let counted = if self.transfer_logs && write_moves_value(write) { - counted.saturating_add(TRANSFER_LOG) + // A log's bytes are history beside the write records; a record's are counted as one. + let log_bytes = match write { + CompletedWrite::Log { .. } => added.data_size, + CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => 0, + }; + let added = if self.transfer_logs && write_moves_value(write) { + added.saturating_add(TRANSFER_LOG) } else { - counted + added }; - if counted == LimitUsage::ZERO { - return (LimitCheck::WithinLimit, history); + (WriteCount { added, log_bytes, ..WriteCount::NONE }, history) + } + + /// Commits what a completed write keeps to the running frame's lane, and holds it to the + /// limits; a crossed limit in the verdict stops the opcode's frame, and the hook charges the + /// history. A record taken back holds nothing. + #[inline] + pub(crate) fn commit_count(&mut self, count: &WriteCount) -> LimitCheck { + if count.taken != LimitUsage::ZERO { + self.tracker.refund(count.taken); + return LimitCheck::WithinLimit; + } + if count.log_bytes != 0 { + self.tracker.record_log_and_code_bytes(count.log_bytes); } - self.tracker.record(counted); - (self.check(), history) + if count.added == LimitUsage::ZERO { + return LimitCheck::WithinLimit; + } + self.tracker.record(count.added); + self.check() } /* Transaction-level records */ @@ -561,16 +611,18 @@ impl AdditionalLimit { /// frame returns on its first run, before any instruction ([`stop_before_run`]). revm moved /// the value, journaled the transfer log and, for a creation, bumped its creator's nonce; the /// stop is a revert of the frame, so its journal checkpoint takes the move and the log back, - /// and the nonce, bumped before the checkpoint, stays, with its record on the creator. + /// and the nonce, bumped before the checkpoint, stays, with its record on the creator. Returns + /// the verdict. /// /// [`stop_before_run`]: Self::stop_before_run #[inline] - pub(crate) fn hold_built_start(&mut self) { + pub(crate) fn hold_built_start(&mut self) -> LimitCheck { let check = self.check(); if check.exceeded_limit() { debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); self.pending_stop = Some(check); } + check } /// The verdict on the start of the frame revm just answered without building it, the @@ -646,6 +698,7 @@ impl AdditionalLimit { // 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); + self.push_start(depth, charge); match input { FrameInput::Call(inputs) => { let target = inputs.target_address; @@ -665,6 +718,8 @@ impl AdditionalLimit { return; } let records = self.records_the_caller_paid_for(input, charge.records); + #[cfg(feature = "ledger-shadow")] + self.note_paid_for(charge.paid_for, records); let inherited = self.tracker.current().is_some_and(|caller| { caller.address == Some(target) && caller.account_recorded }); @@ -685,6 +740,10 @@ impl AdditionalLimit { } FrameInput::Create(inputs) => { let records = self.records_the_caller_paid_for(input, charge.records); + #[cfg(feature = "ledger-shadow")] + if depth > 0 { + self.note_paid_for(charge.paid_for, records); + } self.tracker.push(Lane::new(None, true, budget, charge.on_lane)); self.tracker.record(WRITE_RECORD.times(records.on_lane)); if depth == 0 { @@ -745,6 +804,8 @@ impl AdditionalLimit { /// here in every other 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) { + #[cfg(feature = "ledger-shadow")] + self.note_paid_for(self.top_level_paid_for, counted); if let Some(charged) = self.pending_top_level_records.take() { debug_assert_eq!( charged, counted, @@ -873,12 +934,98 @@ impl AdditionalLimit { /// /// 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) { + pub(crate) fn push_empty_frame(&mut self, depth: usize) { self.frame_began = true; let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); + self.push_start(depth, charge); self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); } + /* The frame side */ + + /// Pushes Satin's side of a frame start at `depth`, whose caller paid `charge` for the records + /// the start makes; the transaction's own frame was paid for before execution. + fn push_start(&mut self, depth: usize, charge: FrameCharge) { + let (on_level, caller) = if depth == 0 { + (self.top_level_write_record_gas, 0) + } else { + (charge.on_lane, charge.caller) + }; + self.starts.push(StartSide::new(depth, on_level, caller)); + } + + /// Notes, for the shadow, whether the records the lanes count for the latest start, `counted`, + /// are those its charge paid for (`paid_for`): an inspector that rewrites a start's input can + /// split them, and then the lanes' refund and the journal's formula part by design. + #[cfg(feature = "ledger-shadow")] + fn note_paid_for(&mut self, paid_for: Option, counted: T) { + let comparable = paid_for.is_none_or(|paid| paid == counted); + if let Some(side) = self.starts.last_mut() { + side.set_comparable(comparable); + } + } + + /// Attaches what the journal's ledger saw the latest start count, and the mark a frame revm + /// built is taken back to, to that start's side. + pub(crate) fn attach_start(&mut self, report: StartReport, mark: Option) { + if let Some(side) = self.starts.last_mut() { + side.attach(report, mark); + } + } + + /// The side of the running frame's start, or of the start just answered. + pub(crate) fn running_start(&self) -> Option<&StartSide> { + self.starts.last() + } + + /// Pops the side of the start of the frame returning now. + pub(crate) fn pop_start(&mut self) -> Option { + self.starts.pop() + } + + /// The number of starts whose frames have not returned yet. + pub(crate) fn starts_open(&self) -> usize { + self.starts.len() + } + + /// What the lanes hold the transaction and the running frame to, for the shadow. + #[cfg(feature = "ledger-shadow")] + pub(crate) fn shadow_view(&self) -> super::shadow::LanesView { + super::shadow::LanesView { + usage: self.tracker.net(), + log_and_code_bytes: self.tracker.log_and_code_bytes(), + frames: self.tracker.depth(), + running: self.tracker.current().map(|lane| (lane.budget, lane.net())), + check: self.check(), + } + } + + /// The stop the lanes left the running frame to return before it runs on, for the shadow. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn shadow_pending_stop(&self) -> Option { + self.pending_stop + } + + /// Notes, for the shadow, history the lanes gave back for the transaction's own frame's record. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn shadow_note_top_level_refund(&mut self, gas: u64) { + self.top_level_refunded = self.top_level_refunded.saturating_add(gas); + } + + /// Notes, for the shadow, what the journal's formula gives back for the transaction's own + /// frame's record once that frame returned. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn shadow_set_top_level_refund(&mut self, gas: u64) { + self.top_level_refund = Some(gas); + } + + /// What the lanes gave back for the transaction's own frame's record, and what the formula + /// gives back (`None` when the frame never started), for the shadow. + #[cfg(feature = "ledger-shadow")] + pub(crate) const fn shadow_top_level_refunds(&self) -> (u64, Option) { + (self.top_level_refunded, self.top_level_refund) + } + /// 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. /// @@ -967,7 +1114,7 @@ impl AdditionalLimit { /// 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 { +pub(super) 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)); @@ -1033,11 +1180,20 @@ struct FrameCharge { on_lane: u64, /// What the record of the caller's own account cost. caller: u64, + /// The same records as [`records`](Self::records), kept when an inspector waives the check. + #[cfg(feature = "ledger-shadow")] + paid_for: Option, } impl FrameCharge { /// Nothing charged. - const NONE: Self = Self { records: None, on_lane: 0, caller: 0 }; + const NONE: Self = Self { + records: None, + on_lane: 0, + caller: 0, + #[cfg(feature = "ledger-shadow")] + paid_for: None, + }; } #[cfg(test)] @@ -1196,7 +1352,7 @@ mod tests { 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(); + limit.push_empty_frame(1); let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); assert_eq!(limit.on_frame_return(&result), 3_000, "{answer:?}: all of it back"); @@ -1684,6 +1840,16 @@ mod tests { } } + /// Counts `write` on `limit` as the completed-write hook does, and reports the verdict and the + /// history bytes. + fn commit( + limit: &mut AdditionalLimit, + write: &CompletedWrite<'_>, + ) -> (LimitCheck, HistoryBytes) { + let (count, history) = limit.write_count(write); + (limit.commit_count(&count), history) + } + /// 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. @@ -1694,7 +1860,7 @@ mod tests { |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; let mut limit = logging(EvmTxRuntimeLimits::no_limits()); limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let (check, history) = limit.commit_write(&destruction(TARGET)); + let (check, history) = commit(&mut limit, &destruction(TARGET)); assert_eq!(check, LimitCheck::WithinLimit); assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); assert_eq!( @@ -1705,7 +1871,7 @@ mod tests { 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); - let (check, history) = limit.commit_write(&destruction(SENDER)); + let (check, history) = commit(&mut limit, &destruction(SENDER)); assert_eq!(history, HistoryBytes::None); assert_eq!( check, @@ -1720,7 +1886,7 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let _ = limit.commit_write(&destruction(TARGET)); + let _ = commit(&mut limit, &destruction(TARGET)); assert_eq!(limit.usage(), WRITE_RECORD, "no log, no bytes"); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 2949b4244..9dcb06298 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -17,6 +17,11 @@ //! counted once the opcode completed, in the Host's completed-write hook, which revm calls after //! every charge the opcode makes. //! +//! The journal ([`MegaJournal`](crate::MegaJournal)) counts the same quantities in its ledger, at +//! the journal's writes and from the same hooks, and revm's checkpoint reverts rewind it. The lanes +//! take every decision; under the `ledger-shadow` feature the two are held to each other wherever +//! they must agree, and a mismatch panics. +//! //! # The data-size limit //! //! A transaction is held to [`EvmTxRuntimeLimits::tx_data_size_limit`] and every frame to a @@ -130,10 +135,16 @@ //! an over-charge, never an under-charge. mod frame_limit; +mod ledger; #[allow(clippy::module_inception)] mod limit; mod record; +#[cfg(feature = "ledger-shadow")] +pub(crate) mod shadow; +#[cfg(test)] +pub(crate) use ledger::StartSide; +pub(crate) use ledger::{ledger_assert, Ledger, Mark, StartFacts, StartReport}; pub use limit::AdditionalLimit; pub(crate) use limit::FrameStartRecords; pub(crate) use record::HistoryBytes; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index d022e5a94..564b6c330 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -37,6 +37,24 @@ pub(crate) enum HistoryBytes { Taken(u64), } +/// What a completed write keeps, as the lanes and the journal's ledger both count it: what it adds, +/// what it takes back, and the log bytes among what it adds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct WriteCount { + /// What the write adds: a record, a log's bytes, a transfer log. + pub(crate) added: LimitUsage, + /// What the write takes back: the record of a slot written back to its original value. + pub(crate) taken: LimitUsage, + /// The bytes of [`added`](Self::added) that are a log's. + pub(crate) log_bytes: u64, +} + +impl WriteCount { + /// Nothing kept. + pub(crate) const NONE: Self = + Self { added: LimitUsage::ZERO, taken: LimitUsage::ZERO, log_bytes: 0 }; +} + impl RecordEffect { /// The history bytes this effect appends or takes back. pub(crate) const fn history_bytes(self) -> HistoryBytes { diff --git a/crates/mega-evm/src/limit/shadow.rs b/crates/mega-evm/src/limit/shadow.rs new file mode 100644 index 000000000..892db3539 --- /dev/null +++ b/crates/mega-evm/src/limit/shadow.rs @@ -0,0 +1,94 @@ +//! The shadow: the journal's ledger held to the lanes wherever the two must agree. +//! +//! The lanes ([`AdditionalLimit`]) take every decision; the ledger ([`Ledger`]) counts the same +//! writes beside them. Under the `ledger-shadow` feature the engine compares the two at the points +//! of a transaction's life where both describe the same thing, and panics on the first mismatch: +//! +//! - after a completed write is counted, a code deposit, an admitted hint, and the keyless +//! take-back of a creator's record: what the transaction keeps, the history bytes beside its +//! records, the check, and the running frame's budget and usage ([`agree`]); +//! - when revm built a frame: the start's verdict, and the new frame's budget and usage — the +//! creation's measured from before its creator's record ([`agree`], [`verdict`]); +//! - when revm answered a start: the verdict the ledger captured while the start's level was open, +//! or, for a call gas detention answers without running, the hypothetical one ([`verdict`]); +//! - when a frame returns: the history its caller gets back ([`refund`]), the check of the caller +//! it returns into ([`verdict`]), and then [`agree`]; +//! - when the transaction's own frame settles: what the transaction keeps, and the history its own +//! frame's record gets back ([`refund`]). +//! +//! Between a start revm answered and that start's return the two differ by design: the ledger has +//! already taken back what a failed answer journaled, and the lanes take it back when the answer's +//! lane is popped. Nothing is compared there. +//! +//! A tool's checkpoint that enclosed a frame start and is reverted takes back what the frames +//! inside it kept; the ledger follows it and the lanes cannot. From then on the transaction is not +//! compared ([`Ledger::diverged`]). + +use super::{ledger::StartSide, AdditionalLimit, Ledger, LimitCheck, LimitUsage}; + +/// What the lanes hold the transaction and the running frame to. +#[derive(Debug)] +pub(crate) struct LanesView { + /// What the transaction keeps. + pub(crate) usage: LimitUsage, + /// The log and code bytes it keeps. + pub(crate) log_and_code_bytes: u64, + /// The frames on the call stack. + pub(crate) frames: usize, + /// The running frame's budget and what it keeps. + pub(crate) running: Option<(u64, LimitUsage)>, + /// The check. + pub(crate) check: LimitCheck, +} + +/// Panics with the point of the transaction and the quantity on which the two disagree. +macro_rules! shadow_eq { + ($lanes:expr, $ledger:expr, $at:expr, $what:expr) => {{ + let (lanes, ledger) = (&$lanes, &$ledger); + assert!( + lanes == ledger, + "ledger shadow mismatch at {}: {}: lanes {:?}, ledger {:?}", + $at, + $what, + lanes, + ledger, + ); + }}; +} + +/// Holds what the two hold the transaction and the running frame to: what the transaction keeps, +/// the log and code bytes, the check, the number of frames and the running frame's budget and +/// usage. +pub(crate) fn agree(lanes: &AdditionalLimit, ledger: &Ledger, at: &str) { + if ledger.diverged() { + return; + } + let view = lanes.shadow_view(); + shadow_eq!(view.usage, ledger.usage(), at, "usage"); + shadow_eq!(view.log_and_code_bytes, ledger.log_and_code_bytes(), at, "log and code bytes"); + shadow_eq!(view.frames, ledger.frame_levels(), at, "frames"); + shadow_eq!(view.running, ledger.running_budget(), at, "running frame's budget and usage"); + shadow_eq!(view.check, ledger.check(), at, "check"); +} + +/// Holds a verdict the lanes reached (`None` where they held nothing) to the ledger's. +pub(crate) fn verdict( + lanes: Option, + ledger_verdict: Option, + ledger: &Ledger, + at: &str, +) { + if ledger.diverged() { + return; + } + shadow_eq!(lanes, ledger_verdict, at, "verdict"); +} + +/// Holds the history the lanes give a frame's caller back (`lanes`) to what `side`'s caller gets +/// back by the ledger's formula, where the records the lanes counted are those the charge paid for. +pub(crate) fn refund(lanes: u64, side: &StartSide, ledger: &Ledger, at: &str) { + if ledger.diverged() || !side.comparable() { + return; + } + shadow_eq!(lanes, side.refund(ledger), at, "refund"); +} diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index d494a7e56..68882bfb9 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -226,6 +226,7 @@ fn start( } }; ctx.additional_limit.set_frame_creator(deployment.signer); + ctx.journal_mut().ledger_mut().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); } diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 6ee7de062..5d6b56a7e 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -250,7 +250,29 @@ fn take_back_bump( ) -> 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 moved_value { + return Ok(()); + } + let taken = ctx.additional_limit.take_back_creator_record(); + let journaled = ctx.journal_mut().ledger_mut().take_back_creator_record(); + #[cfg(feature = "ledger-shadow")] + { + use crate::limit::shadow; + let ledger = ctx.journal_ref().ledger(); + assert_eq!(taken, journaled, "ledger shadow mismatch at a keyless take-back: taken back"); + let pending = ctx.additional_limit.shadow_pending_stop(); + let check = ledger.check(); + shadow::verdict( + pending, + check.exceeded_limit().then_some(check), + ledger, + "a keyless take-back", + ); + shadow::agree(&ctx.additional_limit, ledger, "a keyless take-back"); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = journaled; + if taken { gas.refill_history(started.signer_record_charge); } Ok(()) diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index c4ab0bc23..f005dbbd9 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -92,6 +92,16 @@ pub(crate) fn intercept( } let payload = inputs.input.bytes(&*ctx); let check = ctx.additional_limit.record_hint_bytes(payload.len() as u64); + let journaled = ctx.inner.journaled_state.ledger_mut().admit_hint(payload.len() as u64); + #[cfg(feature = "ledger-shadow")] + { + use crate::limit::shadow; + let ledger = ctx.inner.journaled_state.ledger(); + shadow::verdict(Some(check), Some(journaled), ledger, "an Oracle hint"); + shadow::agree(&ctx.additional_limit, ledger, "an Oracle hint"); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = journaled; if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); diff --git a/crates/mega-state-test/Cargo.toml b/crates/mega-state-test/Cargo.toml index 2aa2624aa..5ffde98f2 100644 --- a/crates/mega-state-test/Cargo.toml +++ b/crates/mega-state-test/Cargo.toml @@ -36,6 +36,11 @@ alloy-eips.workspace = true # misc tempfile.workspace = true +[features] +# The engine with the journal's ledger held to the lanes wherever the two must agree, a mismatch +# panicking: mega-evm's `ledger-shadow`, for verification runs. +ledger-shadow = ["mega-evm/ledger-shadow"] + # Published as `mega-state-test`; the library keeps the `state_test` import name. [lib] name = "state_test" diff --git a/crates/state-test/Cargo.toml b/crates/state-test/Cargo.toml index f425e3029..bca65c32f 100644 --- a/crates/state-test/Cargo.toml +++ b/crates/state-test/Cargo.toml @@ -35,3 +35,8 @@ alloy-rlp = { workspace = true, features = ["std"] } # misc tempfile.workspace = true + +[features] +# The engine with the journal's ledger held to the lanes: mega-evm's `ledger-shadow`, for +# verification runs. +ledger-shadow = ["mega-state-test/ledger-shadow"] From c92b168f3e9858a0155c027094f8acc6c69b255c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:05:55 +0800 Subject: [PATCH 411/458] test(satin): the start kinds and tool paths the ledger shadow is held on Adds the boundary cases the suite lacked: data size winning over gas detention's crossing at one start (the transaction limit and the frame cap), a recipient that cannot hold the value, a failing precompile's start under a limit, a nested creation whose nonce cannot be bumped, repeated value calls to one recipient, a delegate's record of its caller's account, a precompile writing through EvmInternals, a tool checkpoint around a call (committed and reverted) and a frame_start answer. --- .../tests/satin/detained_transfers.rs | 70 +++++ crates/mega-evm/tests/satin/journal_ledger.rs | 260 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/transfer_logs.rs | 125 +++++++++ crates/mega-evm/tests/satin/write_records.rs | 60 +++- 5 files changed, 514 insertions(+), 2 deletions(-) create mode 100644 crates/mega-evm/tests/satin/journal_ledger.rs diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 99e42a71f..051ebfbbe 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -280,6 +280,76 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { } } +/// 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 limit 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 limit", + limits.with_tx_data_size_limit(body + start - 1), + Some(body + 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 }; + assert_eq!(run.outcome.usage, body_alone, "{case}"); + } + } +} + /* ---------- 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 diff --git a/crates/mega-evm/tests/satin/journal_ledger.rs b/crates/mega-evm/tests/satin/journal_ledger.rs new file mode 100644 index 000000000..3606bc16d --- /dev/null +++ b/crates/mega-evm/tests/satin/journal_ledger.rs @@ -0,0 +1,260 @@ +//! The journal's ledger beside the lanes: what it counts of writes made by anything but the +//! transaction's own execution, and how it follows a tool's checkpoints. +//! +//! The ledger counts what the transaction's own execution keeps, at the journal's writes, and the +//! journal's checkpoints rewind it. A precompile's writes through `EvmInternals` and an +//! inspector's are not the transaction's own execution: neither is counted, and neither moves the +//! ledger away from the lanes. A tool's checkpoint around a call is a level of the journal like any +//! other: committed, it changes nothing; reverted, it takes back what the call kept, and the ledger +//! follows it where the lanes, which follow frames, do not. +//! +//! Every test here, as every other, runs under the shadow in a `ledger-shadow` build, which holds +//! the ledger to the lanes wherever the two must agree. + +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}, + transaction_body_bytes, LimitUsage, MegaContext, MegaEvm, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::STOP, + context::{ContextTr, JournalTr}, + context_interface::journaled_state::JournalCheckpoint, + handler::FrameResult, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, + InterpreterResult, + }, + precompile::{PrecompileId, PrecompileOutput}, + Inspector, +}; + +use crate::common::{call, context}; + +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; + +/// Room for every scenario, at any byte price the grid reaches. +const GAS_LIMIT: u64 = 50_000_000; + +/// The data size of a body, `records` write records and `logs` transfer logs. +fn kept(body: u64, records: u64, logs: u64) -> LimitUsage { + LimitUsage { + data_size: body + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, + write_records: records, + } +} + +/// 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. The ledger counts what the lanes count. +#[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, GAS_LIMIT); + let body = transaction_body_bytes(&tx); + 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, kept(body, 2, 1), "the call's start alone is counted"); + assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "the ledger counts the same"); +} + +/// An inspector that opens a checkpoint when a call to `target` starts, and commits it or reverts +/// it when the call ends: a tool's checkpoint around a frame start. +struct Encloses { + target: Address, + revert: bool, + open: Vec, +} + +impl Inspector, EthInterpreter> for Encloses { + fn call( + &mut self, + context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + if inputs.target_address == self.target { + self.open.push(context.journal_mut().checkpoint()); + } + None + } + + fn call_end( + &mut self, + context: &mut MegaContext, + inputs: &CallInputs, + _outcome: &mut CallOutcome, + ) { + if inputs.target_address != self.target { + return; + } + let checkpoint = self.open.pop().expect("opened when the call started"); + if self.revert { + context.journal_mut().checkpoint_revert(checkpoint); + } else { + context.journal_mut().checkpoint_commit(); + } + } +} + +/// A tool's checkpoint opened as a value call to [`RECEIVER`] starts and closed as it ends, before +/// [`CONTRACT`] makes a second value call, to [`PAYEE`]. +/// +/// Committed, it changes nothing: both calls keep their starts — the two recipients' records, +/// `CONTRACT`'s own, once, and the two transfer logs — and the ledger counts what the lanes count. +/// +/// Reverted, it takes back what the first call kept, its value and its transfer log included, so +/// the receipt carries the second call's log alone; the ledger takes back the first call's records +/// and `CONTRACT`'s flag with it, so the second call records `CONTRACT` again, and the ledger +/// holds what the journal kept: two records and one log. The lanes follow frames, not a tool's +/// checkpoints, and keep counting the first call. +#[test] +fn test_a_tool_checkpoint_around_a_call_closes_with_it() { + for revert in [false, true] { + let case = if revert { "reverted" } else { "committed" }; + let code = BytecodeBuilder::default() + .call(RECEIVER, U256::from(VALUE)) + .call(PAYEE, U256::from(VALUE)) + .stop() + .build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(2 * VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])); + let tx = call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT); + let body = transaction_body_bytes(&tx); + let inspector = Encloses { target: RECEIVER, revert, open: Vec::new() }; + let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let ledger = evm.ctx().journal_ref().ledger_usage(); + let paid = transfer_log(CONTRACT, PAYEE, U256::from(VALUE)); + if revert { + assert_eq!(outcome.result.logs(), [paid], "{case}: the second call's log alone"); + assert_eq!( + outcome.state.get(&RECEIVER).map(|account| account.info.balance), + Some(U256::ZERO), + "{case}: the first call's value went back" + ); + assert_eq!(ledger, kept(body, 2, 1), "{case}: what the journal kept"); + } else { + let received = transfer_log(CONTRACT, RECEIVER, U256::from(VALUE)); + assert_eq!(outcome.result.logs(), [received, paid], "{case}"); + assert_eq!(outcome.usage, kept(body, 3, 2), "{case}"); + assert_eq!(ledger, outcome.usage, "{case}: the ledger counts what the lanes count"); + } + } +} + +/// 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, and the ledger counts what the lanes count. +#[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), GAS_LIMIT); + let body = transaction_body_bytes(&tx); + 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, kept(body, 0, 0), "{case}"); + assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "{case}"); + } +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index f5b755c7a..a13bc1531 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -25,6 +25,7 @@ mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; +mod journal_ledger; mod limit_exemption; mod limit_stop; mod neutral; diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index ddc91c99d..2df9a2de1 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -1059,6 +1059,131 @@ 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 }); + 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: 20_000_000, + ..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 }); + + let limit = body + start - 1; + let stopped = + execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + 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 }); +} + +/// A `CREATE` from a contract whose nonce cannot be bumped is answered by revm without bumping it: +/// no account, no record, no log, and the history the creator paid at its opcode for the two +/// records comes back. 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: 20_000_000, + ..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 }); + assert_eq!(outcome.state[&ACTOR].info.nonce, u64::MAX, "{limits:?}: not bumped"); + assert_eq!( + outcome.gas.history, + history_gas(body).unwrap(), + "the records' charge came back" + ); + } +} + /// 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. diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index c3d6a2b65..af04358f7 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -23,8 +23,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, - REVERT, SELFDESTRUCT, SSTORE, STOP, + CALL, CALLDATASIZE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, + PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STOP, }, interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Database, Inspector, @@ -101,6 +101,25 @@ fn test_two_value_calls_record_the_sender_once() { ); } +/// Value transfers to one recipient record it each time, and the sender once: a recipient's record +/// is the transfer's, not the frame's, so nothing deduplicates it. +#[test] +fn test_value_calls_to_one_recipient_record_it_each_time() { + 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, gas_limit()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + with_extra(records(4), 3 * TRANSFER_LOG_SIZE), + "CALLEE once, CONTRACT three times, and a transfer log for each transfer" + ); +} + /// 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() { @@ -172,6 +191,43 @@ fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { ); } +/// 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, gas_limit())); + assert!(result.result.is_success(), "the caller succeeds"); + let expected = if fails { + with_extra(records(2), TRANSFER_LOG_SIZE) + } else { + with_extra(records(3), 2 * TRANSFER_LOG_SIZE) + }; + assert_eq!(usage, expected, "CALLEE once, then CONTRACT2, and CONTRACT unless it failed"); + } +} + const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); /// `PUSH5 ; PUSH1 0; MSTORE; (PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP) x From adf4663180d9cd5576cf8ee2bcdc72f19ec6dde7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:06:01 +0800 Subject: [PATCH 412/458] docs: the journal and its ledger shadow in AGENTS.md --- AGENTS.md | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f4eeb93d8..1399bb348 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,11 @@ 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 ledger shadow: the journal's ledger held to the lanes wherever the two must agree, a mismatch +# panicking; the state-test crates pass the feature on, for the fixtures, blockchain tests and witness replays +cargo test -p mega-evm --features ledger-shadow +cargo build --release --locked -p state-test --features ledger-shadow + # 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 @@ -130,21 +135,22 @@ 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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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, 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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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`; `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`), what a completed write counts (`record.rs`), 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, and the settled transaction's history gas, history bytes and unspent reservoir; `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`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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`; `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`), what a completed write counts (`record.rs`), Satin's side of each frame start (`StartSide`); the journal's ledger, the lanes' quantities counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the start reports, the marks, the creation rule — a shadow of the lanes until it takes the decisions (`ledger.rs`), and the comparison of the two under the `ledger-shadow` feature (`shadow.rs`); 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, and the settled transaction's history gas, history bytes and unspent reservoir; `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. + Its journal is `MegaJournal`: revm's journal, delegated to method by method, with the ledger of what the transaction's own execution keeps beside it (see the journal's ledger below); a node that names the context's journal type names `MegaJournal`, and reads revm's journal through its read-only dereference. 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, 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. @@ -387,7 +393,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 commits the record to the running frame's lane and holds it to the limits first — 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. + It commits the record to the running frame's lane, and the same count to the journal's ledger, and holds it to the limits first — 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 record, 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.** @@ -404,6 +410,12 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. +- **The journal's ledger is a shadow of the lanes, until it takes the decisions.** + `MegaJournal` counts what the lanes count, at the journal's writes: a frame start's records and transfer log inside the start window Satin opens around revm's frame start, a completed write and a deposit's code from the hooks that feed the lanes, the body, the hints and the authorities where the lanes get them; revm's checkpoint reverts rewind it. + Every checkpoint opens a level: a frame level for each frame revm starts — the first checkpoint of a call's start, or a creation's account checkpoint, whose budget and usage are measured from before its creator's nonce record — and a rollback level for any other, a tool's or a precompile's included; a frame level closes only as its frame returns, and a revert that would close one from below trips in debug builds. + The journal's own write methods count nothing, so a tool's or a precompile's writes are not counted (the policy the lanes already hold). + The lanes take every decision; the `ledger-shadow` feature holds the ledger to them — totals, budgets, start verdicts, refunds, caller checks — and panics on a mismatch. + A tool's checkpoint around a frame start that the tool reverts takes the frame's records back in the ledger and not on the lanes: the shadow stops comparing that transaction. - **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. From 972daaebc51584d508de326c4badf65ff77e5f58 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:54:29 +0800 Subject: [PATCH 413/458] fix(limit): a revert from before a creation's start refunds its creator's record The refund formula held a creator's nonce record whenever the start counted it; a tool's checkpoint opened before the creation and reverted after it takes that record back with the rest, and the caller is owed its charge. Each start now has an id and a fate (its level kept, what it counted below its level kept), which a frame level's revert, a rollback level's revert and a revert to a mark update; the built frame's own mark keeps the creator record. Review cleanups: the shadow is one call per point, compiled to nothing without the feature; the context reaches the ledger through ledger()/ledger_mut(); the journal drops its pass-throughs and keeps ledger_usage for test builds; FrameStart carries the start's facts; the entry identity check also runs on the inspected path; the ledger shares its level opening, call-record rule and transfer-log addition; renames (recorded_at_open, creator_record, refunded_by_lanes/by_formula). New unit tests: a tool checkpoint around a creation, and an ordinary method call resolving to the journal's own. --- crates/mega-evm/src/evm/context.rs | 38 +- crates/mega-evm/src/evm/execution.rs | 210 ++++------ crates/mega-evm/src/evm/host.rs | 18 +- crates/mega-evm/src/evm/inspector.rs | 3 +- crates/mega-evm/src/evm/journal.rs | 204 ++++++---- crates/mega-evm/src/evm/precompiles.rs | 3 +- crates/mega-evm/src/limit/ledger.rs | 380 ++++++++++-------- crates/mega-evm/src/limit/limit.rs | 32 +- crates/mega-evm/src/limit/mod.rs | 3 +- crates/mega-evm/src/limit/shadow.rs | 295 +++++++++++--- .../mega-evm/src/system/keyless/dispatch.rs | 2 +- crates/mega-evm/src/system/keyless/settle.rs | 21 +- crates/mega-evm/src/system/oracle.rs | 16 +- 13 files changed, 708 insertions(+), 517 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 1ea6b622b..f40d1e6ec 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -23,6 +23,7 @@ use crate::{ inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, + limit::{shadow, Ledger}, system::{ self, keyless::{self, KeylessFrame}, @@ -258,7 +259,7 @@ impl MegaContext { /// ledger alike. pub(crate) const fn set_tx_runtime_limits(&mut self, limits: EvmTxRuntimeLimits) { self.additional_limit.set_limits(limits); - self.inner.journaled_state.ledger_mut().set_limits(limits); + self.ledger_mut().set_limits(limits); } /// The block hashes execution has read on this context. @@ -304,6 +305,16 @@ impl MegaContext { &self.additional_limit } + /// The journal's ledger of what the running (or last) transaction keeps. + pub(crate) const fn ledger(&self) -> &Ledger { + self.inner.journaled_state.ledger() + } + + /// The journal's ledger, mutably. + pub(crate) const fn ledger_mut(&mut self) -> &mut Ledger { + self.inner.journaled_state.ledger_mut() + } + /// 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 { @@ -485,11 +496,7 @@ impl MegaContext { // a system transaction and a system call are exempt from the charge, not from the count. let body = transaction_body_bytes(self.tx()); self.additional_limit.record_tx_body(body); - self.inner.journaled_state.ledger_mut().begin_transaction( - system_originated, - transfer_logs, - body, - ); + self.ledger_mut().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( @@ -681,23 +688,8 @@ impl ContextTr for MegaContext EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), ItemOrResult::Result(result) => Err(result), }); - let report = self.inner.ctx.journal_mut().close_start(); + let report = self.inner.ctx.ledger_mut().close_start(); (decided?, report) }; let ctx = &mut self.inner.ctx; @@ -609,17 +591,10 @@ impl EvmTr for MegaEvm { @@ -662,7 +637,7 @@ impl EvmTr for MegaEvm Result, ContextDbError> { let rewriting = self.has_rewriting_inspector(); + // A start past the call-stack limit is answered by the depth guard, wherever it comes from. + if frame_init.depth <= CALL_STACK_LIMIT as usize { + assert_running_frame(&self.inner.ctx, frame_init.depth); + } let (ctx, inspector) = self.ctx_inspector(); // What the calling opcode charged upfront, before the inspector's hooks can rewrite the // call it charged for. @@ -845,7 +824,7 @@ where }; if action.is_return() { // revm closes the frame's level as it processes its return. - ctx.journal_mut().ledger_mut().frame_returning(); + ctx.ledger_mut().frame_returning(); } let mut next = frame.process_next_action(ctx, action); after_frame_run(ctx, frame, &mut next); @@ -1179,10 +1158,9 @@ struct FrameStart { /// for it — a creator's nonce bump, the value the start moves and its transfer log, a /// precompile's writes — comes after. mark: Mark, - /// The frame's depth. - depth: usize, - /// The account a creation is made by; `None` for a call. - creator: Option
, + /// What the start is: its depth, its caller, its target or none for a creation, and whether it + /// moves value. + facts: StartFacts, /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. gas_limit: u64, /// The reservoir the frame inherits. @@ -1191,10 +1169,6 @@ struct FrameStart { /// revm journaled. #[cfg(debug_assertions)] transfer_log: bool, - /// The account the start moves value from, and the call's target, which a creation learns - /// when revm builds it: the two ends of the start's own transfer log. - #[cfg(debug_assertions)] - ends: (Address, Option
), } impl FrameStart { @@ -1203,26 +1177,45 @@ impl FrameStart { ctx: &mut MegaContext, frame_init: &FrameInit, ) -> Self { - let input = &frame_init.frame_input; - let (creator, reservoir) = match input { - FrameInput::Call(inputs) => (None, inputs.reservoir), - FrameInput::Create(inputs) => (Some(inputs.caller()), inputs.reservoir()), - FrameInput::Empty => (None, 0), + let (input, depth) = (&frame_init.frame_input, frame_init.depth); + let (facts, reservoir) = match input { + FrameInput::Call(inputs) => ( + StartFacts { + depth, + caller: inputs.caller, + target: Some(inputs.target_address), + transfers_value: inputs.transfers_value(), + }, + inputs.reservoir, + ), + FrameInput::Create(inputs) => ( + StartFacts { + depth, + caller: inputs.caller(), + target: None, + transfers_value: !inputs.value().is_zero(), + }, + inputs.reservoir(), + ), + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), }; Self { mark: ctx.journal_mut().mark(), - depth: frame_init.depth, - creator, + facts, gas_limit: input_gas_limit(input), reservoir, #[cfg(debug_assertions)] transfer_log: ctx.additional_limit.frame_start_transfer_log(input), - #[cfg(debug_assertions)] - ends: match input { - FrameInput::Call(inputs) => (inputs.caller, Some(inputs.target_address)), - FrameInput::Create(inputs) => (inputs.caller(), None), - FrameInput::Empty => (Address::ZERO, None), - }, + } + } + + /// The account a creation is made by; `None` for a call. + const fn creator(&self) -> Option
{ + match self.facts.target { + Some(_) => None, + None => Some(self.facts.caller), } } @@ -1238,7 +1231,7 @@ impl FrameStart { created: Option
, ) { use revm::primitives::eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}; - let (from, to) = (self.ends.0, self.ends.1.or(created).unwrap_or_default()); + let (from, to) = (self.facts.caller, self.facts.target.or(created).unwrap_or_default()); let ends = [ETH_TRANSFER_LOG_TOPIC, from.into_word(), to.into_word()]; let journaled = ctx.journal_ref().logs()[self.mark.position.log_i..] .iter() @@ -1275,19 +1268,12 @@ fn hold_answered_start( report: &StartReport, answer: &mut FrameResult, ) { - #[cfg(feature = "ledger-shadow")] - let held = |ctx: &MegaContext, lanes: Option| { - shadow::verdict(lanes, report.verdict, ctx.journal_ref().ledger(), "an answered start"); - }; - #[cfg(not(feature = "ledger-shadow"))] - let _ = report; - let Some(creator) = start.creator else { + let Some(creator) = start.creator() else { if matches!( answer.instruction_result(), InstructionResult::OutOfFunds | InstructionResult::OverflowPayment ) { - #[cfg(feature = "ledger-shadow")] - held(ctx, None); + shadow::answered_start(ctx.ledger(), None, report); return; } #[cfg(debug_assertions)] @@ -1295,8 +1281,7 @@ fn hold_answered_start( start.assert_transfer_log_journaled(ctx, None); } let check = ctx.additional_limit.check_start(); - #[cfg(feature = "ledger-shadow")] - held(ctx, Some(check)); + shadow::answered_start(ctx.ledger(), Some(check), report); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); stop_the_answer(answer, start, output); @@ -1306,8 +1291,7 @@ fn hold_answered_start( let bumped = ctx.journal_ref().journal()[start.mark.position.journal_i..] .iter() .any(|entry| matches!(entry, JournalEntry::NonceBump { address } if *address == creator)); - #[cfg(feature = "ledger-shadow")] - held(ctx, None); + shadow::answered_start(ctx.ledger(), None, report); if bumped { return; } @@ -1315,10 +1299,9 @@ fn hold_answered_start( // revm answers a creation whose creator's nonce cannot be bumped with a success. The // transaction's own frame, refused so, makes none of the records charged before execution for // it, and the history they cost comes back with the answer, as for a frame that kept nothing. - if start.depth == 0 && answer.instruction_result().is_ok() { + if start.facts.depth == 0 && answer.instruction_result().is_ok() { let top_level = ctx.additional_limit.top_level_write_record_gas(); - #[cfg(feature = "ledger-shadow")] - ctx.additional_limit.shadow_note_top_level_refund(top_level); + ctx.additional_limit.note_top_level_refund(top_level); answer.gas_mut().refill_history(top_level); } } @@ -1389,29 +1372,7 @@ fn built_frame_mark( kept.is_some_and(|mark| mark.position == frame.checkpoint), "a built frame's start side keeps the mark of its own checkpoint" ); - kept.unwrap_or_else(|| ctx.journal_ref().ledger().mark(frame.checkpoint)) -} - -/// What the ledger is told about the start `frame_init` asks revm for. -fn start_facts(frame_init: &FrameInit) -> StartFacts { - let depth = frame_init.depth; - match &frame_init.frame_input { - FrameInput::Call(inputs) => StartFacts { - depth, - caller: inputs.caller, - target: Some(inputs.target_address), - transfers_value: inputs.transfers_value(), - }, - FrameInput::Create(inputs) => StartFacts { - depth, - caller: inputs.caller(), - target: None, - transfers_value: !inputs.value().is_zero(), - }, - FrameInput::Empty => unreachable!( - "a frame input always names a call or a creation, as revm's frame init asserts" - ), - } + kept.unwrap_or_else(|| ctx.ledger().mark(frame.checkpoint)) } /// Asserts, as a frame at `depth` starts, that the journal's nearest frame level is the running @@ -1422,9 +1383,11 @@ fn assert_running_frame( ctx: &MegaContext, depth: usize, ) { - let running = ctx.additional_limit.running_start().and_then(|side| side.seq()); + let running = ctx.additional_limit.running_start().and_then(|side| side.start()); + let expected = + depth.checked_sub(1).zip(running).map(|(depth, start)| FrameIdentity { depth, start }); ledger_assert!( - ctx.journal_ref().ledger().running_frame() == depth.checked_sub(1).zip(running), + ctx.ledger().running_frame() == expected, "a frame starts from the running frame's own level" ); } @@ -1442,34 +1405,22 @@ fn on_start_return( refund: u64, ) { let Some(side) = ctx.additional_limit.pop_start() else { return }; - let caller = ctx.additional_limit.running_start().and_then(|side| side.seq()); + let caller = ctx.additional_limit.running_start().and_then(|side| side.start()); + let expected = side + .depth() + .checked_sub(1) + .zip(caller) + .map(|(depth, start)| FrameIdentity { depth, start }); ledger_assert!( - ctx.journal_ref().ledger().running_frame() == side.depth().checked_sub(1).zip(caller), + ctx.ledger().running_frame() == expected, "a frame returns with its own level closed, into its caller's" ); - #[cfg(feature = "ledger-shadow")] - { - let ledger = ctx.journal_ref().ledger(); - if side.depth() == 0 { - if side.comparable() { - let formula = side.refund(ledger); - ctx.additional_limit.shadow_set_top_level_refund(formula); - } - } else { - shadow::refund(refund, &side, ledger, "a frame's return"); - let check = ledger.check(); - let lanes = ctx.additional_limit.shadow_pending_stop(); - shadow::verdict( - lanes, - check.exceeded_limit().then_some(check), - ledger, - "a caller's check", - ); - } - shadow::agree(&ctx.additional_limit, ctx.journal_ref().ledger(), "a frame's return"); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = refund; + shadow::frame_return( + &mut ctx.additional_limit, + ctx.inner.journaled_state.ledger(), + refund, + &side, + ); } /// Whether executing this transaction creates its caller's account: a deposit-like transaction @@ -1532,7 +1483,7 @@ fn record_applied_authorities( 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); - ctx.journal_mut().ledger_mut().count_authorities(caller, applied, target_is_authority); + ctx.ledger_mut().count_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); @@ -1869,12 +1820,15 @@ mod tests { let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); let start = FrameStart { mark: ctx.journal_mut().mark(), - depth: 1, - creator: None, + facts: StartFacts { + depth: 1, + caller: CALLER, + target: Some(TARGET), + transfers_value: true, + }, gas_limit: 0, reservoir: 0, transfer_log: true, - ends: (CALLER, Some(TARGET)), }; start.assert_transfer_log_journaled(&ctx, None); } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 3a1ff03c2..98716c20f 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -74,8 +74,10 @@ use revm::{ }; use crate::{ - charge_write_records_history, history_gas, limit::HistoryBytes, - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, + charge_write_records_history, history_gas, + limit::{shadow, HistoryBytes}, + system::ORACLE_CONTRACT_ADDRESS, + ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -320,16 +322,8 @@ impl revm::context_interface::Host // One count, committed to the lanes, which decide, and to the journal's ledger. let (count, history) = self.additional_limit.write_count(&write); let check = self.additional_limit.commit_count(&count); - let journaled = self.inner.journaled_state.ledger_mut().count_write(&count); - #[cfg(feature = "ledger-shadow")] - { - use crate::limit::shadow; - let ledger = self.inner.journaled_state.ledger(); - shadow::verdict(Some(check), Some(journaled), ledger, "a completed write"); - shadow::agree(&self.additional_limit, ledger, "a completed write"); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = journaled; + let journaled = self.ledger_mut().count_write(&count); + shadow::completed_write(&self.additional_limit, self.ledger(), check, journaled); if check.exceeded_limit() { return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 53003b0b4..150576d9c 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -639,8 +639,7 @@ fn settle_kept_nothing( 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 }; - #[cfg(feature = "ledger-shadow")] - context.additional_limit.shadow_note_top_level_refund(history); + context.additional_limit.note_top_level_refund(history); let gas = result.gas_mut(); gas.refill_reservoir(upfront.unwrap_or_default()); gas.refill_history(history); diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 9f0ba3f40..bf896649b 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -49,10 +49,9 @@ use revm::{ Database, Journal, JournalEntry, }; -use crate::{ - limit::{ledger_assert, Ledger, Mark, StartFacts, StartReport}, - LimitUsage, -}; +use crate::limit::{ledger_assert, Ledger, Mark}; +#[cfg(any(test, feature = "test-utils"))] +use crate::LimitUsage; /// The journal of the Satin engine: revm's journal, and the ledger of what the transaction's own /// execution keeps. See the module documentation. @@ -70,11 +69,10 @@ pub struct MegaJournal { impl MegaJournal { /// What the journal's ledger holds the running (or last) transaction to keep: its data-size - /// bytes and write records. - /// - /// The engine's decisions are taken on - /// [`AdditionalLimit::usage`](crate::AdditionalLimit::usage), which counts the same writes; the + /// bytes and write records, for a test to hold to what the engine decides on, + /// [`AdditionalLimit::usage`](crate::AdditionalLimit::usage), which counts the same writes. The /// two agree wherever the transaction's own execution, rather than a tool, took its state back. + #[cfg(any(test, feature = "test-utils"))] pub fn ledger_usage(&self) -> LimitUsage { self.ledger.usage() } @@ -90,20 +88,10 @@ impl MegaJournal { } /// Consumes the journal and returns revm's. - pub fn into_revm(self) -> Journal { + pub(crate) fn into_revm(self) -> Journal { self.revm } - /// Opens the start window for the frame start `facts` describes, which revm decides next. - pub(crate) fn open_start(&mut self, facts: StartFacts) { - self.ledger.open_start(facts); - } - - /// Closes the start window, and reports what the start counted. - pub(crate) fn close_start(&mut self) -> StartReport { - self.ledger.close_start() - } - /// Marks where the journal and the ledger stand, without changing the journal's depth. pub(crate) fn mark(&mut self) -> Mark { let position = self.revm.checkpoint(); @@ -111,12 +99,6 @@ impl MegaJournal { self.ledger.mark(position) } - /// The mark the frame revm just built is taken back to when it is rewritten into a failure - /// ([`Ledger::frame_start_mark`]). - pub(crate) fn frame_start_mark(&self) -> Option { - self.ledger.frame_start_mark() - } - /// Takes back every journal entry, log and self-destruct made since `mark`, as revm takes back /// a frame that fails, and the ledger with them; the journal's depth is left as it is. pub(crate) fn revert_to(&mut self, mark: &Mark) { @@ -359,9 +341,10 @@ impl JournalExt for MegaJournal { mod tests { use super::*; use crate::{ - limit::{Mark, StartSide}, + limit::{Mark, StartFacts, StartReport, StartSide}, test_utils::MemoryDatabase, - EvmTxRuntimeLimits, LimitCheck, LimitKind, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use alloy_primitives::address; use revm::{ @@ -374,19 +357,24 @@ mod tests { const A: Address = address!("00000000000000000000000000000000000a0002"); const B: Address = address!("00000000000000000000000000000000000a0003"); const C: Address = address!("00000000000000000000000000000000000a0004"); - /// The account a creation from [`A`] makes. + /// The account a creation makes. const CREATED: Address = address!("00000000000000000000000000000000000a0005"); - const BODY: u64 = 310; + + /// What a start's records and transfer log weigh: `records` write records, and the log when it + /// `moves` value. + const fn start_bytes(records: u64, moves: bool) -> u64 { + records * WRITE_RECORD_SIZE + if moves { TRANSFER_LOG_SIZE } else { 0 } + } /// The transaction's bytes before any frame: the body. - fn body() -> LimitUsage { - LimitUsage { data_size: BODY, write_records: 0 } + const fn body() -> LimitUsage { + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } } - /// `n` write records and `logs` transfer logs on top of the body. - fn kept(records: u64, logs: u64) -> LimitUsage { + /// `records` write records and `logs` transfer logs on top of the body. + const fn kept(records: u64, logs: u64) -> LimitUsage { LimitUsage { - data_size: BODY + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, + data_size: TX_BODY_SIZE + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, write_records: records, } } @@ -404,7 +392,7 @@ mod tests { journal.load_account(account).unwrap(); } journal.ledger_mut().set_limits(limits); - journal.ledger_mut().begin_transaction(false, true, BODY); + journal.ledger_mut().begin_transaction(false, true, TX_BODY_SIZE); journal } @@ -420,28 +408,39 @@ mod tests { let value = U256::from(value); let facts = StartFacts { depth, caller, target: Some(target), transfers_value: !value.is_zero() }; - journal.open_start(facts); + journal.ledger_mut().open_start(facts); let checkpoint = journal.checkpoint(); assert!(journal.transfer_loaded(caller, target, value).is_none()); - (checkpoint, journal.close_start()) + (checkpoint, journal.ledger_mut().close_start()) } - /// Starts a creation from `creator` at `depth` as revm starts one: the nonce bump, then the - /// account checkpoint. + /// Starts a creation of `created` from `creator` at `depth` as revm starts one: the nonce + /// bump, then the account checkpoint. fn start_creation( journal: &mut MegaJournal, depth: usize, creator: Address, + created: Address, value: u64, ) -> (JournalCheckpoint, StartReport) { let value = U256::from(value); let facts = StartFacts { depth, caller: creator, target: None, transfers_value: !value.is_zero() }; - journal.open_start(facts); + journal.ledger_mut().open_start(facts); let _ = journal.load_account_mut(creator).unwrap().data.bump_nonce(); let checkpoint = - journal.create_account_checkpoint(creator, CREATED, value, SpecId::OSAKA).unwrap(); - (checkpoint, journal.close_start()) + journal.create_account_checkpoint(creator, created, value, SpecId::OSAKA).unwrap(); + (checkpoint, journal.ledger_mut().close_start()) + } + + /// Returns from the running frame as revm does: its level closes, committed or reverted to + /// `failed`'s checkpoint. + fn end_frame(journal: &mut MegaJournal, failed: Option) { + journal.ledger_mut().frame_returning(); + match failed { + Some(checkpoint) => journal.checkpoint_revert(checkpoint), + None => journal.checkpoint_commit(), + } } /// The journal's own write methods count nothing, inside a frame start's window and outside @@ -461,7 +460,7 @@ mod tests { writes(&mut journal); assert_eq!(journal.ledger_usage(), body(), "outside a start's window"); - journal.open_start(StartFacts { + journal.ledger_mut().open_start(StartFacts { depth: 1, caller: A, target: Some(B), @@ -469,7 +468,7 @@ mod tests { }); let _ = journal.checkpoint(); writes(&mut journal); - let _ = journal.close_start(); + let _ = journal.ledger_mut().close_start(); assert_eq!(journal.ledger_usage(), body(), "inside a start's window"); assert!(!journal.logs().is_empty(), "the writes reached revm's journal"); } @@ -514,6 +513,20 @@ mod tests { assert_eq!(entries, JournalExt::journal(&*journal), "revm's own"); } + /// An ordinary method call on the journal is the journal's own trait method, not one of revm's + /// journal reached through the dereference: a checkpoint opened and reverted with method syntax + /// opens and closes a level of the ledger, and the extension's entries are revm's. + #[test] + fn test_an_ordinary_method_call_is_the_journals_own() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let checkpoint = journal.checkpoint(); + assert_eq!(journal.ledger().depth(), 1, "the ledger saw the checkpoint"); + journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); + assert_eq!(journal.journal().len(), journal.revm.journal.len()); + journal.checkpoint_revert(checkpoint); + assert_eq!((journal.ledger().depth(), journal.depth()), (0, 0)); + } + /// The ledger holds a level for every checkpoint revm's journal holds open: a commit closes /// one and keeps what was counted inside it, a revert closes one and takes it back, and /// `clear`, the trait's default, closes them all through `finalize`. @@ -524,14 +537,12 @@ mod tests { let (checkpoint, _) = start_call(&mut journal, 1, A, B, 1); assert_eq!((journal.ledger().depth(), journal.depth()), (2, 2)); assert_eq!(journal.ledger_usage(), kept(2, 1), "B's record, A's, and the transfer log"); - journal.ledger_mut().frame_returning(); - journal.checkpoint_revert(checkpoint); + end_frame(&mut journal, Some(checkpoint)); assert_eq!((journal.ledger().depth(), journal.depth()), (1, 1)); assert_eq!(journal.ledger_usage(), body(), "the revert takes the start back"); let _ = start_call(&mut journal, 1, A, B, 1); - journal.ledger_mut().frame_returning(); - journal.checkpoint_commit(); + end_frame(&mut journal, None); assert_eq!(journal.ledger_usage(), kept(2, 1), "the commit keeps it"); let _ = journal.checkpoint(); journal.clear(); @@ -539,14 +550,14 @@ mod tests { assert_eq!(journal.ledger_usage(), kept(2, 1), "readable until the next transaction"); } - /// A tool's checkpoint around a frame start — opened before the start, closed after the frame + /// A tool's checkpoint around a call's start — opened before the start, closed after the frame /// returned — is a rollback level the frame's level sits above. Committed, it changes nothing: - /// the frame's records stand, its refund is none, and its caller's account stays recorded, so - /// a later value call from it records only its recipient. Reverted, it takes back what the - /// frame kept: the records, the caller's flag and the frame's refund all go back to before - /// the start, and the later call records the caller again. + /// the frame's records stand, its refund is none, and its caller's account stays recorded, so a + /// later value call from it records only its recipient. Reverted, it takes back what the frame + /// kept: the records, the caller's flag and the frame's refund all go back to before the + /// start, and the later call records the caller again. #[test] - fn test_a_tool_checkpoint_around_a_frame_start_closes_in_order() { + fn test_a_tool_checkpoint_around_a_call_closes_in_order() { for reverted in [false, true] { let case = if reverted { "reverted" } else { "committed" }; let mut journal = journal(EvmTxRuntimeLimits::no_limits()); @@ -558,8 +569,7 @@ mod tests { (1, true, true), "{case}: B's record, A's, and the log" ); - journal.ledger_mut().frame_returning(); - journal.checkpoint_commit(); + end_frame(&mut journal, None); let mut side = StartSide::new(1, 7, 11); side.attach(report, None); if reverted { @@ -573,14 +583,47 @@ mod tests { let (_, later) = start_call(&mut journal, 1, A, C, 1); assert_eq!(later.caller_on_level, reverted, "{case}: A's flag"); - journal.ledger_mut().frame_returning(); - journal.checkpoint_commit(); + end_frame(&mut journal, None); let records = if reverted { 2 } else { 3 }; - assert_eq!( - journal.ledger_usage(), - kept(records, if reverted { 1 } else { 2 }), - "{case}" - ); + assert_eq!(journal.ledger_usage(), kept(records, if reverted { 1 } else { 2 })); + } + } + + /// A tool's checkpoint around a creation's start closes in order as one around a call does, and + /// a revert of it takes back the creator's nonce record with the rest, which the creation's own + /// failure leaves: the creator's caller gets back the charge for that record too, and the + /// creator's account is unrecorded again, so its next creation records it. + #[test] + fn test_a_tool_checkpoint_around_a_creation_takes_its_creators_record_back() { + for (case, failed, reverted, refund, creator_recorded) in [ + ("a creation that succeeds, the tool's checkpoint committed", false, false, 0, true), + ("a creation that fails, the tool's checkpoint committed", true, false, 7, true), + ( + "a creation that succeeds, the tool's checkpoint reverted", + false, + true, + 7 + 11, + false, + ), + ("a creation that fails, the tool's checkpoint reverted", true, true, 7 + 11, false), + ] { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let _ = start_call(&mut journal, 1, A, B, 0); + let tool = journal.checkpoint(); + let (checkpoint, report) = start_creation(&mut journal, 2, B, CREATED, 1); + assert!(report.creator_record, "{case}: B's nonce record is the start's"); + end_frame(&mut journal, failed.then_some(checkpoint)); + let mut side = StartSide::new(2, 7, 11); + side.attach(report, None); + if reverted { + journal.checkpoint_revert(tool); + } else { + journal.checkpoint_commit(); + } + assert_eq!(side.refund(journal.ledger()), refund, "{case}: the refund"); + let (_, later) = start_creation(&mut journal, 2, B, C, 0); + assert_eq!(!later.creator_record, creator_recorded, "{case}: B's flag"); } } @@ -604,15 +647,18 @@ mod tests { /// leaves the creation 18 bytes. An endowment adds its transfer log to the start. #[test] fn test_a_creation_is_budgeted_from_before_its_creators_record() { - for (left, value, budget, start) in - [(81, 0, 79, 80), (100, 0, 98, 80), (81 + 160, 1, 236, 240), (100 + 160, 1, 254, 240)] + let log = TRANSFER_LOG_SIZE; + for (left, value, budget) in + [(81, 0, 79), (100, 0, 98), (81 + log, 1, 236), (100 + log, 1, 254)] { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(BODY + left); + let start = start_bytes(2, value != 0); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + left); let mut journal = journal(limits); let _ = start_call(&mut journal, 0, SENDER, A, 0); - let (_, report) = start_creation(&mut journal, 1, A, value); + let (_, report) = start_creation(&mut journal, 1, A, CREATED, value); let case = format!("{left} bytes left, value {value}"); - assert!(report.creator, "{case}: the creator's record is the start's"); + assert!(report.creator_record, "{case}: the creator's record is the start's"); let used = LimitUsage { data_size: start, write_records: 2 }; assert_eq!(journal.ledger().running_budget(), Some((budget, used)), "{case}"); let verdict = if start > budget { @@ -636,17 +682,16 @@ mod tests { fn test_a_creations_start_mark_keeps_its_creators_record() { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); let _ = start_call(&mut journal, 0, SENDER, A, 0); - let (checkpoint, _) = start_creation(&mut journal, 1, A, 1); - let mark: Mark = journal.frame_start_mark().expect("the creation's level is open"); + let (checkpoint, _) = start_creation(&mut journal, 1, A, CREATED, 1); + let mark: Mark = journal.ledger().frame_start_mark().expect("the creation's level is open"); assert_eq!(mark.position, checkpoint, "the creation's own checkpoint"); - journal.ledger_mut().frame_returning(); - journal.checkpoint_commit(); + end_frame(&mut journal, None); assert_eq!(journal.ledger_usage(), kept(2, 1)); journal.revert_to(&mark); assert_eq!(journal.ledger_usage(), kept(1, 0), "the creator's record stays"); - let (_, later) = start_creation(&mut journal, 1, A, 0); - assert!(!later.creator, "A stays recorded"); + let (_, later) = start_creation(&mut journal, 1, A, C, 0); + assert!(!later.creator_record, "A stays recorded"); } /// The hypothetical start a call gas detention answers without running is held to the limits @@ -654,9 +699,14 @@ mod tests { /// the same budget. #[test] fn test_a_hypothetical_start_is_held_as_the_start_revm_makes() { - for (depth, value, limit) in [(1, 1, 239), (1, 1, 240), (1, 0, 0), (0, 1, 199), (0, 1, 200)] + // A value call one frame down records its recipient and its caller; the transaction's own + // frame records its recipient alone. + let (below, own) = (start_bytes(2, true), start_bytes(1, true)); + for (depth, value, room) in + [(1, 1, below - 1), (1, 1, below), (1, 0, 0), (0, 1, own - 1), (0, 1, own)] { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(BODY + limit); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + room); let mut journal = journal(limits); let caller = if depth == 0 { SENDER @@ -667,7 +717,7 @@ mod tests { let facts = StartFacts { depth, caller, target: Some(B), transfers_value: value != 0 }; let hypothetical = journal.ledger().hypothetical_start(&facts); let (_, report) = start_call(&mut journal, depth, caller, B, value); - assert_eq!(Some(hypothetical), report.verdict, "depth {depth}, value {value}, {limit}"); + assert_eq!(Some(hypothetical), report.verdict, "depth {depth}, value {value}, {room}"); } } } diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 0e8c6bddb..c2027fe9a 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -247,9 +247,10 @@ impl PrecompileProvider>::warm_addresses(self) } + /// Whether the set holds `address`, as alloy-evm's provider answers it. #[inline] fn contains(&self, address: &Address) -> bool { - self.get(address).is_some() + PrecompileProvider::>::contains(self, address) } } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index e8fd19ddc..ee2cfdc69 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -87,11 +87,24 @@ impl Counts { } } +/// A frame start's number in its transaction, in the order the starts were handed to revm. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct StartId(u64); + +/// Who a frame level's frame is: its depth, and the start that opened the level. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct FrameIdentity { + /// The frame's depth. + pub(crate) depth: usize, + /// The frame's start. + pub(crate) start: StartId, +} + /// A frame level's frame: who it is, and what it may keep. #[derive(Clone, Copy, Debug)] struct FrameLevel { - /// The frame's start, numbered in the order starts opened their levels in the transaction. - seq: u64, + /// The frame's start. + start: StartId, /// The frame's depth. depth: usize, /// Where the frame's usage is measured from: where its level opened, or, for a creation, @@ -127,12 +140,12 @@ struct Level { opened_at: JournalCheckpoint, /// The counts its revert restores. at_open: Counts, - /// The flag of the nearest frame level below it as it stood when it opened, which its revert - /// restores. - flag_at_open: bool, - /// The number the next frame start would get when it opened: a frame level numbered at or - /// above it opened inside it. - seq_at_open: u64, + /// Whether the nearest frame level below it had its account recorded when it opened, which its + /// revert restores. + recorded_at_open: bool, + /// The start the next frame start would be when it opened: a start at or after it began + /// inside it. + next_start_at_open: StartId, /// The frame, for a frame level; `None` for a rollback level. frame: Option, } @@ -155,6 +168,8 @@ pub(crate) struct StartFacts { #[derive(Clone, Copy, Debug)] struct Window { facts: StartFacts, + /// The start the window is open for. + start: StartId, /// Whether the start's frame level opened. opened: bool, /// Whether the start's write — a call's transfer, a creation's account checkpoint — was seen. @@ -164,8 +179,8 @@ struct Window { /// What a frame start counted, as the ledger saw it while revm decided the start. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct StartReport { - /// The number of the frame level the start opened; `None` when revm opened none. - pub(crate) seq: Option, + /// The start, once revm decided it in a start window; `None` for a start answered before. + pub(crate) start: Option, /// The records counted on the start's own level: a value call's recipient, a creation's /// account. pub(crate) on_level: u64, @@ -173,7 +188,7 @@ pub(crate) struct StartReport { pub(crate) caller_on_level: bool, /// Whether the start counted its creator's nonce record, below its own level, where the /// creation's failure leaves it. - pub(crate) creator: bool, + pub(crate) creator_record: bool, /// Whether the start counted the transfer log revm journaled for it. pub(crate) transfer_log: bool, /// Whether revm refused the start's value transfer. @@ -184,6 +199,16 @@ pub(crate) struct StartReport { pub(crate) verdict: Option, } +/// What became of the last start revm decided: whether its level was kept — committed, and not +/// taken back since — and whether anything it counted is still held, which a revert to before the +/// start takes back, a creator's nonce record included. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Fate { + start: StartId, + level_kept: bool, + start_kept: bool, +} + /// A point the ledger and revm's journal can be taken back to together /// ([`MegaJournal::revert_to`](crate::MegaJournal)). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -192,13 +217,15 @@ pub(crate) struct Mark { pub(crate) position: JournalCheckpoint, /// The counts. counts: Counts, - /// The flag of the nearest frame level; `None` when there is none. - flag: Option, - /// The number the next frame start would get: a frame level numbered at or above it is taken - /// back with the mark. - seq: u64, + /// Whether the nearest frame level had its account recorded; `None` when there is none. + recorded: Option, + /// The start the next frame start would be: a start at or after it is taken back with the + /// mark. + next_start: StartId, /// The number of levels open: a revert to the mark finds at most these. levels: usize, + /// For a built frame's own mark, its start, whose creator record the mark keeps. + own_start: Option, } /// The facts of a creation's start, taken before anything of it is counted. @@ -209,7 +236,7 @@ pub(crate) struct CreationStart { /// Where the creation's usage is measured from: before its creator's nonce record. at_base: Counts, /// Whether the creator's nonce record was counted. - creator: bool, + creator_record: bool, /// The creation's depth. depth: usize, } @@ -226,12 +253,12 @@ pub(crate) struct Ledger { levels: Vec, /// The start window, while one is open. window: Option, - /// What the last start counted. + /// What the start of the window counted. last_start: Option, - /// The last frame level closed, and whether it was kept: committed, and not taken back since. - last_closed: Option<(u64, bool)>, - /// The number the next frame level gets. - next_seq: u64, + /// What became of the last start revm decided. + last_decided: Option, + /// The next frame start. + next_start: StartId, /// The transaction's sender, whose account the body counts. sender: Address, /// Whether the transaction's call target is an applied EIP-7702 authority, whose record the @@ -242,12 +269,22 @@ pub(crate) struct Ledger { limits: EvmTxRuntimeLimits, /// Whether the transaction is held to no limit. exempt: bool, - /// Whether a tool's checkpoint that enclosed a frame start was reverted: the lanes do not - /// follow it, and the shadow stops comparing for the transaction. + /// Whether a tool's checkpoint that enclosed a frame start was reverted and took back what the + /// ledger held: the lanes do not follow it, and the shadow stops comparing for the + /// transaction. #[cfg(feature = "ledger-shadow")] diverged: bool, } +/// `counted`, with the transfer log revm journaled for the value it moved when `logged`. +const fn with_transfer_log(counted: LimitUsage, logged: bool) -> LimitUsage { + if logged { + counted.saturating_add(TRANSFER_LOG) + } else { + counted + } +} + impl Ledger { /// Holds every transaction from the next one on to `limits`. pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { @@ -263,8 +300,8 @@ impl Ledger { self.levels.clear(); self.window = None; self.last_start = None; - self.last_closed = None; - self.next_seq = 0; + self.last_decided = None; + self.next_start = StartId::default(); self.sender = Address::ZERO; self.target_is_authority = false; self.transfer_logs = transfer_logs; @@ -287,7 +324,7 @@ impl Ledger { /// The history bytes the transaction keeps beside its write records: its logs and the code it /// deposited. #[cfg(feature = "ledger-shadow")] - pub(crate) fn log_and_code_bytes(&self) -> u64 { + pub(crate) const fn log_and_code_bytes(&self) -> u64 { self.counts.log_and_code_bytes } @@ -317,9 +354,9 @@ impl Ledger { self.levels.iter_mut().rev().filter_map(|level| level.frame.as_mut()).nth(1) } - /// The running frame's depth and number, the identity its level was opened with. - pub(crate) fn running_frame(&self) -> Option<(usize, u64)> { - self.frame_level().map(|level| (level.depth, level.seq)) + /// Who the running frame is: the identity its level was opened with. + pub(crate) fn running_frame(&self) -> Option { + self.frame_level().map(|level| FrameIdentity { depth: level.depth, start: level.start }) } /// The running frame's budget and what it keeps so far. @@ -328,10 +365,13 @@ impl Ledger { self.frame_level().map(|level| (level.budget, level.usage(&self.counts))) } - /// Whether the frame level numbered `seq` is the last one closed, and was kept: committed, and - /// not taken back since. - pub(crate) fn kept(&self, seq: u64) -> bool { - self.last_closed == Some((seq, true)) + /// What became of `start`, which must be the last start revm decided: whether its level was + /// kept, and whether what it counted below its level — a creator's nonce record — is still + /// held. + pub(crate) fn fate(&self, start: StartId) -> (bool, bool) { + let fate = self.last_decided.filter(|fate| fate.start == start); + ledger_assert!(fate.is_some(), "a start's fate is read as its frame returns"); + fate.map_or((false, false), |fate| (fate.level_kept, fate.start_kept)) } /// Whether a tool's checkpoint that enclosed a frame start was reverted in the transaction. @@ -342,8 +382,8 @@ impl Ledger { /* Verdicts */ - /// The verdict on `used` crossing `kind`'s `limit`: within, whatever it crossed, for an exempt - /// transaction. + /// The verdict on `used` crossing a data-size `limit`, a frame budget when `frame_local`: + /// within, whatever it crossed, for an exempt transaction. const fn crossed(&self, limit: u64, used: u64, frame_local: bool) -> LimitCheck { if self.exempt { return LimitCheck::WithinLimit; @@ -377,6 +417,27 @@ impl Ledger { forwarded.min(self.limits.frame_data_size_limit) } + /// The records a value call from `from` to `to` at `depth` makes: its recipient, on its own + /// level, and whether it records its caller's account, which the calling frame has + /// (`caller_recorded`) or has not recorded yet. + /// + /// The transaction's own frame records the recipient unless it is the sender or an applied + /// authority. Any other records the recipient unless it is the caller or the sender, and the + /// caller's own account once per frame; a `CALLCODE` or a call to itself records the caller + /// although revm moves nothing. + fn call_records( + &self, + depth: usize, + from: Address, + to: Address, + caller_recorded: bool, + ) -> (u64, bool) { + if depth == 0 { + return (u64::from(to != from && !self.target_is_authority), false); + } + (u64::from(to != from && to != self.sender), !caller_recorded) + } + /// 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: the records it would count and the /// transfer log of the value it would move, held to the transaction's limit and to the budget @@ -385,19 +446,16 @@ impl Ledger { let Some(target) = facts.target else { unreachable!("only a call is answered without revm deciding its start") }; - let mut counted = LimitUsage::ZERO; - if facts.transfers_value { - let (on_level, caller) = if facts.depth == 0 { - (target != facts.caller && !self.target_is_authority, false) - } else { - let caller = !self.frame_level().is_some_and(|level| level.recorded); - (target != facts.caller && target != self.sender, caller) - }; - counted = WRITE_RECORD.times(u64::from(on_level) + u64::from(caller)); - if self.transfer_logs && target != facts.caller { - counted = counted.saturating_add(TRANSFER_LOG); - } - } + let counted = if facts.transfers_value { + let recorded = self.frame_level().is_some_and(|level| level.recorded); + let (on_level, caller) = self.call_records(facts.depth, facts.caller, target, recorded); + with_transfer_log( + WRITE_RECORD.times(on_level + u64::from(caller)), + self.transfer_logs && target != facts.caller, + ) + } else { + LimitUsage::ZERO + }; let (kept, limit) = (self.usage().saturating_add(counted), self.limits.tx_data_size_limit); if kept.exceeds_data_size(limit) { return self.crossed(limit, kept.data_size, false); @@ -498,13 +556,19 @@ impl Ledger { if facts.depth == 0 { self.sender = facts.caller; } - self.last_start = None; - self.window = Some(Window { facts, opened: false, counted: false }); + let start = self.next_start; + self.next_start = StartId(start.0 + 1); + self.last_start = Some(StartReport { start: Some(start), ..Default::default() }); + self.window = Some(Window { facts, start, opened: false, counted: false }); } - /// Closes the start window once revm decided the start, and reports what the start counted. + /// Closes the start window once revm decided the start, and reports what the start counted. A + /// start whose level never opened is decided here. pub(crate) fn close_start(&mut self) -> StartReport { - self.window = None; + if let Some(window) = self.window.take().filter(|window| !window.opened) { + self.last_decided = + Some(Fate { start: window.start, level_kept: false, start_kept: true }); + } self.last_start.take().unwrap_or_default() } @@ -517,21 +581,42 @@ impl Ledger { /// Opens a level at `opened_at`, a frame level when `frame` is given. fn open_level(&mut self, opened_at: JournalCheckpoint, frame: Option) { - let flag_at_open = self.frame_level().is_some_and(|level| level.recorded); + let recorded_at_open = self.frame_level().is_some_and(|level| level.recorded); self.levels.push(Level { opened_at, at_open: self.counts, - flag_at_open, - seq_at_open: self.next_seq, + recorded_at_open, + next_start_at_open: self.next_start, frame, }); } - /// The number of the next frame level, taken. - const fn take_seq(&mut self) -> u64 { - let seq = self.next_seq; - self.next_seq += 1; - seq + /// Opens the frame level of the window's start at `opened_at`, its usage measured from + /// `at_base` under `budget`, running as `account`, recorded or not: the frame the window's + /// start builds. + fn open_frame_level( + &mut self, + opened_at: JournalCheckpoint, + at_base: Counts, + budget: u64, + account: Address, + recorded: bool, + ) { + let Some(window) = &mut self.window else { + unreachable!("a frame level opens inside its start's window") + }; + window.opened = true; + let (start, depth) = (window.start, window.facts.depth); + let frame = FrameLevel { + start, + depth, + at_base, + budget, + account: Some(account), + recorded, + returning: false, + }; + self.open_level(opened_at, Some(frame)); } /// revm's journal opened a checkpoint at `opened_at`: the frame level of a call whose start the @@ -556,32 +641,15 @@ impl Ledger { .is_some_and(|parent| parent.account == Some(target) && parent.recorded); inherited || target == self.sender || transfers_value }; - let frame = FrameLevel { - seq: self.take_seq(), - depth, - at_base: self.counts, - budget: self.child_budget(), - account: Some(target), - recorded, - returning: false, - }; - self.open_level(opened_at, Some(frame)); - if let Some(window) = &mut self.window { - window.opened = true; - } + self.open_frame_level(opened_at, self.counts, self.child_budget(), target, recorded); let verdict = self.check(); - *self.report_mut() = - StartReport { seq: Some(frame.seq), verdict: Some(verdict), ..Default::default() }; + self.report_mut().verdict = Some(verdict); } /// revm moved `value` from `from` to `to` for the call whose start the window is open for /// (`refused` when it could not), and journaled a transfer log or not (`logged`): counts the - /// records the transfer makes on the call's level, then holds the start to the limits. - /// - /// The transaction's own frame records the recipient unless it is the sender or an applied - /// authority. Any other records the recipient unless it is the caller or the sender, and the - /// caller's own account once per frame; a `CALLCODE` or a call to itself records the caller - /// although revm moves nothing. + /// records the transfer makes on the call's level ([`call_records`](Self::call_records)), then + /// holds the start to the limits. pub(crate) fn on_transfer( &mut self, from: Address, @@ -605,21 +673,15 @@ impl Ledger { if value.is_zero() { return; } - let mut caller_on_level = false; - let on_level = if depth == 0 { - u64::from(to != from && !self.target_is_authority) - } else { + let caller_recorded = self.calling_level_mut().is_none_or(|caller| caller.recorded); + let (on_level, caller_on_level) = self.call_records(depth, from, to, caller_recorded); + if caller_on_level { if let Some(caller) = self.calling_level_mut() { - caller_on_level = !caller.recorded; caller.recorded = true; } - u64::from(to != from && to != self.sender) - }; - let mut counted = WRITE_RECORD.times(on_level + u64::from(caller_on_level)); - if logged { - counted = counted.saturating_add(TRANSFER_LOG); } - self.counts.used = self.counts.used.saturating_add(counted); + let counted = WRITE_RECORD.times(on_level + u64::from(caller_on_level)); + self.counts.used = self.counts.used.saturating_add(with_transfer_log(counted, logged)); let verdict = self.check(); let report = self.report_mut(); report.on_level = on_level; @@ -628,7 +690,7 @@ impl Ledger { report.verdict = Some(verdict); } - /// revm is about to open a creation's account checkpoint for `creator`'s start: takes the + /// revm is about to open a creation's account checkpoint for the start of the window: takes the /// creation's budget and base, then counts the creator's nonce record, before anything of the /// creation. `None` outside a creation's start window. pub(crate) fn before_creation(&mut self) -> Option { @@ -639,20 +701,20 @@ impl Ledger { window.counted = true; let depth = window.facts.depth; let (budget, at_base) = (self.child_budget(), self.counts); - let mut creator = false; + let mut creator_record = false; if depth > 0 { if let Some(level) = self.frame_level_mut() { - creator = !level.recorded; + creator_record = !level.recorded; level.recorded = true; } } - if creator { + if creator_record { self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); } - Some(CreationStart { budget, at_base, creator, depth }) + Some(CreationStart { budget, at_base, creator_record, depth }) } - /// revm opened (`Ok`) or failed to open (`Err`) the account checkpoint of a creation at + /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation at /// `address`, and journaled a transfer log or not (`logged`): opens the creation's frame level, /// counts the created account and the log on it, then holds the start to the limits. The /// creation's usage includes its creator's nonce record; its revert keeps it. @@ -671,37 +733,16 @@ impl Ledger { } return; }; - let Some(opened_at) = opened else { - *self.report_mut() = StartReport { creator: start.creator, ..Default::default() }; - return; - }; - let frame = FrameLevel { - seq: self.take_seq(), - depth: start.depth, - at_base: start.at_base, - budget: start.budget, - account: Some(address), - recorded: true, - returning: false, - }; - self.open_level(opened_at, Some(frame)); - if let Some(window) = &mut self.window { - window.opened = true; - } - let mut counted = WRITE_RECORD; - if logged { - counted = counted.saturating_add(TRANSFER_LOG); - } - self.counts.used = self.counts.used.saturating_add(counted); + self.report_mut().creator_record = start.creator_record; + let Some(opened_at) = opened else { return }; + debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); + self.open_frame_level(opened_at, start.at_base, start.budget, address, true); + self.counts.used = self.counts.used.saturating_add(with_transfer_log(WRITE_RECORD, logged)); let verdict = self.check(); - *self.report_mut() = StartReport { - seq: Some(frame.seq), - on_level: 1, - creator: start.creator, - transfer_log: logged, - verdict: Some(verdict), - ..Default::default() - }; + let report = self.report_mut(); + report.on_level = 1; + report.transfer_log = logged; + report.verdict = Some(verdict); } /// The running frame is returning: revm closes its level next, committing or reverting it. @@ -733,44 +774,52 @@ impl Ledger { caller.recorded |= frame.recorded; } } - self.last_closed = Some((frame.seq, true)); + self.last_decided = Some(Fate { start: frame.start, level_kept: true, start_kept: true }); } /// revm's journal reverted to `checkpoint`: the latest level, which must be the one opened /// there, closes, and the counts and the flag of the nearest frame level below it are what they /// were when it opened. + /// + /// A frame level's revert keeps what its start counted below it, a creator's nonce record. A + /// rollback level a start began inside — a tool's checkpoint around a call — takes everything + /// the start counted back with it. pub(crate) fn on_revert(&mut self, checkpoint: JournalCheckpoint) { let Some(level) = self.levels.pop() else { return }; ledger_assert!( level.opened_at == checkpoint, "a revert closes the latest level: a revert below a level still open is not supported" ); + #[cfg(feature = "ledger-shadow")] + let changed = self.counts != level.at_open || + self.frame_level().is_some_and(|caller| caller.recorded != level.recorded_at_open); self.counts = level.at_open; if let Some(caller) = self.frame_level_mut() { - caller.recorded = level.flag_at_open; + caller.recorded = level.recorded_at_open; } match level.frame { Some(frame) => { self.assert_frame_closes(&frame); - self.last_closed = Some((frame.seq, false)); + self.last_decided = + Some(Fate { start: frame.start, level_kept: false, start_kept: true }); } - // A rollback level a frame started inside — a tool's checkpoint around a call — takes - // back what the frame kept, so the frame's level is no longer kept either. None => { - self.take_back_closed_from(level.seq_at_open); + self.take_back_starts_from(level.next_start_at_open, None); #[cfg(feature = "ledger-shadow")] - if self.next_seq > level.seq_at_open { + if changed && self.next_start > level.next_start_at_open { self.diverged = true; } } } } - /// Notes that the last frame level closed is taken back when it is numbered `seq` or above. - const fn take_back_closed_from(&mut self, seq: u64) { - if let Some((closed, kept)) = &mut self.last_closed { - if *closed >= seq { - *kept = false; + /// Notes that the last start decided is taken back when it is `start` or later: its level is no + /// longer kept, and, unless it is `own_start`, nothing it counted is. + fn take_back_starts_from(&mut self, start: StartId, own_start: Option) { + if let Some(fate) = &mut self.last_decided { + if fate.start >= start { + fate.level_kept = false; + fate.start_kept &= own_start == Some(fate.start); } } } @@ -789,16 +838,17 @@ impl Ledger { Mark { position, counts: self.counts, - flag: self.frame_level().map(|level| level.recorded), - seq: self.next_seq, + recorded: self.frame_level().map(|level| level.recorded), + next_start: self.next_start, levels: self.levels.len(), + own_start: None, } } /// The mark a frame revm just built is taken back to when it is rewritten into a failure: its /// own checkpoint, the counts its level opened with — after a creation's creator record — and - /// the flag of the frame below as it stood then. Never where the frame's usage is measured - /// from, which for a creation is before the creator's record. + /// whether the frame below had its account recorded then. Never where the frame's usage is + /// measured from, which for a creation is before the creator's record. pub(crate) fn frame_start_mark(&self) -> Option { let level = self.levels.last()?; let frame = level.frame?; @@ -807,24 +857,25 @@ impl Ledger { Some(Mark { position: level.opened_at, counts: level.at_open, - flag: caller.then_some(level.flag_at_open), - seq: frame.seq, + recorded: caller.then_some(level.recorded_at_open), + next_start: frame.start, levels: below, + own_start: Some(frame.start), }) } /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, the - /// running frame's flag, and whether the last frame level closed is kept. + /// running frame's flag, and what became of the last start decided. pub(crate) fn revert_to(&mut self, mark: &Mark) { ledger_assert!( self.levels.len() <= mark.levels, "a revert to a mark finds every level opened since closed" ); self.counts = mark.counts; - if let (Some(flag), Some(level)) = (mark.flag, self.frame_level_mut()) { - level.recorded = flag; + if let (Some(recorded), Some(level)) = (mark.recorded, self.frame_level_mut()) { + level.recorded = recorded; } - self.take_back_closed_from(mark.seq); + self.take_back_starts_from(mark.next_start, mark.own_start); } } @@ -857,10 +908,10 @@ impl StartSide { on_level_charge, caller_charge, report: StartReport { - seq: None, + start: None, on_level: 0, caller_on_level: false, - creator: false, + creator_record: false, transfer_log: false, refused: false, verdict: None, @@ -895,9 +946,9 @@ impl StartSide { self.depth } - /// The number of the frame level the start opened. - pub(crate) const fn seq(&self) -> Option { - self.report.seq + /// The start, once revm decided it. + pub(crate) const fn start(&self) -> Option { + self.report.start } /// The mark of a frame revm built. @@ -909,15 +960,18 @@ impl StartSide { /// of the start's records `ledger` holds. /// /// The records on the start's own level are held when that level was kept — committed, and not - /// taken back since; a creator's nonce record, counted below the creation's level, whenever it - /// was counted. So a start answered before revm decided it, or refused before its writes, gets - /// everything back; a call answered with a success keeps its records; a failed precompile, and - /// a frame that fails, give theirs back, a creator's surviving record aside. + /// taken back since; a creator's nonce record, counted below the creation's level, unless a + /// revert to before the start took it back. So a start answered before revm decided it, or + /// refused before its writes, gets everything back; a call answered with a success keeps its + /// records; a failed precompile, and a frame that fails, give theirs back, a creator's + /// surviving record aside. #[cfg_attr(not(feature = "ledger-shadow"), allow(dead_code))] pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { - let kept = self.report.seq.is_some_and(|seq| ledger.kept(seq)); - let on_level = kept && self.report.on_level > 0; - let caller = (kept && self.report.caller_on_level) || self.report.creator; + let (level_kept, start_kept) = + self.report.start.map_or((false, false), |start| ledger.fate(start)); + let on_level = level_kept && self.report.on_level > 0; + let caller = (level_kept && self.report.caller_on_level) || + (start_kept && self.report.creator_record); let mut refund = 0; if !on_level { refund += self.on_level_charge; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 90f7edb5c..28da85ac9 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -125,13 +125,13 @@ pub struct AdditionalLimit { /// refund to. #[cfg(feature = "ledger-shadow")] top_level_paid_for: Option, - /// The history gas given back for the transaction's own frame's write record, at whichever of - /// the three sites gave it back: what the shadow holds the journal's formula to. + /// The history gas the lanes gave back for the transaction's own frame's write record, at + /// whichever of the three sites gave it back: what the shadow holds the journal's formula to. #[cfg(feature = "ledger-shadow")] - top_level_refunded: u64, + top_level_refunded_by_lanes: u64, /// The journal's formula's answer to the same, once the transaction's own frame returned. #[cfg(feature = "ledger-shadow")] - top_level_refund: Option, + top_level_refund_by_formula: Option, } impl AdditionalLimit { @@ -174,8 +174,8 @@ impl AdditionalLimit { #[cfg(feature = "ledger-shadow")] { self.top_level_paid_for = None; - self.top_level_refunded = 0; - self.top_level_refund = None; + self.top_level_refunded_by_lanes = 0; + self.top_level_refund_by_formula = None; } } @@ -1006,24 +1006,30 @@ impl AdditionalLimit { self.pending_stop } - /// Notes, for the shadow, history the lanes gave back for the transaction's own frame's record. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn shadow_note_top_level_refund(&mut self, gas: u64) { - self.top_level_refunded = self.top_level_refunded.saturating_add(gas); + /// Notes, for the shadow, history the lanes gave back for the transaction's own frame's record; + /// nothing without the `ledger-shadow` feature. + #[inline(always)] + pub(crate) const fn note_top_level_refund(&mut self, gas: u64) { + #[cfg(feature = "ledger-shadow")] + { + self.top_level_refunded_by_lanes = self.top_level_refunded_by_lanes.saturating_add(gas); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = gas; } /// Notes, for the shadow, what the journal's formula gives back for the transaction's own /// frame's record once that frame returned. #[cfg(feature = "ledger-shadow")] - pub(crate) const fn shadow_set_top_level_refund(&mut self, gas: u64) { - self.top_level_refund = Some(gas); + pub(crate) const fn shadow_set_top_level_refund_by_formula(&mut self, gas: u64) { + self.top_level_refund_by_formula = Some(gas); } /// What the lanes gave back for the transaction's own frame's record, and what the formula /// gives back (`None` when the frame never started), for the shadow. #[cfg(feature = "ledger-shadow")] pub(crate) const fn shadow_top_level_refunds(&self) -> (u64, Option) { - (self.top_level_refunded, self.top_level_refund) + (self.top_level_refunded_by_lanes, self.top_level_refund_by_formula) } /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 9dcb06298..e1d314a5a 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -139,12 +139,11 @@ mod ledger; #[allow(clippy::module_inception)] mod limit; mod record; -#[cfg(feature = "ledger-shadow")] pub(crate) mod shadow; #[cfg(test)] pub(crate) use ledger::StartSide; -pub(crate) use ledger::{ledger_assert, Ledger, Mark, StartFacts, StartReport}; +pub(crate) use ledger::{ledger_assert, FrameIdentity, Ledger, Mark, StartFacts, StartReport}; pub use limit::AdditionalLimit; pub(crate) use limit::FrameStartRecords; pub(crate) use record::HistoryBytes; diff --git a/crates/mega-evm/src/limit/shadow.rs b/crates/mega-evm/src/limit/shadow.rs index 892db3539..3aff6ef8d 100644 --- a/crates/mega-evm/src/limit/shadow.rs +++ b/crates/mega-evm/src/limit/shadow.rs @@ -2,93 +2,258 @@ //! //! The lanes ([`AdditionalLimit`]) take every decision; the ledger ([`Ledger`]) counts the same //! writes beside them. Under the `ledger-shadow` feature the engine compares the two at the points -//! of a transaction's life where both describe the same thing, and panics on the first mismatch: +//! of a transaction's life where both describe the same thing, and panics on the first mismatch. +//! Each point is a function here, called where the point is; without the feature every one of them +//! compiles to nothing. //! -//! - after a completed write is counted, a code deposit, an admitted hint, and the keyless -//! take-back of a creator's record: what the transaction keeps, the history bytes beside its -//! records, the check, and the running frame's budget and usage ([`agree`]); -//! - when revm built a frame: the start's verdict, and the new frame's budget and usage — the -//! creation's measured from before its creator's record ([`agree`], [`verdict`]); -//! - when revm answered a start: the verdict the ledger captured while the start's level was open, -//! or, for a call gas detention answers without running, the hypothetical one ([`verdict`]); -//! - when a frame returns: the history its caller gets back ([`refund`]), the check of the caller -//! it returns into ([`verdict`]), and then [`agree`]; -//! - when the transaction's own frame settles: what the transaction keeps, and the history its own -//! frame's record gets back ([`refund`]). +//! - After a completed write is counted, a code deposit, an admitted hint and the keyless take-back +//! of a creator's record: the verdicts, then what the transaction keeps, the history bytes beside +//! its records, the number of frames, the running frame's budget and usage, and the check. +//! - When revm built a frame: the start's verdict, then the same, which holds the new frame's +//! budget and usage — a creation's measured from before its creator's record. +//! - When revm answered a start: the verdict the ledger captured while the start's level was open, +//! or, for a call gas detention answers without running, the hypothetical one. +//! - When a frame returns: the history its caller gets back, by the ledger's formula, the check of +//! the caller it returns into, then the totals; for the transaction's own frame, the formula's +//! refund is kept for the settlement. +//! - When the transaction's own frame settles: the history its own record got back, at whichever +//! site the lanes gave it back, then the totals. //! //! Between a start revm answered and that start's return the two differ by design: the ledger has //! already taken back what a failed answer journaled, and the lanes take it back when the answer's -//! lane is popped. Nothing is compared there. +//! lane is popped. Nothing is compared there. A refund is compared only where the records the +//! lanes counted for a start are the ones its charge paid for: an inspector that rewrites a start's +//! input can split them, and then the lanes keep a charge the formula gives back. //! //! A tool's checkpoint that enclosed a frame start and is reverted takes back what the frames //! inside it kept; the ledger follows it and the lanes cannot. From then on the transaction is not //! compared ([`Ledger::diverged`]). -use super::{ledger::StartSide, AdditionalLimit, Ledger, LimitCheck, LimitUsage}; - -/// What the lanes hold the transaction and the running frame to. -#[derive(Debug)] -pub(crate) struct LanesView { - /// What the transaction keeps. - pub(crate) usage: LimitUsage, - /// The log and code bytes it keeps. - pub(crate) log_and_code_bytes: u64, - /// The frames on the call stack. - pub(crate) frames: usize, - /// The running frame's budget and what it keeps. - pub(crate) running: Option<(u64, LimitUsage)>, - /// The check. - pub(crate) check: LimitCheck, -} +use super::{ledger::StartSide, AdditionalLimit, Ledger, LimitCheck, StartReport}; + +#[cfg(feature = "ledger-shadow")] +mod compare { + use super::super::{AdditionalLimit, Ledger, LimitCheck, LimitUsage}; -/// Panics with the point of the transaction and the quantity on which the two disagree. -macro_rules! shadow_eq { - ($lanes:expr, $ledger:expr, $at:expr, $what:expr) => {{ - let (lanes, ledger) = (&$lanes, &$ledger); + /// What the lanes hold the transaction and the running frame to. + #[derive(Debug)] + pub(crate) struct LanesView { + /// What the transaction keeps. + pub(crate) usage: LimitUsage, + /// The log and code bytes it keeps. + pub(crate) log_and_code_bytes: u64, + /// The frames on the call stack. + pub(crate) frames: usize, + /// The running frame's budget and what it keeps. + pub(crate) running: Option<(u64, LimitUsage)>, + /// The check. + pub(crate) check: LimitCheck, + } + + /// Panics with the point of the transaction and the quantity on which the two disagree. + pub(super) fn equal( + lanes: &T, + ledger: &T, + at: &str, + what: &str, + ) { assert!( lanes == ledger, - "ledger shadow mismatch at {}: {}: lanes {:?}, ledger {:?}", - $at, - $what, - lanes, - ledger, + "ledger shadow mismatch at {at}: {what}: lanes {lanes:?}, ledger {ledger:?}" ); - }}; + } + + /// Holds what the two hold the transaction and the running frame to. + pub(super) fn agree(lanes: &AdditionalLimit, ledger: &Ledger, at: &str) { + if ledger.diverged() { + return; + } + let view = lanes.shadow_view(); + equal(&view.usage, &ledger.usage(), at, "usage"); + equal(&view.log_and_code_bytes, &ledger.log_and_code_bytes(), at, "log and code bytes"); + equal(&view.frames, &ledger.frame_levels(), at, "frames"); + equal(&view.running, &ledger.running_budget(), at, "running frame's budget and usage"); + equal(&view.check, &ledger.check(), at, "check"); + } + + /// Holds a verdict the lanes reached (`None` where they held nothing) to the ledger's. + pub(super) fn verdict( + lanes: Option, + ledger_verdict: Option, + ledger: &Ledger, + at: &str, + ) { + if !ledger.diverged() { + equal(&lanes, &ledger_verdict, at, "verdict"); + } + } + + /// The ledger's check, as a verdict: `None` when it holds. + pub(super) fn crossing(ledger: &Ledger) -> Option { + let check = ledger.check(); + check.exceeded_limit().then_some(check) + } +} + +#[cfg(feature = "ledger-shadow")] +pub(crate) use compare::LanesView; + +/// A completed write, counted on both with the lanes' verdict and the ledger's. +#[inline(always)] +pub(crate) fn completed_write( + lanes: &AdditionalLimit, + ledger: &Ledger, + lanes_verdict: LimitCheck, + ledger_verdict: LimitCheck, +) { + #[cfg(feature = "ledger-shadow")] + { + let at = "a completed write"; + compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); + compare::agree(lanes, ledger, at); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, lanes_verdict, ledger_verdict); +} + +/// A creation's deposited code, counted on both: the lanes refused it (`refused`) or not, and the +/// ledger reached `ledger_verdict`. +#[inline(always)] +pub(crate) fn code_deposit( + lanes: &AdditionalLimit, + ledger: &Ledger, + refused: bool, + ledger_verdict: LimitCheck, +) { + #[cfg(feature = "ledger-shadow")] + { + let at = "a code deposit"; + let lanes_verdict = refused.then(|| lanes.shadow_view().check); + let ledger_verdict = ledger_verdict.exceeded_limit().then_some(ledger_verdict); + compare::verdict(lanes_verdict, ledger_verdict, ledger, at); + compare::agree(lanes, ledger, at); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, refused, ledger_verdict); +} + +/// An Oracle hint, admitted or refused by both with the lanes' verdict and the ledger's. +#[inline(always)] +pub(crate) fn hint( + lanes: &AdditionalLimit, + ledger: &Ledger, + lanes_verdict: LimitCheck, + ledger_verdict: LimitCheck, +) { + #[cfg(feature = "ledger-shadow")] + { + let at = "an Oracle hint"; + compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); + compare::agree(lanes, ledger, at); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, lanes_verdict, ledger_verdict); } -/// Holds what the two hold the transaction and the running frame to: what the transaction keeps, -/// the log and code bytes, the check, the number of frames and the running frame's budget and -/// usage. -pub(crate) fn agree(lanes: &AdditionalLimit, ledger: &Ledger, at: &str) { - if ledger.diverged() { - return; +/// A keyless deployment's take-back of its signer's nonce record: whether the lanes took one back +/// (`lanes_taken`) and the ledger did (`ledger_taken`), then the stop the lanes left the call. +#[inline(always)] +pub(crate) fn keyless_take_back( + lanes: &AdditionalLimit, + ledger: &Ledger, + lanes_taken: bool, + ledger_taken: bool, +) { + #[cfg(feature = "ledger-shadow")] + if !ledger.diverged() { + let at = "a keyless take-back"; + compare::equal(&lanes_taken, &ledger_taken, at, "taken back"); + let pending = lanes.shadow_pending_stop(); + compare::verdict(pending, compare::crossing(ledger), ledger, at); + compare::agree(lanes, ledger, at); } - let view = lanes.shadow_view(); - shadow_eq!(view.usage, ledger.usage(), at, "usage"); - shadow_eq!(view.log_and_code_bytes, ledger.log_and_code_bytes(), at, "log and code bytes"); - shadow_eq!(view.frames, ledger.frame_levels(), at, "frames"); - shadow_eq!(view.running, ledger.running_budget(), at, "running frame's budget and usage"); - shadow_eq!(view.check, ledger.check(), at, "check"); + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, lanes_taken, ledger_taken); +} + +/// A start revm built, held by the lanes to `lanes_verdict` and seen by the ledger as `report`. +#[inline(always)] +pub(crate) fn built_start( + lanes: &AdditionalLimit, + ledger: &Ledger, + lanes_verdict: LimitCheck, + report: &StartReport, +) { + #[cfg(feature = "ledger-shadow")] + { + let at = "a built start"; + compare::verdict(Some(lanes_verdict), report.verdict, ledger, at); + compare::agree(lanes, ledger, at); + } + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, lanes_verdict, report); +} + +/// A start revm answered, or gas detention answered without revm, held by the lanes to +/// `lanes_verdict` (`None` where they held nothing) and seen by the ledger as `report`. +#[inline(always)] +pub(crate) fn answered_start( + ledger: &Ledger, + lanes_verdict: Option, + report: &StartReport, +) { + #[cfg(feature = "ledger-shadow")] + compare::verdict(lanes_verdict, report.verdict, ledger, "an answered start"); + #[cfg(not(feature = "ledger-shadow"))] + let _ = (ledger, lanes_verdict, report); } -/// Holds a verdict the lanes reached (`None` where they held nothing) to the ledger's. -pub(crate) fn verdict( - lanes: Option, - ledger_verdict: Option, +/// The return of the frame `side` stands for, whose caller the lanes gave back `refund`. +/// +/// Below the transaction's own frame, the refund is held to the ledger's formula, where the records +/// the lanes counted are the ones the charge paid for, and the stop the lanes left the caller to +/// the ledger's check. The transaction's own frame has no caller: the formula's refund of its +/// record is kept for the settlement ([`settlement`]). +#[inline(always)] +pub(crate) fn frame_return( + lanes: &mut AdditionalLimit, ledger: &Ledger, - at: &str, + refund: u64, + side: &StartSide, ) { - if ledger.diverged() { - return; + #[cfg(feature = "ledger-shadow")] + { + let at = "a frame's return"; + if side.depth() == 0 { + if side.comparable() { + lanes.shadow_set_top_level_refund_by_formula(side.refund(ledger)); + } + } else if !ledger.diverged() { + if side.comparable() { + compare::equal(&refund, &side.refund(ledger), at, "refund"); + } + let pending = lanes.shadow_pending_stop(); + compare::verdict(pending, compare::crossing(ledger), ledger, "a caller's check"); + } + compare::agree(lanes, ledger, at); } - shadow_eq!(lanes, ledger_verdict, at, "verdict"); + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger, refund, side); } -/// Holds the history the lanes give a frame's caller back (`lanes`) to what `side`'s caller gets -/// back by the ledger's formula, where the records the lanes counted are those the charge paid for. -pub(crate) fn refund(lanes: u64, side: &StartSide, ledger: &Ledger, at: &str) { - if ledger.diverged() || !side.comparable() { - return; +/// The settlement of the transaction's own frame: the history its own record got back, at +/// whichever site the lanes gave it back, held to the ledger's formula, then the totals. +#[inline(always)] +pub(crate) fn settlement(lanes: &AdditionalLimit, ledger: &Ledger) { + #[cfg(feature = "ledger-shadow")] + { + let at = "the transaction's settlement"; + let (by_lanes, by_formula) = lanes.shadow_top_level_refunds(); + if let (false, Some(by_formula)) = (ledger.diverged(), by_formula) { + compare::equal(&by_lanes, &by_formula, at, "the own frame's record refund"); + } + compare::agree(lanes, ledger, at); } - shadow_eq!(lanes, side.refund(ledger), at, "refund"); + #[cfg(not(feature = "ledger-shadow"))] + let _ = (lanes, ledger); } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 68882bfb9..a2e3d4cb1 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -226,7 +226,7 @@ fn start( } }; ctx.additional_limit.set_frame_creator(deployment.signer); - ctx.journal_mut().ledger_mut().set_frame_creator(deployment.signer); + ctx.ledger_mut().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); } diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 5d6b56a7e..29032bc5b 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -20,6 +20,7 @@ use revm::{ }; use crate::{ + limit::shadow, system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, ExternalEnvTypes, MegaContext, MegaHaltReason, }; @@ -254,24 +255,8 @@ fn take_back_bump( return Ok(()); } let taken = ctx.additional_limit.take_back_creator_record(); - let journaled = ctx.journal_mut().ledger_mut().take_back_creator_record(); - #[cfg(feature = "ledger-shadow")] - { - use crate::limit::shadow; - let ledger = ctx.journal_ref().ledger(); - assert_eq!(taken, journaled, "ledger shadow mismatch at a keyless take-back: taken back"); - let pending = ctx.additional_limit.shadow_pending_stop(); - let check = ledger.check(); - shadow::verdict( - pending, - check.exceeded_limit().then_some(check), - ledger, - "a keyless take-back", - ); - shadow::agree(&ctx.additional_limit, ledger, "a keyless take-back"); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = journaled; + let journaled = ctx.ledger_mut().take_back_creator_record(); + shadow::keyless_take_back(&ctx.additional_limit, ctx.ledger(), taken, journaled); if taken { gas.refill_history(started.signer_record_charge); } diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index f005dbbd9..057450a8f 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -20,8 +20,8 @@ use revm::{ }; use crate::{ - synthetic_call_result, system::intercept::peek_selector, ExternalEnvTypes, MegaContext, - OracleEnv, + limit::shadow, synthetic_call_result, system::intercept::peek_selector, ExternalEnvTypes, + MegaContext, OracleEnv, }; /// The address of the Oracle system contract. @@ -92,16 +92,8 @@ pub(crate) fn intercept( } let payload = inputs.input.bytes(&*ctx); let check = ctx.additional_limit.record_hint_bytes(payload.len() as u64); - let journaled = ctx.inner.journaled_state.ledger_mut().admit_hint(payload.len() as u64); - #[cfg(feature = "ledger-shadow")] - { - use crate::limit::shadow; - let ledger = ctx.inner.journaled_state.ledger(); - shadow::verdict(Some(check), Some(journaled), ledger, "an Oracle hint"); - shadow::agree(&ctx.additional_limit, ledger, "an Oracle hint"); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = journaled; + let journaled = ctx.ledger_mut().admit_hint(payload.len() as u64); + shadow::hint(&ctx.additional_limit, ctx.ledger(), check, journaled); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); From 0396814e1ae13cea8d5e8065af845aea21114f2b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 05:54:29 +0800 Subject: [PATCH 414/458] test(satin): the new tests size their gas from the schedule and share helpers records_and_moves and the value-call gas room move to common.rs, used by the journal-ledger, transfer-log and write-record tests in place of fixed limits and a duplicate helper. --- crates/mega-evm/tests/satin/common.rs | 18 +++ .../mega-evm/tests/satin/data_size_counts.rs | 8 +- crates/mega-evm/tests/satin/journal_ledger.rs | 32 ++--- crates/mega-evm/tests/satin/transfer_logs.rs | 8 +- crates/mega-evm/tests/satin/write_records.rs | 127 ++++++++++-------- 5 files changed, 104 insertions(+), 89 deletions(-) diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index e70acfc35..5c320cc41 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -230,6 +230,24 @@ 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 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. +pub(crate) fn value_call_room() -> u64 { + (64 * (account_state_gas() + history(4 * mega_evm::WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) +} + +/// 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, + } +} + /// 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/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 24c041faf..55eaa67f8 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::{ @@ -24,6 +24,7 @@ use revm::{ use crate::common::{ call, call_with_data, constructor_returning, context, create, execute, execute_under, + records_and_moves, }; const CALLER: Address = address!("0000000000000000000000000000000000400000"); @@ -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() diff --git a/crates/mega-evm/tests/satin/journal_ledger.rs b/crates/mega-evm/tests/satin/journal_ledger.rs index 3606bc16d..c942ff6d5 100644 --- a/crates/mega-evm/tests/satin/journal_ledger.rs +++ b/crates/mega-evm/tests/satin/journal_ledger.rs @@ -15,7 +15,7 @@ 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}, - transaction_body_bytes, LimitUsage, MegaContext, MegaEvm, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + MegaContext, MegaEvm, }; use revm::{ bytecode::opcode::STOP, @@ -30,7 +30,7 @@ use revm::{ Inspector, }; -use crate::common::{call, context}; +use crate::common::{call, context, records_and_moves, value_call_room}; const CALLER: Address = address!("0000000000000000000000000000000000e10000"); /// The transaction's own frame. @@ -45,17 +45,6 @@ const STATEFUL: Address = address!("0000000000000000000000000000000000e10100"); /// What every value call moves. const VALUE: u64 = 1_000; -/// Room for every scenario, at any byte price the grid reaches. -const GAS_LIMIT: u64 = 50_000_000; - -/// The data size of a body, `records` write records and `logs` transfer logs. -fn kept(body: u64, records: u64, logs: u64) -> LimitUsage { - LimitUsage { - data_size: body + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, - write_records: records, - } -} - /// 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()) } @@ -92,8 +81,7 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { let db = MemoryDatabase::default() .account_code(CONTRACT, code) .account_balance(CONTRACT, U256::from(VALUE)); - let tx = call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT); - let body = transaction_body_bytes(&tx); + 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"); @@ -115,7 +103,7 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { ], "the receipt carries the call's transfer log, then the precompile's log and transfer log", ); - assert_eq!(outcome.usage, kept(body, 2, 1), "the call's start alone is counted"); + assert_eq!(outcome.usage, records_and_moves(2, 1), "the call's start alone is counted"); assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "the ledger counts the same"); } @@ -181,8 +169,7 @@ fn test_a_tool_checkpoint_around_a_call_closes_with_it() { .account_code(CONTRACT, code) .account_balance(CONTRACT, U256::from(2 * VALUE)) .account_code(RECEIVER, Bytes::from_static(&[STOP])); - let tx = call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT); - let body = transaction_body_bytes(&tx); + let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); let inspector = Encloses { target: RECEIVER, revert, open: Vec::new() }; let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); @@ -196,11 +183,11 @@ fn test_a_tool_checkpoint_around_a_call_closes_with_it() { Some(U256::ZERO), "{case}: the first call's value went back" ); - assert_eq!(ledger, kept(body, 2, 1), "{case}: what the journal kept"); + assert_eq!(ledger, records_and_moves(2, 1), "{case}: what the journal kept"); } else { let received = transfer_log(CONTRACT, RECEIVER, U256::from(VALUE)); assert_eq!(outcome.result.logs(), [received, paid], "{case}"); - assert_eq!(outcome.usage, kept(body, 3, 2), "{case}"); + assert_eq!(outcome.usage, records_and_moves(3, 2), "{case}"); assert_eq!(ledger, outcome.usage, "{case}: the ledger counts what the lanes count"); } } @@ -248,13 +235,12 @@ fn test_a_value_call_answered_at_frame_start_counts_nothing() { .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), GAS_LIMIT); - let body = transaction_body_bytes(&tx); + 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, kept(body, 0, 0), "{case}"); + assert_eq!(outcome.usage, records_and_moves(0, 0), "{case}"); assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "{case}"); } } diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 2df9a2de1..e1fa2c675 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -52,7 +52,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 @@ -1125,7 +1127,7 @@ fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { let tx = OpTx(op_transaction(TxEnv { caller: CALLER, kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, + gas_limit: value_call_room(), ..Default::default() })); let body = transaction_body_bytes(&tx); @@ -1161,7 +1163,7 @@ fn test_a_nested_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { let tx = OpTx(op_transaction(TxEnv { caller: CALLER, kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, + gas_limit: value_call_room(), ..Default::default() })); let body = transaction_body_bytes(&tx); diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index af04358f7..26e0adc48 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,19 +30,14 @@ use revm::{ 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, 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 } @@ -91,8 +86,10 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { 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, @@ -110,7 +107,7 @@ fn test_value_calls_to_one_recipient_record_it_each_time() { }); let (result, usage) = run( funded().account_code(CALLEE, code.append(STOP).build()), - call(CALLER, CALLEE, U256::ZERO, gas_limit()), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), ); assert!(result.result.is_success()); assert_eq!( @@ -125,8 +122,10 @@ fn test_value_calls_to_one_recipient_record_it_each_time() { 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, @@ -140,8 +139,10 @@ 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, @@ -157,7 +158,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()); } @@ -182,7 +183,7 @@ 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, @@ -217,7 +218,7 @@ fn test_a_delegates_record_of_its_callers_account_follows_the_delegate() { 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, gas_limit())); + 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 { with_extra(records(2), TRANSFER_LOG_SIZE) @@ -246,7 +247,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)); } @@ -263,7 +264,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"); @@ -275,8 +276,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) } @@ -321,7 +322,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]), value_call_room())); assert!(result.result.is_success()); usage }; @@ -365,7 +366,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}"); } @@ -392,7 +393,7 @@ 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); } @@ -416,7 +417,7 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { 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}"); } @@ -426,13 +427,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)); - 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)); } @@ -533,7 +538,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() }; @@ -628,7 +633,8 @@ fn after_sstore(steps: &[(u8, LimitUsage)]) -> 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), value_call_room(), false); assert_eq!(after_sstore(&steps), records(1)); } @@ -647,7 +653,7 @@ fn test_sstore_out_of_gas_after_the_write_counts_nothing() { .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, value_call_room(), false); assert_eq!(after_sstore(&steps), body_only(), "a failed opcode's write is not counted"); } @@ -656,7 +662,8 @@ fn test_sstore_out_of_gas_after_the_write_counts_nothing() { #[test] 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 steps = + probe(MemoryDatabase::default().account_code(CALLEE, code), value_call_room(), true); assert_eq!(after_sstore(&steps), records(1), "the SSTORE's record, and not the tool's log"); } @@ -677,7 +684,7 @@ fn authorizing_call( CALLER, to, U256::from(value), - gas_limit(), + value_call_room(), DELEGATE, authorizations, ) @@ -766,7 +773,7 @@ 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!( @@ -798,7 +805,7 @@ 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, value_call_room())) .unwrap(); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); @@ -811,7 +818,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"); @@ -835,7 +842,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, 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"); @@ -979,7 +986,7 @@ 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!( @@ -1009,7 +1016,7 @@ 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, @@ -1038,7 +1045,7 @@ 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!( @@ -1058,7 +1065,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 }; @@ -1085,7 +1092,7 @@ 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"); @@ -1127,7 +1134,7 @@ 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!( @@ -1200,7 +1207,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) @@ -1242,7 +1249,7 @@ fn paired_corpus() -> Vec { 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, 1, ), @@ -1280,7 +1287,7 @@ 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, ), @@ -1309,7 +1316,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, ), @@ -1318,7 +1325,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, ) @@ -1326,22 +1333,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(), gas_limit()), 0, 1), + case( + "a creation transaction", + funded(), + create(CALLER, Bytes::new(), value_call_room()), + 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, ), @@ -1357,7 +1370,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, @@ -1372,7 +1385,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 }, @@ -1464,7 +1477,7 @@ 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); From b81ffdb825cbfb91dd9a455944618e5ffbac4fa6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 08:56:05 +0800 Subject: [PATCH 415/458] feat(limit): the journal's ledger decides, and the lanes become its shadow Every count, frame budget, start verdict, refund, caller check and stop is the ledger's: the completed-write hook, the code deposit, the Oracle hint and the keyless take-back read its verdicts; a built frame is held to the verdict its level computed, an answered start to the one captured while the level was open or the hypothetical one; a frame's return refunds its caller by the formula over what the ledger still holds, and checks the caller it returns into every time. The history of the transaction's own frame's record comes back at one site, after op-revm settled the frame into the transaction's gas, by the same formula; the refills in the answered creation and the inspector settlement go. The history allowance moves to the frame side. The body's admission, the write-count rule and the start-record rule at the opcode move to the ledger with the state they read. The lanes stay fed and, under `ledger-shadow`, are held to the ledger in reverse until their deletion; `MegaContext::limit_usage` reports what the ledger holds. --- crates/mega-evm/src/evm/context.rs | 42 +- crates/mega-evm/src/evm/execution.rs | 171 +++--- crates/mega-evm/src/evm/host.rs | 28 +- crates/mega-evm/src/evm/inspector.rs | 24 +- crates/mega-evm/src/evm/mod.rs | 6 +- crates/mega-evm/src/limit/frame_limit.rs | 24 +- crates/mega-evm/src/limit/ledger.rs | 236 +++++++- crates/mega-evm/src/limit/limit.rs | 503 +++++++----------- crates/mega-evm/src/limit/mod.rs | 12 +- crates/mega-evm/src/limit/shadow.rs | 23 +- crates/mega-evm/src/system/keyless/settle.rs | 10 +- crates/mega-evm/src/system/oracle.rs | 14 +- crates/mega-evm/tests/fuzz/properties.rs | 2 +- crates/mega-evm/tests/satin/common.rs | 2 +- crates/mega-evm/tests/satin/data_size.rs | 8 +- .../mega-evm/tests/satin/data_size_counts.rs | 2 +- crates/mega-evm/tests/satin/inspector.rs | 2 +- .../mega-evm/tests/satin/limit_exemption.rs | 6 +- crates/mega-evm/tests/satin/strategic_stop.rs | 4 +- .../tests/satin/synthetic_frame_gas.rs | 2 +- crates/mega-evm/tests/satin/write_records.rs | 19 +- 21 files changed, 622 insertions(+), 518 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index f40d1e6ec..65f3dfb82 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -30,8 +30,8 @@ use crate::{ }, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - MegaJournal, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, - VolatileDataAccess, + LimitUsage, MegaJournal, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, + SaltEnv, VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -305,6 +305,15 @@ 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; it is read off the journal's ledger, which + /// the next transaction or system call resets. + pub fn limit_usage(&self) -> LimitUsage { + self.ledger().usage() + } + /// The journal's ledger of what the running (or last) transaction keeps. pub(crate) const fn ledger(&self) -> &Ledger { self.inner.journaled_state.ledger() @@ -669,11 +678,19 @@ impl ContextTr for MegaContext ContextTr for MegaContext Result { let authorizations = evm.ctx_ref().tx().authorization_list_len() as u64; - if !evm.ctx_ref().additional_limit.admits_tx_body(authorizations) { + if !evm.ctx_ref().ledger().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(); + let bytes = evm.ctx_ref().ledger().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); @@ -325,10 +325,19 @@ where 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. + /// Settles the outermost frame: pops its start's side, 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. + /// + /// The write record the transaction's own frame makes was charged before execution, and the + /// history of it comes back here, at this one site, when the frame did not keep the record — + /// it failed, or it is a success that kept nothing: a creation revm refused on its sender's + /// nonce, a frame an inspector answered or revived — the way EIP-8037 gives back the state gas + /// of the account that frame would have created. The journal's ledger says whether the record + /// is held ([`StartSide::refund`](crate::limit::StartSide)); the refund lands in the pools the + /// charge came from, and a halt burns what of it the regular gas holds. + /// /// 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. @@ -342,29 +351,31 @@ where ctx.additional_limit.on_last_frame_return(frame_result); // The transaction's own frame, answered without returning through `frame_return_result`. if ctx.additional_limit.starts_open() != 0 { - on_start_return(ctx, 0); + on_start_return(ctx, frame_result, 0); } 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() { + // The lanes' site of the refund, noted for the shadow. let top_level = evm.ctx_ref().additional_limit.top_level_write_record_gas(); evm.ctx_mut().additional_limit.note_top_level_refund(top_level); - parent_gas.refill_history(top_level); - if instruction_result.is_halt() { - parent_gas.spend_all(); - } - *frame_result.gas_mut().tracker_mut() = *parent_gas; } + parent_gas.refill_history(evm.ctx_mut().additional_limit.take_top_level_refund()); + 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 (kept, log_and_code_bytes) = { + let ledger = evm.ctx_ref().ledger(); + (ledger.usage(), ledger.log_and_code_bytes()) + }; 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); + layer.settle_history_bytes(priced, kept.write_records, log_and_code_bytes); let ctx = evm.ctx_ref(); shadow::settlement(&ctx.additional_limit, ctx.ledger()); Ok(()) @@ -505,14 +516,15 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm { @@ -648,8 +661,9 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - let refund = self.inner.ctx.additional_limit.on_frame_return(&result); - on_start_return(&mut self.inner.ctx, refund); + let lanes = self.inner.ctx.additional_limit.on_frame_return(&result); + let refund = on_start_return(&mut self.inner.ctx, &result, lanes); 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 @@ -1249,24 +1263,43 @@ impl FrameStart { /// revm decided it: `answer` is revm's answer, or gas detention's to a precompile whose price /// crosses the compute limit, given without running it. /// -/// A call revm refused to move value for — a value its caller cannot fund — moved nothing and is -/// held to nothing: its lane goes with its failure. Any other call's start moved its value, -/// whatever the answer made of it then, and is held to the limits, before gas detention holds the -/// answer: a crossing is the stop, which the answer gives way to, on the gas its caller forwarded, -/// untouched, as a frame stopped before it ran. 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. +/// The verdict is the journal's ledger's (`report`), taken while the start's level was open, +/// before revm committed or reverted it — or, for the call gas detention answers, the hypothetical +/// one: a crossing is the stop, which the answer gives way to, on the gas its caller forwarded, +/// untouched, as a frame stopped before it ran, and before gas detention holds 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. /// -/// A creation revm answers moved nothing and kept no account. It bumped its creator's nonce -/// unless it refused the creation on the creator's account — an endowment it cannot fund, a nonce -/// it cannot bump — which then counts nothing ([`withdraw_refused_start`](crate::AdditionalLimit)); -/// a creation it fails after the bump, onto an occupied address, is held to nothing at its start: -/// its failure takes the created account's record and the transfer log back, and the nonce record, -/// which outlives it, lands on the creator, which is held to its limits with it. +/// A call revm refused to move value for — a value its caller cannot fund — moved nothing and has +/// no verdict. Neither has a creation revm answers, which moved nothing and kept no account: +/// refused on its creator's account — an endowment it cannot fund, a nonce it cannot bump — it +/// bumped nothing and counts nothing; failed after the bump, onto an occupied address, it is held +/// to nothing at its start: its failure takes the created account's record and the transfer log +/// back, and the nonce record, which outlives it, lands on the creator, which is held to its +/// limits with it once the answer returns ([`AdditionalLimit::on_start_return`]). fn hold_answered_start( ctx: &mut MegaContext, start: &FrameStart, report: &StartReport, answer: &mut FrameResult, +) { + hold_answered_start_on_lanes(ctx, start, report, answer); + if let Some(stop) = report.verdict.filter(LimitCheck::exceeded_limit) { + let output = ctx.additional_limit.note_frame_stop(&stop); + stop_the_answer(answer, start, output); + } +} + +/// What the lanes make of a start revm answered, for the shadow to hold to the ledger's verdict: a +/// call revm refused is held to nothing, any other call to the lanes' check; a creation revm +/// refused before it bumped its creator's nonce, read off the journal since the mark, has its +/// count withdrawn ([`withdraw_refused_start`](crate::AdditionalLimit)), and, as the transaction's +/// own frame answered with a success, the history of its record noted as given back. +fn hold_answered_start_on_lanes( + ctx: &mut MegaContext, + start: &FrameStart, + report: &StartReport, + answer: &FrameResult, ) { let Some(creator) = start.creator() else { if matches!( @@ -1280,12 +1313,8 @@ fn hold_answered_start( if answer.instruction_result().is_ok() { start.assert_transfer_log_journaled(ctx, None); } - let check = ctx.additional_limit.check_start(); - shadow::answered_start(ctx.ledger(), Some(check), report); - if check.exceeded_limit() { - let output = ctx.additional_limit.note_frame_stop(&check); - stop_the_answer(answer, start, output); - } + let lanes = ctx.additional_limit.check_start(); + shadow::answered_start(ctx.ledger(), Some(lanes), report); return; }; let bumped = ctx.journal_ref().journal()[start.mark.position.journal_i..] @@ -1298,11 +1327,10 @@ fn hold_answered_start( ctx.additional_limit.withdraw_refused_start(); // revm answers a creation whose creator's nonce cannot be bumped with a success. The // transaction's own frame, refused so, makes none of the records charged before execution for - // it, and the history they cost comes back with the answer, as for a frame that kept nothing. + // it: the lanes' site of the refund, noted for the shadow. if start.facts.depth == 0 && answer.instruction_result().is_ok() { let top_level = ctx.additional_limit.top_level_write_record_gas(); ctx.additional_limit.note_top_level_refund(top_level); - answer.gas_mut().refill_history(top_level); } } @@ -1392,19 +1420,27 @@ fn assert_running_frame( ); } -/// Pops the side of the start of the frame returning now, once the lanes popped its lane and gave -/// its caller back `refund` of the history it paid for the start's records, and asserts the frame's -/// own level, and every level opened inside it, closed: the journal's nearest frame level is the -/// caller's. +/// Pops the side of the start of the frame `result` returns from, once revm closed the frame's +/// level, and answers the history its caller gets back for the start's records the journal's +/// ledger no longer holds; the caller is held to its limits with what the frame left it +/// ([`AdditionalLimit::on_start_return`](crate::AdditionalLimit)). The transaction's own frame has +/// no caller: its record's refund is kept for the settlement. /// -/// Under the shadow, the ledger is held to the lanes: the refund by the formula, the check of the -/// caller the frame returns into, and what the two hold the transaction to. The transaction's own -/// frame has no caller to refund or check: its record's refund is held at the settlement. +/// Asserts the frame's own level, and every level opened inside it, closed: the journal's nearest +/// frame level is the caller's. +/// +/// Under the shadow, the lanes are held to the ledger: the refund they would give (`lanes`), the +/// stop they would leave the caller the frame returns into, and what the two hold the transaction +/// to. fn on_start_return( ctx: &mut MegaContext, - refund: u64, -) { - let Some(side) = ctx.additional_limit.pop_start() else { return }; + result: &FrameResult, + lanes: u64, +) -> u64 { + let ledger = ctx.inner.journaled_state.ledger(); + let Some((side, refund)) = ctx.additional_limit.on_start_return(ledger, result) else { + return 0; + }; let caller = ctx.additional_limit.running_start().and_then(|side| side.start()); let expected = side .depth() @@ -1418,9 +1454,10 @@ fn on_start_return( shadow::frame_return( &mut ctx.additional_limit, ctx.inner.journaled_state.ledger(), - refund, + lanes, &side, ); + refund } /// Whether executing this transaction creates its caller's account: a deposit-like transaction @@ -1515,9 +1552,7 @@ fn charge_records_made_outside_a_frame( 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() + !tx.value().is_zero() && to != tx.caller() && !ctx.ledger().target_is_authority() } }; let records = u64::from(writes_a_record); diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 98716c20f..42a8c0c6a 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -289,11 +289,11 @@ impl revm::context_interface::Host Ok(load) } - /// Commits the record of a write an opcode completed — to the running frame's lane, and to the - /// running frame's level of the journal's ledger — 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. + /// Commits the record of a write an opcode completed to the running frame's level of the + /// journal's ledger — and to the running frame's lane, until the lanes go — 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 @@ -319,11 +319,11 @@ impl revm::context_interface::Host CompletedWrite::Log { .. } => (true, false), CompletedWrite::SelfDestruct { .. } => (false, false), }; - // One count, committed to the lanes, which decide, and to the journal's ledger. - let (count, history) = self.additional_limit.write_count(&write); - let check = self.additional_limit.commit_count(&count); - let journaled = self.ledger_mut().count_write(&count); - shadow::completed_write(&self.additional_limit, self.ledger(), check, journaled); + // One count, committed to the journal's ledger, which decides, and to the lanes. + let (count, history) = self.ledger().write_count(&write); + let lanes = self.additional_limit.commit_count(&count); + let check = self.ledger_mut().count_write(&count); + shadow::completed_write(&self.additional_limit, self.ledger(), lanes, check); if check.exceeded_limit() { return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } @@ -374,7 +374,7 @@ impl revm::context_interface::Host /// taken, and a price that could not be computed failed before any charge. #[inline] fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { - let records = self.additional_limit.opcode_start_records(start); + let records = self.ledger().start_records(start); if !self.prices_history() { return true; } @@ -495,7 +495,7 @@ mod tests { Host::log(&mut ctx, log); let destructed = Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); assert!(destructed.data.had_value); - assert_eq!(ctx.additional_limit.usage(), LimitUsage::ZERO, "the Host counts nothing"); + assert_eq!(ctx.limit_usage(), LimitUsage::ZERO, "the Host counts nothing"); // The hook is what counts: the slot's first change is one write record. let mut gas = GasTracker::new(1_000_000, 1_000_000, 0); @@ -503,8 +503,8 @@ mod tests { 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(), - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }, + ctx.limit_usage(), + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 } ); } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 150576d9c..6f1be8ddd 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -607,11 +607,14 @@ pub(crate) fn frame_end_checked( /// - 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. +/// a frame that restored a slot its caller filled does, and its caller's merge nets it out. +/// +/// What the frame counted is the journal's ledger's, which the frame's checkpoint took back with +/// the frame's writes, or which never counted the start of a frame the inspector answered: its +/// caller gets back the history it paid for the start's records once the frame returns, and the +/// transaction the history of its own frame's record at the settlement, as for any frame that kept +/// nothing. The lanes, which follow frames rather than the journal, are settled as the failure's +/// until they go. fn settle_kept_nothing( context: &mut MegaContext, input: &FrameInput, @@ -637,12 +640,11 @@ fn settle_kept_nothing( 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 }; - context.additional_limit.note_top_level_refund(history); - let gas = result.gas_mut(); - gas.refill_reservoir(upfront.unwrap_or_default()); - gas.refill_history(history); + result.gas_mut().refill_reservoir(upfront.unwrap_or_default()); + if depth == 0 { + let history = context.additional_limit.top_level_write_record_gas(); + context.additional_limit.note_top_level_refund(history); + } context.additional_limit.discard_returning_lane(); } diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index d475917aa..8fa2227ff 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -292,8 +292,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 journal's ledger 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, @@ -310,7 +310,7 @@ where 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(), }) diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 6c6d19214..fa8fd921a 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -53,9 +53,6 @@ pub(crate) struct Lane { 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. @@ -82,7 +79,6 @@ impl Lane { holds_caller_record: false, creator_record: false, budget, - stipend_remaining: 0, log_and_code_bytes: 0, } } @@ -182,6 +178,7 @@ impl FrameLimitTracker { /// 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. + #[cfg(any(test, feature = "ledger-shadow"))] pub(crate) const fn log_and_code_bytes(&self) -> u64 { self.log_and_code_bytes } @@ -196,25 +193,6 @@ 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); diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index ee2cfdc69..a96b95d92 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -39,20 +39,26 @@ //! Nothing a tool or a precompile writes through the journal is counted: the journal's own write //! methods count nothing, and the start window is open only while revm decides a start. //! -//! The lanes ([`AdditionalLimit`](crate::AdditionalLimit)) count the same quantities and stay the -//! ones every decision is taken on; under the `ledger-shadow` feature the two are compared where -//! they must agree. +//! The ledger takes every decision: the counts, the frame budgets, the start verdicts, the +//! refunds of the history a caller paid for a start's records, and the check of a caller its child +//! returns into. The lanes ([`AdditionalLimit`](crate::AdditionalLimit)) count the same quantities +//! beside it until their deletion; under the `ledger-shadow` feature they are held to the ledger +//! wherever the two must agree. #[cfg(not(feature = "std"))] use alloc as std; use std::vec::Vec; use alloy_primitives::{Address, U256}; -use revm::context_interface::journaled_state::JournalCheckpoint; +use revm::context_interface::{ + host::{CompletedWrite, FrameStart, FrameStartKind}, + journaled_state::JournalCheckpoint, +}; use super::{ - limit::share_of_remaining, record::WriteCount, EvmTxRuntimeLimits, LimitCheck, LimitKind, - LimitUsage, TRANSFER_LOG, WRITE_RECORD, + limit::share_of_remaining, + record::{write_effect, write_moves_value, HistoryBytes, RecordEffect, WriteCount}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG, WRITE_RECORD, }; /// Asserts an invariant of the ledger's levels in debug builds and in `ledger-shadow` builds; in @@ -164,6 +170,20 @@ pub(crate) struct StartFacts { pub(crate) transfers_value: bool, } +/// 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 level, which its failure takes back. + 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 start window, open while revm decides one frame start. #[derive(Clone, Copy, Debug)] struct Window { @@ -323,11 +343,36 @@ impl Ledger { /// The history bytes the transaction keeps beside its write records: its logs and the code it /// deposited. - #[cfg(feature = "ledger-shadow")] pub(crate) const fn log_and_code_bytes(&self) -> u64 { self.counts.log_and_code_bytes } + /// The data-size bytes of the transaction's body, which the transaction counts before any + /// frame and no revert takes back. + pub(crate) const fn body(&self) -> u64 { + self.body + } + + /// 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 { + self.exempt || + !LimitUsage { data_size: self.body, write_records: 0 } + .saturating_add(WRITE_RECORD.times(authorizations)) + .exceeds_data_size(self.limits.tx_data_size_limit) + } + + /// Whether the transaction's call target is an applied EIP-7702 authority, whose record the + /// authorities' records hold, so the transaction's own frame writes no recipient. + pub(crate) const fn target_is_authority(&self) -> bool { + self.target_is_authority + } + /// The number of levels open, which is revm's journal depth. pub(crate) fn depth(&self) -> usize { self.levels.len() @@ -438,6 +483,41 @@ impl Ledger { (u64::from(to != from && to != self.sender), !caller_recorded) } + /// The write records the start `start` describes makes, for the opcode about to start it, + /// which pays for them once it took the gas it forwards: 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. + /// + /// A call that moves no value writes nothing. A value call writes its recipient, unless that + /// is the caller itself or the transaction's sender, whose account the body counts. A creation + /// writes the account it creates. Either writes the caller's account — a transfer's sender, a + /// creation's creator nonce — unless the running frame already recorded it. They are the + /// records the start is counted by once revm makes it ([`on_transfer`](Self::on_transfer), + /// [`before_creation`](Self::before_creation)); a debug build holds the two answers to each + /// other where the frame starts. + pub(crate) fn start_records(&self, start: &FrameStart) -> FrameStartRecords { + let recorded = self.frame_level().is_some_and(|level| level.recorded); + let target = match start.kind { + FrameStartKind::Create | FrameStartKind::Create2 => { + return FrameStartRecords { on_lane: 1, caller: !recorded }; + } + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => start.target, + }; + match target { + Some(target) if !start.value.is_zero() => { + // An opcode runs inside a frame, so the frame it starts is below the + // transaction's own. + let depth = self.frame_level().map_or(1, |level| level.depth + 1); + let (on_lane, caller) = self.call_records(depth, start.caller, target, recorded); + FrameStartRecords { on_lane, caller } + } + _ => FrameStartRecords::NONE, + } + } + /// 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: the records it would count and the /// transfer log of the value it would move, held to the transaction's limit and to the budget @@ -498,6 +578,34 @@ impl Ledger { LimitCheck::WithinLimit } + /// What `write`, which the running opcode completed, keeps, and the history bytes it appends or + /// takes back: what [`count_write`](Self::count_write) counts, and what the Host's + /// completed-write hook charges. + /// + /// A `SELFDESTRUCT` that moved value to another account also keeps the EIP-7708 transfer log + /// revm journaled for the move, with the beneficiary's record. The log is the running frame's, + /// as the move is: the frame's own journal checkpoint takes both back when the frame fails. It + /// is data size and nothing else — no write record, and no history: the bytes reported are the + /// record's alone. + pub(crate) fn write_count(&self, write: &CompletedWrite<'_>) -> (WriteCount, HistoryBytes) { + let effect = write_effect(write, self.sender); + let history = effect.history_bytes(); + let added = match effect { + RecordEffect::None => LimitUsage::ZERO, + RecordEffect::Record(usage) => usage, + RecordEffect::Refund(usage) => { + return (WriteCount { taken: usage, ..WriteCount::NONE }, history); + } + }; + // A log's bytes are history beside the write records; a record's are counted as one. + let log_bytes = match write { + CompletedWrite::Log { .. } => added.data_size, + CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => 0, + }; + let added = with_transfer_log(added, self.transfer_logs && write_moves_value(write)); + (WriteCount { added, log_bytes, ..WriteCount::NONE }, history) + } + /// Counts what a completed write keeps on the running frame's level: what it adds, or what it /// takes back. The verdict is the check after an addition; a record taken back holds nothing. pub(crate) fn count_write(&mut self, count: &WriteCount) -> LimitCheck { @@ -880,8 +988,9 @@ impl Ledger { } /// Satin's side of one frame start: what its caller paid for the records it makes, what the -/// ledger saw it count, and, for a frame revm built, the mark it is taken back to when it is -/// rewritten into a failure. One per frame result revm will return, as the lanes are. +/// ledger saw it count, the history allowance the frame was granted, and, for a frame revm built, +/// the mark it is taken back to when it is rewritten into a failure. One per frame result revm +/// will return. #[derive(Clone, Copy, Debug)] pub(crate) struct StartSide { /// The frame's depth. @@ -895,6 +1004,9 @@ pub(crate) struct StartSide { report: StartReport, /// The mark of a frame revm built. mark: Option, + /// What is left of the history allowance the 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. + stipend: u64, /// Whether the records the lanes counted for the start are those its charge paid for. #[cfg(feature = "ledger-shadow")] comparable: bool, @@ -917,6 +1029,7 @@ impl StartSide { verdict: None, }, mark: None, + stipend: 0, #[cfg(feature = "ledger-shadow")] comparable: true, } @@ -946,6 +1059,19 @@ impl StartSide { self.depth } + /// Grants the frame a history allowance of `amount`. + pub(crate) const fn grant_stipend(&mut self, amount: u64) { + self.stipend = amount; + } + + /// Draws up to `amount` from the frame's history allowance and reports what it gave; the frame + /// pays the rest out of its gas. + pub(crate) const fn consume_stipend(&mut self, amount: u64) -> u64 { + let drawn = if self.stipend < amount { self.stipend } else { amount }; + self.stipend -= drawn; + drawn + } + /// The start, once revm decided it. pub(crate) const fn start(&self) -> Option { self.report.start @@ -965,7 +1091,6 @@ impl StartSide { /// refused before its writes, gets everything back; a call answered with a success keeps its /// records; a failed precompile, and a frame that fails, give theirs back, a creator's /// surviving record aside. - #[cfg_attr(not(feature = "ledger-shadow"), allow(dead_code))] pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { let (level_kept, start_kept) = self.report.start.map_or((false, false), |start| ledger.fate(start)); @@ -982,3 +1107,94 @@ impl StartSide { refund } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE}; + use alloy_primitives::address; + use revm::context_interface::context::SelfDestructResult; + + const SENDER: Address = address!("00000000000000000000000000000000000f0001"); + const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); + const TARGET: Address = address!("00000000000000000000000000000000000f0003"); + + /// A ledger holding a transaction from [`SENDER`] with a body of `body` bytes under `limits`, + /// exempt or not, whose value movements journal transfer logs when `transfer_logs`. + fn ledger(limits: EvmTxRuntimeLimits, exempt: bool, transfer_logs: bool, body: u64) -> Ledger { + let mut ledger = Ledger::default(); + ledger.set_limits(limits); + ledger.begin_transaction(exempt, transfer_logs, body); + ledger.count_authorities(SENDER, 0, false); + ledger + } + + /// 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 = TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE; + let at = body + 2 * WRITE_RECORD_SIZE; + let under = |limit: u64, exempt: bool| { + ledger( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + exempt, + false, + body, + ) + }; + assert!(under(at, false).admits_tx_body(2), "at the limit"); + assert!(!under(at - 1, false).admits_tx_body(2), "one byte over it"); + assert!(under(at - 1, false).admits_tx_body(1), "one record fewer"); + assert!(!under(body - 1, false).admits_tx_body(0), "the body alone over it"); + assert!(under(0, true).admits_tx_body(2), "an exempt transaction"); + assert_eq!(under(at, false).body(), body); + assert_eq!(under(at, false).usage().data_size, body, "the body is counted"); + } + + /// Counts `write` on `ledger` as the completed-write hook does, and reports the verdict and + /// the history bytes. + fn commit(ledger: &mut Ledger, write: &CompletedWrite<'_>) -> (LimitCheck, HistoryBytes) { + let (count, history) = ledger.write_count(write); + (ledger.count_write(&count), history) + } + + /// 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; and nothing + /// counts a log when the transaction's value movements journal none. + #[test] + fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { + let moved = SelfDestructResult { had_value: true, ..Default::default() }; + let destruction = + |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; + let mut logging = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + let (check, history) = commit(&mut logging, &destruction(TARGET)); + assert_eq!(check, LimitCheck::WithinLimit); + assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); + assert_eq!( + logging.usage(), + LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + ); + + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1); + let mut tight = ledger(limits, false, true, 0); + let (check, history) = commit(&mut tight, &destruction(SENDER)); + 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 silent = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + let _ = commit(&mut silent, &destruction(TARGET)); + assert_eq!(silent.usage(), WRITE_RECORD, "no log, no bytes"); + } +} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 28da85ac9..8617844d4 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -2,10 +2,7 @@ use alloy_primitives::{Address, Bytes}; use revm::{ - context_interface::{ - context::CodeDeposit, - host::{CompletedWrite, FrameStart, FrameStartKind}, - }, + context_interface::context::CodeDeposit, handler::FrameResult, interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; @@ -16,21 +13,23 @@ use std::vec::Vec; use super::{ frame_limit::{FrameLimitTracker, Lane}, - ledger::{Mark, StartSide}, - record::{write_effect, write_moves_value, HistoryBytes, RecordEffect, WriteCount}, + ledger::{FrameStartRecords, Ledger, Mark, StartSide}, + record::WriteCount, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, StartReport, 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 stops its frames return, and whether it is exempt from -/// every limit. +/// What the common execution layer tracks for the running transaction beside the journal's +/// ledger: Satin's side of each frame start, the stops its frames return, whether it is exempt +/// from every limit, and the figures the settled transaction reports. The per-frame lanes of +/// data-size bytes and write records are kept beside the ledger until their deletion, for the +/// `ledger-shadow` feature to hold them to it. /// /// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and -/// system call, and is driven by the Host's instruction hooks (the records of completed writes and -/// the charge of a frame's start) and the frame lifecycle (lanes, stops). +/// system call, and is driven by the Host's instruction hooks (the charge of a frame's start) and +/// the frame lifecycle (the frame sides, stops). /// /// # The stop /// @@ -63,11 +62,17 @@ pub struct AdditionalLimit { /// transaction. See [`exempt`](Self::exempt). exempt: bool, /// The stop the frame about to run must return instead of running: the one a frame revm built - /// returns on its first run when its start crossed a limit - /// ([`hold_built_start`](Self::hold_built_start)), or the one a frame a child returned into - /// returns when what the child left it put it over a limit - /// ([`on_frame_return`](Self::on_frame_return)). + /// returns on its first run when its start crossed a limit ([`hold_start`](Self::hold_start)), + /// or the one a frame a child returned into returns when what the child left it put it over a + /// limit ([`on_start_return`](Self::on_start_return)). pending_stop: Option, + /// The stop the lanes would leave the frame about to run, which the shadow holds to the + /// ledger's. + lanes_pending_stop: Option, + /// The history gas the transaction's own frame's start gets back, by the ledger's formula, + /// kept once that frame returned for the settlement to give back + /// ([`take_top_level_refund`](Self::take_top_level_refund)). + top_level_refund: u64, /// 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. @@ -155,6 +160,8 @@ impl AdditionalLimit { self.tracker.reset(); self.exempt = false; self.pending_stop = None; + self.lanes_pending_stop = None; + self.top_level_refund = 0; self.frame_stop = None; self.limit_exceeded = None; self.target_is_authority = false; @@ -255,9 +262,10 @@ impl AdditionalLimit { 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. + /// The lanes' check of 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. The shadow holds it to + /// the journal's ledger, whose check decides. fn check(&self) -> LimitCheck { let (kept, limit) = (self.tracker.net(), self.limits.tx_data_size_limit); if kept.exceeds_data_size(limit) { @@ -273,22 +281,48 @@ impl AdditionalLimit { } /// The stop the running frame returns instead of running another instruction: the one its own - /// start left it ([`hold_built_start`](Self::hold_built_start)), or 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. + /// start left it ([`hold_start`](Self::hold_start)), or the one + /// [`on_start_return`](Self::on_start_return) left for a caller its child put over a limit. + /// Taking it clears it, which stops one frame; the lanes' stop for the frame goes with it. pub(crate) const fn stop_before_run(&mut self) -> Option { + self.lanes_pending_stop = None; self.pending_stop.take() } + /// Holds the start of the frame revm just built to `verdict`, the journal's ledger's on what + /// the start counted while the frame's level was open: a crossing is the stop the frame + /// returns on its first run, before any instruction + /// ([`stop_before_run`](Self::stop_before_run)). revm moved the value, journaled the transfer + /// log and, for a creation, bumped its creator's nonce; the stop is a revert of the frame, so + /// its journal checkpoint takes the move and the log back, and the nonce, bumped before the + /// checkpoint, stays, with its record on the creator. + #[inline] + pub(crate) fn hold_start(&mut self, verdict: Option) { + if let Some(stop) = verdict.filter(LimitCheck::exceeded_limit) { + debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); + self.pending_stop = Some(stop); + } + } + + /// Holds the running frame to `check`, the journal's ledger's, once what it keeps changed + /// outside its own instructions — a child returned into it, or a record a child left it was + /// taken back: a crossing is the stop it returns before it runs on, and anything else clears a + /// stop it had. + pub(crate) fn hold_running_frame(&mut self, check: LimitCheck) { + self.pending_stop = check.exceeded_limit().then_some(check); + } + /// Whether the running frame has a stop to return before it runs another instruction /// ([`stop_before_run`](Self::stop_before_run)). pub(crate) const fn has_stop_before_run(&self) -> bool { self.pending_stop.is_some() } - /// 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 { + /// What the lanes hold the transaction to keep so far, with every running frame counted as + /// if it succeeds; what the transaction keeps is the journal's ledger's + /// ([`MegaContext::limit_usage`](crate::MegaContext::limit_usage)). + #[cfg(test)] + pub(crate) fn usage(&self) -> LimitUsage { self.tracker.net() } @@ -334,14 +368,19 @@ impl AdditionalLimit { 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) { + /// Settles [`history_bytes`](Self::history_bytes) from what the transaction kept — its + /// `write_records` and its `log_and_code_bytes`, as the journal's ledger holds them once the + /// transaction's own frame returned: `priced` is whether it pays history at all. + pub(crate) const fn settle_history_bytes( + &mut self, + priced: bool, + write_records: u64, + log_and_code_bytes: u64, + ) { 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()) + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(write_records)) + .saturating_add(log_and_code_bytes) } else { 0 }; @@ -384,13 +423,7 @@ impl AdditionalLimit { /// [`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 + self.starts.last_mut().map_or(0, |side| side.consume_stipend(amount)) } /// Leaves the history gas the running opcode just charged its frame for the records the frame @@ -434,42 +467,9 @@ impl AdditionalLimit { /* Completed writes */ - /// What `write`, which the running opcode completed, keeps, and the history bytes it appends or - /// takes back: one answer, which the Host's completed-write hook commits to the running frame's - /// lane ([`commit_count`](Self::commit_count)) and to the journal's ledger. - /// - /// A `SELFDESTRUCT` that moved value to another account also keeps the EIP-7708 transfer log - /// revm journaled for the move, with the beneficiary's record. 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 write_count(&self, write: &CompletedWrite<'_>) -> (WriteCount, HistoryBytes) { - let effect = write_effect(write, self.sender); - let history = effect.history_bytes(); - let added = match effect { - RecordEffect::None => LimitUsage::ZERO, - RecordEffect::Record(usage) => usage, - RecordEffect::Refund(usage) => { - return (WriteCount { taken: usage, ..WriteCount::NONE }, history); - } - }; - // A log's bytes are history beside the write records; a record's are counted as one. - let log_bytes = match write { - CompletedWrite::Log { .. } => added.data_size, - CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => 0, - }; - let added = if self.transfer_logs && write_moves_value(write) { - added.saturating_add(TRANSFER_LOG) - } else { - added - }; - (WriteCount { added, log_bytes, ..WriteCount::NONE }, history) - } - - /// Commits what a completed write keeps to the running frame's lane, and holds it to the - /// limits; a crossed limit in the verdict stops the opcode's frame, and the hook charges the - /// history. A record taken back holds nothing. + /// Commits what a completed write keeps ([`Ledger::write_count`]) to the running frame's lane, + /// and holds the lanes to the limits, for the shadow to hold them to the journal's ledger, + /// whose verdict decides. A record taken back holds nothing. #[inline] pub(crate) fn commit_count(&mut self, count: &WriteCount) -> LimitCheck { if count.taken != LimitUsage::ZERO { @@ -493,9 +493,9 @@ impl AdditionalLimit { /// /// 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. + /// validation holds the body to the limit ([`Ledger::admits_tx_body`]) on the journal's + /// ledger's count of the same bytes, 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 { @@ -503,41 +503,9 @@ impl AdditionalLimit { } } - /// 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, 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. + /// Counts the `bytes` of an Oracle hint on the lanes, as the journal's ledger admits it + /// ([`Ledger::admit_hint`]), for the shadow to hold the two to each other: the limit is + /// checked before the bytes are counted, and a hint that would cross it is not counted. pub(crate) fn record_hint_bytes(&mut self, bytes: u64) -> LimitCheck { let hint = LimitUsage { data_size: bytes, write_records: 0 }; let (reached, limit) = @@ -557,8 +525,8 @@ impl AdditionalLimit { /// one of them, from the transaction's `sender`. /// /// 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. + /// every entry of the authorization list ([`Ledger::admits_tx_body`]), and only an entry can + /// apply. A debug build asserts it. pub(crate) fn record_applied_authorities( &mut self, sender: Address, @@ -607,20 +575,14 @@ impl AdditionalLimit { } } - /// Holds the start of the frame revm just built to the limits: a crossing is the stop the - /// frame returns on its first run, before any instruction ([`stop_before_run`]). revm moved - /// the value, journaled the transfer log and, for a creation, bumped its creator's nonce; the - /// stop is a revert of the frame, so its journal checkpoint takes the move and the log back, - /// and the nonce, bumped before the checkpoint, stays, with its record on the creator. Returns - /// the verdict. - /// - /// [`stop_before_run`]: Self::stop_before_run + /// The lanes' verdict on the start of the frame revm just built, which they would leave the + /// frame as the stop it returns on its first run; the shadow holds it to the journal's + /// ledger's, which decides ([`hold_start`](Self::hold_start)). #[inline] pub(crate) fn hold_built_start(&mut self) -> LimitCheck { let check = self.check(); if check.exceeded_limit() { - debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); - self.pending_stop = Some(check); + self.lanes_pending_stop = Some(check); } check } @@ -642,39 +604,19 @@ impl AdditionalLimit { self.tracker.discard_running_lane(); } - /// 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> { + /// Counts the code a creation deposits on the creation's own lane, and holds the lanes to the + /// data-size limit with it, for the shadow to hold them to the journal's ledger, which counts + /// the same bytes on the creation's level ([`Ledger::count_code`]) and decides. The bytes are + /// data size and history beside the write records. Empty code deposits nothing. + pub(crate) fn on_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> LimitCheck { let bytes = deposit.code.len() as u64; if bytes == 0 { - return Ok(()); + return LimitCheck::WithinLimit; } 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(()) + self.check() } /// The data-size budget of the frame about to start. @@ -735,7 +677,9 @@ impl AdditionalLimit { } self.tracker.record(WRITE_RECORD.times(records.on_lane)); if grants_stipend(inputs) { - self.tracker.grant_stipend(storage_call_stipend()); + if let Some(side) = self.starts.last_mut() { + side.grant_stipend(storage_call_stipend()); + } } } FrameInput::Create(inputs) => { @@ -829,22 +773,6 @@ impl AdditionalLimit { } } - /// The write records the frame `start` describes makes, for the opcode about to start it, - /// which pays for them ([`start_records`](Self::start_records)). - pub(crate) fn opcode_start_records(&self, start: &FrameStart) -> FrameStartRecords { - match start.kind { - FrameStartKind::Create | FrameStartKind::Create2 => { - self.start_records(start.caller, None, true) - } - FrameStartKind::Call | - FrameStartKind::CallCode | - FrameStartKind::DelegateCall | - FrameStartKind::StaticCall => { - self.start_records(start.caller, start.target, !start.value.is_zero()) - } - } - } - /// The write records a frame's start makes at a depth above the transaction's own frame: a /// call from `caller` to `target` that transfers value or not, or a creation (`target` is /// `None`). `on_lane` are the records the frame's failure discards, `caller` whether its start @@ -858,7 +786,7 @@ impl AdditionalLimit { /// The opcode that starts the frame pays for all of them, after the gas it forwards was taken, /// 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. The answer is asked twice, at the opcode - /// ([`opcode_start_records`](Self::opcode_start_records)) and as the frame starts + /// ([`Ledger::start_records`]) and as the frame starts /// ([`frame_start_records`](Self::frame_start_records)), and the two are checked against each /// other ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). fn start_records( @@ -899,13 +827,12 @@ impl AdditionalLimit { } } - /// 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. + /// Takes back, on the lanes, 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. The journal's + /// ledger takes back the same record ([`Ledger::take_back_creator_record`]) and decides; the + /// shadow holds the lanes to it. 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)) || @@ -914,7 +841,7 @@ impl AdditionalLimit { return false; } let check = self.check(); - self.pending_stop = check.exceeded_limit().then_some(check); + self.lanes_pending_stop = check.exceeded_limit().then_some(check); true } @@ -978,11 +905,6 @@ impl AdditionalLimit { self.starts.last() } - /// Pops the side of the start of the frame returning now. - pub(crate) fn pop_start(&mut self) -> Option { - self.starts.pop() - } - /// The number of starts whose frames have not returned yet. pub(crate) fn starts_open(&self) -> usize { self.starts.len() @@ -1000,10 +922,11 @@ impl AdditionalLimit { } } - /// The stop the lanes left the running frame to return before it runs on, for the shadow. - #[cfg(feature = "ledger-shadow")] + /// The stop the lanes would leave the running frame to return before it runs on, for the + /// shadow. + #[cfg(any(test, feature = "ledger-shadow"))] pub(crate) const fn shadow_pending_stop(&self) -> Option { - self.pending_stop + self.lanes_pending_stop } /// Notes, for the shadow, history the lanes gave back for the transaction's own frame's record; @@ -1033,48 +956,21 @@ impl AdditionalLimit { } /// 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. + /// a failure discards it, a stop's included. The lanes hold the caller to its limits when the + /// return handed it what no check held it to — a failed creation's nonce record, which lands + /// on the creator, or a success past the frame's own budget, which no frame returns — and a + /// debug build asserts any other return leaves it within them. The shadow holds the lanes' + /// refund and stop to the journal's ledger's ([`on_start_return`](Self::on_start_return)). /// - /// 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"] + /// Returns the history gas the lanes would give the caller back for records this frame did + /// not keep. + #[must_use = "the shadow holds the lanes' refund to the ledger's"] 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.pending_stop = if unchecked { + self.lanes_pending_stop = if unchecked { let check = self.check(); check.exceeded_limit().then_some(check) } else { @@ -1087,6 +983,56 @@ impl AdditionalLimit { refund } + /// Pops the side of the start of the frame `result` returns from, once revm closed the frame's + /// level, and settles what the start and the frame leave behind, as the journal's `ledger` + /// holds them: + /// + /// - the history the caller paid for the start's records, less the price of those the ledger + /// still holds ([`StartSide::refund`]), which the caller gets back once the frame merged into + /// it. The transaction's own frame was paid for before execution: its refund is kept for the + /// settlement ([`take_top_level_refund`](Self::take_top_level_refund)); + /// - the caller, held to its limits with what it now holds: a failed creation's nonce record, + /// which outlives the creation, lands on its creator, and a crossing is the stop the caller + /// returns before it runs on ([`stop_before_run`](Self::stop_before_run)). Any other return + /// leaves the caller within its limits — a failure hands it nothing, and a success no more + /// than the share it gave — and is held all the same; + /// - the crossing the result is made of, the stop noted for the frame + /// ([`note_frame_stop`](Self::note_frame_stop)), which 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 side, and the history its caller gets back. + pub(crate) fn on_start_return( + &mut self, + ledger: &Ledger, + result: &FrameResult, + ) -> Option<(StartSide, u64)> { + let noted = self.frame_stop.take(); + // 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 side = self.starts.pop()?; + let refund = side.refund(ledger); + if side.depth() == 0 { + self.limit_exceeded = noted.filter(|stop| is_the_revert_of(result, stop)); + self.top_level_refund = refund; + return Some((side, 0)); + } + self.hold_running_frame(ledger.check()); + Some((side, refund)) + } + + /// The history gas the transaction's own frame's start gets back, once that frame returned + /// ([`on_start_return`](Self::on_start_return)): what the transaction paid before execution + /// for the write record that frame makes, unless the frame kept it. The settlement takes it + /// and gives it back; a transaction whose own frame never started gets nothing back, having + /// paid nothing that stands. + pub(crate) const fn take_top_level_refund(&mut self) -> u64 { + let refund = self.top_level_refund; + self.top_level_refund = 0; + 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. @@ -1162,20 +1108,6 @@ 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 { @@ -1207,10 +1139,7 @@ mod tests { use super::*; use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; use alloy_primitives::{address, Address, Bytes, U256}; - use revm::{ - context_interface::context::SelfDestructResult, - interpreter::{CallInput, CallValue}, - }; + use revm::interpreter::{CallInput, CallValue}; const SENDER: Address = address!("00000000000000000000000000000000000f0001"); const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); @@ -1368,7 +1297,12 @@ mod tests { let result = crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); limit.on_last_frame_return(&result); - limit.settle_history_bytes(true); + let kept = limit.usage(); + limit.settle_history_bytes( + true, + kept.write_records, + limit.tracker.log_and_code_bytes(), + ); assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); } } @@ -1499,10 +1433,12 @@ mod tests { (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. + /// On the lanes, 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. The journal's ledger checks the caller on every return, and the shadow holds the two + /// to each other. #[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)] { @@ -1511,7 +1447,7 @@ mod tests { let result = crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); let _ = limit.on_frame_return(&result); - let stop = limit.stop_before_run(); + let stop = limit.shadow_pending_stop(); let expected = caller_stopped.then_some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: 100, @@ -1570,32 +1506,6 @@ mod tests { 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. @@ -1770,7 +1680,8 @@ mod tests { 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); + let kept = limit.usage(); + limit.settle_history_bytes(true, kept.write_records, limit.tracker.log_and_code_bytes()); assert_eq!(limit.history_bytes(), crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE); } @@ -1846,56 +1757,6 @@ mod tests { } } - /// Counts `write` on `limit` as the completed-write hook does, and reports the verdict and the - /// history bytes. - fn commit( - limit: &mut AdditionalLimit, - write: &CompletedWrite<'_>, - ) -> (LimitCheck, HistoryBytes) { - let (count, history) = limit.write_count(write); - (limit.commit_count(&count), history) - } - - /// 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 moved = SelfDestructResult { had_value: true, ..Default::default() }; - let destruction = - |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let (check, history) = commit(&mut limit, &destruction(TARGET)); - 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); - let (check, history) = commit(&mut limit, &destruction(SENDER)); - 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); - let _ = commit(&mut limit, &destruction(TARGET)); - 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] diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index e1d314a5a..c710ade0f 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -18,9 +18,10 @@ //! every charge the opcode makes. //! //! The journal ([`MegaJournal`](crate::MegaJournal)) counts the same quantities in its ledger, at -//! the journal's writes and from the same hooks, and revm's checkpoint reverts rewind it. The lanes -//! take every decision; under the `ledger-shadow` feature the two are held to each other wherever -//! they must agree, and a mismatch panics. +//! the journal's writes and from the same hooks, and revm's checkpoint reverts rewind it. The +//! ledger takes every decision; the lanes are kept beside it until their deletion, and under the +//! `ledger-shadow` feature they are held to the ledger wherever the two must agree, a mismatch +//! panicking. //! //! # The data-size limit //! @@ -143,9 +144,10 @@ pub(crate) mod shadow; #[cfg(test)] pub(crate) use ledger::StartSide; -pub(crate) use ledger::{ledger_assert, FrameIdentity, Ledger, Mark, StartFacts, StartReport}; +pub(crate) use ledger::{ + ledger_assert, FrameIdentity, FrameStartRecords, Ledger, Mark, StartFacts, StartReport, +}; pub use limit::AdditionalLimit; -pub(crate) use limit::FrameStartRecords; pub(crate) use record::HistoryBytes; use alloy_primitives::Bytes; diff --git a/crates/mega-evm/src/limit/shadow.rs b/crates/mega-evm/src/limit/shadow.rs index 3aff6ef8d..a4d07c66e 100644 --- a/crates/mega-evm/src/limit/shadow.rs +++ b/crates/mega-evm/src/limit/shadow.rs @@ -1,10 +1,10 @@ -//! The shadow: the journal's ledger held to the lanes wherever the two must agree. +//! The shadow: the lanes held to the journal's ledger wherever the two must agree. //! -//! The lanes ([`AdditionalLimit`]) take every decision; the ledger ([`Ledger`]) counts the same -//! writes beside them. Under the `ledger-shadow` feature the engine compares the two at the points -//! of a transaction's life where both describe the same thing, and panics on the first mismatch. -//! Each point is a function here, called where the point is; without the feature every one of them -//! compiles to nothing. +//! The ledger ([`Ledger`]) takes every decision; the lanes ([`AdditionalLimit`]) count the same +//! writes beside it until they go. Under the `ledger-shadow` feature the engine compares the two +//! at the points of a transaction's life where both describe the same thing, and panics on the +//! first mismatch. Each point is a function here, called where the point is; without the feature +//! every one of them compiles to nothing. //! //! - After a completed write is counted, a code deposit, an admitted hint and the keyless take-back //! of a creator's record: the verdicts, then what the transaction keeps, the history bytes beside @@ -116,25 +116,22 @@ pub(crate) fn completed_write( let _ = (lanes, ledger, lanes_verdict, ledger_verdict); } -/// A creation's deposited code, counted on both: the lanes refused it (`refused`) or not, and the -/// ledger reached `ledger_verdict`. +/// A creation's deposited code, counted on both with the lanes' verdict and the ledger's. #[inline(always)] pub(crate) fn code_deposit( lanes: &AdditionalLimit, ledger: &Ledger, - refused: bool, + lanes_verdict: LimitCheck, ledger_verdict: LimitCheck, ) { #[cfg(feature = "ledger-shadow")] { let at = "a code deposit"; - let lanes_verdict = refused.then(|| lanes.shadow_view().check); - let ledger_verdict = ledger_verdict.exceeded_limit().then_some(ledger_verdict); - compare::verdict(lanes_verdict, ledger_verdict, ledger, at); + compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); compare::agree(lanes, ledger, at); } #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, refused, ledger_verdict); + let _ = (lanes, ledger, lanes_verdict, ledger_verdict); } /// An Oracle hint, admitted or refused by both with the lanes' verdict and the ledger's. diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 29032bc5b..2cfeda81a 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -254,12 +254,16 @@ fn take_back_bump( if moved_value { return Ok(()); } - let taken = ctx.additional_limit.take_back_creator_record(); - let journaled = ctx.ledger_mut().take_back_creator_record(); - shadow::keyless_take_back(&ctx.additional_limit, ctx.ledger(), taken, journaled); + let lanes = ctx.additional_limit.take_back_creator_record(); + let taken = ctx.ledger_mut().take_back_creator_record(); if taken { + // A stop the record left the call, by putting it over a limit, goes with it: the call is + // held to its limits again without the record. + let check = ctx.ledger().check(); + ctx.additional_limit.hold_running_frame(check); gas.refill_history(started.signer_record_charge); } + shadow::keyless_take_back(&ctx.additional_limit, ctx.ledger(), lanes, taken); Ok(()) } diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 057450a8f..abcafa097 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -67,8 +67,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 +/// The payload is counted toward the transaction's data size before it is decoded (the journal's +/// ledger admits it, `Ledger::admit_hint`), 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 @@ -91,9 +91,9 @@ 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 journaled = ctx.ledger_mut().admit_hint(payload.len() as u64); - shadow::hint(&ctx.additional_limit, ctx.ledger(), check, journaled); + let lanes = ctx.additional_limit.record_hint_bytes(payload.len() as u64); + let check = ctx.ledger_mut().admit_hint(payload.len() as u64); + shadow::hint(&ctx.additional_limit, ctx.ledger(), lanes, check); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); @@ -177,11 +177,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/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index a712a150d..2130da40d 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -279,7 +279,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)); } diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 5c320cc41..f300ac4b2 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) } diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 95211050b..83d63b8d7 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -119,11 +119,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. @@ -357,7 +353,7 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); ( result, - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), evm.ctx().additional_limit().limit_exceeded().copied(), evm.inspector().clone(), ) diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 55eaa67f8..619d7ba9c 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -397,6 +397,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(), records(1), "run {run}"); } } diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index a3a9c706d..7850c4ac6 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -220,7 +220,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 diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index efe41c39e..894df5f92 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -119,11 +119,7 @@ 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); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 07daad02a..d63cd193e 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -298,7 +298,7 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); assert_eq!( - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, "the body stays; the recipient record does not" ); @@ -400,7 +400,7 @@ fn test_the_stop_does_not_outlive_its_transaction() { .is_success()); assert!(!stopped(&evm)); assert_eq!( - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, "an empty call keeps its body" ); diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 7126fb0da..d2981e802 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -152,7 +152,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"); } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 26e0adc48..9f4479173 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -599,13 +599,13 @@ impl Inspector, EthInterpreter> for LayerProbe { fn step(&mut self, interp: &mut Interpreter, context: &mut MegaContext) { self.opcode = interp.bytecode.opcode(); if self.log_before_sstore && self.opcode == SSTORE { - let before = context.additional_limit().usage(); + 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_eq!(context.additional_limit().usage(), before, "a tool's log counts nothing"); + assert_eq!(context.limit_usage(), before, "a tool's log counts nothing"); } } @@ -614,7 +614,7 @@ impl Inspector, EthInterpreter> for LayerProbe { _interp: &mut Interpreter, context: &mut MegaContext, ) { - self.steps.push((self.opcode, context.additional_limit().usage())); + self.steps.push((self.opcode, context.limit_usage())); } } @@ -809,7 +809,7 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { .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 @@ -847,7 +847,7 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { 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(), records(2), "slot 1 and the creator's nonce"); } /// A transaction is held at validation to its body and a record for every entry of its @@ -1138,7 +1138,7 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { .unwrap(); assert!(result.result.is_success()); assert_eq!( - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), with_extra(records(2), TRANSFER_LOG_SIZE), "CALLEE and CONTRACT2, and the transfer log" ); @@ -1483,10 +1483,7 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { 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); @@ -1525,7 +1522,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); } From 8db4ec692c25c3dc268c5a30e52b09e4da3be4ce Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 09:23:34 +0800 Subject: [PATCH 416/458] refactor(limit): delete the lanes, the start interpretation and the ledger shadow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The journal's ledger has taken every decision since the switch; what counted the same quantities beside it goes: the per-frame lanes and their tracker, the counting of a start's records on the lanes at frame init, `withdraw_refused_start` and the scan of the journal for a creator's nonce bump, the transfer-log prediction and its debug check, the reset of a transaction whose first frame never began, the lanes' half of the inspector settlement, the shadow comparison and the `ledger-shadow` feature. `AdditionalLimit` keeps Satin's side of each frame start — the start charge, the history allowance, a built frame's mark — the stops, the exemption and the settled figures; a debug build holds the ledger's count of every start revm made to the records the start's charge was computed from, on the frame side. The lane-only unit tests go with the lanes; the ones that pin behaviour move onto the ledger. --- AGENTS.md | 73 +- crates/mega-evm/Cargo.toml | 3 - crates/mega-evm/src/evm/context.rs | 30 +- crates/mega-evm/src/evm/execution.rs | 219 +-- crates/mega-evm/src/evm/host.rs | 38 +- crates/mega-evm/src/evm/inspector.rs | 14 +- crates/mega-evm/src/evm/journal.rs | 43 +- crates/mega-evm/src/limit/frame_limit.rs | 684 ------- crates/mega-evm/src/limit/ledger.rs | 475 ++++- crates/mega-evm/src/limit/limit.rs | 1617 ++++------------- crates/mega-evm/src/limit/mod.rs | 39 +- crates/mega-evm/src/limit/record.rs | 4 +- crates/mega-evm/src/limit/shadow.rs | 256 --- .../mega-evm/src/system/keyless/dispatch.rs | 11 +- crates/mega-evm/src/system/keyless/settle.rs | 6 +- crates/mega-evm/src/system/oracle.rs | 6 +- crates/mega-evm/tests/block/inspector.rs | 6 +- crates/mega-evm/tests/satin/journal_ledger.rs | 32 +- crates/mega-state-test/Cargo.toml | 5 - crates/state-test/Cargo.toml | 5 - 20 files changed, 874 insertions(+), 2692 deletions(-) delete mode 100644 crates/mega-evm/src/limit/frame_limit.rs delete mode 100644 crates/mega-evm/src/limit/shadow.rs diff --git a/AGENTS.md b/AGENTS.md index 1399bb348..4754d20df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,11 +34,6 @@ 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 ledger shadow: the journal's ledger held to the lanes wherever the two must agree, a mismatch -# panicking; the state-test crates pass the feature on, for the fixtures, blockchain tests and witness replays -cargo test -p mega-evm --features ledger-shadow -cargo build --release --locked -p state-test --features ledger-shadow - # 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 @@ -135,17 +130,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 | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`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 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 hold of a frame's start to the limits once revm decided it, and the debug check of the transfer log a kept start journaled (`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`; `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`), what a completed write counts (`record.rs`), Satin's side of each frame start (`StartSide`); the journal's ledger, the lanes' quantities counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the start reports, the marks, the creation rule — a shadow of the lanes until it takes the decisions (`ledger.rs`), and the comparison of the two under the `ledger-shadow` feature (`shadow.rs`); 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, and the settled transaction's history gas, history bytes and unspent reservoir; `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`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`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 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 hold of a frame's start to the limits once revm decided it (`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`; the journal's ledger: the data-size bytes, write records and the log and code bytes of the history byte count, counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the frame budgets, the start reports and verdicts, the marks, the creation rule, the refund formula, the body, deployed code and the EIP-7708 transfer logs (`ledger.rs`); what a completed write counts (`record.rs`); `AdditionalLimit`: Satin's side of each frame start (`StartSide`: the start charge, the history allowance, a built frame's mark), 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 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 @@ -193,20 +188,20 @@ 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; 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 as the frame starts, before revm decides it, and held to the limits once revm has, in `MegaEvm::frame_init` (`AdditionalLimit::hold_built_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start (`journal_position`): a frame revm built returns the stop on its first run, before any instruction, 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` is held to nothing and its lane goes with its failure, and a creation it answers before bumping its creator's nonce, read off the journal since the mark, has its count withdrawn (`AdditionalLimit::withdraw_refused_start`); either gets back the history its caller paid at the opcode, which charged it before revm decided, so a caller that cannot pay that charge runs out of gas even where revm would have refused the start. + It is counted where the value moves, on the level of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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 by the ledger as revm makes it, inside the start window, and held to the limits while the frame's level is open, in `MegaEvm::frame_init` (`AdditionalLimit::hold_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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` and a creation it answers before bumping its creator's nonce count nothing and have no verdict, their level never having opened; either gets back the history its caller paid at the opcode, which charged it before revm decided, so a caller that cannot pay that charge runs out of gas even where revm would have refused the start. 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 lands on the creator, which is held to its limits with it. 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 debug build asserts at every start revm made and kept that it 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 ledger counts the log revm journaled for a start, not a prediction of 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. 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 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. +- 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 by the journal's ledger 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. @@ -269,7 +264,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. + Its level of the ledger is the one any depth-0 call opens, 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. @@ -393,43 +388,43 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 commits the record to the running frame's lane, and the same count to the journal's ledger, and holds it to the limits first — 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. + It commits the record to the running frame's level of the journal's ledger and holds it to the limits first — 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 record, 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge for the frame's lane, which gives back on return what the start did not keep. + 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge on the frame's side (`StartSide`), which gives back on return what the ledger reports the start did not keep. revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. 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, asked at the opcode and as the frame starts; a debug build checks the two agree, except under an inspector that may rewrite the frame's input between them. + The records are one rule over caller, target and value, asked at the opcode and counted by the ledger as revm makes the start; a debug build holds the count to the charge for every start revm made and held to the limits, except under an inspector that may rewrite the frame's input between them. - **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`). + Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's level of the journal's ledger: a commit keeps them for the caller, a revert takes them back; a creator's nonce record is counted below the creation's level, so it survives the creation's failure once the nonce was bumped. + That record lands on the creator unchecked, so the creator is held to its budget with it as the creation returns, before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_start_return`). The KV count a node reports is the write-record count; no limit holds it. -- **The journal's ledger is a shadow of the lanes, until it takes the decisions.** - `MegaJournal` counts what the lanes count, at the journal's writes: a frame start's records and transfer log inside the start window Satin opens around revm's frame start, a completed write and a deposit's code from the hooks that feed the lanes, the body, the hints and the authorities where the lanes get them; revm's checkpoint reverts rewind it. +- **The journal's ledger decides.** + `MegaJournal` counts what the transaction's own execution keeps, at the journal's writes: a frame start's records and transfer log inside the start window Satin opens around revm's frame start, a completed write and a deposit's code from the Host's hooks, the body, the hints and the authorities where they are made; revm's checkpoint reverts rewind it, so what the ledger holds is what the journal keeps, whoever reverted what. Every checkpoint opens a level: a frame level for each frame revm starts — the first checkpoint of a call's start, or a creation's account checkpoint, whose budget and usage are measured from before its creator's nonce record — and a rollback level for any other, a tool's or a precompile's included; a frame level closes only as its frame returns, and a revert that would close one from below trips in debug builds. - The journal's own write methods count nothing, so a tool's or a precompile's writes are not counted (the policy the lanes already hold). - The lanes take every decision; the `ledger-shadow` feature holds the ledger to them — totals, budgets, start verdicts, refunds, caller checks — and panics on a mismatch. - A tool's checkpoint around a frame start that the tool reverts takes the frame's records back in the ledger and not on the lanes: the shadow stops comparing that transaction. -- **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. + The journal's own write methods count nothing, so a tool's or a precompile's writes are not counted. + Every verdict is the ledger's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start while its level is open (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return, and the refund of what a caller paid for a start's records, by one formula over what the ledger still holds (`StartSide::refund`): a start's own records when its level was kept, a creator's nonce record unless a revert to before the start took it back. + A tool's checkpoint around a frame start that the tool reverts takes the frame's records back with the frame's writes, and the transaction reports what the journal kept. +- **The frame side stays aligned with frames.** + `frame_init` pushes one side (`StartSide`) per frame result revm will return — what the caller paid for the start's records, the history allowance, and, once revm built the frame, what the ledger saw the start count and the frame's own mark — one for a frame answered without running too (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 side any depth-0 call has, and its creation's side 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. + 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)` (the ledger's verdict for the data size, `AdditionalLimit::crossed` for gas detention's compute stop, both answering the exemption), what it counted goes with its level, 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 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 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. A frame returns a stop before running another instruction in two cases (`AdditionalLimit::stop_before_run`, `before_frame_run`): on its first run, when its own start crossed a limit once revm built it; and on a resume, when a child left it one — 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 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 at the settlement, at one site, 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). 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 `Ledger::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 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. @@ -453,7 +448,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + 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 journal's ledger holds none, the frame's level having been reverted or its start never made, and the history its caller paid for the start's records comes back by the ledger's formula — 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, at the settlement. 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`. diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 087230849..b92d1b6cd 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -68,9 +68,6 @@ test-utils = ["dep:derive_more"] # `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"] -# Verification-only: compares the journal's ledger with the lanes wherever the two must agree, and -# panics on a mismatch. Off by default; without it the comparison compiles out. -ledger-shadow = [] # 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 diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 65f3dfb82..0b2a4ae69 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -23,7 +23,7 @@ use crate::{ inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - limit::{shadow, Ledger}, + limit::Ledger, system::{ self, keyless::{self, KeylessFrame}, @@ -255,8 +255,8 @@ impl MegaContext { self } - /// Holds every transaction from the next one on to `limits`, on the lanes and in the journal's - /// ledger alike. + /// Holds every transaction from the next one on to `limits`, in the journal's ledger and for + /// gas detention alike. pub(crate) const fn set_tx_runtime_limits(&mut self, limits: EvmTxRuntimeLimits) { self.additional_limit.set_limits(limits); self.ledger_mut().set_limits(limits); @@ -475,8 +475,8 @@ impl MegaContext { } /// Prepares the common execution layer for a transaction or a system call that is, or is not, - /// `system_originated`: the lanes and the journal's ledger begin it together, held to the same - /// limits and counting the same body. + /// `system_originated`: the journal's ledger begins it, counting its body, and the frame side + /// is reset. /// /// The SALT bucket multipliers and the oracle reads go with it: they are what one transaction /// read, so the next one reads its own. @@ -489,7 +489,6 @@ impl MegaContext { fn prepare(&mut self, system_originated: bool) { self.additional_limit.reset(); let transfer_logs = emits_transfer_logs(&self.inner.cfg); - self.additional_limit.set_transfer_logs(transfer_logs); self.bucket_multipliers.reset(); self.oracle_reads.clear(); // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call @@ -504,7 +503,6 @@ impl MegaContext { // 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. let body = transaction_body_bytes(self.tx()); - self.additional_limit.record_tx_body(body); self.ledger_mut().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(); @@ -704,9 +702,7 @@ impl ContextTr for MegaContext| { 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.ledger().counts_transfer_logs(), emits_transfer_logs(ctx.cfg())); emits_transfer_logs(ctx.cfg()) }; let with = |enabled: bool, disabled: bool| { @@ -1205,7 +1189,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.ledger().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 80c0f1a44..2cf5386f4 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -51,7 +51,7 @@ use crate::{ charge_write_records_history, evm::inspector::{frame_end_checked, ResultSource, StepGuard, UpfrontRecord}, history_gas, - limit::{ledger_assert, shadow, FrameIdentity, Mark, StartFacts, StartReport}, + limit::{FrameIdentity, Mark, StartFacts, StartReport}, synthetic_frame_result, system::keyless, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, @@ -348,18 +348,14 @@ where parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { let ctx = evm.ctx_mut(); - ctx.additional_limit.on_last_frame_return(frame_result); - // The transaction's own frame, answered without returning through `frame_return_result`. + // The transaction's own frame, answered without returning through `frame_return_result`; + // a transaction whose first frame never reached frame init has no side to pop. + debug_assert!(ctx.additional_limit.starts_open() <= 1, "only the outermost side is left"); if ctx.additional_limit.starts_open() != 0 { - on_start_return(ctx, frame_result, 0); + on_start_return(ctx, frame_result); } self.op.last_frame_result(evm, frame_result, parent_gas)?; let instruction_result = frame_result.instruction_result(); - if !instruction_result.is_ok() { - // The lanes' site of the refund, noted for the shadow. - let top_level = evm.ctx_ref().additional_limit.top_level_write_record_gas(); - evm.ctx_mut().additional_limit.note_top_level_refund(top_level); - } parent_gas.refill_history(evm.ctx_mut().additional_limit.take_top_level_refund()); if instruction_result.is_halt() { parent_gas.spend_all(); @@ -376,8 +372,6 @@ where .saturating_add_signed(frame_result.gas().history_gas_spent()); layer.set_history_gas_spent(history); layer.settle_history_bytes(priced, kept.write_records, log_and_code_bytes); - let ctx = evm.ctx_ref(); - shadow::settlement(&ctx.additional_limit, ctx.ledger()); Ok(()) } @@ -516,8 +510,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), + ItemOrResult::Item(_) => Ok(()), ItemOrResult::Result(result) => Err(result), }); let report = self.inner.ctx.ledger_mut().close_start(); @@ -595,19 +589,14 @@ impl EvmTr for MegaEvm { - ctx.additional_limit.set_frame_address(address); + Ok(()) => { if keyless { ctx.keyless_frame = Some(keyless::KeylessFrame::Built); } - #[cfg(debug_assertions)] - start.assert_transfer_log_journaled(ctx, Some(address)); - let lanes = ctx.additional_limit.hold_built_start(); ctx.additional_limit.hold_start(report.verdict); let mark = ctx.ledger().frame_start_mark(); - ledger_assert!(mark.is_some(), "a frame revm built has its level open"); + debug_assert!(mark.is_some(), "a frame revm built has its level open"); ctx.additional_limit.attach_start(report, mark); - shadow::built_start(&ctx.additional_limit, ctx.ledger(), lanes, &report); Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } Err(mut result) => { @@ -662,8 +651,7 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - let lanes = self.inner.ctx.additional_limit.on_frame_return(&result); - let refund = on_start_return(&mut self.inner.ctx, &result, lanes); + let refund = on_start_return(&mut self.inner.ctx, &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 @@ -735,9 +722,9 @@ 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, and its - /// answer settles as a frame that never started ([`answered_by_inspector`]). + /// revm's inspected frame start, with the frame sides kept aligned: a frame the inspector + /// answers itself never reaches [`EvmTr::frame_init`], so a side of its own 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 @@ -795,7 +782,7 @@ where } } let source = ResultSource::Engine(start); - frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source, upfront); + frame_end_checked(ctx, inspector, &frame_input, &mut output, source, upfront); return Ok(ItemOrResult::Result(output)); } let (ctx, inspector, frame) = self.ctx_inspector_frame(); @@ -845,7 +832,7 @@ where if let Ok(ItemOrResult::Result(result)) = &mut next { let source = ResultSource::Engine(built_frame_mark(ctx, frame)); let upfront = ctx.upfront_records.get(frame.depth).copied().flatten(); - frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source, upfront); + frame_end_checked(ctx, inspector, &frame.input, result, source, upfront); frame.set_finished(true); } next @@ -1106,13 +1093,13 @@ impl MegaEvm { } /// 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 + /// past the call-stack limit ([`call_too_deep`]), with a side of its own standing 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(frame_init.depth); + self.inner.ctx.additional_limit.push_answered_start(frame_init.depth); } answer } @@ -1141,11 +1128,11 @@ fn take_back_a_stopped_answer( /// 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`]). +/// past the call-stack limit; a side of its own 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, @@ -1157,11 +1144,11 @@ where INSP: Inspector, EthInterpreter>, { let mut output = call_too_deep(frame_init).unwrap_or(output); - ctx.additional_limit.push_empty_frame(frame_init.depth); + ctx.additional_limit.push_answered_start(frame_init.depth); 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); + let input = &frame_init.frame_input; + frame_end_checked(ctx, inspector, input, &mut output, ResultSource::Inspector, upfront); output } @@ -1179,10 +1166,6 @@ struct FrameStart { gas_limit: u64, /// The reservoir the frame inherits. reservoir: u64, - /// Whether the start counted an EIP-7708 transfer log, for a debug build to hold to the one - /// revm journaled. - #[cfg(debug_assertions)] - transfer_log: bool, } impl FrameStart { @@ -1215,47 +1198,7 @@ impl FrameStart { "a frame input always names a call or a creation, as revm's frame init asserts" ), }; - Self { - mark: ctx.journal_mut().mark(), - facts, - gas_limit: input_gas_limit(input), - reservoir, - #[cfg(debug_assertions)] - transfer_log: ctx.additional_limit.frame_start_transfer_log(input), - } - } - - /// The account a creation is made by; `None` for a call. - const fn creator(&self) -> Option
{ - match self.facts.target { - Some(_) => None, - None => Some(self.facts.caller), - } - } - - /// Asserts that revm journaled the transfer log the start counted, once it made the start and - /// kept it: the rule the count follows is the one revm journals the log by. Only the transfer - /// logs of the start's own move are compared, from its caller to the frame it starts — for a - /// creation, the account revm `created` — a precompile may journal logs of its own, transfer - /// logs of the value it moves through `EvmInternals` among them. - #[cfg(debug_assertions)] - fn assert_transfer_log_journaled( - &self, - ctx: &MegaContext, - created: Option
, - ) { - use revm::primitives::eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}; - let (from, to) = (self.facts.caller, self.facts.target.or(created).unwrap_or_default()); - let ends = [ETH_TRANSFER_LOG_TOPIC, from.into_word(), to.into_word()]; - let journaled = ctx.journal_ref().logs()[self.mark.position.log_i..] - .iter() - .filter(|log| log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics() == ends) - .count(); - debug_assert_eq!( - journaled, - usize::from(self.transfer_log), - "the transfer log counted is the one revm journaled" - ); + Self { mark: ctx.journal_mut().mark(), facts, gas_limit: input_gas_limit(input), reservoir } } } @@ -1283,57 +1226,12 @@ fn hold_answered_start( report: &StartReport, answer: &mut FrameResult, ) { - hold_answered_start_on_lanes(ctx, start, report, answer); if let Some(stop) = report.verdict.filter(LimitCheck::exceeded_limit) { let output = ctx.additional_limit.note_frame_stop(&stop); stop_the_answer(answer, start, output); } } -/// What the lanes make of a start revm answered, for the shadow to hold to the ledger's verdict: a -/// call revm refused is held to nothing, any other call to the lanes' check; a creation revm -/// refused before it bumped its creator's nonce, read off the journal since the mark, has its -/// count withdrawn ([`withdraw_refused_start`](crate::AdditionalLimit)), and, as the transaction's -/// own frame answered with a success, the history of its record noted as given back. -fn hold_answered_start_on_lanes( - ctx: &mut MegaContext, - start: &FrameStart, - report: &StartReport, - answer: &FrameResult, -) { - let Some(creator) = start.creator() else { - if matches!( - answer.instruction_result(), - InstructionResult::OutOfFunds | InstructionResult::OverflowPayment - ) { - shadow::answered_start(ctx.ledger(), None, report); - return; - } - #[cfg(debug_assertions)] - if answer.instruction_result().is_ok() { - start.assert_transfer_log_journaled(ctx, None); - } - let lanes = ctx.additional_limit.check_start(); - shadow::answered_start(ctx.ledger(), Some(lanes), report); - return; - }; - let bumped = ctx.journal_ref().journal()[start.mark.position.journal_i..] - .iter() - .any(|entry| matches!(entry, JournalEntry::NonceBump { address } if *address == creator)); - shadow::answered_start(ctx.ledger(), None, report); - if bumped { - return; - } - ctx.additional_limit.withdraw_refused_start(); - // revm answers a creation whose creator's nonce cannot be bumped with a success. The - // transaction's own frame, refused so, makes none of the records charged before execution for - // it: the lanes' site of the refund, noted for the shadow. - if start.facts.depth == 0 && answer.instruction_result().is_ok() { - let top_level = ctx.additional_limit.top_level_write_record_gas(); - ctx.additional_limit.note_top_level_refund(top_level); - } -} - /// 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 the call inherited, and no precompile /// output, as [`synthetic_frame_result`] answers a frame that never started. @@ -1396,7 +1294,7 @@ fn built_frame_mark( frame: &EthFrame, ) -> Mark { let kept = ctx.additional_limit.running_start().and_then(|side| side.mark()).copied(); - ledger_assert!( + debug_assert!( kept.is_some_and(|mark| mark.position == frame.checkpoint), "a built frame's start side keeps the mark of its own checkpoint" ); @@ -1414,7 +1312,7 @@ fn assert_running_frame( let running = ctx.additional_limit.running_start().and_then(|side| side.start()); let expected = depth.checked_sub(1).zip(running).map(|(depth, start)| FrameIdentity { depth, start }); - ledger_assert!( + debug_assert!( ctx.ledger().running_frame() == expected, "a frame starts from the running frame's own level" ); @@ -1428,14 +1326,9 @@ fn assert_running_frame( /// /// Asserts the frame's own level, and every level opened inside it, closed: the journal's nearest /// frame level is the caller's. -/// -/// Under the shadow, the lanes are held to the ledger: the refund they would give (`lanes`), the -/// stop they would leave the caller the frame returns into, and what the two hold the transaction -/// to. fn on_start_return( ctx: &mut MegaContext, result: &FrameResult, - lanes: u64, ) -> u64 { let ledger = ctx.inner.journaled_state.ledger(); let Some((side, refund)) = ctx.additional_limit.on_start_return(ledger, result) else { @@ -1447,16 +1340,10 @@ fn on_start_return( .checked_sub(1) .zip(caller) .map(|(depth, start)| FrameIdentity { depth, start }); - ledger_assert!( + debug_assert!( ctx.ledger().running_frame() == expected, "a frame returns with its own level closed, into its caller's" ); - shadow::frame_return( - &mut ctx.additional_limit, - ctx.inner.journaled_state.ledger(), - lanes, - &side, - ); refund } @@ -1519,7 +1406,6 @@ fn record_applied_authorities( 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); ctx.ledger_mut().count_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() { @@ -1533,12 +1419,13 @@ fn record_applied_authorities( /// 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 the charge comes back -/// once revm refused it ([`hold_answered_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. +/// first frame's record does not, so what it cost is kept for the settlement to give back when the +/// frame does not keep the record, and whether it makes one is left for that frame's side to hold +/// the ledger's count to. A first frame revm refuses to start on its sender's account makes no +/// record, and the charge comes back at the settlement as for any frame that kept nothing: 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. /// `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, @@ -1845,26 +1732,4 @@ mod tests { assert_eq!(nonce, u64::from(!taken_back), "{case}"); } } - - /// The check of a start revm made and kept trips on a transfer log the start counted and revm - /// 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 mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let start = FrameStart { - mark: ctx.journal_mut().mark(), - facts: StartFacts { - depth: 1, - caller: CALLER, - target: Some(TARGET), - transfers_value: true, - }, - gas_limit: 0, - reservoir: 0, - transfer_log: true, - }; - start.assert_transfer_log_journaled(&ctx, None); - } } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 42a8c0c6a..41f2e5b94 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -74,10 +74,8 @@ use revm::{ }; use crate::{ - charge_write_records_history, history_gas, - limit::{shadow, HistoryBytes}, - system::ORACLE_CONTRACT_ADDRESS, - ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, + charge_write_records_history, history_gas, limit::HistoryBytes, + system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -290,10 +288,9 @@ impl revm::context_interface::Host } /// Commits the record of a write an opcode completed to the running frame's level of the - /// journal's ledger — and to the running frame's lane, until the lanes go — 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. + /// journal's ledger, 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 @@ -319,11 +316,8 @@ impl revm::context_interface::Host CompletedWrite::Log { .. } => (true, false), CompletedWrite::SelfDestruct { .. } => (false, false), }; - // One count, committed to the journal's ledger, which decides, and to the lanes. let (count, history) = self.ledger().write_count(&write); - let lanes = self.additional_limit.commit_count(&count); let check = self.ledger_mut().count_write(&count); - shadow::completed_write(&self.additional_limit, self.ledger(), lanes, check); if check.exceeded_limit() { return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } @@ -357,13 +351,14 @@ impl revm::context_interface::Host /// frame's input. /// /// 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. 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. 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. + /// the frame's allowance is free for what the recipient does; the frame's side keeps it, and + /// gives back on return what the journal's ledger reports the start did not keep. 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. 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 @@ -378,13 +373,14 @@ impl revm::context_interface::Host if !self.prices_history() { return true; } - let charged = charge_write_records_history(gas, records.on_lane, u64::from(records.caller)); - let Some((on_lane, caller)) = charged else { + let charged = + charge_write_records_history(gas, records.on_level, u64::from(records.caller)); + let Some((on_level, caller)) = charged else { gas.erase_cost(start.forward); gas.set_failed_charge_remaining(Some(gas.remaining())); return false; }; - self.additional_limit.stage_frame_charge(records, on_lane, caller); + self.additional_limit.stage_frame_charge(records, on_level, caller); true } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 6f1be8ddd..5e8ec0f0a 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -548,7 +548,6 @@ pub(crate) fn frame_end_checked( inspector: &mut INSP, frame_input: &FrameInput, frame_result: &mut FrameResult, - depth: usize, source: ResultSource, upfront: Option, ) where @@ -578,11 +577,11 @@ pub(crate) fn frame_end_checked( } }; if answered || !before.is_ok() { - settle_kept_nothing(context, frame_input, frame_result, depth, answered); + settle_kept_nothing(context, frame_input, frame_result, answered); } } -/// Settles the result of a frame at `depth` that kept nothing in the journal — one an inspector +/// Settles the result of a frame 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. /// @@ -613,13 +612,11 @@ pub(crate) fn frame_end_checked( /// the frame's writes, or which never counted the start of a frame the inspector answered: its /// caller gets back the history it paid for the start's records once the frame returns, and the /// transaction the history of its own frame's record at the settlement, as for any frame that kept -/// nothing. The lanes, which follow frames rather than the journal, are settled as the failure's -/// until they go. +/// nothing. fn settle_kept_nothing( context: &mut MegaContext, input: &FrameInput, result: &mut FrameResult, - depth: usize, answered: bool, ) { carry_upfront_flags(input, result); @@ -641,11 +638,6 @@ fn settle_kept_nothing( // 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)); result.gas_mut().refill_reservoir(upfront.unwrap_or_default()); - if depth == 0 { - let history = context.additional_limit.top_level_write_record_gas(); - context.additional_limit.note_top_level_refund(history); - } - context.additional_limit.discard_returning_lane(); } /// Sets `result`'s upfront-charge flags to those of `input`, the frame it answers: what revm's diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index bf896649b..3871affa9 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -49,9 +49,7 @@ use revm::{ Database, Journal, JournalEntry, }; -use crate::limit::{ledger_assert, Ledger, Mark}; -#[cfg(any(test, feature = "test-utils"))] -use crate::LimitUsage; +use crate::limit::{Ledger, Mark}; /// The journal of the Satin engine: revm's journal, and the ledger of what the transaction's own /// execution keeps. See the module documentation. @@ -68,15 +66,6 @@ pub struct MegaJournal { } impl MegaJournal { - /// What the journal's ledger holds the running (or last) transaction to keep: its data-size - /// bytes and write records, for a test to hold to what the engine decides on, - /// [`AdditionalLimit::usage`](crate::AdditionalLimit::usage), which counts the same writes. The - /// two agree wherever the transaction's own execution, rather than a tool, took its state back. - #[cfg(any(test, feature = "test-utils"))] - pub fn ledger_usage(&self) -> LimitUsage { - self.ledger.usage() - } - /// The ledger. pub(crate) const fn ledger(&self) -> &Ledger { &self.ledger @@ -110,7 +99,7 @@ impl MegaJournal { /// Asserts the ledger holds a level for every checkpoint revm's journal holds open. #[inline] fn assert_levels(&self) { - ledger_assert!( + debug_assert!( self.ledger.depth() == self.revm.depth, "the ledger holds one level per open checkpoint" ); @@ -343,7 +332,7 @@ mod tests { use crate::{ limit::{Mark, StartFacts, StartReport, StartSide}, test_utils::MemoryDatabase, - EvmTxRuntimeLimits, LimitCheck, LimitKind, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use alloy_primitives::address; @@ -458,7 +447,7 @@ mod tests { }; let _ = start_call(&mut journal, 0, SENDER, A, 0); writes(&mut journal); - assert_eq!(journal.ledger_usage(), body(), "outside a start's window"); + assert_eq!(journal.ledger().usage(), body(), "outside a start's window"); journal.ledger_mut().open_start(StartFacts { depth: 1, @@ -469,7 +458,7 @@ mod tests { let _ = journal.checkpoint(); writes(&mut journal); let _ = journal.ledger_mut().close_start(); - assert_eq!(journal.ledger_usage(), body(), "inside a start's window"); + assert_eq!(journal.ledger().usage(), body(), "inside a start's window"); assert!(!journal.logs().is_empty(), "the writes reached revm's journal"); } @@ -536,18 +525,18 @@ mod tests { let _ = start_call(&mut journal, 0, SENDER, A, 0); let (checkpoint, _) = start_call(&mut journal, 1, A, B, 1); assert_eq!((journal.ledger().depth(), journal.depth()), (2, 2)); - assert_eq!(journal.ledger_usage(), kept(2, 1), "B's record, A's, and the transfer log"); + assert_eq!(journal.ledger().usage(), kept(2, 1), "B's record, A's, and the transfer log"); end_frame(&mut journal, Some(checkpoint)); assert_eq!((journal.ledger().depth(), journal.depth()), (1, 1)); - assert_eq!(journal.ledger_usage(), body(), "the revert takes the start back"); + assert_eq!(journal.ledger().usage(), body(), "the revert takes the start back"); let _ = start_call(&mut journal, 1, A, B, 1); end_frame(&mut journal, None); - assert_eq!(journal.ledger_usage(), kept(2, 1), "the commit keeps it"); + assert_eq!(journal.ledger().usage(), kept(2, 1), "the commit keeps it"); let _ = journal.checkpoint(); journal.clear(); assert_eq!((journal.ledger().depth(), journal.depth()), (0, 0)); - assert_eq!(journal.ledger_usage(), kept(2, 1), "readable until the next transaction"); + assert_eq!(journal.ledger().usage(), kept(2, 1), "readable until the next transaction"); } /// A tool's checkpoint around a call's start — opened before the start, closed after the frame @@ -570,7 +559,7 @@ mod tests { "{case}: B's record, A's, and the log" ); end_frame(&mut journal, None); - let mut side = StartSide::new(1, 7, 11); + let mut side = StartSide::new(1, 7, 11, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); @@ -579,13 +568,13 @@ mod tests { } let refund = if reverted { 7 + 11 } else { 0 }; assert_eq!(side.refund(journal.ledger()), refund, "{case}: B's refund"); - assert_eq!(journal.ledger_usage(), if reverted { body() } else { kept(2, 1) }); + assert_eq!(journal.ledger().usage(), if reverted { body() } else { kept(2, 1) }); let (_, later) = start_call(&mut journal, 1, A, C, 1); assert_eq!(later.caller_on_level, reverted, "{case}: A's flag"); end_frame(&mut journal, None); let records = if reverted { 2 } else { 3 }; - assert_eq!(journal.ledger_usage(), kept(records, if reverted { 1 } else { 2 })); + assert_eq!(journal.ledger().usage(), kept(records, if reverted { 1 } else { 2 })); } } @@ -614,7 +603,7 @@ mod tests { let (checkpoint, report) = start_creation(&mut journal, 2, B, CREATED, 1); assert!(report.creator_record, "{case}: B's nonce record is the start's"); end_frame(&mut journal, failed.then_some(checkpoint)); - let mut side = StartSide::new(2, 7, 11); + let mut side = StartSide::new(2, 7, 11, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); @@ -630,7 +619,7 @@ mod tests { /// A revert that would close a level from below — a checkpoint taken before a frame started, /// reverted while the frame still runs — is not supported, and trips. #[test] - #[cfg(any(debug_assertions, feature = "ledger-shadow"))] + #[cfg(debug_assertions)] #[should_panic(expected = "a revert closes the latest level")] fn test_a_revert_below_a_running_frame_trips() { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); @@ -686,10 +675,10 @@ mod tests { let mark: Mark = journal.ledger().frame_start_mark().expect("the creation's level is open"); assert_eq!(mark.position, checkpoint, "the creation's own checkpoint"); end_frame(&mut journal, None); - assert_eq!(journal.ledger_usage(), kept(2, 1)); + assert_eq!(journal.ledger().usage(), kept(2, 1)); journal.revert_to(&mark); - assert_eq!(journal.ledger_usage(), kept(1, 0), "the creator's record stays"); + assert_eq!(journal.ledger().usage(), kept(1, 0), "the creator's record stays"); let (_, later) = start_creation(&mut journal, 1, A, C, 0); assert!(!later.creator_record, "A stays recorded"); } 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 fa8fd921a..000000000 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ /dev/null @@ -1,684 +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, - /// 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, - 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. - #[cfg(any(test, feature = "ledger-shadow"))] - 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() - } - - /// 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/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index a96b95d92..37d14b348 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -41,9 +41,9 @@ //! //! The ledger takes every decision: the counts, the frame budgets, the start verdicts, the //! refunds of the history a caller paid for a start's records, and the check of a caller its child -//! returns into. The lanes ([`AdditionalLimit`](crate::AdditionalLimit)) count the same quantities -//! beside it until their deletion; under the `ledger-shadow` feature they are held to the ledger -//! wherever the two must agree. +//! returns into. Satin's side of each frame start ([`StartSide`]) — what its caller paid for its +//! records, the history allowance the frame was granted, a built frame's mark — lives beside it on +//! [`AdditionalLimit`](crate::AdditionalLimit), one side per frame result revm returns. #[cfg(not(feature = "std"))] use alloc as std; @@ -56,25 +56,14 @@ use revm::context_interface::{ }; use super::{ - limit::share_of_remaining, record::{write_effect, write_moves_value, HistoryBytes, RecordEffect, WriteCount}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG, WRITE_RECORD, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, }; -/// Asserts an invariant of the ledger's levels in debug builds and in `ledger-shadow` builds; in -/// any other build the check is type-checked and compiled out, as `debug_assert!`'s is. -macro_rules! ledger_assert { - ($($arg:tt)*) => { - if cfg!(any(debug_assertions, feature = "ledger-shadow")) { - assert!($($arg)*); - } - }; -} -pub(crate) use ledger_assert; - -/// What the ledger counts that the journal rewinds: additions and refunds, kept apart as the lanes -/// keep them, so that a frame's own usage saturates as a lane's does, and the log and code bytes -/// history counts beside the write records. +/// What the ledger counts that the journal rewinds: additions and refunds, kept apart so that a +/// frame's own usage saturates at zero on its own — a child can take back a slot its parent +/// dirtied — and the log and code bytes history counts beside the write records. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Counts { /// What was counted. @@ -174,14 +163,14 @@ pub(crate) struct StartFacts { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct FrameStartRecords { /// Records on the frame's own level, which its failure takes back. - pub(crate) on_lane: u64, + pub(crate) on_level: 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 }; + pub(crate) const NONE: Self = Self { on_level: 0, caller: false }; } /// The start window, open while revm decides one frame start. @@ -289,11 +278,6 @@ pub(crate) struct Ledger { limits: EvmTxRuntimeLimits, /// Whether the transaction is held to no limit. exempt: bool, - /// Whether a tool's checkpoint that enclosed a frame start was reverted and took back what the - /// ledger held: the lanes do not follow it, and the shadow stops comparing for the - /// transaction. - #[cfg(feature = "ledger-shadow")] - diverged: bool, } /// `counted`, with the transfer log revm journaled for the value it moved when `logged`. @@ -326,10 +310,6 @@ impl Ledger { self.target_is_authority = false; self.transfer_logs = transfer_logs; self.exempt = exempt; - #[cfg(feature = "ledger-shadow")] - { - self.diverged = false; - } } /* What the ledger holds */ @@ -378,12 +358,6 @@ impl Ledger { self.levels.len() } - /// The number of frame levels open: the frames on the call stack. - #[cfg(feature = "ledger-shadow")] - pub(crate) fn frame_levels(&self) -> usize { - self.levels.iter().filter(|level| level.frame.is_some()).count() - } - /// The running frame's level: the nearest frame level. fn frame_level(&self) -> Option<&FrameLevel> { self.levels.iter().rev().find_map(|level| level.frame.as_ref()) @@ -404,8 +378,15 @@ impl Ledger { self.frame_level().map(|level| FrameIdentity { depth: level.depth, start: level.start }) } + /// Whether the transaction's value movements journal EIP-7708 transfer logs, which the ledger + /// counts where the value moves. + #[cfg(test)] + pub(crate) const fn counts_transfer_logs(&self) -> bool { + self.transfer_logs + } + /// The running frame's budget and what it keeps so far. - #[cfg(any(test, feature = "ledger-shadow"))] + #[cfg(test)] pub(crate) fn running_budget(&self) -> Option<(u64, LimitUsage)> { self.frame_level().map(|level| (level.budget, level.usage(&self.counts))) } @@ -415,16 +396,10 @@ impl Ledger { /// held. pub(crate) fn fate(&self, start: StartId) -> (bool, bool) { let fate = self.last_decided.filter(|fate| fate.start == start); - ledger_assert!(fate.is_some(), "a start's fate is read as its frame returns"); + debug_assert!(fate.is_some(), "a start's fate is read as its frame returns"); fate.map_or((false, false), |fate| (fate.level_kept, fate.start_kept)) } - /// Whether a tool's checkpoint that enclosed a frame start was reverted in the transaction. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn diverged(&self) -> bool { - self.diverged - } - /* Verdicts */ /// The verdict on `used` crossing a data-size `limit`, a frame budget when `frame_local`: @@ -499,7 +474,7 @@ impl Ledger { let recorded = self.frame_level().is_some_and(|level| level.recorded); let target = match start.kind { FrameStartKind::Create | FrameStartKind::Create2 => { - return FrameStartRecords { on_lane: 1, caller: !recorded }; + return FrameStartRecords { on_level: 1, caller: !recorded }; } FrameStartKind::Call | FrameStartKind::CallCode | @@ -511,8 +486,8 @@ impl Ledger { // An opcode runs inside a frame, so the frame it starts is below the // transaction's own. let depth = self.frame_level().map_or(1, |level| level.depth + 1); - let (on_lane, caller) = self.call_records(depth, start.caller, target, recorded); - FrameStartRecords { on_lane, caller } + let (on_level, caller) = self.call_records(depth, start.caller, target, recorded); + FrameStartRecords { on_level, caller } } _ => FrameStartRecords::NONE, } @@ -552,6 +527,10 @@ impl Ledger { /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts /// other than the transaction's `sender`, `target_is_authority` if the call target is one. /// Inside the pre-execution level, whose revert takes them back. + /// + /// 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 count_authorities( &mut self, sender: Address, @@ -561,6 +540,10 @@ impl Ledger { self.sender = sender; self.target_is_authority = target_is_authority; self.counts.used = self.counts.used.saturating_add(WRITE_RECORD.times(authorities)); + debug_assert!( + 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" + ); } /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and @@ -660,7 +643,7 @@ impl Ledger { /// Opens the start window for the start `facts` describes, which revm decides next. pub(crate) fn open_start(&mut self, facts: StartFacts) { - ledger_assert!(self.window.is_none(), "start windows do not nest"); + debug_assert!(self.window.is_none(), "start windows do not nest"); if facts.depth == 0 { self.sender = facts.caller; } @@ -865,7 +848,7 @@ impl Ledger { /// reverted while a frame opened after it still runs — would leave the frame running without /// its level. fn assert_frame_closes(&self, frame: &FrameLevel) { - ledger_assert!( + debug_assert!( self.window.is_some() || frame.returning, "a revert closes the latest level: a frame's level closes only when the frame returns" ); @@ -894,13 +877,10 @@ impl Ledger { /// the start counted back with it. pub(crate) fn on_revert(&mut self, checkpoint: JournalCheckpoint) { let Some(level) = self.levels.pop() else { return }; - ledger_assert!( + debug_assert!( level.opened_at == checkpoint, "a revert closes the latest level: a revert below a level still open is not supported" ); - #[cfg(feature = "ledger-shadow")] - let changed = self.counts != level.at_open || - self.frame_level().is_some_and(|caller| caller.recorded != level.recorded_at_open); self.counts = level.at_open; if let Some(caller) = self.frame_level_mut() { caller.recorded = level.recorded_at_open; @@ -911,13 +891,7 @@ impl Ledger { self.last_decided = Some(Fate { start: frame.start, level_kept: false, start_kept: true }); } - None => { - self.take_back_starts_from(level.next_start_at_open, None); - #[cfg(feature = "ledger-shadow")] - if changed && self.next_start > level.next_start_at_open { - self.diverged = true; - } - } + None => self.take_back_starts_from(level.next_start_at_open, None), } } @@ -975,7 +949,7 @@ impl Ledger { /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, the /// running frame's flag, and what became of the last start decided. pub(crate) fn revert_to(&mut self, mark: &Mark) { - ledger_assert!( + debug_assert!( self.levels.len() <= mark.levels, "a revert to a mark finds every level opened since closed" ); @@ -1007,14 +981,23 @@ pub(crate) struct StartSide { /// What is left of the history allowance the 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. stipend: u64, - /// Whether the records the lanes counted for the start are those its charge paid for. - #[cfg(feature = "ledger-shadow")] - comparable: bool, + /// The records the charge was computed from, when the charge was made from one and nothing + /// could rewrite the start between the two: what a debug build holds the ledger's count to. + #[cfg(debug_assertions)] + charged: Option, } impl StartSide { - /// The side of a start at `depth` whose caller paid `on_level_charge` and `caller_charge`. - pub(crate) const fn new(depth: usize, on_level_charge: u64, caller_charge: u64) -> Self { + /// The side of a start at `depth` whose caller paid `on_level_charge` and `caller_charge` for + /// the records `charged`, when the charge was computed from them. + pub(crate) const fn new( + depth: usize, + on_level_charge: u64, + caller_charge: u64, + charged: Option, + ) -> Self { + #[cfg(not(debug_assertions))] + let _ = charged; Self { depth, on_level_charge, @@ -1030,28 +1013,41 @@ impl StartSide { }, mark: None, stipend: 0, - #[cfg(feature = "ledger-shadow")] - comparable: true, + #[cfg(debug_assertions)] + charged, } } - /// Attaches what the ledger saw the start count and the built frame's mark. - pub(crate) const fn attach(&mut self, report: StartReport, mark: Option) { + /// Attaches what the ledger saw the start count and the built frame's mark, and holds the + /// count to the records the start's charge was computed from. + /// + /// The two are separate answers to one question, asked at two points: the charge at the + /// opcode, on the facts revm's instruction hands the frame-start hook — or before execution, + /// on the transaction, for its own frame; or at a `keylessDeploy` call's first run, on the + /// creation it starts — and the count, on the writes revm made for the start. They agree + /// because the start revm makes carries the caller, target and value the charge was computed + /// from, and nothing between the two changes it: an interceptor answers a frame or lets it + /// start as it is, and a creation reaches none. A divergence trips in a debug build rather + /// than mis-charging the caller and mis-splitting the refund its failure gets back. An + /// inspector that may rewrite the start runs between the two, and can split them: under one + /// the start is not checked. Only a start revm made and held to the limits is checked: one it + /// refused, or failed before its level opened, counted nothing, and the charge comes back. + pub(crate) fn attach(&mut self, report: StartReport, mark: Option) { self.report = report; self.mark = mark; - } - - /// Notes whether the records the lanes counted are those the charge paid for. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn set_comparable(&mut self, comparable: bool) { - self.comparable = comparable; - } - - /// Whether the shadow compares the refund: the records the lanes counted are those the charge - /// paid for. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn comparable(&self) -> bool { - self.comparable + #[cfg(debug_assertions)] + if let Some(charged) = + self.charged.filter(|_| report.start.is_some() && report.verdict.is_some()) + { + let counted = FrameStartRecords { + on_level: report.on_level, + caller: report.caller_on_level || report.creator_record, + }; + debug_assert_eq!( + charged, counted, + "the records a frame's start makes changed after its caller was charged for them", + ); + } } /// The frame's depth. @@ -1108,6 +1104,20 @@ impl StartSide { } } +/// `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) +} + #[cfg(test)] mod tests { use super::*; @@ -1119,16 +1129,305 @@ mod tests { const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); const TARGET: Address = address!("00000000000000000000000000000000000f0003"); - /// A ledger holding a transaction from [`SENDER`] with a body of `body` bytes under `limits`, - /// exempt or not, whose value movements journal transfer logs when `transfer_logs`. + /// A ledger holding a transaction with a body of `body` bytes under `limits`, exempt or not, + /// whose value movements journal transfer logs when `transfer_logs`. The sender is whoever + /// starts the transaction's own frame. fn ledger(limits: EvmTxRuntimeLimits, exempt: bool, transfer_logs: bool, body: u64) -> Ledger { let mut ledger = Ledger::default(); ledger.set_limits(limits); ledger.begin_transaction(exempt, transfer_logs, body); + ledger + } + + /// [`ledger`], with [`SENDER`] as the transaction's sender before any frame starts. + fn ledger_from_sender(limits: EvmTxRuntimeLimits, transfer_logs: bool) -> Ledger { + let mut ledger = ledger(limits, false, transfer_logs, 0); ledger.count_authorities(SENDER, 0, false); ledger } + /// 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) + } + + /// A checkpoint of revm's journal as the ledger sees one: distinct per open level. + fn checkpoint(ledger: &Ledger) -> JournalCheckpoint { + JournalCheckpoint { log_i: 0, journal_i: ledger.depth(), selfdestructed_i: 0 } + } + + /// Starts a call from `caller` to `target` at `depth` as revm starts one, moving `value`, and + /// journaling a transfer log for it when the ledger's transaction does; reports what the start + /// counted. + fn start_call( + ledger: &mut Ledger, + depth: usize, + caller: Address, + target: Address, + value: u64, + ) -> StartReport { + let facts = StartFacts { depth, caller, target: Some(target), transfers_value: value != 0 }; + ledger.open_start(facts); + ledger.on_checkpoint(checkpoint(ledger)); + let logged = ledger.transfer_logs && value != 0 && target != caller; + ledger.on_transfer(caller, target, U256::from(value), false, logged); + ledger.close_start() + } + + /// Returns from the running frame as revm does: its level closes, committed or reverted. + fn end_frame(ledger: &mut Ledger, failed: bool) { + ledger.frame_returning(); + let opened_at = ledger.levels.last().expect("a frame is running").opened_at; + if failed { + ledger.on_revert(opened_at); + } else { + ledger.on_commit(); + } + } + + /// The stop of a data-size crossing. + const fn stop(limit: u64, used: u64, frame_local: bool) -> LimitCheck { + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local } + } + + #[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}"); + } + } + + /// 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 mut held = ledger(limits, false, false, 40); + assert_eq!(held.admit_hint(59), LimitCheck::WithinLimit); + assert_eq!(held.usage().data_size, 99); + assert_eq!(held.admit_hint(2), stop(100, 101, false), "two more bytes cross"); + assert_eq!(held.usage().data_size, 99, "the hint that crossed is not counted"); + assert_eq!(held.admit_hint(1), LimitCheck::WithinLimit, "one more fits exactly"); + assert_eq!(held.usage().data_size, 100, "and is counted"); + + let mut exempt = ledger(limits, true, false, 40); + assert_eq!(exempt.admit_hint(61), LimitCheck::WithinLimit); + assert_eq!(exempt.usage().data_size, 101, "an exempt transaction's hint is counted"); + } + + /// 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 limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(10_000); + let mut ledger = ledger(limits, false, false, 310); + let budget = |ledger: &Ledger| ledger.running_budget().expect("a frame is running").0; + + start_call(&mut ledger, 0, SENDER, CALLEE, 0); + let first = 10_000 - 310; + assert_eq!(budget(&ledger), first); + + start_call(&mut ledger, 1, CALLEE, TARGET, 0); + let child = share_of_remaining(first); + assert_eq!(child, 9_496); + assert_eq!(budget(&ledger), child); + + start_call(&mut ledger, 2, TARGET, SENDER, 0); + let grandchild = share_of_remaining(child); + assert_eq!(budget(&ledger), grandchild); + + start_call(&mut ledger, 3, SENDER, CALLEE, 0); + assert_eq!( + budget(&ledger), + 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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let mut ledger = ledger(limits, false, false, 0); + start_call(&mut ledger, 0, SENDER, CALLEE, 0); + assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(100)); + start_call(&mut ledger, 1, CALLEE, TARGET, 0); + assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(98)); + } + + /// A transaction that is not exempt is stopped wherever it crosses a limit: 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. An exempt transaction is stopped by no + /// limit, at the transaction or at a frame, and what it uses is counted all the same. + #[test] + fn test_a_transaction_is_stopped_where_it_crosses_unless_exempt() { + for exempt in [false, true] { + let mut ledger = ledger(zero_limits(), exempt, false, TX_BODY_SIZE); + let first = start_call(&mut ledger, 0, SENDER, CALLEE, 0); + let second = start_call(&mut ledger, 1, CALLEE, TARGET, 1); + let verdicts = (first.verdict, second.verdict, ledger.check()); + let expected = if exempt { + ( + Some(LimitCheck::WithinLimit), + Some(LimitCheck::WithinLimit), + LimitCheck::WithinLimit, + ) + } else { + let records = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE; + ( + Some(stop(0, TX_BODY_SIZE, false)), + Some(stop(0, records, false)), + stop(0, records, false), + ) + }; + assert_eq!(verdicts, expected, "exempt {exempt}"); + assert_eq!( + ledger.usage(), + LimitUsage { data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 }, + "exempt {exempt}: counted all the same" + ); + } + } + + /// 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 limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE); + let mut ledger = ledger(limits, false, false, TX_BODY_SIZE); + ledger.count_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 ledger = ledger(zero_limits(), true, false, 0); + ledger.count_authorities(SENDER, 2, false); + assert_eq!(ledger.usage(), WRITE_RECORD.times(2)); + } + + /// A transfer log is data size and nothing else: no write record, and no history byte beside + /// the records — 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 ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, TX_BODY_SIZE); + start_call(&mut ledger, 0, SENDER, CALLEE, 1); + start_call(&mut ledger, 1, CALLEE, TARGET, 1); + assert_eq!( + ledger.usage(), + LimitUsage { + data_size: 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", + ); + assert_eq!(ledger.log_and_code_bytes(), 0, "no history byte beside the records"); + } + + /// 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 ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + start_call(&mut ledger, 0, SENDER, CALLEE, 0); + start_call(&mut ledger, 1, CALLEE, TARGET, 1); + assert_eq!(ledger.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + end_frame(&mut ledger, true); + assert_eq!(ledger.usage(), LimitUsage::ZERO); + } + + /// A frame start whose transfer log crosses a limit is stopped at its start, 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; + // 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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap); + let mut ledger = ledger(limits, false, true, 0); + start_call(&mut ledger, 0, SENDER, CALLEE, 0); + let report = start_call(&mut ledger, 1, CALLEE, TARGET, 1); + let expected = + if fits { LimitCheck::WithinLimit } else { stop(needs - 1, needs, true) }; + assert_eq!(report.verdict, Some(expected), "a cap of {cap}"); + } + + // The transaction's own value: one record, the recipient's, and the log. + let needs = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit); + let mut ledger = ledger(limits, false, true, 0); + let report = start_call(&mut ledger, 0, SENDER, CALLEE, 1); + let expected = + if fits { LimitCheck::WithinLimit } else { stop(tx_limit, needs, false) }; + assert_eq!(report.verdict, Some(expected), "a limit of {tx_limit}"); + } + } + + /// A child's return holds its caller to the ledger's check with what the child left it, every + /// time: a failed creation's nonce record lands on the creator unchecked, and the creator is + /// stopped before it runs on when the record puts it over its budget; a success hands its + /// caller no more than the share it gave, and the caller runs on. + #[test] + fn test_a_childs_return_holds_its_caller_to_what_it_left() { + // A frame cap of 100: the transaction's own frame gets 100, a child 98. + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + for (case, left, failed, stopped) in [ + ("a success within its share", 98, false, false), + ("a failed creation's nonce record, within", 60, true, false), + ("a failed creation's nonce record, over the budget", 61, true, true), + ] { + let mut ledger = ledger(limits, false, false, 0); + start_call(&mut ledger, 0, SENDER, CALLEE, 0); + // What the caller kept of its own before the start. + let count = WriteCount { + added: LimitUsage { data_size: left, write_records: 0 }, + ..WriteCount::NONE + }; + assert_eq!(ledger.count_write(&count), LimitCheck::WithinLimit, "{case}"); + if failed { + ledger.open_start(StartFacts { + depth: 1, + caller: CALLEE, + target: None, + transfers_value: false, + }); + let start = ledger.before_creation(); + ledger.after_creation(start, TARGET, Some(checkpoint(&ledger)), false); + let _ = ledger.close_start(); + } else { + start_call(&mut ledger, 1, CALLEE, TARGET, 0); + } + end_frame(&mut ledger, failed); + let check = ledger.check(); + assert_eq!(check.exceeded_limit(), stopped, "{case}: {check:?}"); + if stopped { + assert_eq!(check, stop(100, left + WRITE_RECORD_SIZE, true), "{case}"); + } + } + } + /// 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. @@ -1169,7 +1468,7 @@ mod tests { let moved = SelfDestructResult { had_value: true, ..Default::default() }; let destruction = |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; - let mut logging = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + let mut logging = ledger_from_sender(EvmTxRuntimeLimits::no_limits(), true); let (check, history) = commit(&mut logging, &destruction(TARGET)); assert_eq!(check, LimitCheck::WithinLimit); assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); @@ -1179,7 +1478,7 @@ mod tests { ); let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1); - let mut tight = ledger(limits, false, true, 0); + let mut tight = ledger_from_sender(limits, true); let (check, history) = commit(&mut tight, &destruction(SENDER)); assert_eq!(history, HistoryBytes::None); assert_eq!( @@ -1193,7 +1492,7 @@ mod tests { "the log alone crosses", ); - let mut silent = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + let mut silent = ledger_from_sender(EvmTxRuntimeLimits::no_limits(), false); let _ = commit(&mut silent, &destruction(TARGET)); assert_eq!(silent.usage(), WRITE_RECORD, "no log, no bytes"); } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 8617844d4..84a6f4592 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,8 +1,7 @@ -//! The per-transaction state of the common execution layer. +//! The per-transaction state of the common execution layer beside the journal's ledger. -use alloy_primitives::{Address, Bytes}; +use alloy_primitives::Bytes; use revm::{ - context_interface::context::CodeDeposit, handler::FrameResult, interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; @@ -12,51 +11,44 @@ use alloc as std; use std::vec::Vec; use super::{ - frame_limit::{FrameLimitTracker, Lane}, ledger::{FrameStartRecords, Ledger, Mark, StartSide}, - record::WriteCount, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, StartReport, - FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, - WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, StartReport, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; /// What the common execution layer tracks for the running transaction beside the journal's -/// ledger: Satin's side of each frame start, the stops its frames return, whether it is exempt -/// from every limit, and the figures the settled transaction reports. The per-frame lanes of -/// data-size bytes and write records are kept beside the ledger until their deletion, for the -/// `ledger-shadow` feature to hold them to it. +/// ledger ([`Ledger`]), which counts what the transaction keeps and holds it to the data-size +/// limit: Satin's side of each frame start ([`StartSide`]), 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 reset before each transaction and -/// system call, and is driven by the Host's instruction hooks (the charge of a frame's start) and -/// the frame lifecycle (the frame sides, stops). +/// system call, and is driven by the Host's frame-start hook (the charge of a frame's start) and +/// the frame lifecycle (the frame sides, the stops). /// /// # 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 -/// 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 frame counted goes with its level of the ledger, 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. +/// comes from one of two places — the ledger's verdict for the data size, +/// [`crossed`](Self::crossed) for gas detention's compute stop — and both answer an exempt +/// transaction with [`LimitCheck::WithinLimit`] whatever it crossed. 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, limits: EvmTxRuntimeLimits, /// Whether the transaction is exempt from every per-transaction limit, sticky for the /// transaction. See [`exempt`](Self::exempt). @@ -66,13 +58,6 @@ pub struct AdditionalLimit { /// or the one a frame a child returned into returns when what the child left it put it over a /// limit ([`on_start_return`](Self::on_start_return)). pending_stop: Option, - /// The stop the lanes would leave the frame about to run, which the shadow holds to the - /// ledger's. - lanes_pending_stop: Option, - /// The history gas the transaction's own frame's start gets back, by the ledger's formula, - /// kept once that frame returned for the settlement to give back - /// ([`take_top_level_refund`](Self::take_top_level_refund)). - top_level_refund: u64, /// 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. @@ -80,19 +65,6 @@ 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 /// [`history_gas_spent`](Self::history_gas_spent). intrinsic_history_gas: u64, @@ -102,41 +74,30 @@ pub struct AdditionalLimit { 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. + /// that frame does not keep the record. 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). + /// execution found them, for the frame's side to hold the ledger's count to. 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. + /// starting will make, waiting for that frame's side to be pushed. pending_frame_charge: FrameCharge, + /// The history gas the transaction's own frame's start gets back, kept once that frame + /// returned for the settlement to give back + /// ([`take_top_level_refund`](Self::take_top_level_refund)). + top_level_refund: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, /// The EIP-8037 reservoir the settled transaction left unspent. reservoir_remaining: 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, - /// Satin's side of every frame start, one per frame result revm will return, as the lanes - /// are: what the start's caller paid for its records, what the journal's ledger saw the start - /// count, and the mark a frame revm built is taken back to when it is rewritten into a - /// failure. + /// Satin's side of every frame start, one per frame result revm will return: what the start's + /// caller paid for its records, what the journal's ledger saw the start count, the history + /// allowance the frame was granted, and the mark a frame revm built is taken back to when it + /// is rewritten into a failure. starts: Vec, - /// The write records the transaction's own frame makes, as the charge of their history before - /// execution found them, kept whatever an inspector does: what the shadow holds the frame's - /// refund to. - #[cfg(feature = "ledger-shadow")] - top_level_paid_for: Option, - /// The history gas the lanes gave back for the transaction's own frame's write record, at - /// whichever of the three sites gave it back: what the shadow holds the journal's formula to. - #[cfg(feature = "ledger-shadow")] - top_level_refunded_by_lanes: u64, - /// The journal's formula's answer to the same, once the transaction's own frame returned. - #[cfg(feature = "ledger-shadow")] - top_level_refund_by_formula: Option, } impl AdditionalLimit { @@ -157,45 +118,20 @@ impl AdditionalLimit { /// Clears the state for a new transaction, keeping allocations and the limits. pub(crate) fn reset(&mut self) { - self.tracker.reset(); self.exempt = false; self.pending_stop = None; - self.lanes_pending_stop = None; - self.top_level_refund = 0; 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.top_level_refund = 0; self.history_gas_spent = 0; self.history_bytes = 0; self.reservoir_remaining = 0; - self.transfer_logs = false; self.starts.clear(); - #[cfg(feature = "ledger-shadow")] - { - self.top_level_paid_for = None; - self.top_level_refunded_by_lanes = 0; - self.top_level_refund_by_formula = None; - } - } - - /// 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 */ @@ -220,7 +156,7 @@ impl AdditionalLimit { /// /// 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 + /// [`on_start_return`](Self::on_start_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"); @@ -237,7 +173,8 @@ impl AdditionalLimit { /// 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. + /// before its body is counted; the journal's ledger begins the transaction exempt alongside. + /// See the type's documentation. pub(crate) const fn exempt(&mut self) { self.exempt = true; } @@ -246,9 +183,9 @@ impl AdditionalLimit { /// 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. + /// Gas detention's compute stop comes from here, as the data-size stops come from the + /// ledger's own verdict, so this is where the exemption applies to it: an exempt + /// transaction's verdict is [`LimitCheck::WithinLimit`], whatever it crossed. pub(crate) const fn crossed( &self, kind: LimitKind, @@ -262,30 +199,11 @@ impl AdditionalLimit { LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// The lanes' check of 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. The shadow holds it to - /// the journal's ledger, whose check decides. - 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); - } - } - LimitCheck::WithinLimit - } - /// The stop the running frame returns instead of running another instruction: the one its own /// start left it ([`hold_start`](Self::hold_start)), or the one /// [`on_start_return`](Self::on_start_return) left for a caller its child put over a limit. - /// Taking it clears it, which stops one frame; the lanes' stop for the frame goes with it. + /// Taking it clears it, which stops one frame. pub(crate) const fn stop_before_run(&mut self) -> Option { - self.lanes_pending_stop = None; self.pending_stop.take() } @@ -318,19 +236,18 @@ impl AdditionalLimit { self.pending_stop.is_some() } - /// What the lanes hold the transaction to keep so far, with every running frame counted as - /// if it succeeds; what the transaction keeps is the journal's ledger's - /// ([`MegaContext::limit_usage`](crate::MegaContext::limit_usage)). - #[cfg(test)] - pub(crate) fn usage(&self) -> LimitUsage { - self.tracker.net() - } + /* What the settled transaction reports */ /// 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; + } + /// 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 @@ -386,514 +303,109 @@ impl AdditionalLimit { }; } - /// 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 - } + /* The charges a frame start is paid for */ - /// Records the history gas charged for the transaction's own write record. + /// Records 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 does not keep the record gets it back at the settlement, with the rest of what the + /// frame did not keep. 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)). + /// before execution found them, for that frame's side to hold the ledger's count to once revm + /// decided the start ([`attach_start`](Self::attach_start)). /// - /// 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. + /// Only a transaction that pays history is charged, and so leaves one. pub(crate) const fn stage_top_level_records(&mut self, records: u64) { self.pending_top_level_records = Some(records); - #[cfg(feature = "ledger-shadow")] - { - self.top_level_paid_for = 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.starts.last_mut().map_or(0, |side| side.consume_stipend(amount)) } /// 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. + /// it starts will make: `on_level` for the records that frame's failure takes back, `caller` + /// for the record of the caller's own account, and `records`, the answer the charge was + /// computed from, for the frame's side to hold the ledger's count to. /// - /// The next lane pushed takes it, whether that is the frame's own or the empty one of a frame - /// answered without running. + /// The next side pushed takes it, whether that is the frame's own or that of a frame answered + /// without running. #[inline] pub(crate) const fn stage_frame_charge( &mut self, records: FrameStartRecords, - on_lane: u64, + on_level: u64, caller: u64, ) { - self.pending_frame_charge = FrameCharge { - records: Some(records), - on_lane, - caller, - #[cfg(feature = "ledger-shadow")] - paid_for: Some(records), - }; + self.pending_frame_charge = FrameCharge { records: Some(records), on_level, caller }; } /// Leaves the frame about to start unchecked against the answer its charge was computed from - /// — its caller's at the opcode - /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)), - /// or the transaction's before execution for the transaction's own frame - /// ([`check_top_level_records`](Self::check_top_level_records)): an inspector that may rewrite - /// the frame's input ran between the charge and the count. + /// — its caller's at the opcode, or the transaction's before execution for the transaction's + /// own frame: an inspector that may rewrite the frame's input runs between the charge and the + /// count. pub(crate) const fn waive_start_check(&mut self) { self.pending_frame_charge.records = None; self.pending_top_level_records = None; } - /// 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; - } - - /* Completed writes */ - - /// Commits what a completed write keeps ([`Ledger::write_count`]) to the running frame's lane, - /// and holds the lanes to the limits, for the shadow to hold them to the journal's ledger, - /// whose verdict decides. A record taken back holds nothing. - #[inline] - pub(crate) fn commit_count(&mut self, count: &WriteCount) -> LimitCheck { - if count.taken != LimitUsage::ZERO { - self.tracker.refund(count.taken); - return LimitCheck::WithinLimit; - } - if count.log_bytes != 0 { - self.tracker.record_log_and_code_bytes(count.log_bytes); - } - if count.added == LimitUsage::ZERO { - return LimitCheck::WithinLimit; - } - self.tracker.record(count.added); - self.check() - } - - /* 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 ([`Ledger::admits_tx_body`]) on the journal's - /// ledger's count of the same bytes, 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 }); - } - } - - /// Counts the `bytes` of an Oracle hint on the lanes, as the journal's ledger admits it - /// ([`Ledger::admit_hint`]), for the shadow to hold the two to each other: the limit is - /// checked before the bytes are counted, and a hint that would cross it is not counted. - 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`. - /// - /// The records cannot cross the data-size limit: validation admitted the body with a record for - /// every entry of the authorization list ([`Ledger::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)); - 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 */ - - /// 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. The lane follows the frame's journal - /// checkpoint: a frame that fails discards both the log and its bytes. + /// 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. /// - /// The count is made as the frame starts, before revm decides the start, and nothing is held - /// to a limit until revm has: a start revm builds the frame for is held to the limits before - /// the frame runs ([`hold_built_start`](Self::hold_built_start)), and one revm answers once - /// the answer is known ([`check_start`](Self::check_start)); a start revm refuses on its - /// caller's account made nothing, and its lane is popped with its failure, or stands for - /// nothing ([`withdraw_refused_start`](Self::withdraw_refused_start)). A start past the - /// call-stack limit, which the depth guard answers before it reaches here, gets an empty - /// lane ([`push_empty_frame`](Self::push_empty_frame)). - pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) { - self.frame_began = true; - self.push_lane(input, depth); - if self.frame_start_transfer_log(input) { - self.tracker.record(TRANSFER_LOG); - } - } - - /// The lanes' verdict on the start of the frame revm just built, which they would leave the - /// frame as the stop it returns on its first run; the shadow holds it to the journal's - /// ledger's, which decides ([`hold_start`](Self::hold_start)). + /// 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 hold_built_start(&mut self) -> LimitCheck { - let check = self.check(); - if check.exceeded_limit() { - self.lanes_pending_stop = Some(check); - } - check - } - - /// The verdict on the start of the frame revm just answered without building it, the - /// writes its start made counted: a crossing means the answer must give way to the stop. - pub(crate) fn check_start(&self) -> LimitCheck { - self.check() - } - - /// Withdraws the count of the start of the frame revm just answered, a creation revm refused - /// on its creator's account before it wrote anything: an empty lane stands in for the - /// frame's, so the creation counts no record, its creator's account is no more recorded than - /// before, and its caller gets back, when the lane is popped, all it paid for the records. - pub(crate) fn withdraw_refused_start(&mut self) { - if let Some(lane) = self.tracker.current_mut() { - lane.creator_record = false; - } - self.tracker.discard_running_lane(); - } - - /// Counts the code a creation deposits on the creation's own lane, and holds the lanes to the - /// data-size limit with it, for the shadow to hold them to the journal's ledger, which counts - /// the same bytes on the creation's level ([`Ledger::count_code`]) and decides. The bytes are - /// data size and history beside the write records. Empty code deposits nothing. - pub(crate) fn on_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> LimitCheck { - let bytes = deposit.code.len() as u64; - if bytes == 0 { - return LimitCheck::WithinLimit; - } - 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); - self.check() + pub(crate) fn try_consume_stipend(&mut self, amount: u64) -> u64 { + self.starts.last_mut().map_or(0, |side| side.consume_stipend(amount)) } - /// 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) - } + /* The frame side */ - 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); - self.push_start(depth, charge); - 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); - #[cfg(feature = "ledger-shadow")] - self.note_paid_for(charge.paid_for, 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) { - if let Some(side) = self.starts.last_mut() { - side.grant_stipend(storage_call_stipend()); - } - } - } - FrameInput::Create(inputs) => { - let records = self.records_the_caller_paid_for(input, charge.records); - #[cfg(feature = "ledger-shadow")] - if depth > 0 { - self.note_paid_for(charge.paid_for, 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); + /// Pushes Satin's side of the start of the frame `input` asks for at `depth`, which revm + /// decides next: what its caller paid for the records the start makes, and, for a + /// value-transferring `CALL` or `CALLCODE` below the transaction's own frame, the history + /// allowance the frame is granted ([`storage_call_stipend`](crate::storage_call_stipend)). + /// What the ledger then sees the start count is attached once revm decided it + /// ([`attach_start`](Self::attach_start)). + pub(crate) fn push_start(&mut self, input: &FrameInput, depth: usize) { + self.push_side(depth); + if let FrameInput::Call(inputs) = input { + if depth > 0 && grants_stipend(inputs) { + if let Some(side) = self.starts.last_mut() { + side.grant_stipend(storage_call_stipend()); } } - // 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 facts revm's instruction hands the frame-start hook, 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 the input revm builds carries the caller, target and value - /// the hook was handed, and nothing between the two changes it: 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. - /// - /// An inspector that may rewrite the input runs between the two, and can split them: under one - /// the frame is not checked ([`waive_start_check`](Self::waive_start_check)). - 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)), and under one the - /// frame is not checked ([`waive_start_check`](Self::waive_start_check)). A divergence trips - /// here in every other 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) { - #[cfg(feature = "ledger-shadow")] - self.note_paid_for(self.top_level_paid_for, counted); - 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, - /// counted as the frame starts ([`start_records`](Self::start_records)). - pub(crate) fn frame_start_records(&self, input: &FrameInput) -> FrameStartRecords { - match input { - FrameInput::Call(inputs) => self.start_records( - inputs.caller, - Some(inputs.target_address), - inputs.transfers_value(), - ), - FrameInput::Create(inputs) => self.start_records(inputs.caller(), None, true), - FrameInput::Empty => FrameStartRecords::NONE, - } + /// Pushes the side of a frame at `depth` answered without revm deciding its start — by the + /// depth guard, an interceptor or an inspector — which keeps the frame sides aligned with the + /// results revm returns. Such a frame makes none of the records its caller paid for, so the + /// whole charge comes back when its side is popped, whatever the answer was. + pub(crate) fn push_answered_start(&mut self, depth: usize) { + self.push_side(depth); } - /// The write records a frame's start makes at a depth above the transaction's own frame: a - /// call from `caller` to `target` that transfers value or not, or a creation (`target` is - /// `None`). `on_lane` are the records the frame's failure discards, `caller` whether its start - /// also writes the caller's own account. - /// - /// A call that moves no value writes nothing. A value call writes its recipient, unless that is - /// the caller itself or the transaction's sender, whose account the body counts. A creation - /// writes the account it creates. Either writes the caller's account — a transfer's sender, a - /// creation's creator nonce — unless the caller's frame already recorded it. - /// - /// The opcode that starts the frame pays for all of them, after the gas it forwards was taken, - /// 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. The answer is asked twice, at the opcode - /// ([`Ledger::start_records`]) and as the frame starts - /// ([`frame_start_records`](Self::frame_start_records)), and the two are checked against each - /// other ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). - fn start_records( - &self, - caller: Address, - target: Option
, - transfers_value: bool, - ) -> FrameStartRecords { - let caller_recorded = self.tracker.current().is_some_and(|lane| lane.account_recorded); - let Some(target) = target else { - return FrameStartRecords { on_lane: 1, caller: !caller_recorded }; - }; - if !transfers_value { - return FrameStartRecords::NONE; - } - let writes_target = target != caller && target != self.sender; - FrameStartRecords { on_lane: u64::from(writes_target), caller: !caller_recorded } - } - - /// 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); - } - } - - /// 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. - pub(crate) fn set_frame_creator(&mut self, creator: Address) { - let sender = self.sender; - if let Some(lane) = self.tracker.current_mut() { - lane.address = Some(creator); - lane.account_recorded = creator == sender; - } - } - - /// Takes back, on the lanes, 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. The journal's - /// ledger takes back the same record ([`Ledger::take_back_creator_record`]) and decides; the - /// shadow holds the lanes to it. 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.lanes_pending_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, depth: usize) { - self.frame_began = true; + /// Pushes a side at `depth` carrying the charge waiting for it: the opcode's for a frame below + /// the transaction's own, and, for the transaction's own frame, what was charged before + /// execution for the write record it makes. + fn push_side(&mut self, depth: usize) { let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - self.push_start(depth, charge); - self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); - } - - /* The frame side */ - - /// Pushes Satin's side of a frame start at `depth`, whose caller paid `charge` for the records - /// the start makes; the transaction's own frame was paid for before execution. - fn push_start(&mut self, depth: usize, charge: FrameCharge) { - let (on_level, caller) = if depth == 0 { - (self.top_level_write_record_gas, 0) + let (on_level, caller, records) = if depth == 0 { + let records = self + .pending_top_level_records + .take() + .map(|on_level| FrameStartRecords { on_level, caller: false }); + (self.top_level_write_record_gas, 0, records) } else { - (charge.on_lane, charge.caller) + (charge.on_level, charge.caller, charge.records) }; - self.starts.push(StartSide::new(depth, on_level, caller)); - } - - /// Notes, for the shadow, whether the records the lanes count for the latest start, `counted`, - /// are those its charge paid for (`paid_for`): an inspector that rewrites a start's input can - /// split them, and then the lanes' refund and the journal's formula part by design. - #[cfg(feature = "ledger-shadow")] - fn note_paid_for(&mut self, paid_for: Option, counted: T) { - let comparable = paid_for.is_none_or(|paid| paid == counted); - if let Some(side) = self.starts.last_mut() { - side.set_comparable(comparable); - } + self.starts.push(StartSide::new(depth, on_level, caller, records)); } /// Attaches what the journal's ledger saw the latest start count, and the mark a frame revm - /// built is taken back to, to that start's side. + /// built is taken back to, to that start's side, and holds the count to the records the start's + /// charge was computed from ([`StartSide::attach`]). pub(crate) fn attach_start(&mut self, report: StartReport, mark: Option) { if let Some(side) = self.starts.last_mut() { side.attach(report, mark); @@ -910,79 +422,6 @@ impl AdditionalLimit { self.starts.len() } - /// What the lanes hold the transaction and the running frame to, for the shadow. - #[cfg(feature = "ledger-shadow")] - pub(crate) fn shadow_view(&self) -> super::shadow::LanesView { - super::shadow::LanesView { - usage: self.tracker.net(), - log_and_code_bytes: self.tracker.log_and_code_bytes(), - frames: self.tracker.depth(), - running: self.tracker.current().map(|lane| (lane.budget, lane.net())), - check: self.check(), - } - } - - /// The stop the lanes would leave the running frame to return before it runs on, for the - /// shadow. - #[cfg(any(test, feature = "ledger-shadow"))] - pub(crate) const fn shadow_pending_stop(&self) -> Option { - self.lanes_pending_stop - } - - /// Notes, for the shadow, history the lanes gave back for the transaction's own frame's record; - /// nothing without the `ledger-shadow` feature. - #[inline(always)] - pub(crate) const fn note_top_level_refund(&mut self, gas: u64) { - #[cfg(feature = "ledger-shadow")] - { - self.top_level_refunded_by_lanes = self.top_level_refunded_by_lanes.saturating_add(gas); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = gas; - } - - /// Notes, for the shadow, what the journal's formula gives back for the transaction's own - /// frame's record once that frame returned. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn shadow_set_top_level_refund_by_formula(&mut self, gas: u64) { - self.top_level_refund_by_formula = Some(gas); - } - - /// What the lanes gave back for the transaction's own frame's record, and what the formula - /// gives back (`None` when the frame never started), for the shadow. - #[cfg(feature = "ledger-shadow")] - pub(crate) const fn shadow_top_level_refunds(&self) -> (u64, Option) { - (self.top_level_refunded_by_lanes, self.top_level_refund_by_formula) - } - - /// 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. The lanes hold the caller to its limits when the - /// return handed it what no check held it to — a failed creation's nonce record, which lands - /// on the creator, or a success past the frame's own budget, which no frame returns — and a - /// debug build asserts any other return leaves it within them. The shadow holds the lanes' - /// refund and stop to the journal's ledger's ([`on_start_return`](Self::on_start_return)). - /// - /// Returns the history gas the lanes would give the caller back for records this frame did - /// not keep. - #[must_use = "the shadow holds the lanes' refund to the ledger's"] - pub(crate) fn on_frame_return(&mut self, result: &FrameResult) -> u64 { - 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.lanes_pending_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 - } - /// Pops the side of the start of the frame `result` returns from, once revm closed the frame's /// level, and settles what the start and the frame leave behind, as the journal's `ledger` /// holds them: @@ -1032,46 +471,6 @@ impl AdditionalLimit { self.top_level_refund = 0; 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. - /// - /// 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"); - } - } -} - -/// `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. -pub(super) 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 @@ -1081,24 +480,6 @@ fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { 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. /// @@ -1114,55 +495,35 @@ 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 records on the frame's own level cost. + on_level: u64, /// What the record of the caller's own account cost. caller: u64, - /// The same records as [`records`](Self::records), kept when an inspector waives the check. - #[cfg(feature = "ledger-shadow")] - paid_for: Option, } impl FrameCharge { /// Nothing charged. - const NONE: Self = Self { - records: None, - on_lane: 0, - caller: 0, - #[cfg(feature = "ledger-shadow")] - paid_for: None, - }; + const NONE: Self = Self { records: None, on_level: 0, caller: 0 }; } #[cfg(test)] mod tests { use super::*; - use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; + use crate::{ + limit::{ledger::StartId, StartFacts}, + test_utils::MemoryDatabase, + MegaContext, MegaSpecId, + }; use alloy_primitives::{address, Address, Bytes, U256}; - use revm::interpreter::{CallInput, CallValue}; + use revm::{ + context::{ContextTr, JournalTr}, + 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()), @@ -1189,122 +550,114 @@ mod tests { })) } - /// 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"); + /// What the ledger reports of a start revm made and held to the limits: `on_level` records on + /// the frame's level, and the caller's own record (`caller`) on it or, for a creation, below. + fn report(on_level: u64, caller: bool, creation: bool) -> StartReport { + StartReport { + start: Some(StartId::default()), + on_level, + caller_on_level: caller && !creation, + creator_record: caller && creation, + transfer_log: false, + refused: false, + verdict: Some(LimitCheck::WithinLimit), + } } - /// 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 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"); + } } - /// 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. + /// The allowance is the started frame's, below the transaction's own frame: its side draws on + /// it, and nothing is left once the side is popped. The transaction's own frame is granted + /// none, however it was started. #[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 }, + fn test_the_allowance_is_granted_to_the_frame_a_value_call_starts() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let ledger = ctx.ledger(); + let stipend = storage_call_stipend(); + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + assert_eq!(limit.try_consume_stipend(1), 0, "the transaction's own frame has none"); + limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + assert_eq!(limit.try_consume_stipend(stipend - 1), stipend - 1); + assert_eq!(limit.try_consume_stipend(5), 1, "what is left of it"); + assert_eq!(limit.try_consume_stipend(5), 0); + let result = crate::synthetic_frame_result( + &call_from_to(CALLEE, TARGET, U256::from(1)), + InstructionResult::Stop, + Bytes::new(), ); + let _ = limit.on_start_return(ledger, &result); + assert_eq!(limit.try_consume_stipend(5), 0, "the caller's own frame has none"); } - /// A creation revm refused on its creator's account counts nothing once its count is - /// withdrawn: whatever revm answered — `OutOfFunds`, or the success with no address it gives a - /// creator whose nonce cannot be bumped — its records are not kept, its creator's account is - /// not recorded, and its caller gets back all it paid, the nonce record's charge included. + /// An exempt layer answers every crossing of gas detention's as within the limits, in any + /// dimension and at the transaction or at a frame; a reset ends the exemption, and the next + /// transaction is held to its limits again. #[test] - fn test_a_refused_start_counts_nothing_and_gives_its_charge_back() { - for answered in [InstructionResult::OutOfFunds, InstructionResult::Return] { - let mut limit = with_the_transactions_frame(); - let input = creation(CALLEE, U256::from(1)); - let records = limit.frame_start_records(&input); - assert_eq!(records, FrameStartRecords { on_lane: 1, caller: true }); - limit.stage_frame_charge(records, 3, 4); - limit.on_frame_init(&input, 1); - limit.withdraw_refused_start(); - assert_eq!(limit.usage(), LimitUsage::ZERO, "{answered:?}"); - let result = crate::synthetic_frame_result(&input, answered, Bytes::new()); - assert_eq!(limit.on_frame_return(&result), 3 + 4, "{answered:?}: the whole charge"); - assert!(!limit.tracker.current().unwrap().account_recorded, "{answered:?}"); - assert_eq!(limit.usage(), LimitUsage::ZERO, "{answered:?}"); + fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { + let mut limit = AdditionalLimit::default(); + limit.exempt(); + 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}"); + } } + limit.reset(); + assert!(!limit.is_exempt()); + assert_eq!( + limit.crossed(LimitKind::ComputeGas, 0, 1, false), + LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 0, + used: 1, + frame_local: false + }, + "after a reset the transaction is held to its limits" + ); } - /// 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. + /// The records the ledger counts for a start are the records its caller was charged for: a + /// value transfer records the caller's account and the recipient's, the two the charge was + /// computed from, and a creation the created account and its creator's nonce. A start revm + /// refused, or failed before its level opened, counted nothing and is not held to the charge. #[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(1); + fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1, 1); + limit.push_start(&inner, 1); + limit.attach_start(report(1, true, false), None); - 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"); + limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: false }, 1, 0); + limit.push_start(&inner, 1); + limit.attach_start(report(1, false, true), None); - 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); - let kept = limit.usage(); - limit.settle_history_bytes( - true, - kept.write_records, - limit.tracker.log_and_code_bytes(), - ); - assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); - } + limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1, 1); + limit.push_start(&inner, 1); + let refused = StartReport { verdict: None, refused: true, ..report(0, false, false) }; + limit.attach_start(refused, None); } /// A charge computed from a different answer than the count is what a rewrite that turns one @@ -1314,478 +667,162 @@ mod tests { #[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(); + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + limit.attach_start(report(1, true, false), None); } - /// 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. + /// The transaction's own frame is held to the records its history was charged for before + /// execution: its value's recipient, or 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); + for records in [0, 1] { 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"); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(records)), 0); + limit.attach_start(report(records, false, false), None); } } - /// 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. + /// A transaction's own frame that makes another record than its history paid for trips the + /// check, rather than counting data size no history matches or keeping history no data size + /// matches. #[test] #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] + #[should_panic(expected = "changed after its caller was charged for them")] 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); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + limit.attach_start(report(1, false, false), None); } - /// 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. + /// Under an inspector that may rewrite a start, the check is waived: the start its charge paid + /// for may not be the one revm made. #[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() { + fn test_a_waived_start_is_not_held_to_its_charge() { 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) - } - - /// On the lanes, 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. The journal's ledger checks the caller on every return, and the shadow holds the two - /// to each other. - #[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.shadow_pending_stop(); - 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); - } - - /// 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); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let first = limit.check_start(); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - [first, limit.check_start()] - } - - /// 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()); - } - - /// 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, - ))) + limit.waive_start_check(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + limit.attach_start(report(1, false, false), None); + limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); + limit.waive_start_check(); + limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + limit.attach_start(report(1, true, false), None); } - /// 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. + /// 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: the whole + /// charge comes back when its side is popped, and the caller it returns into is held to the + /// ledger's check. + /// + /// 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_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:?}"); + fn test_a_frame_answered_without_running_gives_the_whole_charge_back() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let ledger = ctx.ledger(); + for answer in + [InstructionResult::CallTooDeep, InstructionResult::Revert, InstructionResult::Stop] + { + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1_000, 2_000); + limit.push_answered_start(1); + let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); + let (_, refund) = limit.on_start_return(ledger, &result).expect("the side"); + assert_eq!(refund, 3_000, "{answer:?}: all of it back"); + assert_eq!(limit.stop_before_run(), None, "{answer:?}: the caller runs on"); + assert_eq!(limit.starts_open(), 1, "{answer:?}: the caller's side is left"); } } - /// 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. + /// The transaction's own frame's side keeps what was charged before execution for the write + /// record the frame makes, and gives it to the settlement when the frame did not keep the + /// record: a frame that failed, and a frame answered before revm decided it. A frame that kept + /// its record gives nothing back, and a transaction whose first frame never started has + /// nothing to give back. #[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); + fn test_the_top_level_record_comes_back_once_at_the_settlement() { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); 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); - let kept = limit.usage(); - limit.settle_history_bytes(true, kept.write_records, limit.tracker.log_and_code_bytes()); - 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); - limit.on_frame_init(&inner, 1); - let check = limit.check_start(); - if fits { - assert_eq!(check, LimitCheck::WithinLimit, "exactly the budget"); + let ended = |result| crate::synthetic_frame_result(&outer, result, Bytes::new()); + // The start kept: a level revm committed. + for (case, failed, refund) in [("kept", false, 0), ("failed", true, 7)] { + let mut limit = AdditionalLimit::default(); + limit.set_top_level_write_record_gas(7); + limit.push_start(&outer, 0); + ctx.ledger_mut().begin_transaction(false, false, 0); + ctx.ledger_mut().open_start(StartFacts { + depth: 0, + caller: SENDER, + target: Some(CALLEE), + transfers_value: true, + }); + let checkpoint = ctx.journal_mut().checkpoint(); + ctx.ledger_mut().on_transfer(SENDER, CALLEE, U256::from(1), false, false); + let report = ctx.ledger_mut().close_start(); + limit.attach_start(report, None); + ctx.ledger_mut().frame_returning(); + if failed { + ctx.journal_mut().checkpoint_revert(checkpoint); } else { - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: needs - 1, - used: needs, - frame_local: true, - }, - ); + ctx.journal_mut().checkpoint_commit(); } + let result = + ended(if failed { InstructionResult::Revert } else { InstructionResult::Stop }); + let (side, caller) = limit.on_start_return(ctx.ledger(), &result).expect("the side"); + assert_eq!(side.depth(), 0, "{case}"); + assert_eq!(caller, 0, "{case}: the transaction's own frame has no caller to refund"); + assert_eq!(limit.take_top_level_refund(), refund, "{case}"); + assert_eq!(limit.take_top_level_refund(), 0, "{case}: taken once"); } - // 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)); - limit.on_frame_init(&first, 0); - let check = limit.check_start(); - 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, - }, - ); - } - } + // Answered before revm decided it: nothing counted, everything back. + let mut limit = AdditionalLimit::default(); + limit.set_top_level_write_record_gas(7); + limit.push_answered_start(0); + let _ = limit.on_start_return(ctx.ledger(), &ended(InstructionResult::Stop)); + assert_eq!(limit.take_top_level_refund(), 7); - /// 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)); + // Never started: no side, nothing back. + let mut limit = AdditionalLimit::default(); + limit.set_top_level_write_record_gas(7); + assert!(limit.on_start_return(ctx.ledger(), &ended(InstructionResult::OutOfGas)).is_none()); + assert_eq!(limit.take_top_level_refund(), 0); } - /// 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. + /// The stop the transaction reports is the crossing its own frame's result is made of, read as + /// that frame returns, and only while the result is still the stop's revert. #[test] - fn test_only_a_value_call_or_callcode_is_granted_an_allowance() { - for scheme in [ - CallScheme::Call, - CallScheme::CallCode, - CallScheme::DelegateCall, - CallScheme::StaticCall, + fn test_limit_exceeded_is_the_stop_the_own_frames_result_is_made_of() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let outer = call_from_to(SENDER, CALLEE, U256::ZERO); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 3, + used: 4, + frame_local: false, + }; + for (case, output, result, reported) in [ + ("the stop's revert", stop.revert_data(), InstructionResult::Revert, Some(stop)), + ("another output", Bytes::new(), InstructionResult::Revert, None), + ("a success", stop.revert_data(), InstructionResult::Return, None), ] { - 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"); + let mut limit = AdditionalLimit::default(); + limit.push_start(&outer, 0); + let data = limit.note_frame_stop(&stop); + assert_eq!(data, stop.revert_data(), "{case}"); + let result = crate::synthetic_frame_result(&outer, result, output); + let _ = limit.on_start_return(ctx.ledger(), &result); + assert_eq!(limit.limit_exceeded().copied(), reported, "{case}"); } } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index c710ade0f..bf4a73506 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -6,22 +6,19 @@ //! 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 anything the ledger +//! counts, 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`]). A write an opcode makes is -//! counted once the opcode completed, in the Host's completed-write hook, which revm calls after -//! every charge the opcode makes. -//! -//! The journal ([`MegaJournal`](crate::MegaJournal)) counts the same quantities in its ledger, at -//! the journal's writes and from the same hooks, and revm's checkpoint reverts rewind it. The -//! ledger takes every decision; the lanes are kept beside it until their deletion, and under the -//! `ledger-shadow` feature they are held to the ledger wherever the two must agree, a mismatch -//! panicking. +//! What the data-size limit meters — data-size bytes and write records — is counted by the +//! journal's ledger ([`MegaJournal`](crate::MegaJournal), `ledger.rs`), on one level per open +//! checkpoint of revm's journal, at the journal's writes and from the Host's hooks, and revm's +//! checkpoint reverts rewind it: what the ledger holds is what the journal keeps, whoever reverted +//! what. A write an opcode makes is counted once the opcode completed, in the Host's +//! completed-write hook, which revm calls after every charge the opcode makes. Beside the ledger, +//! [`AdditionalLimit`] keeps Satin's side of each frame start, the stops and the settled figures. //! //! # The data-size limit //! @@ -45,16 +42,16 @@ //! - 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 +//! - deployed code, on the creation's level 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 — 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 +//! level 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 as the frame starts and held to the limits once revm decided it, on @@ -82,7 +79,7 @@ //! //! # Write records //! -//! The write-record count the lanes keep is the KV count a node reports: one record per account +//! The write-record count the ledger keeps 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 @@ -135,18 +132,14 @@ //! 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; mod ledger; #[allow(clippy::module_inception)] mod limit; mod record; -pub(crate) mod shadow; #[cfg(test)] pub(crate) use ledger::StartSide; -pub(crate) use ledger::{ - ledger_assert, FrameIdentity, FrameStartRecords, Ledger, Mark, StartFacts, StartReport, -}; +pub(crate) use ledger::{FrameIdentity, FrameStartRecords, Ledger, Mark, StartFacts, StartReport}; pub use limit::AdditionalLimit; pub(crate) use record::HistoryBytes; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 564b6c330..8d9fde71e 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -37,8 +37,8 @@ pub(crate) enum HistoryBytes { Taken(u64), } -/// What a completed write keeps, as the lanes and the journal's ledger both count it: what it adds, -/// what it takes back, and the log bytes among what it adds. +/// What a completed write keeps, as the journal's ledger counts it: what it adds, what it takes +/// back, and the log bytes among what it adds. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct WriteCount { /// What the write adds: a record, a log's bytes, a transfer log. diff --git a/crates/mega-evm/src/limit/shadow.rs b/crates/mega-evm/src/limit/shadow.rs deleted file mode 100644 index a4d07c66e..000000000 --- a/crates/mega-evm/src/limit/shadow.rs +++ /dev/null @@ -1,256 +0,0 @@ -//! The shadow: the lanes held to the journal's ledger wherever the two must agree. -//! -//! The ledger ([`Ledger`]) takes every decision; the lanes ([`AdditionalLimit`]) count the same -//! writes beside it until they go. Under the `ledger-shadow` feature the engine compares the two -//! at the points of a transaction's life where both describe the same thing, and panics on the -//! first mismatch. Each point is a function here, called where the point is; without the feature -//! every one of them compiles to nothing. -//! -//! - After a completed write is counted, a code deposit, an admitted hint and the keyless take-back -//! of a creator's record: the verdicts, then what the transaction keeps, the history bytes beside -//! its records, the number of frames, the running frame's budget and usage, and the check. -//! - When revm built a frame: the start's verdict, then the same, which holds the new frame's -//! budget and usage — a creation's measured from before its creator's record. -//! - When revm answered a start: the verdict the ledger captured while the start's level was open, -//! or, for a call gas detention answers without running, the hypothetical one. -//! - When a frame returns: the history its caller gets back, by the ledger's formula, the check of -//! the caller it returns into, then the totals; for the transaction's own frame, the formula's -//! refund is kept for the settlement. -//! - When the transaction's own frame settles: the history its own record got back, at whichever -//! site the lanes gave it back, then the totals. -//! -//! Between a start revm answered and that start's return the two differ by design: the ledger has -//! already taken back what a failed answer journaled, and the lanes take it back when the answer's -//! lane is popped. Nothing is compared there. A refund is compared only where the records the -//! lanes counted for a start are the ones its charge paid for: an inspector that rewrites a start's -//! input can split them, and then the lanes keep a charge the formula gives back. -//! -//! A tool's checkpoint that enclosed a frame start and is reverted takes back what the frames -//! inside it kept; the ledger follows it and the lanes cannot. From then on the transaction is not -//! compared ([`Ledger::diverged`]). - -use super::{ledger::StartSide, AdditionalLimit, Ledger, LimitCheck, StartReport}; - -#[cfg(feature = "ledger-shadow")] -mod compare { - use super::super::{AdditionalLimit, Ledger, LimitCheck, LimitUsage}; - - /// What the lanes hold the transaction and the running frame to. - #[derive(Debug)] - pub(crate) struct LanesView { - /// What the transaction keeps. - pub(crate) usage: LimitUsage, - /// The log and code bytes it keeps. - pub(crate) log_and_code_bytes: u64, - /// The frames on the call stack. - pub(crate) frames: usize, - /// The running frame's budget and what it keeps. - pub(crate) running: Option<(u64, LimitUsage)>, - /// The check. - pub(crate) check: LimitCheck, - } - - /// Panics with the point of the transaction and the quantity on which the two disagree. - pub(super) fn equal( - lanes: &T, - ledger: &T, - at: &str, - what: &str, - ) { - assert!( - lanes == ledger, - "ledger shadow mismatch at {at}: {what}: lanes {lanes:?}, ledger {ledger:?}" - ); - } - - /// Holds what the two hold the transaction and the running frame to. - pub(super) fn agree(lanes: &AdditionalLimit, ledger: &Ledger, at: &str) { - if ledger.diverged() { - return; - } - let view = lanes.shadow_view(); - equal(&view.usage, &ledger.usage(), at, "usage"); - equal(&view.log_and_code_bytes, &ledger.log_and_code_bytes(), at, "log and code bytes"); - equal(&view.frames, &ledger.frame_levels(), at, "frames"); - equal(&view.running, &ledger.running_budget(), at, "running frame's budget and usage"); - equal(&view.check, &ledger.check(), at, "check"); - } - - /// Holds a verdict the lanes reached (`None` where they held nothing) to the ledger's. - pub(super) fn verdict( - lanes: Option, - ledger_verdict: Option, - ledger: &Ledger, - at: &str, - ) { - if !ledger.diverged() { - equal(&lanes, &ledger_verdict, at, "verdict"); - } - } - - /// The ledger's check, as a verdict: `None` when it holds. - pub(super) fn crossing(ledger: &Ledger) -> Option { - let check = ledger.check(); - check.exceeded_limit().then_some(check) - } -} - -#[cfg(feature = "ledger-shadow")] -pub(crate) use compare::LanesView; - -/// A completed write, counted on both with the lanes' verdict and the ledger's. -#[inline(always)] -pub(crate) fn completed_write( - lanes: &AdditionalLimit, - ledger: &Ledger, - lanes_verdict: LimitCheck, - ledger_verdict: LimitCheck, -) { - #[cfg(feature = "ledger-shadow")] - { - let at = "a completed write"; - compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, lanes_verdict, ledger_verdict); -} - -/// A creation's deposited code, counted on both with the lanes' verdict and the ledger's. -#[inline(always)] -pub(crate) fn code_deposit( - lanes: &AdditionalLimit, - ledger: &Ledger, - lanes_verdict: LimitCheck, - ledger_verdict: LimitCheck, -) { - #[cfg(feature = "ledger-shadow")] - { - let at = "a code deposit"; - compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, lanes_verdict, ledger_verdict); -} - -/// An Oracle hint, admitted or refused by both with the lanes' verdict and the ledger's. -#[inline(always)] -pub(crate) fn hint( - lanes: &AdditionalLimit, - ledger: &Ledger, - lanes_verdict: LimitCheck, - ledger_verdict: LimitCheck, -) { - #[cfg(feature = "ledger-shadow")] - { - let at = "an Oracle hint"; - compare::verdict(Some(lanes_verdict), Some(ledger_verdict), ledger, at); - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, lanes_verdict, ledger_verdict); -} - -/// A keyless deployment's take-back of its signer's nonce record: whether the lanes took one back -/// (`lanes_taken`) and the ledger did (`ledger_taken`), then the stop the lanes left the call. -#[inline(always)] -pub(crate) fn keyless_take_back( - lanes: &AdditionalLimit, - ledger: &Ledger, - lanes_taken: bool, - ledger_taken: bool, -) { - #[cfg(feature = "ledger-shadow")] - if !ledger.diverged() { - let at = "a keyless take-back"; - compare::equal(&lanes_taken, &ledger_taken, at, "taken back"); - let pending = lanes.shadow_pending_stop(); - compare::verdict(pending, compare::crossing(ledger), ledger, at); - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, lanes_taken, ledger_taken); -} - -/// A start revm built, held by the lanes to `lanes_verdict` and seen by the ledger as `report`. -#[inline(always)] -pub(crate) fn built_start( - lanes: &AdditionalLimit, - ledger: &Ledger, - lanes_verdict: LimitCheck, - report: &StartReport, -) { - #[cfg(feature = "ledger-shadow")] - { - let at = "a built start"; - compare::verdict(Some(lanes_verdict), report.verdict, ledger, at); - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, lanes_verdict, report); -} - -/// A start revm answered, or gas detention answered without revm, held by the lanes to -/// `lanes_verdict` (`None` where they held nothing) and seen by the ledger as `report`. -#[inline(always)] -pub(crate) fn answered_start( - ledger: &Ledger, - lanes_verdict: Option, - report: &StartReport, -) { - #[cfg(feature = "ledger-shadow")] - compare::verdict(lanes_verdict, report.verdict, ledger, "an answered start"); - #[cfg(not(feature = "ledger-shadow"))] - let _ = (ledger, lanes_verdict, report); -} - -/// The return of the frame `side` stands for, whose caller the lanes gave back `refund`. -/// -/// Below the transaction's own frame, the refund is held to the ledger's formula, where the records -/// the lanes counted are the ones the charge paid for, and the stop the lanes left the caller to -/// the ledger's check. The transaction's own frame has no caller: the formula's refund of its -/// record is kept for the settlement ([`settlement`]). -#[inline(always)] -pub(crate) fn frame_return( - lanes: &mut AdditionalLimit, - ledger: &Ledger, - refund: u64, - side: &StartSide, -) { - #[cfg(feature = "ledger-shadow")] - { - let at = "a frame's return"; - if side.depth() == 0 { - if side.comparable() { - lanes.shadow_set_top_level_refund_by_formula(side.refund(ledger)); - } - } else if !ledger.diverged() { - if side.comparable() { - compare::equal(&refund, &side.refund(ledger), at, "refund"); - } - let pending = lanes.shadow_pending_stop(); - compare::verdict(pending, compare::crossing(ledger), ledger, "a caller's check"); - } - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger, refund, side); -} - -/// The settlement of the transaction's own frame: the history its own record got back, at -/// whichever site the lanes gave it back, held to the ledger's formula, then the totals. -#[inline(always)] -pub(crate) fn settlement(lanes: &AdditionalLimit, ledger: &Ledger) { - #[cfg(feature = "ledger-shadow")] - { - let at = "the transaction's settlement"; - let (by_lanes, by_formula) = lanes.shadow_top_level_refunds(); - if let (false, Some(by_formula)) = (ledger.diverged(), by_formula) { - compare::equal(&by_lanes, &by_formula, at, "the own frame's record refund"); - } - compare::agree(lanes, ledger, at); - } - #[cfg(not(feature = "ledger-shadow"))] - let _ = (lanes, ledger); -} diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index a2e3d4cb1..83e99a548 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -207,7 +207,7 @@ pub(crate) fn run( /// /// 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 +/// its forward and the reservoir it inherits. The call's level 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( @@ -225,10 +225,9 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - ctx.additional_limit.set_frame_creator(deployment.signer); ctx.ledger_mut().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); + if let Some((on_level, caller)) = deployment.record_charges { + ctx.additional_limit.stage_frame_charge(deployment.records, on_level, caller); } let mut create = CreateInputs::new( deployment.signer, @@ -429,11 +428,11 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } - let records = FrameStartRecords { on_lane: 1, caller: signer != ctx.tx().caller() }; + let records = FrameStartRecords { on_level: 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, + records.on_level, u64::from(records.caller), ); if charged.is_none() { diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 2cfeda81a..1b8b143a0 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -20,7 +20,6 @@ use revm::{ }; use crate::{ - limit::shadow, system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, ExternalEnvTypes, MegaContext, MegaHaltReason, }; @@ -254,16 +253,13 @@ fn take_back_bump( if moved_value { return Ok(()); } - let lanes = ctx.additional_limit.take_back_creator_record(); - let taken = ctx.ledger_mut().take_back_creator_record(); - if taken { + if ctx.ledger_mut().take_back_creator_record() { // A stop the record left the call, by putting it over a limit, goes with it: the call is // held to its limits again without the record. let check = ctx.ledger().check(); ctx.additional_limit.hold_running_frame(check); gas.refill_history(started.signer_record_charge); } - shadow::keyless_take_back(&ctx.additional_limit, ctx.ledger(), lanes, taken); Ok(()) } diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index abcafa097..b63047195 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -20,8 +20,8 @@ use revm::{ }; use crate::{ - limit::shadow, synthetic_call_result, system::intercept::peek_selector, ExternalEnvTypes, - MegaContext, OracleEnv, + synthetic_call_result, system::intercept::peek_selector, ExternalEnvTypes, MegaContext, + OracleEnv, }; /// The address of the Oracle system contract. @@ -91,9 +91,7 @@ pub(crate) fn intercept( return None; } let payload = inputs.input.bytes(&*ctx); - let lanes = ctx.additional_limit.record_hint_bytes(payload.len() as u64); let check = ctx.ledger_mut().admit_hint(payload.len() as u64); - shadow::hint(&ctx.additional_limit, ctx.ledger(), lanes, check); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 82a3430ca..19cdc2349 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -397,9 +397,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. +/// tool takes, its answer stands in for the frame: a side of its own keeps the frame sides 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(); diff --git a/crates/mega-evm/tests/satin/journal_ledger.rs b/crates/mega-evm/tests/satin/journal_ledger.rs index c942ff6d5..c4bc04233 100644 --- a/crates/mega-evm/tests/satin/journal_ledger.rs +++ b/crates/mega-evm/tests/satin/journal_ledger.rs @@ -1,15 +1,12 @@ -//! The journal's ledger beside the lanes: what it counts of writes made by anything but the -//! transaction's own execution, and how it follows a tool's checkpoints. +//! The journal's ledger on the writes made by anything but the transaction's own execution, and on +//! a tool's checkpoints. //! //! The ledger counts what the transaction's own execution keeps, at the journal's writes, and the //! journal's checkpoints rewind it. A precompile's writes through `EvmInternals` and an -//! inspector's are not the transaction's own execution: neither is counted, and neither moves the -//! ledger away from the lanes. A tool's checkpoint around a call is a level of the journal like any -//! other: committed, it changes nothing; reverted, it takes back what the call kept, and the ledger -//! follows it where the lanes, which follow frames, do not. -//! -//! Every test here, as every other, runs under the shadow in a `ledger-shadow` build, which holds -//! the ledger to the lanes wherever the two must agree. +//! inspector's are not the transaction's own execution, and neither is counted. A tool's +//! checkpoint around a call is a level of the journal like any other: committed, it changes +//! nothing; reverted, it takes back what the call kept, and the transaction reports what the +//! journal holds. use alloy_evm::precompiles::DynPrecompile; use alloy_primitives::{address, map::HashMap, Address, Bytes, Log, LogData, B256, U256}; @@ -74,7 +71,7 @@ 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. The ledger counts what the lanes count. +/// 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(); @@ -104,7 +101,6 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { "the receipt carries the call's transfer log, then the precompile's log and transfer log", ); assert_eq!(outcome.usage, records_and_moves(2, 1), "the call's start alone is counted"); - assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "the ledger counts the same"); } /// An inspector that opens a checkpoint when a call to `target` starts, and commits it or reverts @@ -149,13 +145,12 @@ impl Inspector, EthInterpreter> for Encloses { /// [`CONTRACT`] makes a second value call, to [`PAYEE`]. /// /// Committed, it changes nothing: both calls keep their starts — the two recipients' records, -/// `CONTRACT`'s own, once, and the two transfer logs — and the ledger counts what the lanes count. +/// `CONTRACT`'s own, once, and the two transfer logs. /// /// Reverted, it takes back what the first call kept, its value and its transfer log included, so /// the receipt carries the second call's log alone; the ledger takes back the first call's records -/// and `CONTRACT`'s flag with it, so the second call records `CONTRACT` again, and the ledger -/// holds what the journal kept: two records and one log. The lanes follow frames, not a tool's -/// checkpoints, and keep counting the first call. +/// and `CONTRACT`'s flag with it, so the second call records `CONTRACT` again, and the transaction +/// reports what the journal kept: two records and one log. #[test] fn test_a_tool_checkpoint_around_a_call_closes_with_it() { for revert in [false, true] { @@ -174,7 +169,6 @@ fn test_a_tool_checkpoint_around_a_call_closes_with_it() { let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - let ledger = evm.ctx().journal_ref().ledger_usage(); let paid = transfer_log(CONTRACT, PAYEE, U256::from(VALUE)); if revert { assert_eq!(outcome.result.logs(), [paid], "{case}: the second call's log alone"); @@ -183,12 +177,11 @@ fn test_a_tool_checkpoint_around_a_call_closes_with_it() { Some(U256::ZERO), "{case}: the first call's value went back" ); - assert_eq!(ledger, records_and_moves(2, 1), "{case}: what the journal kept"); + assert_eq!(outcome.usage, records_and_moves(2, 1), "{case}: what the journal kept"); } else { let received = transfer_log(CONTRACT, RECEIVER, U256::from(VALUE)); assert_eq!(outcome.result.logs(), [received, paid], "{case}"); assert_eq!(outcome.usage, records_and_moves(3, 2), "{case}"); - assert_eq!(ledger, outcome.usage, "{case}: the ledger counts what the lanes count"); } } } @@ -221,7 +214,7 @@ impl Inspector, EthInterpreter> for AnswersAtFrameSt /// 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, and the ledger counts what the lanes count. +/// 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(); @@ -241,6 +234,5 @@ fn test_a_value_call_answered_at_frame_start_counts_nothing() { 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}"); - assert_eq!(evm.ctx().journal_ref().ledger_usage(), outcome.usage, "{case}"); } } diff --git a/crates/mega-state-test/Cargo.toml b/crates/mega-state-test/Cargo.toml index 5ffde98f2..2aa2624aa 100644 --- a/crates/mega-state-test/Cargo.toml +++ b/crates/mega-state-test/Cargo.toml @@ -36,11 +36,6 @@ alloy-eips.workspace = true # misc tempfile.workspace = true -[features] -# The engine with the journal's ledger held to the lanes wherever the two must agree, a mismatch -# panicking: mega-evm's `ledger-shadow`, for verification runs. -ledger-shadow = ["mega-evm/ledger-shadow"] - # Published as `mega-state-test`; the library keeps the `state_test` import name. [lib] name = "state_test" diff --git a/crates/state-test/Cargo.toml b/crates/state-test/Cargo.toml index bca65c32f..f425e3029 100644 --- a/crates/state-test/Cargo.toml +++ b/crates/state-test/Cargo.toml @@ -35,8 +35,3 @@ alloy-rlp = { workspace = true, features = ["std"] } # misc tempfile.workspace = true - -[features] -# The engine with the journal's ledger held to the lanes: mega-evm's `ledger-shadow`, for -# verification runs. -ledger-shadow = ["mega-state-test/ledger-shadow"] From d080d399c0cbaeade8b16f3839f26dc5a12e7afd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 10:02:35 +0800 Subject: [PATCH 417/458] perf(limit): the frames beside the levels, a creation's base as a flag, a slimmer frame side MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ledger keeps the frames whose levels are open in a vector of their own, the running frame last, so the running frame and its caller are found without a scan and a rollback level is 80 bytes rather than 168; a creation's usage base is its creator-record flag over its level's opening counts, in the arithmetic the two snapshots had. A frame side keeps the rollback a rewrite needs — the counts a built frame's level opened with, the caller's flag, the levels below — rather than a whole mark, and the start's kept records as flags rather than the report: 112 bytes rather than 192. A call that moves value is held to the limits once, when its transfer is counted, instead of at its checkpoint too. --- crates/mega-evm/src/evm/execution.rs | 18 +- crates/mega-evm/src/limit/ledger.rs | 281 ++++++++++++++++----------- crates/mega-evm/src/limit/limit.rs | 16 +- 3 files changed, 183 insertions(+), 132 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 2cf5386f4..8cedd0e77 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -594,9 +594,9 @@ impl EvmTr for MegaEvm { @@ -1287,17 +1287,15 @@ fn inspect_logs( } /// The mark the built frame `frame` is taken back to when an inspector rewrites its success into a -/// failure: the one its start's side kept, which is the frame's own checkpoint, with the counts its -/// level opened with. +/// failure: the frame's own checkpoint, with what its start's side kept of the counts its level +/// opened with. fn built_frame_mark( ctx: &MegaContext, frame: &EthFrame, ) -> Mark { - let kept = ctx.additional_limit.running_start().and_then(|side| side.mark()).copied(); - debug_assert!( - kept.is_some_and(|mark| mark.position == frame.checkpoint), - "a built frame's start side keeps the mark of its own checkpoint" - ); + let kept = + ctx.additional_limit.running_start().and_then(|side| side.built_mark(frame.checkpoint)); + debug_assert!(kept.is_some(), "a built frame's start side keeps what it is taken back to"); kept.unwrap_or_else(|| ctx.ledger().mark(frame.checkpoint)) } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 37d14b348..24ccd80a8 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -74,14 +74,6 @@ pub(crate) struct Counts { log_and_code_bytes: u64, } -impl Counts { - /// What was counted since `base`, an earlier snapshot of the same count, net of what was taken - /// back since: a frame's usage when `base` is where the frame began. - const fn usage_since(&self, base: &Self) -> LimitUsage { - self.used.saturating_sub(base.used).saturating_sub(self.refund.saturating_sub(base.refund)) - } -} - /// A frame start's number in its transaction, in the order the starts were handed to revm. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub(crate) struct StartId(u64); @@ -95,16 +87,16 @@ pub(crate) struct FrameIdentity { pub(crate) start: StartId, } -/// A frame level's frame: who it is, and what it may keep. +/// A frame level's frame: who it is, and what it may keep. Kept beside the levels, the running +/// frame's last, so that the running frame and its caller are found without a scan. #[derive(Clone, Copy, Debug)] struct FrameLevel { + /// The frame's level: its index among the open levels. + level: usize, /// The frame's start. start: StartId, /// The frame's depth. depth: usize, - /// Where the frame's usage is measured from: where its level opened, or, for a creation, - /// before its creator's nonce record. - at_base: Counts, /// The most data-size bytes the frame may keep. budget: u64, /// The account the frame runs as. @@ -112,22 +104,13 @@ struct FrameLevel { /// 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. recorded: bool, + /// Whether the frame's start counted its creator's nonce record, right before its level + /// opened: the frame's usage is measured from before it. + creator_record: bool, /// Whether the frame is returning, so revm may close its level. returning: bool, } -impl FrameLevel { - /// What the frame keeps so far, the children it kept included. - const fn usage(&self, counts: &Counts) -> LimitUsage { - counts.usage_since(&self.at_base) - } - - /// The data-size bytes the frame may still keep. - const fn remaining(&self, counts: &Counts) -> u64 { - self.budget.saturating_sub(self.usage(counts).data_size) - } -} - /// One open checkpoint of revm's journal. #[derive(Clone, Copy, Debug)] struct Level { @@ -141,8 +124,9 @@ struct Level { /// The start the next frame start would be when it opened: a start at or after it began /// inside it. next_start_at_open: StartId, - /// The frame, for a frame level; `None` for a rollback level. - frame: Option, + /// Whether it is a frame level, whose frame is the last of the frames when it is the latest + /// level; a rollback level otherwise. + frame: bool, } /// What the engine tells the ledger about a frame start it is about to hand revm. @@ -218,21 +202,28 @@ struct Fate { start_kept: bool, } +/// What a revert of the ledger restores: the counts, the running frame's flag and the levels open. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Rollback { + /// The counts. + counts: Counts, + /// Whether the nearest frame level had its account recorded; `None` when there is none. + recorded: Option, + /// The number of levels open: a revert finds at most these. + levels: usize, +} + /// A point the ledger and revm's journal can be taken back to together /// ([`MegaJournal::revert_to`](crate::MegaJournal)). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Mark { /// Where revm's journal stood. pub(crate) position: JournalCheckpoint, - /// The counts. - counts: Counts, - /// Whether the nearest frame level had its account recorded; `None` when there is none. - recorded: Option, + /// What the ledger goes back to. + rollback: Rollback, /// The start the next frame start would be: a start at or after it is taken back with the /// mark. next_start: StartId, - /// The number of levels open: a revert to the mark finds at most these. - levels: usize, /// For a built frame's own mark, its start, whose creator record the mark keeps. own_start: Option, } @@ -242,8 +233,6 @@ pub(crate) struct Mark { pub(crate) struct CreationStart { /// The creation's budget, from what its creator had left before its nonce record. budget: u64, - /// Where the creation's usage is measured from: before its creator's nonce record. - at_base: Counts, /// Whether the creator's nonce record was counted. creator_record: bool, /// The creation's depth. @@ -260,6 +249,8 @@ pub(crate) struct Ledger { hints: u64, /// One level per checkpoint revm's journal holds open, the latest last. levels: Vec, + /// The frames whose levels are open, the running frame last. + frames: Vec, /// The start window, while one is open. window: Option, /// What the start of the window counted. @@ -302,6 +293,7 @@ impl Ledger { self.body = body; self.hints = 0; self.levels.clear(); + self.frames.clear(); self.window = None; self.last_start = None; self.last_decided = None; @@ -360,17 +352,38 @@ impl Ledger { /// The running frame's level: the nearest frame level. fn frame_level(&self) -> Option<&FrameLevel> { - self.levels.iter().rev().find_map(|level| level.frame.as_ref()) + self.frames.last() } /// The running frame's level, mutably. fn frame_level_mut(&mut self) -> Option<&mut FrameLevel> { - self.levels.iter_mut().rev().find_map(|level| level.frame.as_mut()) + self.frames.last_mut() } /// The level of the frame below the running one: the one that started it. fn calling_level_mut(&mut self) -> Option<&mut FrameLevel> { - self.levels.iter_mut().rev().filter_map(|level| level.frame.as_mut()).nth(1) + let caller = self.frames.len().checked_sub(2)?; + self.frames.get_mut(caller) + } + + /// What `frame` keeps so far, the children it kept included: what was counted since its level + /// opened, and its creator's nonce record, counted right before. + fn frame_usage(&self, frame: &FrameLevel) -> LimitUsage { + let at_open = &self.levels[frame.level].at_open; + let base = if frame.creator_record { + at_open.used.saturating_sub(WRITE_RECORD) + } else { + at_open.used + }; + self.counts + .used + .saturating_sub(base) + .saturating_sub(self.counts.refund.saturating_sub(at_open.refund)) + } + + /// The data-size bytes `frame` may still keep. + fn frame_remaining(&self, frame: &FrameLevel) -> u64 { + frame.budget.saturating_sub(self.frame_usage(frame).data_size) } /// Who the running frame is: the identity its level was opened with. @@ -388,7 +401,7 @@ impl Ledger { /// The running frame's budget and what it keeps so far. #[cfg(test)] pub(crate) fn running_budget(&self) -> Option<(u64, LimitUsage)> { - self.frame_level().map(|level| (level.budget, level.usage(&self.counts))) + self.frame_level().map(|frame| (frame.budget, self.frame_usage(frame))) } /// What became of `start`, which must be the last start revm decided: whether its level was @@ -418,10 +431,10 @@ impl Ledger { if kept.exceeds_data_size(limit) { return self.crossed(limit, kept.data_size, false); } - if let Some(level) = self.frame_level() { - let used = level.usage(&self.counts); - if used.exceeds_data_size(level.budget) { - return self.crossed(level.budget, used.data_size, true); + if let Some(frame) = self.frame_level() { + let used = self.frame_usage(frame); + if used.exceeds_data_size(frame.budget) { + return self.crossed(frame.budget, used.data_size, true); } } LimitCheck::WithinLimit @@ -431,7 +444,7 @@ impl Ledger { /// the transaction's own frame, what the transaction has left, under the frame cap. fn child_budget(&self) -> u64 { let forwarded = match self.frame_level() { - Some(parent) => share_of_remaining(parent.remaining(&self.counts)), + Some(parent) => share_of_remaining(self.frame_remaining(parent)), None => self.limits.tx_data_size_limit.saturating_sub(self.usage().data_size), }; forwarded.min(self.limits.frame_data_size_limit) @@ -670,8 +683,8 @@ impl Ledger { /* Levels */ - /// Opens a level at `opened_at`, a frame level when `frame` is given. - fn open_level(&mut self, opened_at: JournalCheckpoint, frame: Option) { + /// Opens a level at `opened_at`, a frame level when `frame`. + fn open_level(&mut self, opened_at: JournalCheckpoint, frame: bool) { let recorded_at_open = self.frame_level().is_some_and(|level| level.recorded); self.levels.push(Level { opened_at, @@ -682,32 +695,33 @@ impl Ledger { }); } - /// Opens the frame level of the window's start at `opened_at`, its usage measured from - /// `at_base` under `budget`, running as `account`, recorded or not: the frame the window's - /// start builds. + /// Opens the frame level of the window's start at `opened_at`, under `budget`, running as + /// `account`, recorded or not, its usage measured from before its creator's nonce record when + /// the start counted one (`creator_record`): the frame the window's start builds. fn open_frame_level( &mut self, opened_at: JournalCheckpoint, - at_base: Counts, budget: u64, account: Address, recorded: bool, + creator_record: bool, ) { let Some(window) = &mut self.window else { unreachable!("a frame level opens inside its start's window") }; window.opened = true; let (start, depth) = (window.start, window.facts.depth); - let frame = FrameLevel { + self.open_level(opened_at, true); + self.frames.push(FrameLevel { + level: self.levels.len() - 1, start, depth, - at_base, budget, account: Some(account), recorded, + creator_record, returning: false, - }; - self.open_level(opened_at, Some(frame)); + }); } /// revm's journal opened a checkpoint at `opened_at`: the frame level of a call whose start the @@ -715,12 +729,12 @@ impl Ledger { /// otherwise. pub(crate) fn on_checkpoint(&mut self, opened_at: JournalCheckpoint) { let Some(window) = self.window.filter(|window| !window.opened) else { - return self.open_level(opened_at, None); + return self.open_level(opened_at, false); }; let StartFacts { depth, caller, target, transfers_value } = window.facts; let Some(target) = target else { // A creation's frame level is the one its account checkpoint opens. - return self.open_level(opened_at, None); + return self.open_level(opened_at, false); }; // The one start rule that stays an interpretation of the input: whether the frame's own // account is recorded before anything of the frame is counted. @@ -732,9 +746,13 @@ impl Ledger { .is_some_and(|parent| parent.account == Some(target) && parent.recorded); inherited || target == self.sender || transfers_value }; - self.open_frame_level(opened_at, self.counts, self.child_budget(), target, recorded); - let verdict = self.check(); - self.report_mut().verdict = Some(verdict); + self.open_frame_level(opened_at, self.child_budget(), target, recorded, false); + // A start that moves value is held once its transfer is counted (`on_transfer`); any + // other has nothing of its own to count, and is held now. + if !transfers_value { + let verdict = self.check(); + self.report_mut().verdict = Some(verdict); + } } /// revm moved `value` from `from` to `to` for the call whose start the window is open for @@ -791,7 +809,7 @@ impl Ledger { } window.counted = true; let depth = window.facts.depth; - let (budget, at_base) = (self.child_budget(), self.counts); + let budget = self.child_budget(); let mut creator_record = false; if depth > 0 { if let Some(level) = self.frame_level_mut() { @@ -802,7 +820,7 @@ impl Ledger { if creator_record { self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); } - Some(CreationStart { budget, at_base, creator_record, depth }) + Some(CreationStart { budget, creator_record, depth }) } /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation at @@ -820,14 +838,14 @@ impl Ledger { ) { let Some(start) = start else { if let Some(opened_at) = opened { - self.open_level(opened_at, None); + self.open_level(opened_at, false); } return; }; self.report_mut().creator_record = start.creator_record; let Some(opened_at) = opened else { return }; debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); - self.open_frame_level(opened_at, start.at_base, start.budget, address, true); + self.open_frame_level(opened_at, start.budget, address, true, start.creator_record); self.counts.used = self.counts.used.saturating_add(with_transfer_log(WRITE_RECORD, logged)); let verdict = self.check(); let report = self.report_mut(); @@ -858,7 +876,10 @@ impl Ledger { /// its frame's flag to a caller running as the same account. pub(crate) fn on_commit(&mut self) { let Some(level) = self.levels.pop() else { return }; - let Some(frame) = level.frame else { return }; + if !level.frame { + return; + } + let frame = self.pop_frame(); self.assert_frame_closes(&frame); if let Some(caller) = self.frame_level_mut() { if frame.account.is_some() && frame.account == caller.account { @@ -881,11 +902,12 @@ impl Ledger { level.opened_at == checkpoint, "a revert closes the latest level: a revert below a level still open is not supported" ); + let frame = level.frame.then(|| self.pop_frame()); self.counts = level.at_open; if let Some(caller) = self.frame_level_mut() { caller.recorded = level.recorded_at_open; } - match level.frame { + match frame { Some(frame) => { self.assert_frame_closes(&frame); self.last_decided = @@ -895,6 +917,13 @@ impl Ledger { } } + /// Pops the frame of the frame level just popped. + fn pop_frame(&mut self) -> FrameLevel { + let frame = self.frames.pop().expect("a frame level has its frame"); + debug_assert!(frame.level == self.levels.len(), "the frames follow the frame levels"); + frame + } + /// Notes that the last start decided is taken back when it is `start` or later: its level is no /// longer kept, and, unless it is `own_start`, nothing it counted is. fn take_back_starts_from(&mut self, start: StartId, own_start: Option) { @@ -910,6 +939,7 @@ impl Ledger { /// until the next transaction begins. pub(crate) fn on_transaction_end(&mut self) { self.levels.clear(); + self.frames.clear(); self.window = None; } @@ -919,52 +949,72 @@ impl Ledger { pub(crate) fn mark(&self, position: JournalCheckpoint) -> Mark { Mark { position, - counts: self.counts, - recorded: self.frame_level().map(|level| level.recorded), + rollback: Rollback { + counts: self.counts, + recorded: self.frame_level().map(|level| level.recorded), + levels: self.levels.len(), + }, next_start: self.next_start, - levels: self.levels.len(), own_start: None, } } - /// The mark a frame revm just built is taken back to when it is rewritten into a failure: its - /// own checkpoint, the counts its level opened with — after a creation's creator record — and - /// whether the frame below had its account recorded then. Never where the frame's usage is - /// measured from, which for a creation is before the creator's record. - pub(crate) fn frame_start_mark(&self) -> Option { + /// What a frame revm just built is taken back to when it is rewritten into a failure, with its + /// start: the counts its level opened with — after a creation's creator record — and whether + /// the frame below had its account recorded then. Never where the frame's usage is measured + /// from, which for a creation is before the creator's record. The frame's side keeps it past + /// the level's commit, for the mark the rewrite reverts to ([`StartSide::built_mark`]). + pub(crate) fn frame_start_rollback(&self) -> Option<(StartId, Rollback)> { let level = self.levels.last()?; - let frame = level.frame?; + if !level.frame { + return None; + } + let frame = self.frames.last()?; let below = self.levels.len() - 1; - let caller = self.levels[..below].iter().rev().any(|level| level.frame.is_some()); - Some(Mark { - position: level.opened_at, + let caller = self.frames.len() > 1; + let rollback = Rollback { counts: level.at_open, recorded: caller.then_some(level.recorded_at_open), - next_start: frame.start, levels: below, - own_start: Some(frame.start), - }) + }; + Some((frame.start, rollback)) + } + + /// The mark a frame revm just built is taken back to when it is rewritten into a failure + /// ([`frame_start_rollback`](Self::frame_start_rollback), at the frame's own checkpoint). + #[cfg(test)] + pub(crate) fn frame_start_mark(&self) -> Option { + let (start, rollback) = self.frame_start_rollback()?; + Some(Mark::of_built(self.levels.last()?.opened_at, start, rollback)) } /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, the /// running frame's flag, and what became of the last start decided. pub(crate) fn revert_to(&mut self, mark: &Mark) { debug_assert!( - self.levels.len() <= mark.levels, + self.levels.len() <= mark.rollback.levels, "a revert to a mark finds every level opened since closed" ); - self.counts = mark.counts; - if let (Some(recorded), Some(level)) = (mark.recorded, self.frame_level_mut()) { + self.counts = mark.rollback.counts; + if let (Some(recorded), Some(level)) = (mark.rollback.recorded, self.frame_level_mut()) { level.recorded = recorded; } self.take_back_starts_from(mark.next_start, mark.own_start); } } +impl Mark { + /// The mark of a frame revm built at `position`, its own checkpoint: `rollback` is what its + /// level opened with, and `start` the frame's, whose creator record the mark keeps. + const fn of_built(position: JournalCheckpoint, start: StartId, rollback: Rollback) -> Self { + Self { position, rollback, next_start: start, own_start: Some(start) } + } +} + /// Satin's side of one frame start: what its caller paid for the records it makes, what the /// ledger saw it count, the history allowance the frame was granted, and, for a frame revm built, -/// the mark it is taken back to when it is rewritten into a failure. One per frame result revm -/// will return. +/// what it is taken back to when it is rewritten into a failure. One per frame result revm will +/// return. #[derive(Clone, Copy, Debug)] pub(crate) struct StartSide { /// The frame's depth. @@ -973,14 +1023,19 @@ pub(crate) struct StartSide { on_level_charge: u64, /// What the caller paid for the record of its own account. caller_charge: u64, - /// What the ledger saw the start count; the default for a start answered before revm decided - /// it, which counted nothing. - report: StartReport, - /// The mark of a frame revm built. - mark: Option, /// What is left of the history allowance the 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. stipend: u64, + /// The start, once revm decided it; `None` for a start answered before, which counted nothing. + start: Option, + /// Whether the start counted records on its own level. + on_level: bool, + /// Whether the start counted its caller's record on its own level: a value transfer's sender. + caller_on_level: bool, + /// Whether the start counted its creator's nonce record, below its own level. + creator_record: bool, + /// What a frame revm built is taken back to when it is rewritten into a failure. + rollback: Option, /// The records the charge was computed from, when the charge was made from one and nothing /// could rewrite the start between the two: what a debug build holds the ledger's count to. #[cfg(debug_assertions)] @@ -1002,24 +1057,19 @@ impl StartSide { depth, on_level_charge, caller_charge, - report: StartReport { - start: None, - on_level: 0, - caller_on_level: false, - creator_record: false, - transfer_log: false, - refused: false, - verdict: None, - }, - mark: None, stipend: 0, + start: None, + on_level: false, + caller_on_level: false, + creator_record: false, + rollback: None, #[cfg(debug_assertions)] charged, } } - /// Attaches what the ledger saw the start count and the built frame's mark, and holds the - /// count to the records the start's charge was computed from. + /// Attaches what the ledger saw the start count and, for a frame revm built, what it is taken + /// back to, and holds the count to the records the start's charge was computed from. /// /// The two are separate answers to one question, asked at two points: the charge at the /// opcode, on the facts revm's instruction hands the frame-start hook — or before execution, @@ -1032,9 +1082,15 @@ impl StartSide { /// inspector that may rewrite the start runs between the two, and can split them: under one /// the start is not checked. Only a start revm made and held to the limits is checked: one it /// refused, or failed before its level opened, counted nothing, and the charge comes back. - pub(crate) fn attach(&mut self, report: StartReport, mark: Option) { - self.report = report; - self.mark = mark; + pub(crate) fn attach(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { + self.start = report.start; + self.on_level = report.on_level > 0; + self.caller_on_level = report.caller_on_level; + self.creator_record = report.creator_record; + self.rollback = built.map(|(start, rollback)| { + debug_assert!(report.start == Some(start), "a built frame's rollback is its start's"); + rollback + }); #[cfg(debug_assertions)] if let Some(charged) = self.charged.filter(|_| report.start.is_some() && report.verdict.is_some()) @@ -1070,12 +1126,14 @@ impl StartSide { /// The start, once revm decided it. pub(crate) const fn start(&self) -> Option { - self.report.start + self.start } - /// The mark of a frame revm built. - pub(crate) const fn mark(&self) -> Option<&Mark> { - self.mark.as_ref() + /// The mark a frame revm built is taken back to when it is rewritten into a failure, at + /// `position`, the frame's own checkpoint; `None` for a frame revm did not build. + pub(crate) fn built_mark(&self, position: JournalCheckpoint) -> Option { + let (start, rollback) = self.start.zip(self.rollback)?; + Some(Mark::of_built(position, start, rollback)) } /// The history gas the caller gets back once the frame returned: what it paid less the price @@ -1089,10 +1147,9 @@ impl StartSide { /// surviving record aside. pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { let (level_kept, start_kept) = - self.report.start.map_or((false, false), |start| ledger.fate(start)); - let on_level = level_kept && self.report.on_level > 0; - let caller = (level_kept && self.report.caller_on_level) || - (start_kept && self.report.creator_record); + self.start.map_or((false, false), |start| ledger.fate(start)); + let on_level = level_kept && self.on_level; + let caller = (level_kept && self.caller_on_level) || (start_kept && self.creator_record); let mut refund = 0; if !on_level { refund += self.on_level_charge; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 84a6f4592..50effeae8 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -11,7 +11,7 @@ use alloc as std; use std::vec::Vec; use super::{ - ledger::{FrameStartRecords, Ledger, Mark, StartSide}, + ledger::{FrameStartRecords, Ledger, Rollback, StartId, StartSide}, EvmTxRuntimeLimits, LimitCheck, LimitKind, StartReport, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -403,12 +403,12 @@ impl AdditionalLimit { self.starts.push(StartSide::new(depth, on_level, caller, records)); } - /// Attaches what the journal's ledger saw the latest start count, and the mark a frame revm - /// built is taken back to, to that start's side, and holds the count to the records the start's + /// Attaches what the journal's ledger saw the latest start count, and what a frame revm built + /// is taken back to, to that start's side, and holds the count to the records the start's /// charge was computed from ([`StartSide::attach`]). - pub(crate) fn attach_start(&mut self, report: StartReport, mark: Option) { + pub(crate) fn attach_start(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { if let Some(side) = self.starts.last_mut() { - side.attach(report, mark); + side.attach(report, built); } } @@ -509,11 +509,7 @@ impl FrameCharge { #[cfg(test)] mod tests { use super::*; - use crate::{ - limit::{ledger::StartId, StartFacts}, - test_utils::MemoryDatabase, - MegaContext, MegaSpecId, - }; + use crate::{limit::StartFacts, test_utils::MemoryDatabase, MegaContext, MegaSpecId}; use alloy_primitives::{address, Address, Bytes, U256}; use revm::{ context::{ContextTr, JournalTr}, From e4c1b9bb3071487d67151c3134ad751b5be2842b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 10:47:12 +0800 Subject: [PATCH 418/458] test(limit): the allowance test returns early at a history price of nothing At a cost per history byte of nothing the frame's history allowance is nothing, and the byte-price grid's free-history points left the test drawing one byte less than none; it now leaves the price guard's note and returns, as every test does where its byte costs nothing. --- crates/mega-evm/src/limit/limit.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 50effeae8..61001db64 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -583,12 +583,17 @@ mod tests { /// The allowance is the started frame's, below the transaction's own frame: its side draws on /// it, and nothing is left once the side is popped. The transaction's own frame is granted - /// none, however it was started. + /// none, however it was started. At a history price of nothing the allowance is nothing, and + /// there is nothing to draw. #[test] fn test_the_allowance_is_granted_to_the_frame_a_value_call_starts() { let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); let ledger = ctx.ledger(); let stipend = storage_call_stipend(); + if stipend == 0 { + crate::test_utils::note_price_guard("MEGA_SATIN_CPHB prices a history byte at nothing"); + return; + } let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); assert_eq!(limit.try_consume_stipend(1), 0, "the transaction's own frame has none"); From d67327b7a93285e07d917fc31b3f7961b97f82ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 13:36:44 +0800 Subject: [PATCH 419/458] fix(handler): consume the captured reservoir so a reused handler reports its own --- crates/mega-evm/src/evm/execution.rs | 88 ++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 8cedd0e77..076d29648 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -76,7 +76,10 @@ pub struct MegaHandler { 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 - /// reported once the result is built ([`execution_result`](Handler::execution_result)). + /// 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>, } @@ -425,7 +428,8 @@ where /// ([`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. A deposit that halts is not a result: op-revm + /// 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, @@ -433,7 +437,7 @@ where result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - let reservoir = self.settled_reservoir.get().unwrap_or_else(|| result.gas().reservoir()); + 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) @@ -443,12 +447,14 @@ where /// 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. fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, ) -> Result, Self::Error> { + self.settled_reservoir.take(); self.op.catch_error(evm, error) } } @@ -1730,4 +1736,78 @@ mod tests { assert_eq!(nonce, u64::from(!taken_back), "{case}"); } } + + /// 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] + 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" + ); + } + } } From e3b606976967e9e9ddfd137968eb5d44b695451e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 13:40:42 +0800 Subject: [PATCH 420/458] refactor(inspector): delete the block-execution admission gate --- .claude/skills/satin-review/SKILL.md | 6 +- AGENTS.md | 19 +- bin/mega-evme/src/block/satin.rs | 22 +- bin/mega-evme/src/replay/cmd.rs | 31 +- crates/mega-evm/README.md | 18 +- crates/mega-evm/src/block/executor.rs | 61 +--- crates/mega-evm/src/block/factory.rs | 40 +-- crates/mega-evm/src/evm/execution.rs | 9 +- crates/mega-evm/src/evm/inspector.rs | 308 +----------------- crates/mega-evm/src/evm/mod.rs | 42 +-- crates/mega-evm/src/lib.rs | 10 +- crates/mega-evm/src/test_utils/mod.rs | 2 + .../src/test_utils/read_only_observer.rs | 264 +++++++++++++++ crates/mega-evm/tests/block/factory.rs | 12 +- crates/mega-evm/tests/block/inspector.rs | 237 +++----------- crates/mega-evm/tests/satin/inspector.rs | 89 ++--- 16 files changed, 413 insertions(+), 757 deletions(-) create mode 100644 crates/mega-evm/src/test_utils/read_only_observer.rs diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index ee29909c7..ff3ee7b6c 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -127,7 +127,7 @@ 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. + - Block execution admits any inspector; the node decides which run on block production. - 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. @@ -225,7 +225,7 @@ Each is a decision with its reason; "in this pull request" means review the code - **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. +- **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. @@ -240,7 +240,7 @@ Each is a decision with its reason; "in this pull request" means review the code - **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. +- **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. - **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 diff --git a/AGENTS.md b/AGENTS.md index 4754d20df..c2b876741 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,8 +132,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | Module | Holds | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`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 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 hold of a frame's start to the limits once revm decided it (`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`) | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`precompiles.rs`); synthetic frame results (`frame.rs`); 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 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 hold of a frame's start to the limits once revm decided it (`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`; `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`; the journal's ledger: the data-size bytes, write records and the log and code bytes of the history byte count, counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the frame budgets, the start reports and verdicts, the marks, the creation rule, the refund formula, the body, deployed code and the EIP-7708 transfer logs (`ledger.rs`); what a completed write counts (`record.rs`); `AdditionalLimit`: Satin's side of each frame start (`StartSide`: the start charge, the history allowance, a built frame's mark), 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 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`) | @@ -236,7 +236,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. + `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. @@ -437,12 +437,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. +- **Inspectors in block execution.** + Block execution admits any inspector: the journal's ledger follows the journal, so a rewrite cannot put the ledger out of step with state, and 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 module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase. + `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: 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. @@ -482,7 +481,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; 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;`, 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. 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/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/crates/mega-evm/README.md b/crates/mega-evm/README.md index 0ef6b341a..33f33cbb3 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -38,7 +38,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 and write records 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. @@ -203,18 +203,10 @@ 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. +Block execution admits any inspector: a node decides which inspectors may run on block production, and the engine no longer refuses one. +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 failed creation rewritten into a success hands its creator the address the inspector gave, with nothing deployed there. 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. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 39ae6ab14..eb929b555 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 @@ -225,11 +213,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 +260,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 +278,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 { .. } | @@ -532,19 +511,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 +591,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 @@ -661,8 +627,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 +856,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 +875,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 +890,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 +996,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 @@ -1146,9 +1105,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 +1131,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/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 076d29648..eece34018 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -748,7 +748,6 @@ where &mut self, mut frame_init: FrameInit, ) -> Result, ContextDbError> { - let rewriting = self.has_rewriting_inspector(); // A start past the call-stack limit is answered by the depth guard, wherever it comes from. if frame_init.depth <= CALL_STACK_LIMIT as usize { assert_running_frame(&self.inner.ctx, frame_init.depth); @@ -761,11 +760,9 @@ where let output = answered_by_inspector(ctx, inspector, &frame_init, output, upfront); return Ok(ItemOrResult::Result(output)); } - if rewriting { - // The start its charge paid for — the calling opcode's, or the transaction's for its - // own frame — may not be the one the inspector lets start. - ctx.additional_limit.waive_start_check(); - } + // The start its charge paid for — the calling opcode's, or the transaction's for its own + // frame — may not be the one the inspector lets start. + ctx.additional_limit.waive_start_check(); 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 diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index 5e8ec0f0a..b4e208cc1 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -30,25 +30,11 @@ //! - **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 +//! # Block execution //! -//! [`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. +//! Block execution admits any inspector: the journal's ledger follows the journal, so a rewrite +//! cannot put the ledger out of step with state, and which inspectors may run on block production +//! is a node's decision, not the engine's. //! //! # What a rewrite does not change //! @@ -108,13 +94,12 @@ //! included. use revm::{ - context::{ContextTr, JournalTr}, + context::ContextTr, context_interface::{cfg::StateGasCharge, Host}, handler::FrameResult, - inspector::{handler::frame_end, JournalExt, NoOpInspector}, + inspector::handler::frame_end, interpreter::{ - gas::WithheldCrossing, CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, - Gas, InstructionResult, Interpreter, InterpreterTypes, + gas::WithheldCrossing, FrameInput, Gas, InstructionResult, Interpreter, InterpreterTypes, }, primitives::{Address, Bytes, Log, U256}, Database, Inspector, @@ -122,188 +107,6 @@ use revm::{ use crate::{limit::Mark, 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. /// @@ -382,103 +185,6 @@ const fn restore_gas_records(gas: &mut Gas, (crossing, failed): GasRecords) { gas.set_failed_charge_remaining(failed); } -/// 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. /// diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8fa2227ff..4d60c1f36 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -27,7 +27,6 @@ pub use execution::*; pub use factory::*; pub use frame::*; pub use history::*; -pub use inspector::*; pub use journal::*; pub use precompiles::*; pub use prices::*; @@ -94,9 +93,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, } @@ -112,12 +108,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 `inspector` module). 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 diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index c66b3f2d7..7b7c5cb87 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -51,11 +51,11 @@ pub use evm::{ 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, - MegaJournal, 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, + BlockHashRecord, BucketRecord, BytePrice, DynPrecompilesBuilder, EthSpecId, IntrinsicGas, + MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, MegaJournal, + MegaSpecId, MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, + SatinPriceError, SatinPrices, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, + LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; #[cfg(any(test, feature = "test-utils"))] 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/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/factory.rs b/crates/mega-evm/tests/block/factory.rs index 0a2aa1ddc..b798280c4 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() }; diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 19cdc2349..da525507e 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,8 +237,8 @@ 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: a side of its own keeps the frame sides aligned +/// produces. Block execution does not refuse it, and on the EVM alike its answer stands in for the +/// frame: a side of its own keeps the frame sides aligned /// with the frames, the answered call ends as every call does, and the transaction settles as one /// whose nested call never ran. #[test] @@ -417,8 +258,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(); @@ -429,4 +271,5 @@ fn test_inspector_early_return_with_additional_limits() { let body = transaction_body_bytes(&tx); assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 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/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index 7850c4ac6..77a6ad638 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -1,16 +1,14 @@ -//! 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, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, context::result::EVMError, - inspector::NoOpInspector, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, @@ -299,33 +297,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 +332,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 +365,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 +507,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 +532,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 +546,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 +611,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() }); } From f973624d93c52da05bc07abe4c3f14f7121bcb1b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 13:40:55 +0800 Subject: [PATCH 421/458] docs(satin): a halt's burn adds nothing to compute, the paid work before it still counts --- docs/spec/upgrades/satin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 4faa323ad..8884902d3 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -538,7 +538,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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. 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 adds nothing to the compute (see Compute, above), so no halt takes the transaction's compute past the limit: the compute after a read is at most the cap. + 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.** 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. From 6aa4fff9a32de7e50518ab5ada3525e75ace6a70 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 13:41:03 +0800 Subject: [PATCH 422/458] docs: realign the module table after the gate's removal --- AGENTS.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c2b876741..f5a8044c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,17 +130,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 | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Module | Holds | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `evm/` | `MegaSpecId`; `MegaContext`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`precompiles.rs`); synthetic frame results (`frame.rs`); 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 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 hold of a frame's start to the limits once revm decided it (`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`; `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`; the journal's ledger: the data-size bytes, write records and the log and code bytes of the history byte count, counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the frame budgets, the start reports and verdicts, the marks, the creation rule, the refund formula, the body, deployed code and the EIP-7708 transfer logs (`ledger.rs`); what a completed write counts (`record.rs`); `AdditionalLimit`: Satin's side of each frame start (`StartSide`: the start charge, the history allowance, a built frame's mark), 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 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`) | +| `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 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`; the journal's ledger: the data-size bytes, write records and the log and code bytes of the history byte count, counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the frame budgets, the start reports and verdicts, the marks, the creation rule, the refund formula, the body, deployed code and the EIP-7708 transfer logs (`ledger.rs`); what a completed write counts (`record.rs`); `AdditionalLimit`: Satin's side of each frame start (`StartSide`: the start charge, the history allowance, a built frame's mark), 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 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 From 3097c3eb61c074b292eaa2d07d3ffbdcd5ac3149 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 16:12:36 +0800 Subject: [PATCH 423/458] feat(limit): an account's write record follows the net change of its info MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An account's write record exists exactly while the account's nonce, balance or code differs from what the transaction loaded, which revm keeps as the account's original info. The journal compares the accounts a counted write touches before and after it — a value transfer's two sides, a creation's creator and created account, a SELFDESTRUCT's beneficiary and the account it clears — and tells the ledger which records the write makes and which it takes back; the frame-start hook predicts the same from the journal's state and charges the caller for the records a start makes, with the price of a take-back credited once the start's level is kept. A start whose value the caller cannot fund is charged nothing. This replaces the per-frame deduplication of a frame's own account, the inherited flag of value-less frames and the rule that N transfers to one recipient keep N records: a transfer to an account already changed adds nothing, a transfer that returns an account takes its record back, a value CALLCODE or a call to the calling account itself records nothing, and a SELFDESTRUCT records the account it clears as well as its beneficiary. The sender, changed by its fee and nonce before execution, and the fee accounts, unchanged until written, come out of the rule as the body already has them. --- crates/mega-evm/src/evm/execution.rs | 59 +- crates/mega-evm/src/evm/host.rs | 70 +- crates/mega-evm/src/evm/journal.rs | 338 ++++++-- crates/mega-evm/src/limit/ledger.rs | 734 ++++++++---------- crates/mega-evm/src/limit/limit.rs | 102 +-- crates/mega-evm/src/limit/mod.rs | 2 +- crates/mega-evm/src/limit/record.rs | 200 ++--- .../mega-evm/src/system/keyless/dispatch.rs | 33 +- crates/mega-evm/src/system/keyless/settle.rs | 18 +- crates/mega-evm/tests/block/transfer_logs.rs | 4 +- crates/mega-evm/tests/satin/data_size.rs | 20 +- .../mega-evm/tests/satin/data_size_counts.rs | 10 +- .../tests/satin/detained_transfers.rs | 17 +- crates/mega-evm/tests/satin/detention.rs | 11 +- crates/mega-evm/tests/satin/history_bytes.rs | 13 +- crates/mega-evm/tests/satin/history_gas.rs | 9 +- crates/mega-evm/tests/satin/salt.rs | 5 +- .../tests/satin/storage_call_stipend.rs | 31 +- crates/mega-evm/tests/satin/transfer_logs.rs | 67 +- crates/mega-evm/tests/satin/write_records.rs | 424 ++++++++-- ...erential__keyless_differential_record.snap | 10 +- 21 files changed, 1370 insertions(+), 807 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index eece34018..9a3d2492c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -577,7 +577,7 @@ impl EvmTr for MegaEvm( } } +/// The verdict the journal's ledger gives a call `input` starts had revm made it: the records its +/// transfer would make and take back, as the journal predicts them, and the transfer log of the +/// value it would move, for a start the engine answers without revm deciding it +/// ([`Ledger::hypothetical_start`](crate::limit::Ledger)). +fn hypothetical_start( + ctx: &MegaContext, + input: &FrameInput, +) -> LimitCheck { + let FrameInput::Call(inputs) = input else { + unreachable!("only a call is answered without revm deciding its start") + }; + let value = inputs.value.get(); + let records = ctx.journal_ref().transfer_records(inputs.caller, inputs.target_address, value); + let logged = ctx.ledger().counts_transfer_logs() && + !value.is_zero() && + inputs.target_address != inputs.caller; + ctx.ledger().hypothetical_start(records, logged) +} + /// 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; a side of its own stands in for the frame, and the answer is held to @@ -1180,21 +1199,11 @@ impl FrameStart { let (input, depth) = (&frame_init.frame_input, frame_init.depth); let (facts, reservoir) = match input { FrameInput::Call(inputs) => ( - StartFacts { - depth, - caller: inputs.caller, - target: Some(inputs.target_address), - transfers_value: inputs.transfers_value(), - }, + StartFacts { depth, creation: false, transfers_value: inputs.transfers_value() }, inputs.reservoir, ), FrameInput::Create(inputs) => ( - StartFacts { - depth, - caller: inputs.caller(), - target: None, - transfers_value: !inputs.value().is_zero(), - }, + StartFacts { depth, creation: true, transfers_value: !inputs.value().is_zero() }, inputs.reservoir(), ), FrameInput::Empty => unreachable!( @@ -1394,7 +1403,6 @@ fn record_applied_authorities( return 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 { @@ -1404,10 +1412,8 @@ fn record_applied_authorities( .collect(); 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.ledger_mut().count_authorities(caller, applied, target_is_authority); + ctx.ledger_mut().count_authorities(applied); // 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); @@ -1416,8 +1422,14 @@ fn record_applied_authorities( } /// 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 +/// ([`MegaJournal::transfer_records`](crate::MegaJournal)): 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 a record whatever +/// the address held. /// /// 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 when the @@ -1437,13 +1449,14 @@ fn charge_records_made_outside_a_frame( return true; } let tx = ctx.tx(); - let writes_a_record = match tx.kind() { - TxKind::Create => true, + let records = match tx.kind() { + TxKind::Create => 1, TxKind::Call(to) => { - !tx.value().is_zero() && to != tx.caller() && !ctx.ledger().target_is_authority() + let predicted = ctx.journal_ref().transfer_records(tx.caller(), to, tx.value()); + debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); + predicted.added } }; - let records = u64::from(writes_a_record); let Some((top_level, _)) = charge_write_records_history(gas, records, applied_authorities) else { return false; diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 41f2e5b94..2d28c07bd 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -301,10 +301,13 @@ impl revm::context_interface::Host /// /// A log's history is drawn from the frame's history allowance first, and the frame's gas pays /// the rest ([`storage_call_stipend`](crate::storage_call_stipend)): a write record is the - /// frame's own to pay for, and a record taken back — a slot written back to its original value - /// — 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. + /// 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. /// /// 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) @@ -322,20 +325,20 @@ impl revm::context_interface::Host return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } if self.prices_history() { - match history { - HistoryBytes::None => {} - HistoryBytes::Appended(bytes) => { - let Some(cost) = history_gas(bytes) else { return WriteVerdict::OutOfGas }; - let drawn = if from_allowance { - self.additional_limit.try_consume_stipend(cost) - } else { - 0 - }; - if !gas.record_history_cost(cost - drawn) { - return WriteVerdict::OutOfGas; - } + let HistoryBytes { appended, taken } = history; + if taken != 0 { + gas.refill_history(history_gas(taken).unwrap_or(0)); + } + if appended != 0 { + let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; + let drawn = if from_allowance { + self.additional_limit.try_consume_stipend(cost) + } else { + 0 + }; + if !gas.record_history_cost(cost - drawn) { + return WriteVerdict::OutOfGas; } - HistoryBytes::Taken(bytes) => gas.refill_history(history_gas(bytes).unwrap_or(0)), } } if holds_again { @@ -345,20 +348,22 @@ impl revm::context_interface::Host } /// Charges the running frame the history of the write records the frame it is starting makes - /// — a value transfer's sender and recipient, a creation's creator nonce and created account. - /// 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. + /// — the accounts a value transfer changes from what the transaction loaded, a creation's + /// created account and its creator's nonce — as the journal predicts them from its state + /// ([`MegaJournal::start_records`](crate::MegaJournal)). 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. /// /// 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; the frame's side keeps it, and - /// gives back on return what the journal's ledger reports the start did not keep. 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. 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. + /// gives back on return what the journal's ledger reports the start did not keep, and the + /// price of the records a transfer returned to what the transaction loaded, once that stands. + /// 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. 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 @@ -369,18 +374,19 @@ impl revm::context_interface::Host /// taken, and a price that could not be computed failed before any charge. #[inline] fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { - let records = self.ledger().start_records(start); + let records = self.journal_ref().start_records(start); if !self.prices_history() { + self.additional_limit.stage_frame_charge(records, 0, 0, false); return true; } let charged = - charge_write_records_history(gas, records.on_level, u64::from(records.caller)); - let Some((on_level, caller)) = charged else { + charge_write_records_history(gas, records.on_level.added, u64::from(records.creator)); + let Some((added, creator)) = charged else { gas.erase_cost(start.forward); gas.set_failed_charge_remaining(Some(gas.remaining())); return false; }; - self.additional_limit.stage_frame_charge(records, on_level, caller); + self.additional_limit.stage_frame_charge(records, added, creator, true); true } } diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 3871affa9..7cc2aede4 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -6,11 +6,19 @@ //! //! - **Counted writes.** A call's value transfer (`transfer_loaded`) and a creation's account //! checkpoint (`create_account_checkpoint`) are counted when revm makes them for a frame start, -//! inside the start window the engine opens around revm's frame start, and only there. Every -//! other write — `sstore`, `log`, `selfdestruct`, a `transfer`, anything through an account -//! handle — is forwarded and counts nothing: a write an opcode completed reaches the ledger from -//! the Host's completed-write hook, and a write a tool or a precompile makes is not the -//! transaction's own execution. +//! inside the start window the engine opens around revm's frame start, and only there. A +//! `SELFDESTRUCT`'s move (`selfdestruct`) is observed here and counted by the Host's +//! completed-write hook once the opcode completed. Every other write — `sstore`, `log`, a +//! `transfer`, anything through an account handle — is forwarded and counts nothing: a write an +//! opcode completed reaches the ledger from the Host's completed-write hook, and a write a tool +//! or a precompile makes is not the transaction's own execution. +//! - **What a write counts.** An account's write record follows the net change of its info within +//! the transaction: the journal compares the account's nonce, balance and code hash with what the +//! transaction loaded ([`is_changed`](MegaJournal::is_changed)) before and after each counted +//! write, and tells the ledger which accounts the write changed and which it returned +//! ([`RecordDelta`]). The same prediction, on the journal's state as it stands, is what the +//! frame-start hook charges a start's records from +//! ([`start_records`](MegaJournal::start_records)). //! - **Levels and the transaction's end.** `checkpoint`, `checkpoint_commit` and //! `checkpoint_revert` open and close the ledger's levels with revm's checkpoints; `commit_tx`, //! `discard_tx` and `finalize` close them all. @@ -39,17 +47,20 @@ use revm::{ }, JournalTr, }, - context_interface::context::{SStoreResult, SelfDestructResult, StateLoad}, + context_interface::{ + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::{FrameStart, FrameStartKind}, + }, inspector::JournalExt, primitives::{ hardfork::SpecId, Address, AddressMap, AddressSet, Bytes, HashSet, Log, StorageKey, StorageValue, B256, U256, }, - state::{Account, Bytecode, EvmState}, + state::{Account, AccountInfo, Bytecode, EvmState}, Database, Journal, JournalEntry, }; -use crate::limit::{Ledger, Mark}; +use crate::limit::{FrameStartRecords, Ledger, Mark, RecordDelta}; /// The journal of the Satin engine: revm's journal, and the ledger of what the transaction's own /// execution keeps. See the module documentation. @@ -65,6 +76,14 @@ pub struct MegaJournal { ledger: Ledger, } +/// 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 +} + impl MegaJournal { /// The ledger. pub(crate) const fn ledger(&self) -> &Ledger { @@ -104,6 +123,106 @@ impl MegaJournal { "the ledger holds one level per open checkpoint" ); } + + /* What a write changes */ + + /// 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<&Account> { + self.revm + .state + .get(&address) + .filter(|account| account.transaction_id == self.revm.transaction_id) + } + + /// Whether the transaction changed the account at `address` from what it loaded: its nonce, + /// balance or code differs from the account's original info, which revm sets at the account's + /// first load in the transaction. 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 transaction changed the account at `address` from what it loaded, before the + /// nonce bump revm just made on it: the creator of a creation, whose nonce revm bumps before + /// it asks for the creation's account checkpoint. + fn is_changed_before_bump(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| { + let before = + AccountInfo { nonce: account.info.nonce.wrapping_sub(1), ..account.info.clone() }; + differs(&before, &account.original_info()) + }) + } + + /// How the record of the account at `address` moves when its balance becomes `balance`: a + /// record when the write changes an account the transaction had not changed, a record back when + /// it returns a changed one to what the transaction loaded. + fn balance_change(&self, address: Address, balance: U256) -> RecordDelta { + let Some(account) = self.loaded(address) else { + // An account the transaction has not loaded is unchanged, and a balance it did not + // hold changes it: what the transaction loads for it will be what the chain holds. + return RecordDelta::of_account(false, balance != U256::ZERO); + }; + let original = account.original_info(); + let after = AccountInfo { balance, ..account.info.clone() }; + RecordDelta::of_account(differs(&account.info, &original), differs(&after, &original)) + } + + /// The current balance of the account at `address`, as the transaction holds it; nothing for + /// one it 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: 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) -> RecordDelta { + if from == to || value.is_zero() { + return RecordDelta::NONE; + } + let Some(from_after) = self.balance(from).checked_sub(value) else { + return RecordDelta::NONE; + }; + let to_after = self.balance(to).saturating_add(value); + self.balance_change(from, from_after).with(self.balance_change(to, to_after)) + } + + /// The records a creation by `creator` with an endowment of `value` makes: the account it + /// creates, and the creator's nonce, when the bump changes an account the transaction had not + /// changed; nothing for an endowment `creator` cannot fund, which revm refuses before it bumps + /// the nonce. + pub(crate) fn creation_records(&self, creator: Address, value: U256) -> FrameStartRecords { + if self.balance(creator) < value { + return FrameStartRecords::NONE; + } + FrameStartRecords { + on_level: RecordDelta { added: 1, taken: 0 }, + creator: !self.is_changed(creator), + } + } + + /// The records the frame `start` makes, for the frame-start hook to charge its caller for: a + /// call's value transfer ([`transfer_records`](Self::transfer_records)), a creation's created + /// account and creator nonce ([`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. Nor does a start whose value the caller cannot fund, + /// which revm refuses on the caller's account. + pub(crate) fn start_records(&self, start: &FrameStart) -> FrameStartRecords { + match start.kind { + FrameStartKind::Create | FrameStartKind::Create2 => { + self.creation_records(start.caller, start.value) + } + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => FrameStartRecords { + on_level: start.target.map_or(RecordDelta::NONE, |target| { + self.transfer_records(start.caller, target, start.value) + }), + creator: false, + }, + } + } } impl Deref for MegaJournal { @@ -167,12 +286,6 @@ impl JournalTr for MegaJournal { fn log(&mut self, log: Log); fn take_logs(&mut self) -> Vec; fn logs(&self) -> &[Log]; - fn selfdestruct( - &mut self, - address: Address, - target: Address, - skip_cold_load: bool, - ) -> Result, JournalLoadError>; fn warm_access_list(&mut self, access_list: AddressMap>); fn warm_coinbase_account(&mut self, address: Address); fn warm_precompiles(&mut self, addresses: &AddressSet); @@ -245,22 +358,33 @@ impl JournalTr for MegaJournal { } } - /// Counted inside a call's start window: the records the transfer makes and its transfer log. + /// Counted inside a call's start window: the records the transfer makes and takes back, as + /// the accounts it writes stand before and after it, and its transfer log. fn transfer_loaded( &mut self, from: Address, to: Address, balance: U256, ) -> Option { + let moves = from != to && !balance.is_zero(); + let before = moves.then(|| (self.is_changed(from), self.is_changed(to))); let logs = self.revm.logs().len(); let refused = self.revm.transfer_loaded(from, to, balance); let logged = self.revm.logs().len() > logs; - self.ledger.on_transfer(from, to, balance, refused.is_some(), logged); + let records = match before.filter(|_| refused.is_none()) { + Some((from_before, to_before)) => { + RecordDelta::of_account(from_before, self.is_changed(from)) + .with(RecordDelta::of_account(to_before, self.is_changed(to))) + } + None => RecordDelta::NONE, + }; + self.ledger.on_transfer(records, refused.is_some(), logged); refused } /// Counted inside a creation's start window: the creator's nonce record before the creation's - /// level opens, then the created account and the transfer log on it. + /// level opens, when the bump revm made changed an account the transaction had not changed, + /// then the created account and the transfer log on it. fn create_account_checkpoint( &mut self, caller: Address, @@ -268,15 +392,36 @@ impl JournalTr for MegaJournal { balance: U256, spec_id: SpecId, ) -> Result { - let start = self.ledger.before_creation(); + let start = self.ledger.before_creation(!self.is_changed_before_bump(caller)); let logs = self.revm.logs().len(); let opened = self.revm.create_account_checkpoint(caller, address, balance, spec_id); let logged = self.revm.logs().len() > logs; - self.ledger.after_creation(start, address, opened.ok(), logged); + self.ledger.after_creation(start, opened.ok(), logged); self.assert_levels(); opened } + /// Observed for the completed-write hook: the records the destruction makes and takes back, as + /// the destructed account and its beneficiary stand before and after the move. The hook counts + /// them once the opcode completed; the write itself counts nothing here. + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, JournalLoadError> { + let before = (self.is_changed(address), self.is_changed(target)); + let result = self.revm.selfdestruct(address, target, skip_cold_load); + let records = if result.is_ok() { + RecordDelta::of_account(before.0, self.is_changed(address)) + .with(RecordDelta::of_account(before.1, self.is_changed(target))) + } else { + RecordDelta::NONE + }; + self.ledger.observe_destruction(records); + result + } + fn checkpoint(&mut self) -> JournalCheckpoint { let checkpoint = self.revm.checkpoint(); self.ledger.on_checkpoint(checkpoint); @@ -330,7 +475,7 @@ impl JournalExt for MegaJournal { mod tests { use super::*; use crate::{ - limit::{Mark, StartFacts, StartReport, StartSide}, + limit::{HistoryBytes, Mark, StartFacts, StartReport, StartSide}, test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, @@ -369,7 +514,8 @@ mod tests { } /// A journal on Satin's base spec, with transfer logs, every account funded, holding a - /// transaction from [`SENDER`] under `limits`. + /// transaction from [`SENDER`] under `limits`. The sender is changed as validation leaves it: + /// its nonce bumped. fn journal(limits: EvmTxRuntimeLimits) -> MegaJournal { let db = [SENDER, A, B, C].into_iter().fold(MemoryDatabase::default(), |db, account| { db.account_balance(account, U256::from(10)) @@ -380,6 +526,7 @@ mod tests { for account in [SENDER, A, B, C, CREATED] { journal.load_account(account).unwrap(); } + let _ = journal.load_account_mut(SENDER).unwrap().data.bump_nonce(); journal.ledger_mut().set_limits(limits); journal.ledger_mut().begin_transaction(false, true, TX_BODY_SIZE); journal @@ -395,8 +542,7 @@ mod tests { value: u64, ) -> (JournalCheckpoint, StartReport) { let value = U256::from(value); - let facts = - StartFacts { depth, caller, target: Some(target), transfers_value: !value.is_zero() }; + let facts = StartFacts { depth, creation: false, transfers_value: !value.is_zero() }; journal.ledger_mut().open_start(facts); let checkpoint = journal.checkpoint(); assert!(journal.transfer_loaded(caller, target, value).is_none()); @@ -413,8 +559,7 @@ mod tests { value: u64, ) -> (JournalCheckpoint, StartReport) { let value = U256::from(value); - let facts = - StartFacts { depth, caller: creator, target: None, transfers_value: !value.is_zero() }; + let facts = StartFacts { depth, creation: true, transfers_value: !value.is_zero() }; journal.ledger_mut().open_start(facts); let _ = journal.load_account_mut(creator).unwrap().data.bump_nonce(); let checkpoint = @@ -434,7 +579,8 @@ mod tests { /// The journal's own write methods count nothing, inside a frame start's window and outside /// it: a write an opcode completed is counted by the Host's completed-write hook, and any other - /// is not the transaction's own execution. + /// is not the transaction's own execution. A `SELFDESTRUCT` is observed for that hook, and + /// counts nothing until the hook counts it. #[test] fn test_the_journals_own_writes_count_nothing() { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); @@ -451,8 +597,7 @@ mod tests { journal.ledger_mut().open_start(StartFacts { depth: 1, - caller: A, - target: Some(B), + creation: false, transfers_value: false, }); let _ = journal.checkpoint(); @@ -539,12 +684,70 @@ mod tests { assert_eq!(journal.ledger().usage(), kept(2, 1), "readable until the next transaction"); } + /// An account is changed once its nonce, balance or code differs from what the transaction + /// loaded, and unchanged again once a write returns it; one the transaction has not loaded is + /// unchanged. The sender is changed from the start, by the nonce validation bumped. + #[test] + fn test_an_account_is_changed_while_its_info_differs_from_what_was_loaded() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + assert!(journal.is_changed(SENDER), "validation bumped its nonce"); + assert!(!journal.is_changed(A)); + assert!( + !journal.is_changed(address!("00000000000000000000000000000000000a00ff")), + "not loaded" + ); + assert_eq!(journal.transfer(A, B, U256::from(3)).unwrap(), None); + assert!(journal.is_changed(A) && journal.is_changed(B)); + assert_eq!(journal.transfer(B, A, U256::from(3)).unwrap(), None); + assert!(!journal.is_changed(A) && !journal.is_changed(B), "both returned"); + let _ = journal.load_account_mut(A).unwrap().data.bump_nonce(); + assert!(journal.is_changed(A), "a nonce bump changes it"); + assert!(!journal.is_changed_before_bump(A), "but not before the bump"); + journal.set_code(B, Bytecode::new_raw(Bytes::from_static(&[0x00]))); + assert!(journal.is_changed(B), "code changes it"); + } + + /// The records a transfer makes are predicted from the journal's state as the hook sees it and + /// counted as revm makes the transfer, and the two agree: a transfer that changes both + /// accounts, one whose sender the transaction changed, one that returns an account, and the + /// moves that make none — to the same account, of nothing, of more than the sender holds. + #[test] + fn test_the_records_predicted_for_a_transfer_are_the_records_counted() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let none = RecordDelta::NONE; + let both = RecordDelta { added: 2, taken: 0 }; + let recipient = RecordDelta { added: 1, taken: 0 }; + assert_eq!(journal.transfer_records(A, A, U256::from(1)), none, "to itself"); + assert_eq!(journal.transfer_records(A, B, U256::ZERO), none, "of nothing"); + assert_eq!(journal.transfer_records(A, B, U256::from(11)), none, "unfunded"); + assert_eq!(journal.transfer_records(SENDER, B, U256::from(1)), recipient, "the sender"); + assert_eq!(journal.transfer_records(A, B, U256::from(1)), both); + + let (_, report) = start_call(&mut journal, 1, A, B, 1); + assert_eq!(report.records.on_level, both, "counted as predicted"); + end_frame(&mut journal, None); + assert_eq!( + journal.transfer_records(B, A, U256::from(1)), + RecordDelta { added: 0, taken: 2 }, + "the return takes both back" + ); + assert_eq!( + journal.transfer_records(B, C, U256::from(1)), + RecordDelta { added: 1, taken: 1 }, + "B returns, C changes" + ); + let (_, report) = start_call(&mut journal, 1, B, A, 1); + assert_eq!(report.records.on_level, RecordDelta { added: 0, taken: 2 }); + assert_eq!(journal.ledger().usage(), kept(0, 2), "the records went, the logs stay"); + } + /// A tool's checkpoint around a call's start — opened before the start, closed after the frame /// returned — is a rollback level the frame's level sits above. Committed, it changes nothing: - /// the frame's records stand, its refund is none, and its caller's account stays recorded, so a + /// the frame's records stand, its refund is none, and its caller's account stays changed, so a /// later value call from it records only its recipient. Reverted, it takes back what the frame - /// kept: the records, the caller's flag and the frame's refund all go back to before the - /// start, and the later call records the caller again. + /// kept: the records and the frame's refund all go back to before the start, and the later + /// call finds the caller unchanged and records it again. #[test] fn test_a_tool_checkpoint_around_a_call_closes_in_order() { for reverted in [false, true] { @@ -554,24 +757,25 @@ mod tests { let tool = journal.checkpoint(); let (_, report) = start_call(&mut journal, 1, A, B, 1); assert_eq!( - (report.on_level, report.caller_on_level, report.transfer_log), - (1, true, true), + (report.records.on_level, report.transfer_log), + (RecordDelta { added: 2, taken: 0 }, true), "{case}: B's record, A's, and the log" ); end_frame(&mut journal, None); - let mut side = StartSide::new(1, 7, 11, None); + let mut side = StartSide::new(1, 7, 0, true, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); } else { journal.checkpoint_commit(); } - let refund = if reverted { 7 + 11 } else { 0 }; + let refund = if reverted { 7 } else { 0 }; assert_eq!(side.refund(journal.ledger()), refund, "{case}: B's refund"); assert_eq!(journal.ledger().usage(), if reverted { body() } else { kept(2, 1) }); let (_, later) = start_call(&mut journal, 1, A, C, 1); - assert_eq!(later.caller_on_level, reverted, "{case}: A's flag"); + let records = if reverted { 2 } else { 1 }; + assert_eq!(later.records.on_level.added, records, "{case}: A's account"); end_frame(&mut journal, None); let records = if reverted { 2 } else { 3 }; assert_eq!(journal.ledger().usage(), kept(records, if reverted { 1 } else { 2 })); @@ -581,10 +785,10 @@ mod tests { /// A tool's checkpoint around a creation's start closes in order as one around a call does, and /// a revert of it takes back the creator's nonce record with the rest, which the creation's own /// failure leaves: the creator's caller gets back the charge for that record too, and the - /// creator's account is unrecorded again, so its next creation records it. + /// creator's account is unchanged again, so its next creation records it. #[test] fn test_a_tool_checkpoint_around_a_creation_takes_its_creators_record_back() { - for (case, failed, reverted, refund, creator_recorded) in [ + for (case, failed, reverted, refund, creator_changed) in [ ("a creation that succeeds, the tool's checkpoint committed", false, false, 0, true), ("a creation that fails, the tool's checkpoint committed", true, false, 7, true), ( @@ -601,9 +805,9 @@ mod tests { let _ = start_call(&mut journal, 1, A, B, 0); let tool = journal.checkpoint(); let (checkpoint, report) = start_creation(&mut journal, 2, B, CREATED, 1); - assert!(report.creator_record, "{case}: B's nonce record is the start's"); + assert!(report.records.creator, "{case}: B's nonce record is the start's"); end_frame(&mut journal, failed.then_some(checkpoint)); - let mut side = StartSide::new(2, 7, 11, None); + let mut side = StartSide::new(2, 7, 11, true, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); @@ -612,7 +816,7 @@ mod tests { } assert_eq!(side.refund(journal.ledger()), refund, "{case}: the refund"); let (_, later) = start_creation(&mut journal, 2, B, C, 0); - assert_eq!(!later.creator_record, creator_recorded, "{case}: B's flag"); + assert_eq!(!later.records.creator, creator_changed, "{case}: B's account"); } } @@ -630,7 +834,7 @@ mod tests { } /// A creation's budget and usage are measured from before its creator's nonce record, and its - /// level opens after it: with `R` bytes left to an unrecorded creator, the creation gets + /// level opens after it: with `R` bytes left to an unchanged creator, the creation gets /// `R − ⌈R / 50⌉` and starts with the created account's record and the creator's, 80 bytes. /// At 81 bytes that is a budget of 79, which the start crosses; at 100, a budget of 98, which /// leaves the creation 18 bytes. An endowment adds its transfer log to the start. @@ -647,7 +851,7 @@ mod tests { let _ = start_call(&mut journal, 0, SENDER, A, 0); let (_, report) = start_creation(&mut journal, 1, A, CREATED, value); let case = format!("{left} bytes left, value {value}"); - assert!(report.creator_record, "{case}: the creator's record is the start's"); + assert!(report.records.creator, "{case}: the creator's record is the start's"); let used = LimitUsage { data_size: start, write_records: 2 }; assert_eq!(journal.ledger().running_budget(), Some((budget, used)), "{case}"); let verdict = if start > budget { @@ -666,7 +870,7 @@ mod tests { /// A creation's start mark is its level's opening — after the creator's record — never where /// its usage is measured from: a creation rewritten into a failure is taken back to it, and - /// keeps its creator's record and flag, as a creation that fails does. + /// keeps its creator's record, as a creation that fails does, the creator's nonce standing. #[test] fn test_a_creations_start_mark_keeps_its_creators_record() { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); @@ -680,7 +884,7 @@ mod tests { journal.revert_to(&mark); assert_eq!(journal.ledger().usage(), kept(1, 0), "the creator's record stays"); let (_, later) = start_creation(&mut journal, 1, A, C, 0); - assert!(!later.creator_record, "A stays recorded"); + assert!(!later.records.creator, "A stays changed"); } /// The hypothetical start a call gas detention answers without running is held to the limits @@ -703,10 +907,50 @@ mod tests { let _ = start_call(&mut journal, 0, SENDER, A, 0); A }; - let facts = StartFacts { depth, caller, target: Some(B), transfers_value: value != 0 }; - let hypothetical = journal.ledger().hypothetical_start(&facts); + let records = journal.transfer_records(caller, B, U256::from(value)); + let logged = journal.ledger().counts_transfer_logs() && value != 0; + let hypothetical = journal.ledger().hypothetical_start(records, logged); let (_, report) = start_call(&mut journal, depth, caller, B, value); assert_eq!(Some(hypothetical), report.verdict, "depth {depth}, value {value}, {room}"); } } + + /// A `SELFDESTRUCT` is observed for the completed-write hook as its move leaves the two + /// accounts: the destructed account, whose balance it clears, and the beneficiary. A + /// beneficiary the transaction gave its balance is returned by the move; a destruction to + /// itself, of an account the transaction did not create, moves nothing. + #[test] + fn test_a_destruction_is_observed_for_the_hook() { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + let records = |journal: &mut MegaJournal, from, to| { + journal.selfdestruct(from, to, false).unwrap(); + journal.ledger().write_count( + &revm::context_interface::host::CompletedWrite::SelfDestruct { + address: from, + target: to, + result: &SelfDestructResult { had_value: true, ..Default::default() }, + }, + ) + }; + let (count, history) = records(&mut journal, A, B); + assert_eq!( + count.added, + LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 2 } + ); + assert_eq!(count.taken, LimitUsage::ZERO); + assert_eq!(history, HistoryBytes { appended: 2 * WRITE_RECORD_SIZE, taken: 0 }); + + // C gives three of its ten to an account that holds nothing, which destructs back to C: + // both are as the transaction loaded them again. + assert_eq!(journal.transfer(C, CREATED, U256::from(3)).unwrap(), None); + let (count, history) = records(&mut journal, CREATED, C); + assert_eq!(count.added, LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }); + assert_eq!(count.taken, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); + assert_eq!(history, HistoryBytes { appended: 0, taken: 2 * WRITE_RECORD_SIZE }); + + let (count, _) = records(&mut journal, C, C); + assert_eq!(count.added, LimitUsage::ZERO, "a destruction to itself moves nothing"); + assert_eq!(count.taken, LimitUsage::ZERO); + } } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 24ccd80a8..74ac9d849 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -13,18 +13,23 @@ //! - a **frame level**, for each frame revm starts: the first checkpoint revm opens while it //! decides a call's start, or the one a creation's account checkpoint returns. Only the engine's //! start window ([`open_start`](Ledger::open_start)) opens one. It carries the frame's data-size -//! budget, the account the frame runs as and whether that account is already recorded; +//! budget; //! - a **rollback level**, for every other checkpoint: the pre-execution phase's, a system call's, //! a precompile's, a tool's. It carries what its revert restores and nothing else. //! -//! Budgets, the per-frame dedup of a frame's own account and the running frame's check use the -//! nearest frame level. A rollback level may enclose a frame start (a tool's checkpoint opened -//! before a call and closed after it) as long as the two close in order. A revert that would close -//! a level from below — a checkpoint reverted while a level opened after it is still open — is not -//! supported, and trips in debug builds. +//! Budgets and the running frame's check use the nearest frame level. A rollback level may enclose +//! a frame start (a tool's checkpoint opened before a call and closed after it) as long as the two +//! close in order. A revert that would close a level from below — a checkpoint reverted while a +//! level opened after it is still open — is not supported, and trips in debug builds. //! //! # What is counted where //! +//! An account's write record follows the net change of its info within the transaction: the +//! journal tells the ledger, at each write, which accounts the write changed from what the +//! transaction loaded and which it returned to that ([`RecordDelta`]), and the ledger counts a +//! record for the first and takes one back for the second. A storage slot's record follows the +//! slot's original value the same way. So: +//! //! - the body and the Oracle hints, as the ledger's base, which no revert takes back; //! - the records of the applied EIP-7702 authorities, inside the pre-execution level; //! - a frame start's records and its transfer log, inside the start window, at the two writes revm @@ -49,17 +54,14 @@ use alloc as std; use std::vec::Vec; -use alloy_primitives::{Address, U256}; -use revm::context_interface::{ - host::{CompletedWrite, FrameStart, FrameStartKind}, - journaled_state::JournalCheckpoint, -}; +use revm::context_interface::{host::CompletedWrite, journaled_state::JournalCheckpoint}; use super::{ - record::{write_effect, write_moves_value, HistoryBytes, RecordEffect, WriteCount}, + record::{write_effect, write_moves_value, HistoryBytes, RecordDelta, WriteCount}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, }; +use crate::write_record_history_gas; /// What the ledger counts that the journal rewinds: additions and refunds, kept apart so that a /// frame's own usage saturates at zero on its own — a child can take back a slot its parent @@ -68,7 +70,8 @@ use super::{ pub(crate) struct Counts { /// What was counted. used: LimitUsage, - /// What was taken back: a slot written back to its original value. + /// What was taken back: a slot written back to its original value, an account returned to + /// what the transaction loaded. refund: LimitUsage, /// The log and code bytes among [`used`](Self::used). log_and_code_bytes: u64, @@ -99,11 +102,6 @@ struct FrameLevel { depth: usize, /// The most data-size bytes the frame may keep. budget: u64, - /// The account the frame runs as. - account: 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. - recorded: bool, /// Whether the frame's start counted its creator's nonce record, right before its level /// opened: the frame's usage is measured from before it. creator_record: bool, @@ -118,9 +116,6 @@ struct Level { opened_at: JournalCheckpoint, /// The counts its revert restores. at_open: Counts, - /// Whether the nearest frame level below it had its account recorded when it opened, which its - /// revert restores. - recorded_at_open: bool, /// The start the next frame start would be when it opened: a start at or after it began /// inside it. next_start_at_open: StartId, @@ -134,10 +129,8 @@ struct Level { pub(crate) struct StartFacts { /// The frame's depth. pub(crate) depth: usize, - /// The account starting the frame. - pub(crate) caller: Address, - /// The call's target; `None` for a creation. - pub(crate) target: Option
, + /// Whether the start is a creation; a call otherwise. + pub(crate) creation: bool, /// Whether the start transfers value: a call carrying a non-zero transfer, or a creation with /// an endowment. pub(crate) transfers_value: bool, @@ -146,15 +139,17 @@ pub(crate) struct StartFacts { /// 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 level, which its failure takes back. - pub(crate) on_level: u64, - /// Whether the frame's start also writes its caller's account. - pub(crate) caller: bool, + /// The records on the frame's own level, which its failure takes back: the accounts a value + /// transfer changes and returns, a creation's created account. + pub(crate) on_level: RecordDelta, + /// Whether the start writes its creator's nonce record, on the creating frame, which the + /// creation's failure leaves there. + pub(crate) creator: bool, } impl FrameStartRecords { /// No record at all. - pub(crate) const NONE: Self = Self { on_level: 0, caller: false }; + pub(crate) const NONE: Self = Self { on_level: RecordDelta::NONE, creator: false }; } /// The start window, open while revm decides one frame start. @@ -174,14 +169,8 @@ struct Window { pub(crate) struct StartReport { /// The start, once revm decided it in a start window; `None` for a start answered before. pub(crate) start: Option, - /// The records counted on the start's own level: a value call's recipient, a creation's - /// account. - pub(crate) on_level: u64, - /// Whether the start counted its caller's record on its own level: a value transfer's sender. - pub(crate) caller_on_level: bool, - /// Whether the start counted its creator's nonce record, below its own level, where the - /// creation's failure leaves it. - pub(crate) creator_record: bool, + /// The records the start counted: on its own level, and its creator's below it. + pub(crate) records: FrameStartRecords, /// Whether the start counted the transfer log revm journaled for it. pub(crate) transfer_log: bool, /// Whether revm refused the start's value transfer. @@ -202,13 +191,11 @@ struct Fate { start_kept: bool, } -/// What a revert of the ledger restores: the counts, the running frame's flag and the levels open. +/// What a revert of the ledger restores: the counts and the levels open. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Rollback { /// The counts. counts: Counts, - /// Whether the nearest frame level had its account recorded; `None` when there is none. - recorded: Option, /// The number of levels open: a revert finds at most these. levels: usize, } @@ -259,11 +246,9 @@ pub(crate) struct Ledger { last_decided: Option, /// The next frame start. next_start: StartId, - /// The transaction's sender, whose account the body counts. - sender: Address, - /// Whether the transaction's call target is an applied EIP-7702 authority, whose record the - /// authorities' records hold. - target_is_authority: bool, + /// The records the journal saw the last `SELFDESTRUCT` make and take back, for the + /// completed-write hook to count once the opcode completed. + destruction: RecordDelta, /// Whether a value movement journals an EIP-7708 transfer log. transfer_logs: bool, limits: EvmTxRuntimeLimits, @@ -298,8 +283,7 @@ impl Ledger { self.last_start = None; self.last_decided = None; self.next_start = StartId::default(); - self.sender = Address::ZERO; - self.target_is_authority = false; + self.destruction = RecordDelta::NONE; self.transfer_logs = transfer_logs; self.exempt = exempt; } @@ -339,12 +323,6 @@ impl Ledger { .exceeds_data_size(self.limits.tx_data_size_limit) } - /// Whether the transaction's call target is an applied EIP-7702 authority, whose record the - /// authorities' records hold, so the transaction's own frame writes no recipient. - pub(crate) const fn target_is_authority(&self) -> bool { - self.target_is_authority - } - /// The number of levels open, which is revm's journal depth. pub(crate) fn depth(&self) -> usize { self.levels.len() @@ -360,12 +338,6 @@ impl Ledger { self.frames.last_mut() } - /// The level of the frame below the running one: the one that started it. - fn calling_level_mut(&mut self) -> Option<&mut FrameLevel> { - let caller = self.frames.len().checked_sub(2)?; - self.frames.get_mut(caller) - } - /// What `frame` keeps so far, the children it kept included: what was counted since its level /// opened, and its creator's nonce record, counted right before. fn frame_usage(&self, frame: &FrameLevel) -> LimitUsage { @@ -393,7 +365,6 @@ impl Ledger { /// Whether the transaction's value movements journal EIP-7708 transfer logs, which the ledger /// counts where the value moves. - #[cfg(test)] pub(crate) const fn counts_transfer_logs(&self) -> bool { self.transfer_logs } @@ -450,87 +421,24 @@ impl Ledger { forwarded.min(self.limits.frame_data_size_limit) } - /// The records a value call from `from` to `to` at `depth` makes: its recipient, on its own - /// level, and whether it records its caller's account, which the calling frame has - /// (`caller_recorded`) or has not recorded yet. - /// - /// The transaction's own frame records the recipient unless it is the sender or an applied - /// authority. Any other records the recipient unless it is the caller or the sender, and the - /// caller's own account once per frame; a `CALLCODE` or a call to itself records the caller - /// although revm moves nothing. - fn call_records( - &self, - depth: usize, - from: Address, - to: Address, - caller_recorded: bool, - ) -> (u64, bool) { - if depth == 0 { - return (u64::from(to != from && !self.target_is_authority), false); - } - (u64::from(to != from && to != self.sender), !caller_recorded) - } - - /// The write records the start `start` describes makes, for the opcode about to start it, - /// which pays for them once it took the gas it forwards: 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. - /// - /// A call that moves no value writes nothing. A value call writes its recipient, unless that - /// is the caller itself or the transaction's sender, whose account the body counts. A creation - /// writes the account it creates. Either writes the caller's account — a transfer's sender, a - /// creation's creator nonce — unless the running frame already recorded it. They are the - /// records the start is counted by once revm makes it ([`on_transfer`](Self::on_transfer), - /// [`before_creation`](Self::before_creation)); a debug build holds the two answers to each - /// other where the frame starts. - pub(crate) fn start_records(&self, start: &FrameStart) -> FrameStartRecords { - let recorded = self.frame_level().is_some_and(|level| level.recorded); - let target = match start.kind { - FrameStartKind::Create | FrameStartKind::Create2 => { - return FrameStartRecords { on_level: 1, caller: !recorded }; - } - FrameStartKind::Call | - FrameStartKind::CallCode | - FrameStartKind::DelegateCall | - FrameStartKind::StaticCall => start.target, - }; - match target { - Some(target) if !start.value.is_zero() => { - // An opcode runs inside a frame, so the frame it starts is below the - // transaction's own. - let depth = self.frame_level().map_or(1, |level| level.depth + 1); - let (on_level, caller) = self.call_records(depth, start.caller, target, recorded); - FrameStartRecords { on_level, caller } - } - _ => FrameStartRecords::NONE, - } - } - /// 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: the records it would count and the - /// transfer log of the value it would move, held to the transaction's limit and to the budget - /// its frame would get. Nothing is counted. - pub(crate) fn hypothetical_start(&self, facts: &StartFacts) -> LimitCheck { - let Some(target) = facts.target else { - unreachable!("only a call is answered without revm deciding its start") - }; - let counted = if facts.transfers_value { - let recorded = self.frame_level().is_some_and(|level| level.recorded); - let (on_level, caller) = self.call_records(facts.depth, facts.caller, target, recorded); - with_transfer_log( - WRITE_RECORD.times(on_level + u64::from(caller)), - self.transfer_logs && target != facts.caller, - ) - } else { - LimitUsage::ZERO - }; - let (kept, limit) = (self.usage().saturating_add(counted), self.limits.tx_data_size_limit); + /// running the precompile it targets — had revm made it: the records its value transfer would + /// make and take back (`records`, as the journal predicts them) and the transfer log of the + /// value it would move (`logged`), held to the transaction's limit and to the budget its frame + /// would get. Nothing is counted. + pub(crate) fn hypothetical_start(&self, records: RecordDelta, logged: bool) -> LimitCheck { + let added = with_transfer_log(WRITE_RECORD.times(records.added), logged); + let taken = WRITE_RECORD.times(records.taken); + let (kept, limit) = ( + self.usage().saturating_add(added).saturating_sub(taken), + self.limits.tx_data_size_limit, + ); if kept.exceeds_data_size(limit) { return self.crossed(limit, kept.data_size, false); } - let budget = self.child_budget(); - if counted.exceeds_data_size(budget) { - return self.crossed(budget, counted.data_size, true); + let (budget, used) = (self.child_budget(), added.saturating_sub(taken)); + if used.exceeds_data_size(budget) { + return self.crossed(budget, used.data_size, true); } LimitCheck::WithinLimit } @@ -538,20 +446,13 @@ impl Ledger { /* What the transaction counts outside the journal's writes */ /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts - /// other than the transaction's `sender`, `target_is_authority` if the call target is one. - /// Inside the pre-execution level, whose revert takes them back. + /// other than the transaction's sender. Inside the pre-execution level, whose revert takes + /// them back. /// /// 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 count_authorities( - &mut self, - sender: Address, - authorities: u64, - target_is_authority: bool, - ) { - self.sender = sender; - self.target_is_authority = target_is_authority; + pub(crate) fn count_authorities(&mut self, authorities: u64) { self.counts.used = self.counts.used.saturating_add(WRITE_RECORD.times(authorities)); debug_assert!( self.exempt || !self.usage().exceeds_data_size(self.limits.tx_data_size_limit), @@ -574,40 +475,40 @@ impl Ledger { LimitCheck::WithinLimit } - /// What `write`, which the running opcode completed, keeps, and the history bytes it appends or - /// takes back: what [`count_write`](Self::count_write) counts, and what the Host's - /// completed-write hook charges. + /// Notes the records the journal saw a `SELFDESTRUCT` make and take back, for the + /// completed-write hook to count once the opcode completed; a `SELFDESTRUCT` whose opcode + /// then fails leaves them for the next one to overwrite. + pub(crate) const fn observe_destruction(&mut self, records: RecordDelta) { + self.destruction = records; + } + + /// What `write`, which the running opcode completed, keeps and takes back, and the history + /// bytes it appends and takes back: what [`count_write`](Self::count_write) counts, and what + /// the Host's completed-write hook charges and refills. /// /// A `SELFDESTRUCT` that moved value to another account also keeps the EIP-7708 transfer log - /// revm journaled for the move, with the beneficiary's record. The log is the running frame's, - /// as the move is: the frame's own journal checkpoint takes both back when the frame fails. It - /// is data size and nothing else — no write record, and no history: the bytes reported are the - /// record's alone. + /// revm journaled for the move, with the records its move made. The log is the running + /// frame's, as the move is: the frame's own journal checkpoint takes both back when the frame + /// fails. It is data size and nothing else — no write record, and no history: the bytes + /// reported are the records' alone. pub(crate) fn write_count(&self, write: &CompletedWrite<'_>) -> (WriteCount, HistoryBytes) { - let effect = write_effect(write, self.sender); - let history = effect.history_bytes(); - let added = match effect { - RecordEffect::None => LimitUsage::ZERO, - RecordEffect::Record(usage) => usage, - RecordEffect::Refund(usage) => { - return (WriteCount { taken: usage, ..WriteCount::NONE }, history); - } - }; + let (added, taken) = write_effect(write, self.destruction); + let history = HistoryBytes { appended: added.data_size, taken: taken.data_size }; // A log's bytes are history beside the write records; a record's are counted as one. let log_bytes = match write { CompletedWrite::Log { .. } => added.data_size, CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => 0, }; let added = with_transfer_log(added, self.transfer_logs && write_moves_value(write)); - (WriteCount { added, log_bytes, ..WriteCount::NONE }, history) + (WriteCount { added, taken, log_bytes }, history) } - /// Counts what a completed write keeps on the running frame's level: what it adds, or what it - /// takes back. The verdict is the check after an addition; a record taken back holds nothing. + /// Counts what a completed write keeps on the running frame's level: what it takes back, then + /// what it adds. The verdict is the check after an addition; a write that adds nothing holds + /// nothing. pub(crate) fn count_write(&mut self, count: &WriteCount) -> LimitCheck { if count.taken != LimitUsage::ZERO { self.counts.refund = self.counts.refund.saturating_add(count.taken); - return LimitCheck::WithinLimit; } self.counts.log_and_code_bytes = self.counts.log_and_code_bytes.saturating_add(count.log_bytes); @@ -629,27 +530,11 @@ impl Ledger { self.check() } - /// Runs the running frame — a `keylessDeploy` call's — as `creator`, whose nonce the creation - /// it starts writes: recorded already when the creator is the transaction's sender. - pub(crate) fn set_frame_creator(&mut self, creator: Address) { - let sender = self.sender; - if let Some(level) = self.frame_level_mut() { - level.account = Some(creator); - level.recorded = creator == sender; - } - } - - /// Takes back the nonce record a creation left the running frame, a `keylessDeploy` call's, - /// when its nonce bump is taken back. `false` when there was none to take. - pub(crate) fn take_back_creator_record(&mut self) -> bool { - let sender = self.sender; - let Some(level) = self.frame_level_mut() else { return false }; - if level.account == Some(sender) || !level.recorded { - return false; - } - level.recorded = false; - self.counts.used = self.counts.used.saturating_sub(WRITE_RECORD); - true + /// Takes back one write record on the running frame's level, for an account a write outside + /// the journal's counted writes returned to what the transaction loaded: a `keylessDeploy` + /// call's signer, whose nonce the settlement sets back. + pub(crate) fn take_back_record(&mut self) { + self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD); } /* The start window */ @@ -657,9 +542,6 @@ impl Ledger { /// Opens the start window for the start `facts` describes, which revm decides next. pub(crate) fn open_start(&mut self, facts: StartFacts) { debug_assert!(self.window.is_none(), "start windows do not nest"); - if facts.depth == 0 { - self.sender = facts.caller; - } let start = self.next_start; self.next_start = StartId(start.0 + 1); self.last_start = Some(StartReport { start: Some(start), ..Default::default() }); @@ -685,25 +567,21 @@ impl Ledger { /// Opens a level at `opened_at`, a frame level when `frame`. fn open_level(&mut self, opened_at: JournalCheckpoint, frame: bool) { - let recorded_at_open = self.frame_level().is_some_and(|level| level.recorded); self.levels.push(Level { opened_at, at_open: self.counts, - recorded_at_open, next_start_at_open: self.next_start, frame, }); } - /// Opens the frame level of the window's start at `opened_at`, under `budget`, running as - /// `account`, recorded or not, its usage measured from before its creator's nonce record when - /// the start counted one (`creator_record`): the frame the window's start builds. + /// Opens the frame level of the window's start at `opened_at`, under `budget`, its usage + /// measured from before its creator's nonce record when the start counted one + /// (`creator_record`): the frame the window's start builds. fn open_frame_level( &mut self, opened_at: JournalCheckpoint, budget: u64, - account: Address, - recorded: bool, creator_record: bool, ) { let Some(window) = &mut self.window else { @@ -717,8 +595,6 @@ impl Ledger { start, depth, budget, - account: Some(account), - recorded, creator_record, returning: false, }); @@ -731,108 +607,78 @@ impl Ledger { let Some(window) = self.window.filter(|window| !window.opened) else { return self.open_level(opened_at, false); }; - let StartFacts { depth, caller, target, transfers_value } = window.facts; - let Some(target) = target else { + if window.facts.creation { // A creation's frame level is the one its account checkpoint opens. return self.open_level(opened_at, false); - }; - // The one start rule that stays an interpretation of the input: whether the frame's own - // account is recorded before anything of the frame is counted. - let recorded = if depth == 0 { - target == caller || self.target_is_authority || transfers_value - } else { - let inherited = self - .frame_level() - .is_some_and(|parent| parent.account == Some(target) && parent.recorded); - inherited || target == self.sender || transfers_value - }; - self.open_frame_level(opened_at, self.child_budget(), target, recorded, false); + } + self.open_frame_level(opened_at, self.child_budget(), false); // A start that moves value is held once its transfer is counted (`on_transfer`); any // other has nothing of its own to count, and is held now. - if !transfers_value { + if !window.facts.transfers_value { let verdict = self.check(); self.report_mut().verdict = Some(verdict); } } - /// revm moved `value` from `from` to `to` for the call whose start the window is open for - /// (`refused` when it could not), and journaled a transfer log or not (`logged`): counts the - /// records the transfer makes on the call's level ([`call_records`](Self::call_records)), then - /// holds the start to the limits. - pub(crate) fn on_transfer( - &mut self, - from: Address, - to: Address, - value: U256, - refused: bool, - logged: bool, - ) { + /// revm moved the value of the call whose start the window is open for (`refused` when it + /// could not), changing and returning the accounts `records` says, and journaled a transfer + /// log or not (`logged`): counts the records on the call's level, then holds the start to the + /// limits. + pub(crate) fn on_transfer(&mut self, records: RecordDelta, refused: bool, logged: bool) { let Some(window) = &mut self.window else { return }; - if window.counted || !window.opened || window.facts.target.is_none() { + if window.counted || !window.opened || window.facts.creation { return; } window.counted = true; - let depth = window.facts.depth; if refused { let report = self.report_mut(); report.refused = true; report.verdict = None; return; } - if value.is_zero() { + if !window.facts.transfers_value { return; } - let caller_recorded = self.calling_level_mut().is_none_or(|caller| caller.recorded); - let (on_level, caller_on_level) = self.call_records(depth, from, to, caller_recorded); - if caller_on_level { - if let Some(caller) = self.calling_level_mut() { - caller.recorded = true; - } - } - let counted = WRITE_RECORD.times(on_level + u64::from(caller_on_level)); - self.counts.used = self.counts.used.saturating_add(with_transfer_log(counted, logged)); + let added = with_transfer_log(WRITE_RECORD.times(records.added), logged); + self.counts.used = self.counts.used.saturating_add(added); + self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD.times(records.taken)); let verdict = self.check(); let report = self.report_mut(); - report.on_level = on_level; - report.caller_on_level = caller_on_level; + report.records = FrameStartRecords { on_level: records, creator: false }; report.transfer_log = logged; report.verdict = Some(verdict); } - /// revm is about to open a creation's account checkpoint for the start of the window: takes the - /// creation's budget and base, then counts the creator's nonce record, before anything of the - /// creation. `None` outside a creation's start window. - pub(crate) fn before_creation(&mut self) -> Option { + /// revm is about to open a creation's account checkpoint for the start of the window, having + /// bumped its creator's nonce: takes the creation's budget and base, then counts the creator's + /// nonce record when the bump changed an account the transaction had not changed + /// (`creator_unchanged`), before anything of the creation. The transaction's own creation + /// writes its sender's nonce, which the body counts. `None` outside a creation's start + /// window. + pub(crate) fn before_creation(&mut self, creator_unchanged: bool) -> Option { let window = self.window.as_mut()?; - if window.counted || window.facts.target.is_some() { + if window.counted || !window.facts.creation { return None; } window.counted = true; let depth = window.facts.depth; let budget = self.child_budget(); - let mut creator_record = false; - if depth > 0 { - if let Some(level) = self.frame_level_mut() { - creator_record = !level.recorded; - level.recorded = true; - } - } + let creator_record = depth > 0 && creator_unchanged; if creator_record { self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); } Some(CreationStart { budget, creator_record, depth }) } - /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation at - /// `address`, and journaled a transfer log or not (`logged`): opens the creation's frame level, - /// counts the created account and the log on it, then holds the start to the limits. The - /// creation's usage includes its creator's nonce record; its revert keeps it. + /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation, and + /// journaled a transfer log or not (`logged`): opens the creation's frame level, counts the + /// created account and the log on it, then holds the start to the limits. The creation's usage + /// includes its creator's nonce record; its revert keeps it. /// /// A checkpoint opened outside a creation's start window opens a rollback level. pub(crate) fn after_creation( &mut self, start: Option, - address: Address, opened: Option, logged: bool, ) { @@ -842,14 +688,14 @@ impl Ledger { } return; }; - self.report_mut().creator_record = start.creator_record; + self.report_mut().records.creator = start.creator_record; let Some(opened_at) = opened else { return }; debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); - self.open_frame_level(opened_at, start.budget, address, true, start.creator_record); + self.open_frame_level(opened_at, start.budget, start.creator_record); self.counts.used = self.counts.used.saturating_add(with_transfer_log(WRITE_RECORD, logged)); let verdict = self.check(); let report = self.report_mut(); - report.on_level = 1; + report.records.on_level = RecordDelta { added: 1, taken: 0 }; report.transfer_log = logged; report.verdict = Some(verdict); } @@ -872,8 +718,8 @@ impl Ledger { ); } - /// revm's journal committed its latest checkpoint: the level closes, and a frame level hands - /// its frame's flag to a caller running as the same account. + /// revm's journal committed its latest checkpoint: the level closes, and what it counted stays + /// with the level below. pub(crate) fn on_commit(&mut self) { let Some(level) = self.levels.pop() else { return }; if !level.frame { @@ -881,17 +727,11 @@ impl Ledger { } let frame = self.pop_frame(); self.assert_frame_closes(&frame); - if let Some(caller) = self.frame_level_mut() { - if frame.account.is_some() && frame.account == caller.account { - caller.recorded |= frame.recorded; - } - } self.last_decided = Some(Fate { start: frame.start, level_kept: true, start_kept: true }); } /// revm's journal reverted to `checkpoint`: the latest level, which must be the one opened - /// there, closes, and the counts and the flag of the nearest frame level below it are what they - /// were when it opened. + /// there, closes, and the counts are what they were when it opened. /// /// A frame level's revert keeps what its start counted below it, a creator's nonce record. A /// rollback level a start began inside — a tool's checkpoint around a call — takes everything @@ -904,9 +744,6 @@ impl Ledger { ); let frame = level.frame.then(|| self.pop_frame()); self.counts = level.at_open; - if let Some(caller) = self.frame_level_mut() { - caller.recorded = level.recorded_at_open; - } match frame { Some(frame) => { self.assert_frame_closes(&frame); @@ -949,34 +786,24 @@ impl Ledger { pub(crate) fn mark(&self, position: JournalCheckpoint) -> Mark { Mark { position, - rollback: Rollback { - counts: self.counts, - recorded: self.frame_level().map(|level| level.recorded), - levels: self.levels.len(), - }, + rollback: Rollback { counts: self.counts, levels: self.levels.len() }, next_start: self.next_start, own_start: None, } } /// What a frame revm just built is taken back to when it is rewritten into a failure, with its - /// start: the counts its level opened with — after a creation's creator record — and whether - /// the frame below had its account recorded then. Never where the frame's usage is measured - /// from, which for a creation is before the creator's record. The frame's side keeps it past - /// the level's commit, for the mark the rewrite reverts to ([`StartSide::built_mark`]). + /// start: the counts its level opened with — after a creation's creator record. Never where + /// the frame's usage is measured from, which for a creation is before the creator's record. + /// The frame's side keeps it past the level's commit, for the mark the rewrite reverts to + /// ([`StartSide::built_mark`]). pub(crate) fn frame_start_rollback(&self) -> Option<(StartId, Rollback)> { let level = self.levels.last()?; if !level.frame { return None; } let frame = self.frames.last()?; - let below = self.levels.len() - 1; - let caller = self.frames.len() > 1; - let rollback = Rollback { - counts: level.at_open, - recorded: caller.then_some(level.recorded_at_open), - levels: below, - }; + let rollback = Rollback { counts: level.at_open, levels: self.levels.len() - 1 }; Some((frame.start, rollback)) } @@ -988,17 +815,14 @@ impl Ledger { Some(Mark::of_built(self.levels.last()?.opened_at, start, rollback)) } - /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, the - /// running frame's flag, and what became of the last start decided. + /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, and + /// what became of the last start decided. pub(crate) fn revert_to(&mut self, mark: &Mark) { debug_assert!( self.levels.len() <= mark.rollback.levels, "a revert to a mark finds every level opened since closed" ); self.counts = mark.rollback.counts; - if let (Some(recorded), Some(level)) = (mark.rollback.recorded, self.frame_level_mut()) { - level.recorded = recorded; - } self.take_back_starts_from(mark.next_start, mark.own_start); } } @@ -1011,6 +835,12 @@ impl Mark { } } +/// The history gas `records` write records cost; nothing for a count with no price, which no +/// charge was made for. +fn records_history_gas(records: u64) -> u64 { + write_record_history_gas(records).unwrap_or(0) +} + /// Satin's side of one frame start: what its caller paid for the records it makes, what the /// ledger saw it count, the history allowance the frame was granted, and, for a frame revm built, /// what it is taken back to when it is rewritten into a failure. One per frame result revm will @@ -1019,21 +849,20 @@ impl Mark { pub(crate) struct StartSide { /// The frame's depth. depth: usize, - /// What the caller paid for the records on the frame's own level. - on_level_charge: u64, - /// What the caller paid for the record of its own account. - caller_charge: u64, + /// What the caller paid for the records the start adds on the frame's own level. + added_charge: u64, + /// What the caller paid for the record of its own nonce, for a creation. + creator_charge: u64, + /// Whether the transaction prices history, so that a record the start took back is history + /// the caller gets back. + priced: bool, /// What is left of the history allowance the 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. stipend: u64, /// The start, once revm decided it; `None` for a start answered before, which counted nothing. start: Option, - /// Whether the start counted records on its own level. - on_level: bool, - /// Whether the start counted its caller's record on its own level: a value transfer's sender. - caller_on_level: bool, - /// Whether the start counted its creator's nonce record, below its own level. - creator_record: bool, + /// The records the ledger saw the start count. + counted: FrameStartRecords, /// What a frame revm built is taken back to when it is rewritten into a failure. rollback: Option, /// The records the charge was computed from, when the charge was made from one and nothing @@ -1043,25 +872,26 @@ pub(crate) struct StartSide { } impl StartSide { - /// The side of a start at `depth` whose caller paid `on_level_charge` and `caller_charge` for - /// the records `charged`, when the charge was computed from them. + /// The side of a start at `depth` whose caller paid `added_charge` and `creator_charge` for + /// the records `charged`, when the charge was computed from them, in a transaction that + /// prices history or not (`priced`). pub(crate) const fn new( depth: usize, - on_level_charge: u64, - caller_charge: u64, + added_charge: u64, + creator_charge: u64, + priced: bool, charged: Option, ) -> Self { #[cfg(not(debug_assertions))] let _ = charged; Self { depth, - on_level_charge, - caller_charge, + added_charge, + creator_charge, + priced, stipend: 0, start: None, - on_level: false, - caller_on_level: false, - creator_record: false, + counted: FrameStartRecords::NONE, rollback: None, #[cfg(debug_assertions)] charged, @@ -1072,21 +902,20 @@ impl StartSide { /// back to, and holds the count to the records the start's charge was computed from. /// /// The two are separate answers to one question, asked at two points: the charge at the - /// opcode, on the facts revm's instruction hands the frame-start hook — or before execution, - /// on the transaction, for its own frame; or at a `keylessDeploy` call's first run, on the - /// creation it starts — and the count, on the writes revm made for the start. They agree - /// because the start revm makes carries the caller, target and value the charge was computed - /// from, and nothing between the two changes it: an interceptor answers a frame or lets it - /// start as it is, and a creation reaches none. A divergence trips in a debug build rather - /// than mis-charging the caller and mis-splitting the refund its failure gets back. An - /// inspector that may rewrite the start runs between the two, and can split them: under one - /// the start is not checked. Only a start revm made and held to the limits is checked: one it - /// refused, or failed before its level opened, counted nothing, and the charge comes back. + /// opcode, on the journal's state as revm's instruction hands the frame-start hook the start — + /// or before execution, on the transaction, for its own frame; or at a `keylessDeploy` call's + /// first run, on the creation it starts — and the count, on the writes revm made for the + /// start. They agree because the start revm makes carries the caller, target and value the + /// charge was computed from, and nothing between the two changes it or the accounts it + /// writes: an interceptor answers a frame or lets it start as it is, and a creation reaches + /// none. A divergence trips in a debug build rather than mis-charging the caller and + /// mis-splitting the refund its failure gets back. An inspector that may rewrite the start + /// runs between the two, and can split them: under one the start is not checked. Only a start + /// revm made and held to the limits is checked: one it refused, or failed before its level + /// opened, counted nothing, and the charge comes back. pub(crate) fn attach(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { self.start = report.start; - self.on_level = report.on_level > 0; - self.caller_on_level = report.caller_on_level; - self.creator_record = report.creator_record; + self.counted = report.records; self.rollback = built.map(|(start, rollback)| { debug_assert!(report.start == Some(start), "a built frame's rollback is its start's"); rollback @@ -1095,12 +924,8 @@ impl StartSide { if let Some(charged) = self.charged.filter(|_| report.start.is_some() && report.verdict.is_some()) { - let counted = FrameStartRecords { - on_level: report.on_level, - caller: report.caller_on_level || report.creator_record, - }; debug_assert_eq!( - charged, counted, + charged, report.records, "the records a frame's start makes changed after its caller was charged for them", ); } @@ -1136,26 +961,31 @@ impl StartSide { Some(Mark::of_built(position, start, rollback)) } - /// The history gas the caller gets back once the frame returned: what it paid less the price - /// of the start's records `ledger` holds. + /// The history gas the caller gets back once the frame returned: what it paid for the start's + /// records less the price of those `ledger` holds, and the price of the records the start took + /// back, when it stands. /// /// The records on the start's own level are held when that level was kept — committed, and not - /// taken back since; a creator's nonce record, counted below the creation's level, unless a + /// taken back since — and so is what the start took back there: the caller then gets back the + /// price of every record the start returned to what the transaction loaded, which nobody paid + /// for again. A creator's nonce record, counted below the creation's level, is held unless a /// revert to before the start took it back. So a start answered before revm decided it, or /// refused before its writes, gets everything back; a call answered with a success keeps its /// records; a failed precompile, and a frame that fails, give theirs back, a creator's - /// surviving record aside. + /// surviving record aside, and give back nothing for a take-back their failure undid. pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { let (level_kept, start_kept) = self.start.map_or((false, false), |start| ledger.fate(start)); - let on_level = level_kept && self.on_level; - let caller = (level_kept && self.caller_on_level) || (start_kept && self.creator_record); - let mut refund = 0; - if !on_level { - refund += self.on_level_charge; - } - if !caller { - refund += self.caller_charge; + let on_level = self.counted.on_level; + let mut refund = if level_kept { + let kept = records_history_gas(on_level.added); + let taken = if self.priced { records_history_gas(on_level.taken) } else { 0 }; + self.added_charge.saturating_sub(kept).saturating_add(taken) + } else { + self.added_charge + }; + if !(start_kept && self.counted.creator) { + refund = refund.saturating_add(self.creator_charge); } refund } @@ -1179,16 +1009,20 @@ const fn share_of_remaining(remaining: u64) -> u64 { mod tests { use super::*; use crate::{AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::address; + use alloy_primitives::{address, Address}; use revm::context_interface::context::SelfDestructResult; const SENDER: Address = address!("00000000000000000000000000000000000f0001"); const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); const TARGET: Address = address!("00000000000000000000000000000000000f0003"); + /// Two records added: a value transfer between two accounts the transaction has not changed. + const BOTH: RecordDelta = RecordDelta { added: 2, taken: 0 }; + /// One record added: a transfer whose sender the transaction changed already. + const ONE: RecordDelta = RecordDelta { added: 1, taken: 0 }; + /// A ledger holding a transaction with a body of `body` bytes under `limits`, exempt or not, - /// whose value movements journal transfer logs when `transfer_logs`. The sender is whoever - /// starts the transaction's own frame. + /// whose value movements journal transfer logs when `transfer_logs`. fn ledger(limits: EvmTxRuntimeLimits, exempt: bool, transfer_logs: bool, body: u64) -> Ledger { let mut ledger = Ledger::default(); ledger.set_limits(limits); @@ -1196,13 +1030,6 @@ mod tests { ledger } - /// [`ledger`], with [`SENDER`] as the transaction's sender before any frame starts. - fn ledger_from_sender(limits: EvmTxRuntimeLimits, transfer_logs: bool) -> Ledger { - let mut ledger = ledger(limits, false, transfer_logs, 0); - ledger.count_authorities(SENDER, 0, false); - ledger - } - /// 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) @@ -1213,21 +1040,20 @@ mod tests { JournalCheckpoint { log_i: 0, journal_i: ledger.depth(), selfdestructed_i: 0 } } - /// Starts a call from `caller` to `target` at `depth` as revm starts one, moving `value`, and - /// journaling a transfer log for it when the ledger's transaction does; reports what the start - /// counted. + /// Starts a call at `depth` as revm starts one, moving `value` to another account, which + /// changes and returns the accounts `records` says, and journaling a transfer log for it when + /// the ledger's transaction does; reports what the start counted. fn start_call( ledger: &mut Ledger, depth: usize, - caller: Address, - target: Address, value: u64, + records: RecordDelta, ) -> StartReport { - let facts = StartFacts { depth, caller, target: Some(target), transfers_value: value != 0 }; + let facts = StartFacts { depth, creation: false, transfers_value: value != 0 }; ledger.open_start(facts); ledger.on_checkpoint(checkpoint(ledger)); - let logged = ledger.transfer_logs && value != 0 && target != caller; - ledger.on_transfer(caller, target, U256::from(value), false, logged); + let logged = ledger.transfer_logs && value != 0; + ledger.on_transfer(if value == 0 { RecordDelta::NONE } else { records }, false, logged); ledger.close_start() } @@ -1293,20 +1119,20 @@ mod tests { let mut ledger = ledger(limits, false, false, 310); let budget = |ledger: &Ledger| ledger.running_budget().expect("a frame is running").0; - start_call(&mut ledger, 0, SENDER, CALLEE, 0); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); let first = 10_000 - 310; assert_eq!(budget(&ledger), first); - start_call(&mut ledger, 1, CALLEE, TARGET, 0); + start_call(&mut ledger, 1, 0, RecordDelta::NONE); let child = share_of_remaining(first); assert_eq!(child, 9_496); assert_eq!(budget(&ledger), child); - start_call(&mut ledger, 2, TARGET, SENDER, 0); + start_call(&mut ledger, 2, 0, RecordDelta::NONE); let grandchild = share_of_remaining(child); assert_eq!(budget(&ledger), grandchild); - start_call(&mut ledger, 3, SENDER, CALLEE, 0); + start_call(&mut ledger, 3, 0, RecordDelta::NONE); assert_eq!( budget(&ledger), share_of_remaining(grandchild), @@ -1319,9 +1145,9 @@ mod tests { fn test_the_frame_cap_binds_when_it_is_tighter_than_the_share() { let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); let mut ledger = ledger(limits, false, false, 0); - start_call(&mut ledger, 0, SENDER, CALLEE, 0); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(100)); - start_call(&mut ledger, 1, CALLEE, TARGET, 0); + start_call(&mut ledger, 1, 0, RecordDelta::NONE); assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(98)); } @@ -1333,8 +1159,8 @@ mod tests { fn test_a_transaction_is_stopped_where_it_crosses_unless_exempt() { for exempt in [false, true] { let mut ledger = ledger(zero_limits(), exempt, false, TX_BODY_SIZE); - let first = start_call(&mut ledger, 0, SENDER, CALLEE, 0); - let second = start_call(&mut ledger, 1, CALLEE, TARGET, 1); + let first = start_call(&mut ledger, 0, 0, RecordDelta::NONE); + let second = start_call(&mut ledger, 1, 1, BOTH); let verdicts = (first.verdict, second.verdict, ledger.check()); let expected = if exempt { ( @@ -1369,14 +1195,14 @@ mod tests { let limits = EvmTxRuntimeLimits::no_limits() .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut ledger = ledger(limits, false, false, TX_BODY_SIZE); - ledger.count_authorities(SENDER, 2, false); + ledger.count_authorities(2); } /// Applied authorities are recorded for an exempt transaction, whatever they cross. #[test] fn test_an_exempt_transaction_records_its_authorities() { let mut ledger = ledger(zero_limits(), true, false, 0); - ledger.count_authorities(SENDER, 2, false); + ledger.count_authorities(2); assert_eq!(ledger.usage(), WRITE_RECORD.times(2)); } @@ -1385,15 +1211,16 @@ mod tests { #[test] fn test_a_transfer_log_is_data_size_and_never_history() { let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, TX_BODY_SIZE); - start_call(&mut ledger, 0, SENDER, CALLEE, 1); - start_call(&mut ledger, 1, CALLEE, TARGET, 1); + start_call(&mut ledger, 0, 1, ONE); + start_call(&mut ledger, 1, 1, ONE); assert_eq!( ledger.usage(), LimitUsage { data_size: 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", + "the recipient of each move — the inner one's sender is the outer one's recipient — \ + and two logs", ); assert_eq!(ledger.log_and_code_bytes(), 0, "no history byte beside the records"); } @@ -1403,13 +1230,44 @@ mod tests { #[test] fn test_a_failed_frame_gives_its_transfer_log_back() { let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); - start_call(&mut ledger, 0, SENDER, CALLEE, 0); - start_call(&mut ledger, 1, CALLEE, TARGET, 1); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + start_call(&mut ledger, 1, 1, BOTH); assert_eq!(ledger.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); end_frame(&mut ledger, true); assert_eq!(ledger.usage(), LimitUsage::ZERO); } + /// A transfer that returns an account to what the transaction loaded takes its record back on + /// the call's level: the usage falls by the record, the frame's own usage saturates at nothing, + /// and the call's failure puts the record back with the rest. + #[test] + fn test_a_transfer_that_returns_an_account_takes_its_record_back() { + let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + start_call(&mut ledger, 0, 1, ONE); + assert_eq!(ledger.usage(), LimitUsage { data_size: 40 + 160, write_records: 1 }); + // The recipient hands the value back: its own record goes, the sender's is the body's. + let report = start_call(&mut ledger, 1, 1, RecordDelta { added: 0, taken: 1 }); + assert_eq!(report.records.on_level, RecordDelta { added: 0, taken: 1 }); + assert_eq!(report.verdict, Some(LimitCheck::WithinLimit)); + assert_eq!( + ledger.usage(), + LimitUsage { data_size: 2 * TRANSFER_LOG_SIZE, write_records: 0 }, + "the record went; both logs stay" + ); + assert_eq!( + ledger.running_budget().map(|(_, used)| used), + Some(LimitUsage { data_size: TRANSFER_LOG_SIZE - WRITE_RECORD_SIZE, write_records: 0 }), + "the returning frame's own usage is its log less the record it took back, and its \ + record count saturates at nothing" + ); + end_frame(&mut ledger, true); + assert_eq!( + ledger.usage(), + LimitUsage { data_size: 40 + 160, write_records: 1 }, + "the failed return puts the record back" + ); + } + /// A frame start whose transfer log crosses a limit is stopped at its start, 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. @@ -1423,8 +1281,8 @@ mod tests { for (cap, fits) in [(cap, true), (cap - 1, false)] { let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap); let mut ledger = ledger(limits, false, true, 0); - start_call(&mut ledger, 0, SENDER, CALLEE, 0); - let report = start_call(&mut ledger, 1, CALLEE, TARGET, 1); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + let report = start_call(&mut ledger, 1, 1, BOTH); let expected = if fits { LimitCheck::WithinLimit } else { stop(needs - 1, needs, true) }; assert_eq!(report.verdict, Some(expected), "a cap of {cap}"); @@ -1435,7 +1293,7 @@ mod tests { for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit); let mut ledger = ledger(limits, false, true, 0); - let report = start_call(&mut ledger, 0, SENDER, CALLEE, 1); + let report = start_call(&mut ledger, 0, 1, ONE); let expected = if fits { LimitCheck::WithinLimit } else { stop(tx_limit, needs, false) }; assert_eq!(report.verdict, Some(expected), "a limit of {tx_limit}"); @@ -1456,7 +1314,7 @@ mod tests { ("a failed creation's nonce record, over the budget", 61, true, true), ] { let mut ledger = ledger(limits, false, false, 0); - start_call(&mut ledger, 0, SENDER, CALLEE, 0); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); // What the caller kept of its own before the start. let count = WriteCount { added: LimitUsage { data_size: left, write_records: 0 }, @@ -1464,17 +1322,12 @@ mod tests { }; assert_eq!(ledger.count_write(&count), LimitCheck::WithinLimit, "{case}"); if failed { - ledger.open_start(StartFacts { - depth: 1, - caller: CALLEE, - target: None, - transfers_value: false, - }); - let start = ledger.before_creation(); - ledger.after_creation(start, TARGET, Some(checkpoint(&ledger)), false); + ledger.open_start(StartFacts { depth: 1, creation: true, transfers_value: false }); + let start = ledger.before_creation(true); + ledger.after_creation(start, Some(checkpoint(&ledger)), false); let _ = ledger.close_start(); } else { - start_call(&mut ledger, 1, CALLEE, TARGET, 0); + start_call(&mut ledger, 1, 0, RecordDelta::NONE); } end_frame(&mut ledger, failed); let check = ledger.check(); @@ -1485,6 +1338,36 @@ mod tests { } } + /// A creation's creator record is the creating frame's, counted when the bump changed an + /// account the transaction had not changed, and never for the transaction's own creation, + /// whose creator is the sender, whom the body counts. + #[test] + fn test_a_creators_record_is_counted_below_the_creations_level() { + for (depth, creator_unchanged, expected) in + [(1, true, true), (1, false, false), (0, true, false), (0, false, false)] + { + let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + if depth > 0 { + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + } + ledger.open_start(StartFacts { depth, creation: true, transfers_value: false }); + let start = ledger.before_creation(creator_unchanged); + ledger.after_creation(start, Some(checkpoint(&ledger)), false); + let report = ledger.close_start(); + let case = format!("depth {depth}, creator unchanged {creator_unchanged}"); + assert_eq!(report.records.creator, expected, "{case}"); + assert_eq!(report.records.on_level, RecordDelta { added: 1, taken: 0 }, "{case}"); + let records = 1 + u64::from(expected); + assert_eq!(ledger.usage(), WRITE_RECORD.times(records), "{case}"); + end_frame(&mut ledger, true); + assert_eq!( + ledger.usage(), + WRITE_RECORD.times(u64::from(expected)), + "{case}: the creator's record survives the creation's failure" + ); + } + } + /// 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. @@ -1516,28 +1399,45 @@ mod tests { (ledger.count_write(&count), history) } - /// 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; and nothing - /// counts a log when the transaction's value movements journal none. + /// A `SELFDESTRUCT` that moved value to another account counts the records the journal saw its + /// move make and take back, with its transfer log, in one check, and reports the records' + /// history alone: appended for a record made, taken for one taken back. Where the move + /// changes nothing — a beneficiary that is the sender, whose account the transaction changed, + /// and a destructed account the transaction gave its balance — it is the log alone, and the + /// log alone can cross; and nothing counts a log when the transaction's value movements + /// journal none. #[test] - fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { + fn test_a_destruction_counts_its_transfer_log_with_its_records() { let moved = SelfDestructResult { had_value: true, ..Default::default() }; let destruction = |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; - let mut logging = ledger_from_sender(EvmTxRuntimeLimits::no_limits(), true); + let mut logging = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + logging.observe_destruction(RecordDelta { added: 2, taken: 0 }); let (check, history) = commit(&mut logging, &destruction(TARGET)); assert_eq!(check, LimitCheck::WithinLimit); - assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); + assert_eq!(history, HistoryBytes { appended: 2 * WRITE_RECORD_SIZE, taken: 0 }); assert_eq!( logging.usage(), + LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 2 }, + ); + + let mut returning = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); + returning.count_authorities(1); + returning.observe_destruction(RecordDelta { added: 1, taken: 1 }); + let (check, history) = commit(&mut returning, &destruction(TARGET)); + assert_eq!(check, LimitCheck::WithinLimit); + assert_eq!(history, HistoryBytes { appended: WRITE_RECORD_SIZE, taken: WRITE_RECORD_SIZE }); + assert_eq!( + returning.usage(), LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + "one record made, one taken back, and the log" ); let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1); - let mut tight = ledger_from_sender(limits, true); + let mut tight = ledger(limits, false, true, 0); + tight.observe_destruction(RecordDelta::NONE); let (check, history) = commit(&mut tight, &destruction(SENDER)); - assert_eq!(history, HistoryBytes::None); + assert_eq!(history, HistoryBytes::default()); assert_eq!( check, LimitCheck::ExceedsLimit { @@ -1549,8 +1449,42 @@ mod tests { "the log alone crosses", ); - let mut silent = ledger_from_sender(EvmTxRuntimeLimits::no_limits(), false); + let mut silent = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + silent.observe_destruction(RecordDelta { added: 1, taken: 0 }); let _ = commit(&mut silent, &destruction(TARGET)); assert_eq!(silent.usage(), WRITE_RECORD, "no log, no bytes"); } + + /// The hypothetical start a call gas detention answers without running counts the records + /// its transfer would make and take back and the log it would journal, against the + /// transaction's limit and the budget its frame would get, and counts nothing. + #[test] + fn test_a_hypothetical_start_counts_what_its_transfer_would() { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(WRITE_RECORD_SIZE); + let mut ledger = ledger(limits, false, true, 0); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + assert_eq!( + ledger.hypothetical_start(BOTH, true), + stop(WRITE_RECORD_SIZE, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, false) + ); + assert_eq!( + ledger.hypothetical_start(RecordDelta { added: 1, taken: 1 }, false), + LimitCheck::WithinLimit, + "a record taken back pays for one made" + ); + assert_eq!(ledger.usage(), LimitUsage::ZERO, "nothing was counted"); + } + + /// A record taken back outside the journal's counted writes — a `keylessDeploy` signer's nonce + /// set back — is a refund on the running frame's level, which its failure puts back. + #[test] + fn test_a_record_taken_back_by_hand_goes_with_the_level() { + let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + ledger.count_authorities(1); + ledger.take_back_record(); + assert_eq!(ledger.usage(), LimitUsage::ZERO); + end_frame(&mut ledger, true); + assert_eq!(ledger.usage(), LimitUsage::ZERO, "the record and its take-back went together"); + } } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 61001db64..cdbd07947 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -12,6 +12,7 @@ use std::vec::Vec; use super::{ ledger::{FrameStartRecords, Ledger, Rollback, StartId, StartSide}, + record::RecordDelta, EvmTxRuntimeLimits, LimitCheck, LimitKind, StartReport, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -323,9 +324,11 @@ impl AdditionalLimit { } /// Leaves the history gas the running opcode just charged its frame for the records the frame - /// it starts will make: `on_level` for the records that frame's failure takes back, `caller` - /// for the record of the caller's own account, and `records`, the answer the charge was - /// computed from, for the frame's side to hold the ledger's count to. + /// it starts will make: `added` for the records that frame's failure takes back, `creator` for + /// the record of the creator's own nonce, and `records`, the answer the charge was computed + /// from, for the frame's side to hold the ledger's count to; `priced` says whether the + /// transaction prices history at all, so that a record the start takes back is history the + /// caller gets back. /// /// The next side pushed takes it, whether that is the frame's own or that of a frame answered /// without running. @@ -333,10 +336,11 @@ impl AdditionalLimit { pub(crate) const fn stage_frame_charge( &mut self, records: FrameStartRecords, - on_level: u64, - caller: u64, + added: u64, + creator: u64, + priced: bool, ) { - self.pending_frame_charge = FrameCharge { records: Some(records), on_level, caller }; + self.pending_frame_charge = FrameCharge { records: Some(records), added, creator, priced }; } /// Leaves the frame about to start unchecked against the answer its charge was computed from @@ -391,16 +395,18 @@ impl AdditionalLimit { /// execution for the write record it makes. fn push_side(&mut self, depth: usize) { let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - let (on_level, caller, records) = if depth == 0 { - let records = self - .pending_top_level_records - .take() - .map(|on_level| FrameStartRecords { on_level, caller: false }); - (self.top_level_write_record_gas, 0, records) + let side = if depth == 0 { + // The transaction's own frame takes nothing back: its recipient, when it writes one, + // is an account the transaction had not changed. + let records = self.pending_top_level_records.take().map(|added| FrameStartRecords { + on_level: RecordDelta { added, taken: 0 }, + creator: false, + }); + StartSide::new(depth, self.top_level_write_record_gas, 0, false, records) } else { - (charge.on_level, charge.caller, charge.records) + StartSide::new(depth, charge.added, charge.creator, charge.priced, charge.records) }; - self.starts.push(StartSide::new(depth, on_level, caller, records)); + self.starts.push(side); } /// Attaches what the journal's ledger saw the latest start count, and what a frame revm built @@ -493,17 +499,19 @@ fn grants_stipend(inputs: &CallInputs) -> bool { #[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. + /// frame has no such opcode. records: Option, - /// What the records on the frame's own level cost. - on_level: u64, - /// What the record of the caller's own account cost. - caller: u64, + /// What the records the start adds on the frame's own level cost. + added: u64, + /// What the record of the creator's own nonce cost. + creator: u64, + /// Whether the transaction prices history. + priced: bool, } impl FrameCharge { /// Nothing charged. - const NONE: Self = Self { records: None, on_level: 0, caller: 0 }; + const NONE: Self = Self { records: None, added: 0, creator: 0, priced: false }; } #[cfg(test)] @@ -546,20 +554,23 @@ mod tests { })) } - /// What the ledger reports of a start revm made and held to the limits: `on_level` records on - /// the frame's level, and the caller's own record (`caller`) on it or, for a creation, below. - fn report(on_level: u64, caller: bool, creation: bool) -> StartReport { + /// What the ledger reports of a start revm made and held to the limits: `added` records on + /// the frame's level, and the creator's own record (`creator`) below it. + fn report(added: u64, creator: bool) -> StartReport { StartReport { start: Some(StartId::default()), - on_level, - caller_on_level: caller && !creation, - creator_record: caller && creation, + records: records(added, creator), transfer_log: false, refused: false, verdict: Some(LimitCheck::WithinLimit), } } + /// `added` records on the frame's level, and the creator's own record (`creator`) below it. + const fn records(added: u64, creator: bool) -> FrameStartRecords { + FrameStartRecords { on_level: RecordDelta { added, taken: 0 }, creator } + } + /// 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. @@ -647,17 +658,17 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1, 1); + limit.stage_frame_charge(records(2, false), 2, 0, true); limit.push_start(&inner, 1); - limit.attach_start(report(1, true, false), None); + limit.attach_start(report(2, false), None); - limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: false }, 1, 0); + limit.stage_frame_charge(records(1, true), 1, 1, true); limit.push_start(&inner, 1); - limit.attach_start(report(1, false, true), None); + limit.attach_start(report(1, true), None); - limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1, 1); + limit.stage_frame_charge(records(2, false), 2, 0, true); limit.push_start(&inner, 1); - let refused = StartReport { verdict: None, refused: true, ..report(0, false, false) }; + let refused = StartReport { verdict: None, refused: true, ..report(0, false) }; limit.attach_start(refused, None); } @@ -670,20 +681,20 @@ mod tests { fn test_a_charge_computed_from_another_answer_trips() { let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); + limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(1, true, false), None); + limit.attach_start(report(2, false), None); } /// The transaction's own frame is held to the records its history was charged for before /// execution: its value's recipient, or the account a creation makes. #[test] fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { - for records in [0, 1] { + for added in [0, 1] { let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(records); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(records)), 0); - limit.attach_start(report(records, false, false), None); + limit.stage_top_level_records(added); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(added)), 0); + limit.attach_start(report(added, false), None); } } @@ -697,7 +708,7 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.stage_top_level_records(0); limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(1, false, false), None); + limit.attach_start(report(1, false), None); } /// Under an inspector that may rewrite a start, the check is waived: the start its charge paid @@ -708,11 +719,11 @@ mod tests { limit.stage_top_level_records(0); limit.waive_start_check(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(1, false, false), None); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); + limit.attach_start(report(1, false), None); + limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); limit.waive_start_check(); limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(1, true, false), None); + limit.attach_start(report(2, false), None); } /// A frame answered without running — by the depth guard, a stop, an interceptor or an @@ -735,7 +746,7 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(FrameStartRecords { on_level: 1, caller: true }, 1_000, 2_000); + limit.stage_frame_charge(records(1, true), 1_000, 2_000, true); limit.push_answered_start(1); let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); let (_, refund) = limit.on_start_return(ledger, &result).expect("the side"); @@ -763,12 +774,11 @@ mod tests { ctx.ledger_mut().begin_transaction(false, false, 0); ctx.ledger_mut().open_start(StartFacts { depth: 0, - caller: SENDER, - target: Some(CALLEE), + creation: false, transfers_value: true, }); let checkpoint = ctx.journal_mut().checkpoint(); - ctx.ledger_mut().on_transfer(SENDER, CALLEE, U256::from(1), false, false); + ctx.ledger_mut().on_transfer(RecordDelta { added: 1, taken: 0 }, false, false); let report = ctx.ledger_mut().close_start(); limit.attach_start(report, None); ctx.ledger_mut().frame_returning(); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index bf4a73506..0bcb4110f 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -141,7 +141,7 @@ mod record; pub(crate) use ledger::StartSide; pub(crate) use ledger::{FrameIdentity, FrameStartRecords, Ledger, Mark, StartFacts, StartReport}; pub use limit::AdditionalLimit; -pub(crate) use record::HistoryBytes; +pub(crate) use record::{HistoryBytes, RecordDelta}; 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 8d9fde71e..27649a86a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -5,45 +5,67 @@ //! ([`Host::write_completed`](revm::context_interface::Host::write_completed)). A failed opcode //! offers nothing, so nothing here is counted for a write its failure takes back. -use alloy_primitives::Address; use revm::context_interface::host::CompletedWrite; use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; -/// 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), +/// 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. +/// +/// A value transfer moves at most one record per side, and a `SELFDESTRUCT` one per account it +/// writes; a creation's created account is one record, and its creator's nonce bump another, kept +/// apart from this delta because it lands on the creating frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct RecordDelta { + /// Records created. + pub(crate) added: u64, + /// Records taken back. + pub(crate) taken: u64, } -/// The history bytes a committed record appends, or takes back. +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 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, 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), +#[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. + pub(crate) taken: u64, } /// What a completed write keeps, as the journal's ledger counts it: what it adds, what it takes /// back, and the log bytes among what it adds. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct WriteCount { - /// What the write adds: a record, a log's bytes, a transfer log. + /// What the write adds: records, a log's bytes, a transfer log. pub(crate) added: LimitUsage, - /// What the write takes back: the record of a slot written back to its original value. + /// What the write takes back: the records of accounts and slots returned to what the + /// transaction loaded. pub(crate) taken: LimitUsage, /// The bytes of [`added`](Self::added) that are a log's. pub(crate) log_bytes: u64, @@ -51,53 +73,47 @@ pub(crate) struct WriteCount { impl WriteCount { /// Nothing kept. + #[cfg(test)] pub(crate) const NONE: Self = Self { added: LimitUsage::ZERO, taken: LimitUsage::ZERO, log_bytes: 0 }; } -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), - } - } -} - -/// What committing the write `write` counts, per site: +/// What committing the write `write` counts, per site, as records added and taken back and as +/// bytes appended and taken 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 write_effect(write: &CompletedWrite<'_>, sender: Address) -> RecordEffect { +/// - `SELFDESTRUCT`: `destruction`, the records of the accounts the move changed and returned, +/// which the journal observed as it made the write: the beneficiary, and the destructed account +/// whose balance the move clears. +pub(crate) fn write_effect( + write: &CompletedWrite<'_>, + destruction: RecordDelta, +) -> (LimitUsage, LimitUsage) { match *write { CompletedWrite::Sstore { result: slot, .. } => { if slot.is_original_eq_present() { if slot.is_original_eq_new() { - RecordEffect::None + (LimitUsage::ZERO, LimitUsage::ZERO) } else { - RecordEffect::Record(WRITE_RECORD) + (WRITE_RECORD, LimitUsage::ZERO) } } else if slot.is_original_eq_new() { - RecordEffect::Refund(WRITE_RECORD) + (LimitUsage::ZERO, WRITE_RECORD) } else { - RecordEffect::None + (LimitUsage::ZERO, LimitUsage::ZERO) } } - CompletedWrite::Log { topics, data_len, .. } => RecordEffect::Record(LimitUsage { - data_size: log_history_bytes(u64::from(topics), data_len), - write_records: 0, - }), - CompletedWrite::SelfDestruct { address, target, result } => { - if result.had_value && target != address && target != sender { - RecordEffect::Record(WRITE_RECORD) - } else { - RecordEffect::None - } + CompletedWrite::Log { topics, data_len, .. } => ( + LimitUsage { + data_size: log_history_bytes(u64::from(topics), data_len), + write_records: 0, + }, + LimitUsage::ZERO, + ), + CompletedWrite::SelfDestruct { .. } => { + (WRITE_RECORD.times(destruction.added), WRITE_RECORD.times(destruction.taken)) } } } @@ -118,8 +134,8 @@ pub(crate) fn write_moves_value(write: &CompletedWrite<'_>) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, U256}; + use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE}; + use alloy_primitives::{address, Address, U256}; use revm::context_interface::context::{SStoreResult, SelfDestructResult}; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); @@ -150,67 +166,71 @@ mod tests { CompletedWrite::SelfDestruct { address: DESTRUCTED, target, result } } + const RECORD: (LimitUsage, LimitUsage) = (WRITE_RECORD, LimitUsage::ZERO); + const TAKEN: (LimitUsage, LimitUsage) = (LimitUsage::ZERO, WRITE_RECORD); + const NOTHING: (LimitUsage, LimitUsage) = (LimitUsage::ZERO, LimitUsage::ZERO); + /// 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() { - let effect = - |original, present, new| write_effect(&sstore(&slot(original, present, new)), SENDER); - assert_eq!(effect(0, 0, 1), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(effect(5, 5, 0), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(effect(0, 1, 0), RecordEffect::Refund(WRITE_RECORD)); - assert_eq!(effect(0, 1, 2), RecordEffect::None); - assert_eq!(effect(3, 3, 3), RecordEffect::None); - assert_eq!(effect(3, 4, 4), RecordEffect::None); + let effect = |original, present, new| { + write_effect(&sstore(&slot(original, present, new)), RecordDelta::NONE) + }; + assert_eq!(effect(0, 0, 1), RECORD); + assert_eq!(effect(5, 5, 0), RECORD); + assert_eq!(effect(0, 1, 0), TAKEN); + assert_eq!(effect(0, 1, 2), NOTHING); + assert_eq!(effect(3, 3, 3), NOTHING); + assert_eq!(effect(3, 4, 4), NOTHING); } /// A log is 32 bytes for its address, 32 per topic and its data. #[test] fn test_log_bytes() { - let effect = |topics, data_len| write_effect(&log(topics, data_len), SENDER); + let effect = |topics, data_len| write_effect(&log(topics, data_len), RecordDelta::NONE); assert_eq!( effect(0, 0), - RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 }) + (LimitUsage { data_size: 32, write_records: 0 }, LimitUsage::ZERO) ); assert_eq!( effect(4, 100), - RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) + (LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }, LimitUsage::ZERO) ); assert_eq!( effect(1, u64::MAX), - RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) + (LimitUsage { data_size: u64::MAX, write_records: 0 }, LimitUsage::ZERO) ); } - /// 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` counts the records the journal saw its move make and take back, whatever + /// the beneficiary: the sender is told apart by its account, which the transaction changed, + /// not by its address. #[test] - fn test_history_bytes_are_the_records_data_size() { - let history = |write: &CompletedWrite<'_>| write_effect(write, SENDER).history_bytes(); - assert_eq!(history(&sstore(&slot(0, 0, 1))), HistoryBytes::Appended(WRITE_RECORD_SIZE)); - assert_eq!(history(&sstore(&slot(0, 1, 0))), HistoryBytes::Taken(WRITE_RECORD_SIZE)); - assert_eq!(history(&sstore(&slot(3, 3, 3))), HistoryBytes::None); + fn test_selfdestruct_counts_the_records_the_journal_observed() { + let moved = destruction(true); + let effect = |target, delta| write_effect(&selfdestruct(&moved, target), delta); assert_eq!( - history(&log(3, 32)), - HistoryBytes::Appended(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32) - ); - assert_eq!( - history(&selfdestruct(&destruction(true), OTHER)), - HistoryBytes::Appended(WRITE_RECORD_SIZE) + effect(OTHER, RecordDelta { added: 2, taken: 0 }), + (WRITE_RECORD.times(2), LimitUsage::ZERO) ); + assert_eq!(effect(OTHER, RecordDelta { added: 1, taken: 1 }), (WRITE_RECORD, WRITE_RECORD)); + assert_eq!(effect(SENDER, RecordDelta { added: 1, taken: 0 }), RECORD); + assert_eq!(effect(DESTRUCTED, RecordDelta::NONE), NOTHING); } - /// Only value that moves to another account is a beneficiary write. + /// 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_selfdestruct_record_rules() { - let effect = |had_value, target| { - write_effect(&selfdestruct(&destruction(had_value), target), SENDER) - }; - assert_eq!(effect(true, OTHER), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(effect(true, DESTRUCTED), RecordEffect::None); - assert_eq!(effect(false, OTHER), RecordEffect::None); - assert_eq!(effect(false, DESTRUCTED), RecordEffect::None); - assert_eq!(effect(true, SENDER), RecordEffect::None, "the body counts the sender"); + 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 } + ); } /// Value moves to another account only when a destructed account had a balance and a @@ -231,9 +251,7 @@ mod tests { /// of its own. #[test] fn test_a_transfer_log_counts_what_a_log3_of_one_word_counts() { - assert_eq!( - write_effect(&log(3, 32), SENDER), - RecordEffect::Record(crate::limit::TRANSFER_LOG) - ); + assert_eq!(write_effect(&log(3, 32), RecordDelta::NONE).0, crate::limit::TRANSFER_LOG,); + assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, crate::limit::TRANSFER_LOG.data_size); } } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 83e99a548..14686a821 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -9,7 +9,7 @@ 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}, Host, @@ -61,11 +61,10 @@ 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)). pub(super) empty_deposit_refused: bool, @@ -225,10 +224,13 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - ctx.ledger_mut().set_frame_creator(deployment.signer); - if let Some((on_level, caller)) = deployment.record_charges { - ctx.additional_limit.stage_frame_charge(deployment.records, on_level, caller); - } + let (added, creator) = deployment.record_charges.unwrap_or((0, 0)); + ctx.additional_limit.stage_frame_charge( + deployment.records, + added, + creator, + deployment.record_charges.is_some(), + ); let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, @@ -244,8 +246,7 @@ fn start( 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: deployment.record_charges.map_or(0, |(_, creator)| creator), empty_deposit_refused: false, })); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) @@ -266,8 +267,8 @@ struct Deployment { 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 them: the created account's, and the signer's nonce. `None` when + /// the transaction pays no history. record_charges: Option<(u64, u64)>, } @@ -428,12 +429,12 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } - let records = FrameStartRecords { on_level: 1, caller: signer != ctx.tx().caller() }; + let records = ctx.journal_ref().creation_records(signer, tx.value); let record_charges = if ctx.prices_history() { let charged = charge_write_records_history( gas.tracker_mut(), - records.on_level, - u64::from(records.caller), + records.on_level.added, + u64::from(records.creator), ); if charged.is_none() { return Ok(Err(Refusal::OutOfGas)); diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 1b8b143a0..d16e87f54 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -162,7 +162,7 @@ pub(crate) fn settle( // 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(()) @@ -239,21 +239,19 @@ fn holds_code( /// 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. +/// 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> { + let changed = ctx.journal_ref().is_changed(started.signer); 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 { - return Ok(()); - } - if ctx.ledger_mut().take_back_creator_record() { + if changed && !ctx.journal_ref().is_changed(started.signer) { + ctx.ledger_mut().take_back_record(); // A stop the record left the call, by putting it over a limit, goes with it: the call is // held to its limits again without the record. let check = ctx.ledger().check(); diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs index 1276242de..71c42ae95 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -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; diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 83d63b8d7..f8ab71088 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -883,9 +883,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(); @@ -895,8 +895,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 { @@ -1155,8 +1155,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 { @@ -1241,9 +1241,9 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ selfdestruct_to_c(), 3 + (5_000 + params.selfdestruct_cost(true, true)), account_state_gas(), - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, - 1, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, + 2, ), ]; let body = body_history(0); diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 619d7ba9c..73badf40c 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -259,21 +259,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", diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 051ebfbbe..2d77c41b7 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -406,12 +406,12 @@ 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 +/// 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 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. @@ -435,7 +435,10 @@ 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); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 5367e04e6..0b882aa6c 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1863,7 +1863,8 @@ fn test_a_history_refill_after_the_read_does_not_lift_the_cap() { /// `MIDDLE` starts each kind of frame that makes records, with all but a 64th of what it holds, a /// 64th 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. +/// 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 @@ -1919,14 +1920,6 @@ fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { spilled: 0, given: None, }, - Start { - name: "a value CALLCODE", - code: value_call(CALLCODE, None), - charges: value_call_charges(false), - price: price(1), - 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]), ]; diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 4bf3bce20..3a9800d6a 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -654,11 +654,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, ), @@ -852,20 +852,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, ), diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 5c2815df7..d3636200d 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -233,7 +233,8 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { /// 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 makes no records: from the same gas it starts, and pays no history. +/// 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 @@ -284,7 +285,7 @@ fn test_every_call_kind_charges_its_records_after_its_forward() { (started, outcome) }; - for (scheme, records) in [(CALL, 2), (CALLCODE, 1)] { + 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:?}"); @@ -310,7 +311,9 @@ fn test_every_call_kind_charges_its_records_after_its_forward() { assert_eq!(exact.gas.reservoir_remaining, 0, "{case}: the reservoir paid first"); } - for scheme in [DELEGATECALL, STATICCALL] { + // 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); 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/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs index 675db36b0..76e18dcef 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -465,8 +465,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. @@ -484,7 +484,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); @@ -665,10 +665,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", ); } @@ -709,8 +710,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. @@ -732,22 +733,22 @@ 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 * STORAGE_CALL_STIPEND_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 * STORAGE_CALL_STIPEND_BYTES, "the byte column has every event on it", ); diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index e1fa2c675..2f1407c92 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -137,10 +137,11 @@ impl Site { } /// 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, } } @@ -686,9 +687,9 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { .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), + // 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), + ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 0, 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), ( @@ -731,10 +732,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); @@ -753,18 +755,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 = @@ -803,14 +798,18 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { } } -/// A value call its caller cannot fund is charged the history of the records it would make at its -/// opcode, as every start is, before revm decides it, and gets the charge back once revm refused -/// it: given room for the charge, the caller runs on past the refused call, billed its body's -/// history alone and counting nothing more. A caller that keeps less than those records cost, -/// once it has forwarded all it can, runs out of gas at the opcode, as it does when it can fund the -/// value. +/// 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_gets_its_charge_back() { +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| { @@ -857,11 +856,13 @@ fn test_a_value_call_its_caller_cannot_fund_gets_its_charge_back() { } assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); let gas_limit = 21_000 + history_gas(body).unwrap() + actor_gas; - for held in [VALUE - 1, VALUE] { - let short = execute_under(db(held), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); - assert!(short.result.is_halt(), "holding {held}: {:?}", short.result); - assert_eq!(short.gas.gas_used, gas_limit, "holding {held}: the halt used the gas limit"); - } + 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 diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 9f4479173..88e80c9bf 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -5,8 +5,14 @@ //! 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. +//! 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 records the account it creates. 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. @@ -23,8 +29,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CREATE, DELEGATECALL, 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, }, interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Database, Inspector, @@ -79,9 +85,10 @@ 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); @@ -98,10 +105,13 @@ fn test_two_value_calls_record_the_sender_once() { ); } -/// Value transfers to one recipient record it each time, and the sender once: a recipient's record -/// is the transfer's, not the frame's, so nothing deduplicates it. +/// 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_each_time() { +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) }); @@ -112,11 +122,326 @@ fn test_value_calls_to_one_recipient_record_it_each_time() { assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(4), 3 * TRANSFER_LOG_SIZE), - "CALLEE once, CONTRACT three times, and a transfer log for each transfer" + with_extra(records(2), 3 * TRANSFER_LOG_SIZE), + "CALLEE once, CONTRACT once, and a transfer log for each transfer" ); } +/* ---------- 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(with_extra(records(2), TRANSFER_LOG_SIZE)), + "CALLEE, CONTRACT, a log" + ); + 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, records(3), "CALLEE, the account it created, and the one that created"); + 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", + destruct_to(BytecodeBuilder::default(), CONTRACT).build(), + Bytes::new(), + 5, + guarded(with_extra(records(2), TRANSFER_LOG_SIZE)), + ), + ( + "to a beneficiary a transfer changed", + sends_then_destructs.build(), + Bytes::new(), + 5, + guarded(with_extra(records(2), 2 * TRANSFER_LOG_SIZE)), + ), + ( + "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 and a value transfer from one frame record the frame's account once. #[test] fn test_create_then_call_record_the_frame_account_once() { @@ -329,12 +654,6 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { 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] @@ -399,18 +718,22 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { } } -/// `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)), + (U256::from(5), CONTRACT, with_extra(records(2), TRANSFER_LOG_SIZE)), (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 { @@ -465,7 +788,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 @@ -486,11 +810,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, @@ -503,10 +827,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, @@ -519,7 +843,7 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { COINBASE, COINBASE, SelfDestruct, - 0, + 1, ), ]; for (row, sender, target, path, records) in rows { @@ -971,12 +1295,15 @@ 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 ---------- */ +/* ---------- 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 = @@ -989,15 +1316,16 @@ fn test_value_receiving_child_records_itself_once() { 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" + with_extra(records(2), 2 * TRANSFER_LOG_SIZE), + "CALLEE, CONTRACT2, and two transfer logs: CONTRACT passed on what it received" ); } -/// 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() @@ -1037,7 +1365,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) @@ -1050,13 +1382,13 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { 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" + with_extra(records(1), 2 * TRANSFER_LOG_SIZE), + "CONTRACT2 and two transfer logs: CALLEE passed on the value it received" ); } -/// 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) @@ -1080,7 +1412,8 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { ); } -/// 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) @@ -1245,13 +1578,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]), value_call_room()), 0, - 1, + 0, ), case( "a log over one word", @@ -1291,6 +1624,7 @@ fn paired_corpus() -> Vec { 0, 1, ), + // The account it clears and its beneficiary. Paired { transfer_logs: 1, ..case( @@ -1301,7 +1635,7 @@ fn paired_corpus() -> Vec { .account_balance(CALLEE, U256::from(1)), plain(), 0, - 1, + 2, ) }, case( 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 d142aee16..7c3b19ddb 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 @@ -42,8 +42,8 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "the signer sends it @ 50000000 | keccak256=0xf4b217ee909a34fa24eb33e69e22d991934921666a4b7c09575b408d26a8b649", "the signer sends it, and it reverts @ 50000000 | keccak256=0x68fc6964cb808234a2d1d33f585fb4c9657f484b0d356ffd331bf6397d41128d", "a delegated signer @ 50000000 | keccak256=0x7330f3b25240cd042d903a307ceebd468712ab0e0c9bc53956b352a836793277", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xdd703fa6882916d0ca48e3fd6471a71950ba478f7d2efd69c8e3801c81dbe3b2", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x41ee8ae476e6201aaa92cdd797aaff01b27948cf491fa6c3c56cdc0424fd1724", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xe7d24ab0f4d912f15fb76b088ccecc75ffdf592db8046874805a7cc617effc3c", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xd71d46b795d405e858eef0b6f1d6e6731fe1aa4c8718389b46a8f7c0694303a2", "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x37a162d66e66eaef26783bc9561e06aba6dce9824835444dfc73e7034f404684", "limit: compute, nonce 0 @ 50000000 | keccak256=0xc2631c368e7d21e89e7323514c180d9b25e176ed5f9670dbd34913cd5187eff7", "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xa65b39c137245c46091e529c2f7944aa2e62cf30dcbc9a73becaf82c0896fb43", @@ -107,8 +107,8 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "the signer sends it @ 400000000 | keccak256=0x23d3e43c0591e50bead0e091db67aef632a77f7b789a26ab426cfc7a69814e21", "the signer sends it, and it reverts @ 400000000 | keccak256=0xa530a2b24e4f4c977e1a73999e343d6230c3372f7467d49901451ab310e9df54", "a delegated signer @ 400000000 | keccak256=0xe0d591f3e38dda862488a1009602e3f3b24a7ba333a9fbda56fc2f8c0caaa7a7", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x0b7d568b7270ccde9eb252f3a60aef197c80f4e4720c9f673d6b09da8538aa6c", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xa2c3e89c11a418a2ad592b75dbf3ba4ef19f95e5634dbdd9a2552f4cbbb223b9", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x8ef3d795d097ab68240ed2275bc691470ad3c4a72869cb570ad0efc0add5437d", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xad96560f17165fc62cb06d04e4a2ffc2bacb69852fe08b0b1aef0d9dec664690", "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x3fda5141c92c11c841821a4754de70393a313b6384e6e0bf8d2606dbe6d03f02", "limit: compute, nonce 0 @ 400000000 | keccak256=0x02f6f21cfc59e30ec997eaf750e39eba6a2b2cce4844e781dbcf118e2be5a1f1", "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xa3d35dab98f17e60684b7fbcdb827fe82f004950301da26d87e78d7ba5125ec1", @@ -145,7 +145,7 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "rule: init code over the limit @ 2000000000 | keccak256=0x58da5d395d2b47867b957a47072721843bc4fd359f62379c21e38c78965b156c" ], "summary": { - "bytes": 2407322, + "bytes": 2407306, "cases": 139, "lines": 11452, "runs": 556 From c9881030c81380ff885551cbe2538943ae93bdac Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 16:39:02 +0800 Subject: [PATCH 424/458] feat(limit): the creator's nonce record is the creating frame's A creation's creator nonce record is counted on the creating frame's level before the creation's budget is taken from what the creator has left, so it is held to the creator's budget and not the creation's, and the creation's usage is measured from its level's opening alone. The budget a creation gets is the share of what the record leaves its creator: the boundary cases shift by the record's 40 bytes, and the tests say what moved. --- crates/mega-evm/src/evm/journal.rs | 34 +++++--- crates/mega-evm/src/limit/ledger.rs | 63 ++++++-------- crates/mega-evm/tests/satin/data_size.rs | 82 ++++++++++++------- crates/mega-evm/tests/satin/inspector.rs | 14 ++-- crates/mega-evm/tests/satin/transfer_logs.rs | 55 ++++++++++--- .../mega-evm/tests/system/keyless/limits.rs | 12 ++- ...erential__keyless_differential_record.snap | 16 ++-- 7 files changed, 166 insertions(+), 110 deletions(-) diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 7cc2aede4..0668609bd 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -833,18 +833,23 @@ mod tests { journal.checkpoint_revert(tool); } - /// A creation's budget and usage are measured from before its creator's nonce record, and its - /// level opens after it: with `R` bytes left to an unchanged creator, the creation gets - /// `R − ⌈R / 50⌉` and starts with the created account's record and the creator's, 80 bytes. - /// At 81 bytes that is a budget of 79, which the start crosses; at 100, a budget of 98, which - /// leaves the creation 18 bytes. An endowment adds its transfer log to the start. + /// A creation's creator nonce record is the creating frame's, counted on its level before the + /// creation's budget is taken from what it has left: with `R` bytes left to an unchanged + /// creator, the record leaves it `R − 40`, the creation gets `(R − 40) − ⌈(R − 40) / 50⌉`, and + /// starts with the created account's record alone, 40 bytes. At 81 bytes that is a budget of + /// 40, which the start fills exactly; at 100, a budget of 58, which leaves the creation 18 + /// bytes. An endowment adds its transfer log to the start. + /// + /// Before the creator's record moved to the creating frame, the creation's budget was taken + /// from `R` and its usage was measured from before the record: a budget of 79 against 80 bytes + /// at 81, which the start crossed, and of 98 against 80 at 100, the same 18 bytes left. #[test] - fn test_a_creation_is_budgeted_from_before_its_creators_record() { + fn test_a_creation_is_budgeted_after_its_creators_record() { let log = TRANSFER_LOG_SIZE; for (left, value, budget) in - [(81, 0, 79), (100, 0, 98), (81 + log, 1, 236), (100 + log, 1, 254)] + [(81, 0, 40), (100, 0, 58), (81 + log, 1, 196), (100 + log, 1, 215)] { - let start = start_bytes(2, value != 0); + let start = start_bytes(1, value != 0); let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + left); let mut journal = journal(limits); @@ -852,8 +857,13 @@ mod tests { let (_, report) = start_creation(&mut journal, 1, A, CREATED, value); let case = format!("{left} bytes left, value {value}"); assert!(report.records.creator, "{case}: the creator's record is the start's"); - let used = LimitUsage { data_size: start, write_records: 2 }; + let used = LimitUsage { data_size: start, write_records: 1 }; assert_eq!(journal.ledger().running_budget(), Some((budget, used)), "{case}"); + assert_eq!( + journal.ledger().usage(), + kept(2, u64::from(value != 0)), + "{case}: the creator's record is counted, below the creation's level" + ); let verdict = if start > budget { LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, @@ -868,9 +878,9 @@ mod tests { } } - /// A creation's start mark is its level's opening — after the creator's record — never where - /// its usage is measured from: a creation rewritten into a failure is taken back to it, and - /// keeps its creator's record, as a creation that fails does, the creator's nonce standing. + /// A creation's start mark is its level's opening, after the creator's record: a creation + /// rewritten into a failure is taken back to it, and keeps its creator's record, as a creation + /// that fails does, the creator's nonce standing. #[test] fn test_a_creations_start_mark_keeps_its_creators_record() { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 74ac9d849..6ba3e9ef6 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -34,9 +34,9 @@ //! - the records of the applied EIP-7702 authorities, inside the pre-execution level; //! - a frame start's records and its transfer log, inside the start window, at the two writes revm //! makes for the start: a call's value transfer, and a creation's account checkpoint. A -//! creation's creator nonce record is counted before the creation's level opens, so the -//! creation's failure leaves it with the creator, and the creation's budget and usage are -//! measured from before it; +//! creation's creator nonce record is the creating frame's: counted on its level before the +//! creation's budget is taken from what it has left, so the creation's failure leaves it with the +//! creator, and the creator is held to its own budget with it; //! - a completed write's record, on the running frame's level, fed by the Host's completed-write //! hook; //! - deployed code, on the creation's level before revm commits it. @@ -102,9 +102,6 @@ struct FrameLevel { depth: usize, /// The most data-size bytes the frame may keep. budget: u64, - /// Whether the frame's start counted its creator's nonce record, right before its level - /// opened: the frame's usage is measured from before it. - creator_record: bool, /// Whether the frame is returning, so revm may close its level. returning: bool, } @@ -215,10 +212,10 @@ pub(crate) struct Mark { own_start: Option, } -/// The facts of a creation's start, taken before anything of it is counted. +/// The facts of a creation's start, taken as its creator's nonce record is counted. #[derive(Clone, Copy, Debug)] pub(crate) struct CreationStart { - /// The creation's budget, from what its creator had left before its nonce record. + /// The creation's budget, from what its creator has left after its nonce record. budget: u64, /// Whether the creator's nonce record was counted. creator_record: bool, @@ -339,17 +336,12 @@ impl Ledger { } /// What `frame` keeps so far, the children it kept included: what was counted since its level - /// opened, and its creator's nonce record, counted right before. + /// opened. fn frame_usage(&self, frame: &FrameLevel) -> LimitUsage { let at_open = &self.levels[frame.level].at_open; - let base = if frame.creator_record { - at_open.used.saturating_sub(WRITE_RECORD) - } else { - at_open.used - }; self.counts .used - .saturating_sub(base) + .saturating_sub(at_open.used) .saturating_sub(self.counts.refund.saturating_sub(at_open.refund)) } @@ -575,15 +567,9 @@ impl Ledger { }); } - /// Opens the frame level of the window's start at `opened_at`, under `budget`, its usage - /// measured from before its creator's nonce record when the start counted one - /// (`creator_record`): the frame the window's start builds. - fn open_frame_level( - &mut self, - opened_at: JournalCheckpoint, - budget: u64, - creator_record: bool, - ) { + /// Opens the frame level of the window's start at `opened_at`, under `budget`: the frame the + /// window's start builds. + fn open_frame_level(&mut self, opened_at: JournalCheckpoint, budget: u64) { let Some(window) = &mut self.window else { unreachable!("a frame level opens inside its start's window") }; @@ -595,7 +581,6 @@ impl Ledger { start, depth, budget, - creator_record, returning: false, }); } @@ -611,7 +596,7 @@ impl Ledger { // A creation's frame level is the one its account checkpoint opens. return self.open_level(opened_at, false); } - self.open_frame_level(opened_at, self.child_budget(), false); + self.open_frame_level(opened_at, self.child_budget()); // A start that moves value is held once its transfer is counted (`on_transfer`); any // other has nothing of its own to count, and is held now. if !window.facts.transfers_value { @@ -650,11 +635,14 @@ impl Ledger { } /// revm is about to open a creation's account checkpoint for the start of the window, having - /// bumped its creator's nonce: takes the creation's budget and base, then counts the creator's - /// nonce record when the bump changed an account the transaction had not changed - /// (`creator_unchanged`), before anything of the creation. The transaction's own creation - /// writes its sender's nonce, which the body counts. `None` outside a creation's start - /// window. + /// bumped its creator's nonce: counts the creator's nonce record on the creating frame's level + /// when the bump changed an account the transaction had not changed (`creator_unchanged`), + /// then takes the creation's budget from what the creator has left. The transaction's own + /// creation writes its sender's nonce, which the body counts. `None` outside a creation's + /// start window. + /// + /// The record is the creator's to keep within its budget, not the creation's: it lands on the + /// creator unchecked, and the creator is held to its limits with it as the creation returns. pub(crate) fn before_creation(&mut self, creator_unchanged: bool) -> Option { let window = self.window.as_mut()?; if window.counted || !window.facts.creation { @@ -662,18 +650,18 @@ impl Ledger { } window.counted = true; let depth = window.facts.depth; - let budget = self.child_budget(); let creator_record = depth > 0 && creator_unchanged; if creator_record { self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); } + let budget = self.child_budget(); Some(CreationStart { budget, creator_record, depth }) } /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation, and /// journaled a transfer log or not (`logged`): opens the creation's frame level, counts the - /// created account and the log on it, then holds the start to the limits. The creation's usage - /// includes its creator's nonce record; its revert keeps it. + /// created account and the log on it, then holds the start to the limits. The creator's nonce + /// record is below the creation's level; its revert keeps it. /// /// A checkpoint opened outside a creation's start window opens a rollback level. pub(crate) fn after_creation( @@ -691,7 +679,7 @@ impl Ledger { self.report_mut().records.creator = start.creator_record; let Some(opened_at) = opened else { return }; debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); - self.open_frame_level(opened_at, start.budget, start.creator_record); + self.open_frame_level(opened_at, start.budget); self.counts.used = self.counts.used.saturating_add(with_transfer_log(WRITE_RECORD, logged)); let verdict = self.check(); let report = self.report_mut(); @@ -793,9 +781,8 @@ impl Ledger { } /// What a frame revm just built is taken back to when it is rewritten into a failure, with its - /// start: the counts its level opened with — after a creation's creator record. Never where - /// the frame's usage is measured from, which for a creation is before the creator's record. - /// The frame's side keeps it past the level's commit, for the mark the rewrite reverts to + /// start: the counts its level opened with, after a creation's creator record. The frame's + /// side keeps it past the level's commit, for the mark the rewrite reverts to /// ([`StartSide::built_mark`]). pub(crate) fn frame_start_rollback(&self) -> Option<(StartId, Rollback)> { let level = self.levels.last()?; diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index f8ab71088..102b27219 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -337,10 +337,11 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() #[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; + // The transaction's frame is capped at `CAP` and has spent nothing but its nonce record, + // counted on it as the creation starts, so the creation gets 98% of what the record leaves. + // Its start records the created account before the code. + let child_budget = share(CAP - 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); @@ -365,7 +366,11 @@ 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, + }, + "the creator's nonce record, and the creation's whole budget" ); assert_eq!(kept.state[&created].info.code_hash, keccak256(vec![0_u8; fits as usize])); @@ -410,16 +415,20 @@ fn create_returning_its_output(init: &Bytes, value: u64) -> Bytes { } /// A creation's start counts against the creation's own budget — the share of what its creator -/// has left — the created account's record and its creator's nonce record, the creator not having -/// recorded its account, and with an endowment the transfer log. The creator here is the -/// transaction's own frame, with `R` bytes left under the transaction's limit. +/// has left once the creator's own nonce record is counted on the creator — the created account's +/// record, and with an endowment the transfer log. The creator here is the transaction's own +/// frame, with `R` bytes left under the transaction's limit, of which its nonce record takes 40. +/// +/// The largest `R` whose remainder's share falls short of the start stops the creation at its +/// start, which keeps its creator's nonce record: 80 without an endowment, a share of 39 against +/// 40 bytes. One byte more, a share of 40, starts it. With 100 left the share of the 60 left is +/// 58, so the creation may deposit the 18 bytes beyond its start, and the 19th stops it at its +/// deposit; with an endowment, 260 left leave room for 15. A stopped creation keeps nothing of +/// its own, and its creator resumes with the nonce record alone. /// -/// The largest `R` whose share falls short of the start stops the creation at its start, which -/// keeps its creator's nonce record: 81 without an endowment, a share of 79 against 80 bytes. One -/// byte more, a share of 80, starts it. With 100 left the share is 98, so the creation may deposit -/// the 18 bytes beyond its start, and the 19th stops it at its deposit; with an endowment, 260 -/// left leave room for 14. A stopped creation keeps nothing of its own, and its creator resumes -/// with the nonce record alone. +/// Before the creator's record moved to the creating frame the creation's budget was the share of +/// the whole `R`, against a start of 80 bytes: 81 stopped it and 82 started it, 100 left the same +/// 18 bytes, and 260 with an endowment left 14. #[test] fn test_a_creation_is_held_to_its_share_from_its_start() { let run = |left: u64, endowment: u64, deployed: u64| { @@ -453,27 +462,37 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { ); }; + // The creation's budget: the share of what the creator has left after its nonce record. + let budget = |left: u64| share(left - WRITE_RECORD_SIZE); for endowment in [0, 1] { let log = if endowment == 0 { 0 } else { TRANSFER_LOG_SIZE }; - let at_start = 2 * WRITE_RECORD_SIZE + log; - let starts = child_room(at_start); + let at_start = WRITE_RECORD_SIZE + log; + let starts = WRITE_RECORD_SIZE + child_room(at_start); let case = format!("endowment {endowment}, {} left", starts - 1); - assert_stopped(&run(starts - 1, endowment, 0), share(starts - 1), &case); + assert_stopped(&run(starts - 1, endowment, 0), budget(starts - 1), &case); let case = format!("endowment {endowment}, {starts} left"); let started = run(starts, 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, usage(at_start, 2), "{case}: both records and the log"); + assert_eq!( + started.usage, + usage(WRITE_RECORD_SIZE + at_start, 2), + "{case}: both records and the log" + ); let left = 100 + log; - let room = share(left) - at_start; + 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, usage(share(left), 2), "{case}: exactly its share"); + assert_eq!( + fits.usage, + usage(WRITE_RECORD_SIZE + budget(left), 2), + "{case}: the creator's record, and exactly the creation's share" + ); assert_eq!( fits.state[&A.create(0)].info.code_hash, keccak256(vec![0_u8; room as usize]), @@ -481,13 +500,14 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { ); let case = format!("endowment {endowment}, {left} left, {} bytes deployed", room + 1); - assert_stopped(&run(left, endowment, room + 1), share(left), &case); + assert_stopped(&run(left, endowment, room + 1), budget(left), &case); if endowment == 0 { - assert_eq!((starts - 1, share(starts - 1), starts), (81, 79, 82)); - assert_eq!((share(left), room), (98, 18)); + assert_eq!((starts - 1, budget(starts - 1), starts), (80, 39, 81)); + assert_eq!((budget(left), room), (58, 18)); } else { - assert_eq!((share(left), room), (254, 14)); + assert_eq!((starts - 1, budget(starts - 1), starts), (244, 199, 245)); + assert_eq!((budget(left), room), (215, 15)); } } } @@ -1543,13 +1563,13 @@ fn call_and_return_its_output(target: Address) -> Bytes { /// 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. +/// `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; diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index 77a6ad638..f093fee5f 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -241,11 +241,11 @@ 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. +/// body and 121 bytes, the creator keeps its nonce record, 40, and the creation 98% of the 81 +/// left, 79: the creation's start makes the created account's record, 40 bytes, and the write in +/// its init code a second, 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_a_creation_its_frame_budget_stops_may_be_revived() { // A write of 1 to slot 1, short enough for `create_and_store_address`. @@ -272,12 +272,12 @@ fn test_a_creation_its_frame_budget_stops_may_be_revived() { // 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(121); 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(121); 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())) diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 2f1407c92..ae10a3630 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -146,11 +146,26 @@ impl Site { } } - /// The bytes the move counts on its frame's lane: its records and its transfer log. + /// The bytes the move counts: its records and its transfer log. const fn bytes(self) -> u64 { self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE } + /// The bytes of the move the creating frame keeps below the moving frame's lane: a creation's + /// creator nonce record, counted on the creator before the creation's budget is taken. + const fn below_the_frame(self) -> u64 { + match self { + Self::Create | Self::Create2 => WRITE_RECORD_SIZE, + _ => 0, + } + } + + /// The bytes the move counts on the moving frame's own lane: its records there and its + /// transfer log. + const fn frame_bytes(self) -> u64 { + self.bytes() - self.below_the_frame() + } + /// 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 { @@ -295,6 +310,24 @@ fn cap_for(depth: u32, bytes: u64) -> u64 { cap } +/// The budget of `site`'s moving frame under a frame cap of `cap`, when no frame above it has +/// kept anything but what the move itself puts below the frame: a creation's creator nonce record, +/// which the creator keeps before the creation's budget is taken from what it has left. +fn frame_budget(site: Site, cap: u64) -> u64 { + match site.depth() { + 0 => cap, + depth => share(budget(depth - 1, cap).saturating_sub(site.below_the_frame())), + } +} + +/// The smallest frame cap under which `site`'s moving frame has exactly `bytes` of budget. +fn cap_for_site(site: Site, bytes: u64) -> u64 { + let cap = (bytes..).find(|cap| frame_budget(site, *cap) >= bytes).unwrap(); + assert_eq!(frame_budget(site, cap), bytes, "a cap that gives exactly the bytes"); + assert_eq!(frame_budget(site, 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 { @@ -419,18 +452,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, which keeps nothing of the move, 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 on the moving frame's lane, and +/// one byte short of them stops the frame that moves the value, which keeps nothing of the move, +/// 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 creator nonce record is below the creation's lane, on the creator, which +/// keeps it before the creation's budget is taken. /// /// 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(site, site.frame_bytes()); for gas_limit in GAS_LIMITS { for variant in [Variant::Plain, Variant::Twin] { let case = format!("{site:?} {variant:?} at {gas_limit}"); @@ -448,8 +483,8 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { 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(), + limit: site.frame_bytes() - 1, + used: site.frame_bytes(), frame_local: true, }); assert_eq!( @@ -464,7 +499,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { ); let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), - limit: site.bytes() - 1, + limit: site.frame_bytes() - 1, }; match variant { Variant::Plain => assert_stopped_at_the_move(&case, site, &over, body, stop), diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 8ad2ef057..8924715d0 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -123,8 +123,10 @@ 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. - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 980 }); + // The call's own lane gets the frame cap, which the signer's nonce record, counted on the + // call before the creation's budget is taken, takes 40 of; the creation gets 98% of the + // 960 left. Before the record moved to the call the creation got 98% of the cap, 980. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 940 }); 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"); @@ -200,8 +202,10 @@ 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. - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 38 }); + // The call's lane gets the frame cap, which the signer's nonce record, counted on the + // call before the creation's budget is taken, uses up: the creation gets 98% of nothing. + // Before the record moved to the call the creation got 98% of the cap, 38. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 0 }); 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}"); 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 7c3b19ddb..09a811dd2 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 @@ -46,13 +46,13 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xd71d46b795d405e858eef0b6f1d6e6731fe1aa4c8718389b46a8f7c0694303a2", "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x37a162d66e66eaef26783bc9561e06aba6dce9824835444dfc73e7034f404684", "limit: compute, nonce 0 @ 50000000 | keccak256=0xc2631c368e7d21e89e7323514c180d9b25e176ed5f9670dbd34913cd5187eff7", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xa65b39c137245c46091e529c2f7944aa2e62cf30dcbc9a73becaf82c0896fb43", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x0ceeaf101b1fee07554f6921d6569826a7ec2c3a3cf0536aa0aa2ac3bba5f861", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xebe09eadbe683fa4f548e91770a9464d733d4e0d1a2786c2ad0c9b4bd17e11ab", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0xf4f161f8718555179819b157019d486c1fd6bb5d8817bf63a1bd8494af920311", "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x16ef5657b25cfc98fde279c24028149997b65d743364890fdcc5f2a6ededeac6", "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfc3ec81976944e9a9a74e281b679e51cb8fa90dd35d22e93d9a7b87051e6be8c", "limit: compute, nonce 1 @ 50000000 | keccak256=0x2ec14b4f0383ea6b0f12d50f0cd563bc00fa9092e50d22a156ca442852284686", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x519591ff76aad51fcf7b46f3f07b43680648bb0fe64308d600dc7ae0fd10d477", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x8f1596f86a5a6443ee8242b11d986b0a2d525485d2f579b0373cc2c44d12f4d1", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x28490ec07658b55c1c9fbb116430ee583fef5707812b694ccfb4e546a439b40f", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x04f9a5724edf49c4fec791ab8d222898a565f85efc67f836840ae03ca2138c4a", "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xe3e92aa87207f7c32e09845c17a80c911567cfd6938857c8f39e41ec2ceee873", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", "limit: the default limits @ 50000000 | keccak256=0xd8fc1b80ef6e59850a033311e764a0c0b324711ab87b7e9f228d81fef2b6e862", @@ -111,13 +111,13 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xad96560f17165fc62cb06d04e4a2ffc2bacb69852fe08b0b1aef0d9dec664690", "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x3fda5141c92c11c841821a4754de70393a313b6384e6e0bf8d2606dbe6d03f02", "limit: compute, nonce 0 @ 400000000 | keccak256=0x02f6f21cfc59e30ec997eaf750e39eba6a2b2cce4844e781dbcf118e2be5a1f1", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xa3d35dab98f17e60684b7fbcdb827fe82f004950301da26d87e78d7ba5125ec1", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xdb5e2d786cf84bd8c57d844f9d33c074735b0c7457e6cbf68c3fb66a9a88aabf", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x26449cdf1808167f44cbcd787486f5741d7f0e6fde01d26a17f5501c875c4596", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xf141cd7567627de8bf2653832e229ede610b5aabc446163038bfe3549db881f7", "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x97e3915f1b9d2e3fe4c473a182b1dd5262fd8143ad765da63a3d20aa6ed5beb6", "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x9482d4309b67ed34e4a9cd81480f3ac412dc428b4f8be119c8ce6da847650bf0", "limit: compute, nonce 1 @ 400000000 | keccak256=0x51b12b6471b58aae1bf288e49fc96363dabad62935fed9e53d5e988f1714f280", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xbe7a4b9b28f7b381c4889456ad8396f07fff0bc465722d021db69769e81852f3", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x79c1c1a6ba7f1d66e3e10cd3f5a19d706963fce44e18365bc61ddb2a56aaf830", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x685e111500442c8884fa6afcc8c5604ebc6b9071e64e62dd98b650664fccb836", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x6bc2427776359900918af73774b1e78be9360ee15982b8eb30d99ff8700ada8b", "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xed059de9072084c0cb48a30e520a4cbe621eb6e181f487dda43010e8a4b8e3a8", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", "limit: the default limits @ 400000000 | keccak256=0xb30a667ac091db1a3cd9ec446b4a07a89c5708d5ef2828142a56116ec8a9b532", From ebb9946b36771876e70f728b628862ab2a3cf8e6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 16:41:57 +0800 Subject: [PATCH 425/458] docs(satin): write records follow the net change of an account The spec's records section states the rule revm's block access list states: an account's record exists while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original, and a write that returns either takes its record back. Per-frame deduplication and the N-transfers-N-records rule are gone; a value call to the calling account records nothing; the creator's nonce record is the creating frame's, held to its budget and not the creation's, which gets a share of what the record leaves. The glossary and AGENTS.md say the same. --- AGENTS.md | 11 +++--- docs/spec/glossary.md | 2 +- docs/spec/upgrades/satin.md | 72 +++++++++++++++++++------------------ 3 files changed, 45 insertions(+), 40 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f5a8044c2..30667f40c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,7 +190,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 level of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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 by the ledger as revm makes it, inside the start window, and held to the limits while the frame's level is open, in `MegaEvm::frame_init` (`AdditionalLimit::hold_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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` and a creation it answers before bumping its creator's nonce count nothing and have no verdict, their level never having opened; either gets back the history its caller paid at the opcode, which charged it before revm decided, so a caller that cannot pay that charge runs out of gas even where revm would have refused the start. + A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` and a creation it answers before bumping its creator's nonce count nothing and have no verdict, their level never having opened; the call 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, and the creation gets back the history its caller paid. 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 lands on the creator, which is held to its limits with it. 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. @@ -203,7 +203,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `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 by the journal's ledger 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. +- No 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 — 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. @@ -400,9 +400,10 @@ 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: 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 level of the journal's ledger: a commit keeps them for the caller, a revert takes them back; a creator's nonce record is counted below the creation's level, so it survives the creation's failure once the nonce was bumped. + 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 (`MegaJournal::is_changed`): the journal compares the accounts a counted write touches before and after it — a value transfer's two sides, a creation's creator and created account (the created account a record whatever the address held), a `SELFDESTRUCT`'s beneficiary and the account it clears — and tells the ledger the records the write makes and takes back (`RecordDelta`), the frame-start hook predicts the same from the journal's state to charge the caller (`MegaJournal::start_records`), and 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 frame's level of the journal's ledger: a commit keeps them for the caller, a revert takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its level once the nonce was bumped and before the creation's budget is taken from what the creator has left, so it survives the creation's failure and is held to the creator's budget, not the creation's. That record lands on the creator unchecked, so the creator is held to its budget with it as the creation returns, before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_start_return`). The KV count a node reports is the write-record count; no limit holds it. - **The journal's ledger decides.** diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 359d3df64..cf8aa3c9a 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -85,7 +85,7 @@ _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) stat ## 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, a slot's while its value differs from its original value in the transaction. The KV-update count is the number of write records. ## History allowance diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 8884902d3..2fedf1dcb 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -337,19 +337,20 @@ When each charge is made: - 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. +- 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 — MUST be given back by it then, before what it makes is charged. 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 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. + 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 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. +- 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 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 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 pays for them whether or not the start then happens: a start refused on its caller's account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — makes no record and MUST give the charge back when its failed frame returns, and a caller that cannot pay the charge MUST halt with out-of-gas at the opcode though the start would have been refused. +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 is charged as any creation, and the charge MUST come back when its refused start returns. These MUST NOT pay history gas: @@ -410,18 +411,21 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw 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. + 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 records whether or not the transaction wrote it before, 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 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 on the lane of 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. + 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 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 is counted on the creator once the nonce was bumped, before the creation's budget is taken from what the creator has left, so it is held to the creator's budget and not the creation's, and it survives the creation's failure. 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. + 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, a creation of what its creator has left once the creator's nonce record is counted. 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. @@ -431,7 +435,7 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw - **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 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 and be stopped by no limit; its caller is charged for the records at its opcode and gets the charge back (see [History Gas](#7-history-gas)). + A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing and be stopped by no limit; a value the caller cannot fund is charged nothing at its opcode, and the charge for a creation whose creator nonce cannot be bumped comes back (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, lands on the creator, which MUST be held to its limits with it. - **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. @@ -640,23 +644,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 and, unless the transaction 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. @@ -676,7 +680,7 @@ An out-of-gas step halts the call, consuming its regular gas. 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 bump's write record and that record's history gas go back with it when the nonce set back leaves the signer's account as the transaction loaded it; 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. @@ -1021,7 +1025,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. From b5a82c2e32503eeb44e6c03c915b47eace8417b4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 22:11:37 +0800 Subject: [PATCH 426/458] test(limit): hold the start refund tests at any history byte price The refund now subtracts the price of the records a start kept, so a hand-picked charge only came out right where a record costs something; the three tests take their charges from the price in effect, as the hooks charge them. --- crates/mega-evm/src/evm/journal.rs | 33 ++++++++++++++++++++++++------ crates/mega-evm/src/limit/limit.rs | 14 ++++++++----- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 0668609bd..471f2a3d0 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -500,6 +500,12 @@ mod tests { records * WRITE_RECORD_SIZE + if moves { TRANSFER_LOG_SIZE } else { 0 } } + /// What a caller pays for `records` write records at the history price in effect, as the + /// frame-start hook charges them: nothing at a price of nothing. + fn record_charge(records: u64) -> u64 { + crate::write_record_history_gas(records).unwrap_or(0) + } + /// The transaction's bytes before any frame: the body. const fn body() -> LimitUsage { LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } @@ -748,8 +754,12 @@ mod tests { /// later value call from it records only its recipient. Reverted, it takes back what the frame /// kept: the records and the frame's refund all go back to before the start, and the later /// call finds the caller unchanged and records it again. + /// + /// The caller paid for the start's two records at the price in effect, as the frame-start hook + /// charges them, so the refund holds at any history byte price, a price of nothing included. #[test] fn test_a_tool_checkpoint_around_a_call_closes_in_order() { + let charge = record_charge(2); for reverted in [false, true] { let case = if reverted { "reverted" } else { "committed" }; let mut journal = journal(EvmTxRuntimeLimits::no_limits()); @@ -762,14 +772,14 @@ mod tests { "{case}: B's record, A's, and the log" ); end_frame(&mut journal, None); - let mut side = StartSide::new(1, 7, 0, true, None); + let mut side = StartSide::new(1, charge, 0, true, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); } else { journal.checkpoint_commit(); } - let refund = if reverted { 7 } else { 0 }; + let refund = if reverted { charge } else { 0 }; assert_eq!(side.refund(journal.ledger()), refund, "{case}: B's refund"); assert_eq!(journal.ledger().usage(), if reverted { body() } else { kept(2, 1) }); @@ -786,19 +796,30 @@ mod tests { /// a revert of it takes back the creator's nonce record with the rest, which the creation's own /// failure leaves: the creator's caller gets back the charge for that record too, and the /// creator's account is unchanged again, so its next creation records it. + /// + /// The caller paid one record's price for the created account and one for the creator's nonce, + /// at the price in effect, as the frame-start hook charges them, so the refunds hold at any + /// history byte price, a price of nothing included. #[test] fn test_a_tool_checkpoint_around_a_creation_takes_its_creators_record_back() { + let (created, creator) = (record_charge(1), record_charge(1)); for (case, failed, reverted, refund, creator_changed) in [ ("a creation that succeeds, the tool's checkpoint committed", false, false, 0, true), - ("a creation that fails, the tool's checkpoint committed", true, false, 7, true), + ("a creation that fails, the tool's checkpoint committed", true, false, created, true), ( "a creation that succeeds, the tool's checkpoint reverted", false, true, - 7 + 11, + created + creator, + false, + ), + ( + "a creation that fails, the tool's checkpoint reverted", + true, + true, + created + creator, false, ), - ("a creation that fails, the tool's checkpoint reverted", true, true, 7 + 11, false), ] { let mut journal = journal(EvmTxRuntimeLimits::no_limits()); let _ = start_call(&mut journal, 0, SENDER, A, 0); @@ -807,7 +828,7 @@ mod tests { let (checkpoint, report) = start_creation(&mut journal, 2, B, CREATED, 1); assert!(report.records.creator, "{case}: B's nonce record is the start's"); end_frame(&mut journal, failed.then_some(checkpoint)); - let mut side = StartSide::new(2, 7, 11, true, None); + let mut side = StartSide::new(2, created, creator, true, None); side.attach(report, None); if reverted { journal.checkpoint_revert(tool); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index cdbd07947..2ed9857f4 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -761,15 +761,19 @@ mod tests { /// record: a frame that failed, and a frame answered before revm decided it. A frame that kept /// its record gives nothing back, and a transaction whose first frame never started has /// nothing to give back. + /// + /// The record's history is charged at the price in effect, as pre-execution charges it, so the + /// refunds hold at any history byte price, a price of nothing included. #[test] fn test_the_top_level_record_comes_back_once_at_the_settlement() { + let charge = crate::write_record_history_gas(1).unwrap_or(0); let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); let outer = call_from_to(SENDER, CALLEE, U256::from(1)); let ended = |result| crate::synthetic_frame_result(&outer, result, Bytes::new()); // The start kept: a level revm committed. - for (case, failed, refund) in [("kept", false, 0), ("failed", true, 7)] { + for (case, failed, refund) in [("kept", false, 0), ("failed", true, charge)] { let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(7); + limit.set_top_level_write_record_gas(charge); limit.push_start(&outer, 0); ctx.ledger_mut().begin_transaction(false, false, 0); ctx.ledger_mut().open_start(StartFacts { @@ -798,14 +802,14 @@ mod tests { // Answered before revm decided it: nothing counted, everything back. let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(7); + limit.set_top_level_write_record_gas(charge); limit.push_answered_start(0); let _ = limit.on_start_return(ctx.ledger(), &ended(InstructionResult::Stop)); - assert_eq!(limit.take_top_level_refund(), 7); + assert_eq!(limit.take_top_level_refund(), charge); // Never started: no side, nothing back. let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(7); + limit.set_top_level_write_record_gas(charge); assert!(limit.on_start_return(ctx.ledger(), &ended(InstructionResult::OutOfGas)).is_none()); assert_eq!(limit.take_top_level_refund(), 0); } From aa864b05872295300e88a4d6da542a0a39dfda87 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 22:12:22 +0800 Subject: [PATCH 427/458] docs: a SELFDESTRUCT records the account it clears, and records follow the net change The texts that still named a SELFDESTRUCT's beneficiary as its only record, or said records are deduplicated per frame, now state the rule the engine runs. --- AGENTS.md | 8 ++++---- crates/mega-evm/src/limit/mod.rs | 16 +++++++++------- .../mega-evm/tests/satin/detained_transfers.rs | 10 +++++----- crates/mega-evm/tests/satin/state_growth.rs | 2 +- crates/mega-evm/tests/satin/transfer_logs.rs | 4 ++-- crates/mega-evm/tests/satin/write_records.rs | 6 +++--- docs/spec/upgrades/satin.md | 2 +- 7 files changed, 25 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 30667f40c..d399ac8ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,7 +175,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 completed-write hook charges a storage write's, a log's and a `SELFDESTRUCT`'s record 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. + 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. 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. @@ -188,7 +188,7 @@ 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 level of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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. + It is counted where the value moves, on the level of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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 is counted by the ledger as revm makes it, inside the start window, and held to the limits while the frame's level is open, in `MegaEvm::frame_init` (`AdditionalLimit::hold_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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` and a creation it answers before bumping its creator's nonce count nothing and have no verdict, their level never having opened; the call 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, and the creation gets back the history its caller paid. 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 lands on the creator, which is held to its limits with it. @@ -196,7 +196,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. The ledger counts the log revm journaled for a start, not a prediction of 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. - 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 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). + 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). @@ -389,7 +389,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 commits the record to the running frame's level of the journal's ledger and holds it to the limits first — 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 record, and is charged nothing for it. + 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge on the frame's side (`StartSide`), which gives back on return what the ledger reports the start did not keep. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0bcb4110f..7a413fddb 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -40,8 +40,8 @@ //! - 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; +//! - 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 level 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 @@ -80,11 +80,13 @@ //! # Write records //! //! The write-record count the ledger keeps 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. +//! 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 — taken back by a write that returns the slot or the account 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 //! diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 2d77c41b7..5ac44f2ae 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -1,11 +1,11 @@ //! 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, 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 -//! 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 diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 2c4439f10..3d0b22373 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -522,7 +522,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, ), diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index ae10a3630..87533d237 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -8,8 +8,8 @@ //! - 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, 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 the beneficiary's record, once the -//! opcode completed, and a crossing stops the destructing frame, which 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 diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 88e80c9bf..406db9962 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -3,9 +3,9 @@ //! 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. +//! `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 diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 2fedf1dcb..6d1e64a69 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -408,7 +408,7 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw | 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)). + 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. From cc83823a523f43a3eacdcc00d55ea01bd8183f73 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:54:40 +0800 Subject: [PATCH 428/458] fix(limit): a creation records its created account only when it changes it The created account follows the net-change rule like every account write: an address the transaction funded, or a SELFDESTRUCT paid, before a creation lands on it keeps the one record it has. The frame-start hook still charges the record for every creation, since it cannot tell the address a CREATE2 lands on, and the refund gives back what the count fell short of. --- crates/mega-evm/src/evm/execution.rs | 14 +- crates/mega-evm/src/evm/host.rs | 10 +- crates/mega-evm/src/evm/journal.rs | 67 ++++++++-- crates/mega-evm/src/limit/ledger.rs | 122 ++++++++++++------ crates/mega-evm/src/limit/limit.rs | 114 ++++++++++------ crates/mega-evm/src/limit/mod.rs | 10 +- crates/mega-evm/src/limit/record.rs | 6 +- .../mega-evm/src/system/keyless/dispatch.rs | 2 +- crates/mega-evm/tests/satin/write_records.rs | 116 ++++++++++++++++- 9 files changed, 350 insertions(+), 111 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9a3d2492c..ba1fd98d1 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -51,7 +51,7 @@ use crate::{ charge_write_records_history, evm::inspector::{frame_end_checked, ResultSource, StepGuard, UpfrontRecord}, history_gas, - limit::{FrameIdentity, Mark, StartFacts, StartReport}, + limit::{FrameIdentity, FrameStartRecords, Mark, StartFacts, StartReport}, synthetic_frame_result, system::keyless, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, @@ -1428,8 +1428,9 @@ fn record_applied_authorities( /// The recipient's record is predicted as the journal's state stands before the first frame /// ([`MegaJournal::transfer_records`](crate::MegaJournal)): 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 a record whatever -/// the address held. +/// 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, and the ledger counts it. /// /// 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 when the @@ -1450,14 +1451,15 @@ fn charge_records_made_outside_a_frame( } let tx = ctx.tx(); let records = match tx.kind() { - TxKind::Create => 1, + TxKind::Create => FrameStartRecords { created: true, ..FrameStartRecords::NONE }, TxKind::Call(to) => { let predicted = ctx.journal_ref().transfer_records(tx.caller(), to, tx.value()); debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); - predicted.added + FrameStartRecords { on_level: predicted, ..FrameStartRecords::NONE } } }; - let Some((top_level, _)) = charge_write_records_history(gas, records, applied_authorities) + let Some((top_level, _)) = + charge_write_records_history(gas, records.added_on_level(), applied_authorities) else { return false; }; diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 2d28c07bd..2fa994237 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -350,9 +350,11 @@ impl revm::context_interface::Host /// 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 and its creator's nonce — as the journal predicts them from its state - /// ([`MegaJournal::start_records`](crate::MegaJournal)). 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. + /// ([`MegaJournal::start_records`](crate::MegaJournal)). The created account is charged for + /// every creation: the address a `CREATE2` lands on is not known here, and a creation onto an + /// address the transaction changed already makes no record for it. 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. /// /// 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; the frame's side keeps it, and @@ -380,7 +382,7 @@ impl revm::context_interface::Host return true; } let charged = - charge_write_records_history(gas, records.on_level.added, u64::from(records.creator)); + charge_write_records_history(gas, records.added_on_level(), u64::from(records.creator)); let Some((added, creator)) = charged else { gas.erase_cost(start.forward); gas.set_failed_charge_remaining(Some(gas.remaining())); diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 471f2a3d0..2ba50cb05 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -18,7 +18,8 @@ //! write, and tells the ledger which accounts the write changed and which it returned //! ([`RecordDelta`]). The same prediction, on the journal's state as it stands, is what the //! frame-start hook charges a start's records from -//! ([`start_records`](MegaJournal::start_records)). +//! ([`start_records`](MegaJournal::start_records)), but for a creation's created account, which +//! the hook charges for every creation, not knowing the address. //! - **Levels and the transaction's end.** `checkpoint`, `checkpoint_commit` and //! `checkpoint_revert` open and close the ledger's levels with revm's checkpoints; `commit_tx`, //! `discard_tx` and `finalize` close them all. @@ -187,26 +188,30 @@ impl MegaJournal { self.balance_change(from, from_after).with(self.balance_change(to, to_after)) } - /// The records a creation by `creator` with an endowment of `value` makes: the account it - /// creates, and the creator's nonce, when the bump changes an account the transaction had not - /// changed; nothing for an endowment `creator` cannot fund, which revm refuses before it bumps - /// the nonce. + /// The records a creation by `creator` with an endowment of `value` may make, for a charge made + /// before revm decides the start: the creator's nonce, when the bump changes an account the + /// transaction had not changed, and the account it creates, counted as a record whatever the + /// address held — the address a `CREATE2` lands on is not known before revm decides the + /// start, and the refund gives back the record when the creation made none. Nothing for an + /// endowment `creator` cannot fund, which revm refuses before it bumps the nonce. pub(crate) fn creation_records(&self, creator: Address, value: U256) -> FrameStartRecords { if self.balance(creator) < value { return FrameStartRecords::NONE; } FrameStartRecords { - on_level: RecordDelta { added: 1, taken: 0 }, + on_level: RecordDelta::NONE, + created: true, creator: !self.is_changed(creator), } } /// The records the frame `start` makes, for the frame-start hook to charge its caller for: a - /// call's value transfer ([`transfer_records`](Self::transfer_records)), a creation's created - /// account and creator nonce ([`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. Nor does a start whose value the caller cannot fund, - /// which revm refuses on the caller's account. + /// call's value transfer ([`transfer_records`](Self::transfer_records)), a creation's creator + /// nonce and, as an upper bound, its created account + /// ([`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. Nor does a start whose value the caller cannot fund, which revm refuses on the + /// caller's account. pub(crate) fn start_records(&self, start: &FrameStart) -> FrameStartRecords { match start.kind { FrameStartKind::Create | FrameStartKind::Create2 => { @@ -219,7 +224,7 @@ impl MegaJournal { on_level: start.target.map_or(RecordDelta::NONE, |target| { self.transfer_records(start.caller, target, start.value) }), - creator: false, + ..FrameStartRecords::NONE }, } } @@ -384,7 +389,8 @@ impl JournalTr for MegaJournal { /// Counted inside a creation's start window: the creator's nonce record before the creation's /// level opens, when the bump revm made changed an account the transaction had not changed, - /// then the created account and the transfer log on it. + /// then, on the creation's level, the created account's record, when the creation changes an + /// account the transaction had not changed, and the transfer log. fn create_account_checkpoint( &mut self, caller: Address, @@ -393,10 +399,11 @@ impl JournalTr for MegaJournal { spec_id: SpecId, ) -> Result { let start = self.ledger.before_creation(!self.is_changed_before_bump(caller)); + let created_unchanged = !self.is_changed(address); let logs = self.revm.logs().len(); let opened = self.revm.create_account_checkpoint(caller, address, balance, spec_id); let logged = self.revm.logs().len() > logs; - self.ledger.after_creation(start, opened.ok(), logged); + self.ledger.after_creation(start, opened.ok(), created_unchanged, logged); self.assert_levels(); opened } @@ -899,6 +906,38 @@ mod tests { } } + /// A creation records the account it creates as every counted write records an account: when + /// the creation changes an account the transaction had not changed. An address a transfer + /// funded is changed already, and the creation adds no record for it, however it then changes + /// it. The records the frame-start hook charges from count the account for every creation, the + /// address not being known there. + #[test] + fn test_a_creation_records_its_account_by_the_net_change() { + for funded in [false, true] { + let mut journal = journal(EvmTxRuntimeLimits::no_limits()); + let _ = start_call(&mut journal, 0, SENDER, A, 0); + if funded { + let _ = start_call(&mut journal, 1, A, CREATED, 1); + end_frame(&mut journal, None); + } + let charged = journal.creation_records(B, U256::from(1)); + assert_eq!( + charged, + FrameStartRecords { on_level: RecordDelta::NONE, created: true, creator: true }, + "funded {funded}: charged for the created account and B's nonce" + ); + let (_, report) = start_creation(&mut journal, 1, B, CREATED, 1); + assert_eq!( + report.records, + FrameStartRecords { on_level: RecordDelta::NONE, created: !funded, creator: true }, + "funded {funded}: the created account is counted where the creation changed it" + ); + let (records, logs) = if funded { (3, 2) } else { (2, 1) }; + assert_eq!(journal.ledger().usage(), kept(records, logs), "funded {funded}"); + assert!(journal.is_changed(CREATED), "funded {funded}: the creation changed it"); + } + } + /// A creation's start mark is its level's opening, after the creator's record: a creation /// rewritten into a failure is taken back to it, and keeps its creator's record, as a creation /// that fails does, the creator's nonce standing. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 6ba3e9ef6..c5ba51ad9 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -136,9 +136,16 @@ pub(crate) struct StartFacts { /// 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 { - /// The records on the frame's own level, which its failure takes back: the accounts a value - /// transfer changes and returns, a creation's created account. + /// The records a call's value transfer makes and takes back on the frame's own level, which + /// its failure takes back: the accounts it changes from what the transaction loaded, and those + /// it returns to that. pub(crate) on_level: RecordDelta, + /// Whether the start records the account a creation creates, on the frame's own level, which + /// its failure takes back. The ledger counts it when the creation changed an account the + /// transaction had not changed; a charge made before revm decides the start counts it for + /// every creation, the address a `CREATE2` lands on not being known there, and the refund + /// gives back what the count fell short of. + pub(crate) created: bool, /// Whether the start writes its creator's nonce record, on the creating frame, which the /// creation's failure leaves there. pub(crate) creator: bool, @@ -146,7 +153,24 @@ pub(crate) struct FrameStartRecords { impl FrameStartRecords { /// No record at all. - pub(crate) const NONE: Self = Self { on_level: RecordDelta::NONE, creator: false }; + pub(crate) const NONE: Self = + Self { on_level: RecordDelta::NONE, created: false, creator: false }; + + /// The records the start adds on the frame's own level: the accounts a transfer changes, and + /// the created account. + pub(crate) const fn added_on_level(self) -> u64 { + self.on_level.added + self.created as u64 + } + + /// Whether a charge computed from `self` paid for the records `counted`: the same records, + /// but for the created account, which the charge counts for every creation and the ledger only + /// where the creation changed it. + #[cfg(debug_assertions)] + fn covers(self, counted: Self) -> bool { + self.on_level == counted.on_level && + self.creator == counted.creator && + (self.created || !counted.created) + } } /// The start window, open while revm decides one frame start. @@ -629,7 +653,7 @@ impl Ledger { self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD.times(records.taken)); let verdict = self.check(); let report = self.report_mut(); - report.records = FrameStartRecords { on_level: records, creator: false }; + report.records = FrameStartRecords { on_level: records, ..FrameStartRecords::NONE }; report.transfer_log = logged; report.verdict = Some(verdict); } @@ -659,15 +683,19 @@ impl Ledger { } /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation, and - /// journaled a transfer log or not (`logged`): opens the creation's frame level, counts the - /// created account and the log on it, then holds the start to the limits. The creator's nonce - /// record is below the creation's level; its revert keeps it. + /// journaled a transfer log or not (`logged`): opens the creation's frame level, counts on it + /// the created account's record when the creation changed an account the transaction had not + /// changed (`created_unchanged`), and the log, then holds the start to the limits. A creation + /// sets the account's nonce to one, so it leaves the account changed, and never returns it to + /// what the transaction loaded. The creator's nonce record is below the creation's level; its + /// revert keeps it. /// /// A checkpoint opened outside a creation's start window opens a rollback level. pub(crate) fn after_creation( &mut self, start: Option, opened: Option, + created_unchanged: bool, logged: bool, ) { let Some(start) = start else { @@ -680,10 +708,11 @@ impl Ledger { let Some(opened_at) = opened else { return }; debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); self.open_frame_level(opened_at, start.budget); - self.counts.used = self.counts.used.saturating_add(with_transfer_log(WRITE_RECORD, logged)); + let created = WRITE_RECORD.times(u64::from(created_unchanged)); + self.counts.used = self.counts.used.saturating_add(with_transfer_log(created, logged)); let verdict = self.check(); let report = self.report_mut(); - report.records.on_level = RecordDelta { added: 1, taken: 0 }; + report.records.created = created_unchanged; report.transfer_log = logged; report.verdict = Some(verdict); } @@ -900,6 +929,11 @@ impl StartSide { /// runs between the two, and can split them: under one the start is not checked. Only a start /// revm made and held to the limits is checked: one it refused, or failed before its level /// opened, counted nothing, and the charge comes back. + /// + /// The one record the charge may count where the ledger does not is a creation's created + /// account ([`FrameStartRecords::created`]): the charge cannot tell the address a `CREATE2` + /// lands on, and counts it for every creation; the refund gives back what it paid for a record + /// the ledger did not count. pub(crate) fn attach(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { self.start = report.start; self.counted = report.records; @@ -911,9 +945,11 @@ impl StartSide { if let Some(charged) = self.charged.filter(|_| report.start.is_some() && report.verdict.is_some()) { - debug_assert_eq!( - charged, report.records, - "the records a frame's start makes changed after its caller was charged for them", + debug_assert!( + charged.covers(report.records), + "the records a frame's start makes changed after its caller was charged for them: \ + charged {charged:?}, counted {:?}", + report.records, ); } } @@ -955,17 +991,19 @@ impl StartSide { /// The records on the start's own level are held when that level was kept — committed, and not /// taken back since — and so is what the start took back there: the caller then gets back the /// price of every record the start returned to what the transaction loaded, which nobody paid - /// for again. A creator's nonce record, counted below the creation's level, is held unless a - /// revert to before the start took it back. So a start answered before revm decided it, or - /// refused before its writes, gets everything back; a call answered with a success keeps its - /// records; a failed precompile, and a frame that fails, give theirs back, a creator's - /// surviving record aside, and give back nothing for a take-back their failure undid. + /// for again, and of a created account's record it paid for and the ledger did not count, the + /// account having been changed before. A creator's nonce record, counted below the creation's + /// level, is held unless a revert to before the start took it back. So a start answered before + /// revm decided it, or refused before its writes, gets everything back; a call answered with a + /// success keeps its records; a failed precompile, and a frame that fails, give theirs back, a + /// creator's surviving record aside, and give back nothing for a take-back their failure + /// undid. pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { let (level_kept, start_kept) = self.start.map_or((false, false), |start| ledger.fate(start)); let on_level = self.counted.on_level; let mut refund = if level_kept { - let kept = records_history_gas(on_level.added); + let kept = records_history_gas(self.counted.added_on_level()); let taken = if self.priced { records_history_gas(on_level.taken) } else { 0 }; self.added_charge.saturating_sub(kept).saturating_add(taken) } else { @@ -1311,7 +1349,7 @@ mod tests { if failed { ledger.open_start(StartFacts { depth: 1, creation: true, transfers_value: false }); let start = ledger.before_creation(true); - ledger.after_creation(start, Some(checkpoint(&ledger)), false); + ledger.after_creation(start, Some(checkpoint(&ledger)), true, false); let _ = ledger.close_start(); } else { start_call(&mut ledger, 1, 0, RecordDelta::NONE); @@ -1327,31 +1365,39 @@ mod tests { /// A creation's creator record is the creating frame's, counted when the bump changed an /// account the transaction had not changed, and never for the transaction's own creation, - /// whose creator is the sender, whom the body counts. + /// whose creator is the sender, whom the body counts. The created account's record is the + /// creation's own, counted on its level when the creation changed an account the transaction + /// had not changed, at any depth. #[test] fn test_a_creators_record_is_counted_below_the_creations_level() { for (depth, creator_unchanged, expected) in [(1, true, true), (1, false, false), (0, true, false), (0, false, false)] { - let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); - if depth > 0 { - start_call(&mut ledger, 0, 0, RecordDelta::NONE); + for created_unchanged in [true, false] { + let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); + if depth > 0 { + start_call(&mut ledger, 0, 0, RecordDelta::NONE); + } + ledger.open_start(StartFacts { depth, creation: true, transfers_value: false }); + let start = ledger.before_creation(creator_unchanged); + ledger.after_creation(start, Some(checkpoint(&ledger)), created_unchanged, false); + let report = ledger.close_start(); + let case = format!( + "depth {depth}, creator unchanged {creator_unchanged}, created account \ + unchanged {created_unchanged}" + ); + assert_eq!(report.records.creator, expected, "{case}"); + assert_eq!(report.records.created, created_unchanged, "{case}"); + assert_eq!(report.records.on_level, RecordDelta::NONE, "{case}"); + let records = u64::from(created_unchanged) + u64::from(expected); + assert_eq!(ledger.usage(), WRITE_RECORD.times(records), "{case}"); + end_frame(&mut ledger, true); + assert_eq!( + ledger.usage(), + WRITE_RECORD.times(u64::from(expected)), + "{case}: the creator's record survives the creation's failure" + ); } - ledger.open_start(StartFacts { depth, creation: true, transfers_value: false }); - let start = ledger.before_creation(creator_unchanged); - ledger.after_creation(start, Some(checkpoint(&ledger)), false); - let report = ledger.close_start(); - let case = format!("depth {depth}, creator unchanged {creator_unchanged}"); - assert_eq!(report.records.creator, expected, "{case}"); - assert_eq!(report.records.on_level, RecordDelta { added: 1, taken: 0 }, "{case}"); - let records = 1 + u64::from(expected); - assert_eq!(ledger.usage(), WRITE_RECORD.times(records), "{case}"); - end_frame(&mut ledger, true); - assert_eq!( - ledger.usage(), - WRITE_RECORD.times(u64::from(expected)), - "{case}: the creator's record survives the creation's failure" - ); } } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 2ed9857f4..97995a793 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -12,7 +12,6 @@ use std::vec::Vec; use super::{ ledger::{FrameStartRecords, Ledger, Rollback, StartId, StartSide}, - record::RecordDelta, EvmTxRuntimeLimits, LimitCheck, LimitKind, StartReport, WRITE_RECORD_SIZE, }; use crate::storage_call_stipend; @@ -80,7 +79,7 @@ pub struct AdditionalLimit { /// The write records the transaction's own frame makes, as the charge of their history before /// execution found them, for the frame's side to hold the ledger's count to. See /// [`stage_top_level_records`](Self::stage_top_level_records). - pending_top_level_records: Option, + 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 side to be pushed. pending_frame_charge: FrameCharge, @@ -319,7 +318,7 @@ impl AdditionalLimit { /// decided the start ([`attach_start`](Self::attach_start)). /// /// Only a transaction that pays history is charged, and so leaves one. - pub(crate) const fn stage_top_level_records(&mut self, records: u64) { + pub(crate) const fn stage_top_level_records(&mut self, records: FrameStartRecords) { self.pending_top_level_records = Some(records); } @@ -398,10 +397,7 @@ impl AdditionalLimit { let side = if depth == 0 { // The transaction's own frame takes nothing back: its recipient, when it writes one, // is an account the transaction had not changed. - let records = self.pending_top_level_records.take().map(|added| FrameStartRecords { - on_level: RecordDelta { added, taken: 0 }, - creator: false, - }); + let records = self.pending_top_level_records.take(); StartSide::new(depth, self.top_level_write_record_gas, 0, false, records) } else { StartSide::new(depth, charge.added, charge.creator, charge.priced, charge.records) @@ -517,7 +513,11 @@ impl FrameCharge { #[cfg(test)] mod tests { use super::*; - use crate::{limit::StartFacts, test_utils::MemoryDatabase, MegaContext, MegaSpecId}; + use crate::{ + limit::{RecordDelta, StartFacts}, + test_utils::MemoryDatabase, + MegaContext, MegaSpecId, + }; use alloy_primitives::{address, Address, Bytes, U256}; use revm::{ context::{ContextTr, JournalTr}, @@ -554,21 +554,26 @@ mod tests { })) } - /// What the ledger reports of a start revm made and held to the limits: `added` records on - /// the frame's level, and the creator's own record (`creator`) below it. - fn report(added: u64, creator: bool) -> StartReport { + /// What the ledger reports of a start revm made and held to the limits: `records`. + fn report(records: FrameStartRecords) -> StartReport { StartReport { start: Some(StartId::default()), - records: records(added, creator), + records, transfer_log: false, refused: false, verdict: Some(LimitCheck::WithinLimit), } } - /// `added` records on the frame's level, and the creator's own record (`creator`) below it. - const fn records(added: u64, creator: bool) -> FrameStartRecords { - FrameStartRecords { on_level: RecordDelta { added, taken: 0 }, creator } + /// `added` records a call's value transfer makes on the frame's level. + const fn transfer(added: u64) -> FrameStartRecords { + FrameStartRecords { on_level: RecordDelta { added, taken: 0 }, ..FrameStartRecords::NONE } + } + + /// A creation's records: its created account's on the frame's level (`created`), and its + /// creator's own below it (`creator`). + const fn creation(created: bool, creator: bool) -> FrameStartRecords { + FrameStartRecords { on_level: RecordDelta::NONE, created, creator } } /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` @@ -651,27 +656,62 @@ mod tests { /// The records the ledger counts for a start are the records its caller was charged for: a /// value transfer records the caller's account and the recipient's, the two the charge was - /// computed from, and a creation the created account and its creator's nonce. A start revm - /// refused, or failed before its level opened, counted nothing and is not held to the charge. + /// computed from, and a creation the created account and its creator's nonce. The charge counts + /// the created account for every creation, the address not being known at the opcode, so a + /// creation onto an account the transaction changed already counts less than it was charged + /// for. A start revm refused, or failed before its level opened, counted nothing and is not + /// held to the charge. #[test] fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(records(2, false), 2, 0, true); - limit.push_start(&inner, 1); - limit.attach_start(report(2, false), None); - - limit.stage_frame_charge(records(1, true), 1, 1, true); - limit.push_start(&inner, 1); - limit.attach_start(report(1, true), None); + for (charged, counted) in [ + (transfer(2), transfer(2)), + (creation(true, true), creation(true, true)), + (creation(true, true), creation(false, true)), + (creation(true, false), creation(false, false)), + ] { + limit.stage_frame_charge(charged, 2, 0, true); + limit.push_start(&inner, 1); + limit.attach_start(report(counted), None); + } - limit.stage_frame_charge(records(2, false), 2, 0, true); + limit.stage_frame_charge(transfer(2), 2, 0, true); limit.push_start(&inner, 1); - let refused = StartReport { verdict: None, refused: true, ..report(0, false) }; + let refused = + StartReport { verdict: None, refused: true, ..report(FrameStartRecords::NONE) }; limit.attach_start(refused, None); } + /// Every record but a creation's created account is held to the charge exactly: a transfer + /// that counts fewer records than its caller was charged for trips, as one that counts more + /// does, and so does a creator's nonce record counted where none was charged. + #[test] + #[cfg(debug_assertions)] + fn test_only_the_created_account_may_count_less_than_it_was_charged() { + let trips = |charged: FrameStartRecords, counted: FrameStartRecords| { + std::panic::catch_unwind(move || { + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_frame_charge(charged, 0, 0, true); + limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + limit.attach_start(report(counted), None); + }) + .is_err() + }; + assert!(trips(transfer(2), transfer(1)), "a transfer that counts one record fewer"); + assert!(trips(creation(true, false), creation(true, true)), "a creator record not charged"); + assert!( + trips(creation(false, false), creation(true, false)), + "a created account not charged" + ); + assert!( + !trips(creation(true, false), creation(false, false)), + "a created account not made" + ); + } + /// 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. @@ -683,18 +723,18 @@ mod tests { limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(2, false), None); + limit.attach_start(report(transfer(2)), None); } /// The transaction's own frame is held to the records its history was charged for before /// execution: its value's recipient, or the account a creation makes. #[test] fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { - for added in [0, 1] { + for records in [transfer(0), transfer(1), creation(true, false)] { let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(added); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(added)), 0); - limit.attach_start(report(added, false), None); + limit.stage_top_level_records(records); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + limit.attach_start(report(records), None); } } @@ -706,9 +746,9 @@ mod tests { #[should_panic(expected = "changed after its caller was charged for them")] 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.stage_top_level_records(transfer(0)); limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(1, false), None); + limit.attach_start(report(transfer(1)), None); } /// Under an inspector that may rewrite a start, the check is waived: the start its charge paid @@ -716,14 +756,14 @@ mod tests { #[test] fn test_a_waived_start_is_not_held_to_its_charge() { let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(0); + limit.stage_top_level_records(transfer(0)); limit.waive_start_check(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(1, false), None); + limit.attach_start(report(transfer(1)), None); limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); limit.waive_start_check(); limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(2, false), None); + limit.attach_start(report(transfer(2)), None); } /// A frame answered without running — by the depth guard, a stop, an interceptor or an @@ -746,7 +786,7 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(records(1, true), 1_000, 2_000, true); + limit.stage_frame_charge(creation(true, true), 1_000, 2_000, true); limit.push_answered_start(1); let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); let (_, refund) = limit.on_start_return(ledger, &result).expect("the side"); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 7a413fddb..2d4d26619 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -82,11 +82,11 @@ //! The write-record count the ledger 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 — taken back by a write that returns the slot or the account 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. +//! 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 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 //! diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 27649a86a..2ca8c26ac 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -13,8 +13,10 @@ use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; /// the transaction loaded, and the records it takes back, for accounts it returns to that. /// /// A value transfer moves at most one record per side, and a `SELFDESTRUCT` one per account it -/// writes; a creation's created account is one record, and its creator's nonce bump another, kept -/// apart from this delta because it lands on the creating frame. +/// writes. A creation's records are kept apart from this delta +/// ([`FrameStartRecords`](super::FrameStartRecords)): its created account, which the creation +/// leaves changed and never returns, and its creator's nonce bump, which lands on the creating +/// frame. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct RecordDelta { /// Records created. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 14686a821..d13c90138 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -433,7 +433,7 @@ fn prepare( let record_charges = if ctx.prices_history() { let charged = charge_write_records_history( gas.tracker_mut(), - records.on_level.added, + records.added_on_level(), u64::from(records.creator), ); if charged.is_none() { diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 406db9962..be693adc7 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -10,14 +10,15 @@ //! 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 records the account it creates. 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. +//! 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::{ @@ -442,6 +443,113 @@ fn test_a_destruction_to_a_fresh_and_to_a_changed_beneficiary() { } } +/// 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 caller pays the created account's history at the opcode, which cannot tell the address a +/// `CREATE2` lands on, and gets it back when the creation recorded nothing — and, with everything +/// else the creation made, when it fails: 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) + let rows: [(&str, Prelude, Created, u64, u64); 6] = [ + ("fund X only: CALLEE and X", fund, None, 2, 1), + ("create X only: CALLEE's nonce and X", nothing, Some((SUCCEEDS, 0)), 2, 0), + ("fund X, then create X: CALLEE and X", fund, Some((SUCCEEDS, 0)), 2, 1), + ("fund X, then create X with an endowment: CALLEE and X", fund, Some((SUCCEEDS, 1)), 2, 2), + ( + "a destruction pays X, then create X: DESTRUCTOR, X and CALLEE's nonce", + destruct, + Some((SUCCEEDS, 0)), + 3, + 1, + ), + ("fund X, then a creation at X that fails: CALLEE and X", fund, Some((FAILS, 0)), 2, 1), + ]; + for creation in [Creation::Create2, Creation::Create] { + for (case, prelude, created, records_kept, logs) 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, + with_extra(records(records_kept), logs * TRANSFER_LOG_SIZE), + "{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. #[test] fn test_create_then_call_record_the_frame_account_once() { From 588cd57e340273c735b5906c9584f102fd2abb0c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:54:40 +0800 Subject: [PATCH 429/458] docs(satin): a created account follows the net-change rule --- AGENTS.md | 4 ++-- docs/spec/glossary.md | 2 +- docs/spec/upgrades/satin.md | 8 +++++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d399ac8ef..04bab0a9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -395,12 +395,12 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge on the frame's side (`StartSide`), which gives back on return what the ledger reports the start did not keep. revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. 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, asked at the opcode and counted by the ledger as revm makes the start; a debug build holds the count to the charge for every start revm made and held to the limits, except under an inspector that may rewrite the frame's input between them. + The records are one rule over caller, target and value, asked at the opcode and counted by the ledger as revm makes the start; a debug build holds the count to the charge for every start revm made and held to the limits, except under an inspector that may rewrite the frame's input between them, exactly but for a creation's created account, which the hook charges for every creation — it cannot tell the address a `CREATE2` lands on — and whose record the refund gives back where the creation did not make it. - **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, 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 (`MegaJournal::is_changed`): the journal compares the accounts a counted write touches before and after it — a value transfer's two sides, a creation's creator and created account (the created account a record whatever the address held), a `SELFDESTRUCT`'s beneficiary and the account it clears — and tells the ledger the records the write makes and takes back (`RecordDelta`), the frame-start hook predicts the same from the journal's state to charge the caller (`MegaJournal::start_records`), and 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 (`MegaJournal::is_changed`): the journal compares the accounts a counted write touches before and after it — a value transfer's two sides, 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), a `SELFDESTRUCT`'s beneficiary and the account it clears — and tells the ledger the records the write makes and takes back (`RecordDelta`), the frame-start hook predicts the same from the journal's state to charge the caller (`MegaJournal::start_records`), and 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 frame's level of the journal's ledger: a commit keeps them for the caller, a revert takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its level once the nonce was bumped and before the creation's budget is taken from what the creator has left, so it survives the creation's failure and is held to the creator's budget, not the creation's. diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index cf8aa3c9a..b77de32fa 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -85,7 +85,7 @@ _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) stat ## Write record -_(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, a slot's while its value differs from its original value in the transaction. +_(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. ## History allowance diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 6d1e64a69..5bf65fe38 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -340,8 +340,9 @@ When each charge is made: - 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 — MUST be given back by it then, before what it makes is charged. 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 (the accounts a value transfer changes from what the transaction loaded; a creation's created account 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 `CREATE` or `CREATE2` MUST charge the created account's record whether or not the creation will make it: the opcode does not know the address a `CREATE2` lands on, and the creation makes no record for an address the transaction has changed already. A caller that cannot pay MUST halt with out-of-gas, and the frame MUST NOT start. - 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. + The price of a record the start takes back — an account the transfer returns to what the transaction loaded — and of a created account's record the creation did not make 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 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)). @@ -414,9 +415,10 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw 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 records whether or not the transaction wrote it before, 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. + 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 on the lane of 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. - 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. + 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. From 0b603984f9d6e518ec43493aad59df300be534f6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:07:10 +0800 Subject: [PATCH 430/458] test(fuzz): a target a program can fund before it creates there Target::Created names the address one of the program's own CREATE2 ops lands on, computed from ADDRESS as the op computes it, so a call, an account read or a SELFDESTRUCT can reach an account before and after its creation. A regression pins a program that funds the account it then creates. --- AGENTS.md | 1 + crates/mega-evm/tests/fuzz/gen/program.rs | 72 ++++++++++++++++++--- crates/mega-evm/tests/fuzz/regressions.rs | 76 ++++++++++++++++++++++- 3 files changed, 140 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 04bab0a9a..acfd29db1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -515,6 +515,7 @@ 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. diff --git a/crates/mega-evm/tests/fuzz/gen/program.rs b/crates/mega-evm/tests/fuzz/gen/program.rs index 5a1fa45d5..fc9d7d1dd 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 }), ] } @@ -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/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 3d0614db0..14552062b 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -27,7 +27,7 @@ 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}, Value, Who, @@ -148,3 +148,77 @@ 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 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::Medium, + 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, + }, + "the contract and the account it funded and created, and the transfer log\n{rendered}" + ); + if !runs_at_measurement_prices() { + 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}" + ); + } +} From 2d1d93c298acc6b40c37058e081e807d5d4ff6b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:07:49 +0800 Subject: [PATCH 431/458] refactor(limit): drop the start report's unread refused flag --- crates/mega-evm/src/limit/ledger.rs | 6 +----- crates/mega-evm/src/limit/limit.rs | 4 +--- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index c5ba51ad9..ccc0903af 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -194,8 +194,6 @@ pub(crate) struct StartReport { pub(crate) records: FrameStartRecords, /// Whether the start counted the transfer log revm journaled for it. pub(crate) transfer_log: bool, - /// Whether revm refused the start's value transfer. - pub(crate) refused: bool, /// The verdict on the start, held to the limits while its level was open; `None` when nothing /// was held: a refused transfer, a creation that failed before its level opened, a start revm /// never decided. @@ -640,9 +638,7 @@ impl Ledger { } window.counted = true; if refused { - let report = self.report_mut(); - report.refused = true; - report.verdict = None; + self.report_mut().verdict = None; return; } if !window.facts.transfers_value { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 97995a793..1b22cdc12 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -560,7 +560,6 @@ mod tests { start: Some(StartId::default()), records, transfer_log: false, - refused: false, verdict: Some(LimitCheck::WithinLimit), } } @@ -679,8 +678,7 @@ mod tests { limit.stage_frame_charge(transfer(2), 2, 0, true); limit.push_start(&inner, 1); - let refused = - StartReport { verdict: None, refused: true, ..report(FrameStartRecords::NONE) }; + let refused = StartReport { verdict: None, ..report(FrameStartRecords::NONE) }; limit.attach_start(refused, None); } From 99b953f12934d780c6b6b6618e328b846df8dca5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:08:24 +0800 Subject: [PATCH 432/458] test: two record comments still described per-frame records --- crates/mega-evm/tests/satin/history_exemption.rs | 6 +++--- crates/mega-evm/tests/satin/write_records.rs | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 099c248a1..ce5085543 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; diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index be693adc7..bd96922e5 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1973,10 +1973,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. From f69c7d370e2ae583cc2bbc59cc0a0ac7ea86f181 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:10:15 +0800 Subject: [PATCH 433/458] test(limit): a transaction changes only its sender and authorities before its own frame The transaction's own frame's side gives back no price for a record taken back, on the premise that its value returns no account. The premise held only in a debug assertion; a test over every transaction shape now holds it in the release build too. --- crates/mega-evm/src/limit/limit.rs | 5 +- crates/mega-evm/tests/satin/write_records.rs | 124 ++++++++++++++++++- 2 files changed, 125 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 1b22cdc12..5c65bc994 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -395,8 +395,9 @@ impl AdditionalLimit { fn push_side(&mut self, depth: usize) { let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); let side = if depth == 0 { - // The transaction's own frame takes nothing back: its recipient, when it writes one, - // is an account the transaction had not changed. + // The transaction's own frame takes no record back: before it, the transaction changed + // only its sender, to which no value moves, and the authorities it applied, which + // differ by a nonce no transfer returns. let records = self.pending_top_level_records.take(); StartSide::new(depth, self.top_level_write_record_gas, 0, false, records) } else { diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index bd96922e5..c88e8e524 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -33,12 +33,17 @@ use revm::{ CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STOP, }, - interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, + context::ContextTr, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, Database, Inspector, }; use crate::common::{ - account_state_gas, call, call_with_data, context, create, history, run, value_call_room, + account_state_gas, call, call_with_data, context, create, deposit, history, run, + value_call_room, }; const CALLER: Address = address!("0000000000000000000000000000000000100000"); @@ -1403,6 +1408,121 @@ fn test_an_inspected_runtime_out_of_gas_unwinds_as_a_plain_one() { assert_eq!(inspected.state, plain.state); } +/* ---------- 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 frame's side builds on that, giving back no price +/// 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 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", funded(), call(CALLER, CONTRACT, one, value_call_room()), vec![], 1), + ( + "a value call to the sender", + funded(), + call(CALLER, CALLER, one, value_call_room()), + vec![], + 0, + ), + ( + "a creation", + 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", + funded(), + authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)]), + vec![AUTHORITY_1], + 1, + ), + ( + "a value call past the authority it applies", + 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"); From b1140b33a41726972a2ab14935b3a2b7d78e4dfe Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 01:49:24 +0800 Subject: [PATCH 434/458] refactor(limit): name a start's transfer records, and check the created account's charge exactly FrameStartRecords::on_level held only a call's transfer records once the created account moved out of it; it is now transfer, built with of_transfer. The covers check is pinned by should_panic tests that expect its own message, and the funds-then-creates fuzz regression holds its history figure at any integral byte price. --- crates/mega-evm/src/evm/execution.rs | 2 +- crates/mega-evm/src/evm/journal.rs | 23 ++++---- crates/mega-evm/src/limit/ledger.rs | 23 +++++--- crates/mega-evm/src/limit/limit.rs | 59 +++++++++++--------- crates/mega-evm/tests/fuzz/harness.rs | 16 ++++++ crates/mega-evm/tests/fuzz/regressions.rs | 6 +- crates/mega-evm/tests/satin/write_records.rs | 18 ++++-- 7 files changed, 91 insertions(+), 56 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ba1fd98d1..c5fa12d68 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1455,7 +1455,7 @@ fn charge_records_made_outside_a_frame( TxKind::Call(to) => { let predicted = ctx.journal_ref().transfer_records(tx.caller(), to, tx.value()); debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); - FrameStartRecords { on_level: predicted, ..FrameStartRecords::NONE } + FrameStartRecords::of_transfer(predicted) } }; let Some((top_level, _)) = diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index 2ba50cb05..b54dec109 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -199,7 +199,7 @@ impl MegaJournal { return FrameStartRecords::NONE; } FrameStartRecords { - on_level: RecordDelta::NONE, + transfer: RecordDelta::NONE, created: true, creator: !self.is_changed(creator), } @@ -220,12 +220,11 @@ impl MegaJournal { FrameStartKind::Call | FrameStartKind::CallCode | FrameStartKind::DelegateCall | - FrameStartKind::StaticCall => FrameStartRecords { - on_level: start.target.map_or(RecordDelta::NONE, |target| { + FrameStartKind::StaticCall => { + FrameStartRecords::of_transfer(start.target.map_or(RecordDelta::NONE, |target| { self.transfer_records(start.caller, target, start.value) - }), - ..FrameStartRecords::NONE - }, + })) + } } } } @@ -738,7 +737,7 @@ mod tests { assert_eq!(journal.transfer_records(A, B, U256::from(1)), both); let (_, report) = start_call(&mut journal, 1, A, B, 1); - assert_eq!(report.records.on_level, both, "counted as predicted"); + assert_eq!(report.records.transfer, both, "counted as predicted"); end_frame(&mut journal, None); assert_eq!( journal.transfer_records(B, A, U256::from(1)), @@ -751,7 +750,7 @@ mod tests { "B returns, C changes" ); let (_, report) = start_call(&mut journal, 1, B, A, 1); - assert_eq!(report.records.on_level, RecordDelta { added: 0, taken: 2 }); + assert_eq!(report.records.transfer, RecordDelta { added: 0, taken: 2 }); assert_eq!(journal.ledger().usage(), kept(0, 2), "the records went, the logs stay"); } @@ -774,7 +773,7 @@ mod tests { let tool = journal.checkpoint(); let (_, report) = start_call(&mut journal, 1, A, B, 1); assert_eq!( - (report.records.on_level, report.transfer_log), + (report.records.transfer, report.transfer_log), (RecordDelta { added: 2, taken: 0 }, true), "{case}: B's record, A's, and the log" ); @@ -792,7 +791,7 @@ mod tests { let (_, later) = start_call(&mut journal, 1, A, C, 1); let records = if reverted { 2 } else { 1 }; - assert_eq!(later.records.on_level.added, records, "{case}: A's account"); + assert_eq!(later.records.transfer.added, records, "{case}: A's account"); end_frame(&mut journal, None); let records = if reverted { 2 } else { 3 }; assert_eq!(journal.ledger().usage(), kept(records, if reverted { 1 } else { 2 })); @@ -923,13 +922,13 @@ mod tests { let charged = journal.creation_records(B, U256::from(1)); assert_eq!( charged, - FrameStartRecords { on_level: RecordDelta::NONE, created: true, creator: true }, + FrameStartRecords { transfer: RecordDelta::NONE, created: true, creator: true }, "funded {funded}: charged for the created account and B's nonce" ); let (_, report) = start_creation(&mut journal, 1, B, CREATED, 1); assert_eq!( report.records, - FrameStartRecords { on_level: RecordDelta::NONE, created: !funded, creator: true }, + FrameStartRecords { transfer: RecordDelta::NONE, created: !funded, creator: true }, "funded {funded}: the created account is counted where the creation changed it" ); let (records, logs) = if funded { (3, 2) } else { (2, 1) }; diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index ccc0903af..40603ab3b 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -139,7 +139,7 @@ pub(crate) struct FrameStartRecords { /// The records a call's value transfer makes and takes back on the frame's own level, which /// its failure takes back: the accounts it changes from what the transaction loaded, and those /// it returns to that. - pub(crate) on_level: RecordDelta, + pub(crate) transfer: RecordDelta, /// Whether the start records the account a creation creates, on the frame's own level, which /// its failure takes back. The ledger counts it when the creation changed an account the /// transaction had not changed; a charge made before revm decides the start counts it for @@ -154,12 +154,17 @@ pub(crate) struct FrameStartRecords { impl FrameStartRecords { /// No record at all. pub(crate) const NONE: Self = - Self { on_level: RecordDelta::NONE, created: false, creator: false }; + Self { transfer: RecordDelta::NONE, created: false, creator: false }; + + /// The records of a call's value transfer, which makes and takes back `records`. + pub(crate) const fn of_transfer(records: RecordDelta) -> Self { + Self { transfer: records, ..Self::NONE } + } /// The records the start adds on the frame's own level: the accounts a transfer changes, and /// the created account. pub(crate) const fn added_on_level(self) -> u64 { - self.on_level.added + self.created as u64 + self.transfer.added + self.created as u64 } /// Whether a charge computed from `self` paid for the records `counted`: the same records, @@ -167,7 +172,7 @@ impl FrameStartRecords { /// where the creation changed it. #[cfg(debug_assertions)] fn covers(self, counted: Self) -> bool { - self.on_level == counted.on_level && + self.transfer == counted.transfer && self.creator == counted.creator && (self.created || !counted.created) } @@ -649,7 +654,7 @@ impl Ledger { self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD.times(records.taken)); let verdict = self.check(); let report = self.report_mut(); - report.records = FrameStartRecords { on_level: records, ..FrameStartRecords::NONE }; + report.records = FrameStartRecords::of_transfer(records); report.transfer_log = logged; report.verdict = Some(verdict); } @@ -997,10 +1002,10 @@ impl StartSide { pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { let (level_kept, start_kept) = self.start.map_or((false, false), |start| ledger.fate(start)); - let on_level = self.counted.on_level; let mut refund = if level_kept { let kept = records_history_gas(self.counted.added_on_level()); - let taken = if self.priced { records_history_gas(on_level.taken) } else { 0 }; + let taken = + if self.priced { records_history_gas(self.counted.transfer.taken) } else { 0 }; self.added_charge.saturating_sub(kept).saturating_add(taken) } else { self.added_charge @@ -1268,7 +1273,7 @@ mod tests { assert_eq!(ledger.usage(), LimitUsage { data_size: 40 + 160, write_records: 1 }); // The recipient hands the value back: its own record goes, the sender's is the body's. let report = start_call(&mut ledger, 1, 1, RecordDelta { added: 0, taken: 1 }); - assert_eq!(report.records.on_level, RecordDelta { added: 0, taken: 1 }); + assert_eq!(report.records.transfer, RecordDelta { added: 0, taken: 1 }); assert_eq!(report.verdict, Some(LimitCheck::WithinLimit)); assert_eq!( ledger.usage(), @@ -1384,7 +1389,7 @@ mod tests { ); assert_eq!(report.records.creator, expected, "{case}"); assert_eq!(report.records.created, created_unchanged, "{case}"); - assert_eq!(report.records.on_level, RecordDelta::NONE, "{case}"); + assert_eq!(report.records.transfer, RecordDelta::NONE, "{case}"); let records = u64::from(created_unchanged) + u64::from(expected); assert_eq!(ledger.usage(), WRITE_RECORD.times(records), "{case}"); end_frame(&mut ledger, true); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 5c65bc994..8d6d86a7a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -567,13 +567,13 @@ mod tests { /// `added` records a call's value transfer makes on the frame's level. const fn transfer(added: u64) -> FrameStartRecords { - FrameStartRecords { on_level: RecordDelta { added, taken: 0 }, ..FrameStartRecords::NONE } + FrameStartRecords::of_transfer(RecordDelta { added, taken: 0 }) } /// A creation's records: its created account's on the frame's level (`created`), and its /// creator's own below it (`creator`). const fn creation(created: bool, creator: bool) -> FrameStartRecords { - FrameStartRecords { on_level: RecordDelta::NONE, created, creator } + FrameStartRecords { transfer: RecordDelta::NONE, created, creator } } /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` @@ -683,32 +683,41 @@ mod tests { limit.attach_start(refused, None); } + /// Attaches to a value call's side, charged for `charged`, a start the ledger counted + /// `counted` for: what the check below holds every start to. + fn attach_counted_against_charged(charged: FrameStartRecords, counted: FrameStartRecords) { + let mut limit = AdditionalLimit::default(); + limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_frame_charge(charged, 0, 0, true); + limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + limit.attach_start(report(counted), None); + } + /// Every record but a creation's created account is held to the charge exactly: a transfer - /// that counts fewer records than its caller was charged for trips, as one that counts more - /// does, and so does a creator's nonce record counted where none was charged. + /// that counts one record fewer than its caller was charged for trips, as one that counts more + /// does. #[test] #[cfg(debug_assertions)] - fn test_only_the_created_account_may_count_less_than_it_was_charged() { - let trips = |charged: FrameStartRecords, counted: FrameStartRecords| { - std::panic::catch_unwind(move || { - let mut limit = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_frame_charge(charged, 0, 0, true); - limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(counted), None); - }) - .is_err() - }; - assert!(trips(transfer(2), transfer(1)), "a transfer that counts one record fewer"); - assert!(trips(creation(true, false), creation(true, true)), "a creator record not charged"); - assert!( - trips(creation(false, false), creation(true, false)), - "a created account not charged" - ); - assert!( - !trips(creation(true, false), creation(false, false)), - "a created account not made" - ); + #[should_panic(expected = "changed after its caller was charged for them")] + fn test_a_transfer_counting_fewer_records_than_charged_trips() { + attach_counted_against_charged(transfer(2), transfer(1)); + } + + /// A creator's nonce record the ledger counted where none was charged trips. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "changed after its caller was charged for them")] + fn test_a_creator_record_not_charged_trips() { + attach_counted_against_charged(creation(true, false), creation(true, true)); + } + + /// A created account's record the ledger counted where none was charged trips: the charge may + /// count it where the ledger does not, never the reverse. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "changed after its caller was charged for them")] + fn test_a_created_account_not_charged_trips() { + attach_counted_against_charged(creation(false, false), creation(true, false)); } /// A charge computed from a different answer than the count is what a rewrite that turns one 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/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 14552062b..d381bfeb2 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -32,7 +32,7 @@ use crate::{ world::{AccountShape, Balance, BeneficiaryIs, BlockShape, Limits, Salt, World}, Value, Who, }, - harness::runs_at_measurement_prices, + harness::{history_rounds, runs_at_measurement_prices}, render::render, }; @@ -182,7 +182,7 @@ fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it tx: Tx { shape: Shape::Call { to: Who::Contract, data_len: 0, access_list: vec![] }, value: Value::Zero, - gas: GasTier::Medium, + gas: GasTier::Large, price: Price::Free, nonce_ok: true, }, @@ -213,7 +213,7 @@ fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it }, "the contract and the account it funded and created, and the transfer log\n{rendered}" ); - if !runs_at_measurement_prices() { + if !history_rounds() { assert_eq!( outcome.gas.history, mega_evm::history_gas(body + 2 * WRITE_RECORD_SIZE).expect("the bytes have a price"), diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index c88e8e524..c7e9bde5a 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1464,22 +1464,28 @@ impl Inspector, EthInterpreter> for ChangedBeforeT /// 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 funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + 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", funded(), call(CALLER, CONTRACT, one, value_call_room()), vec![], 1), + ( + "a value call", + sender_funded(), + call(CALLER, CONTRACT, one, value_call_room()), + vec![], + 1, + ), ( "a value call to the sender", - funded(), + sender_funded(), call(CALLER, CALLER, one, value_call_room()), vec![], 0, ), ( "a creation", - funded(), + sender_funded(), create(CALLER, Bytes::from_static(&[STOP]), value_call_room()), vec![], 1, @@ -1487,14 +1493,14 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti ("a deposit that mints and moves value", MemoryDatabase::default(), minted, vec![], 1), ( "a value call to the authority it applies", - funded(), + sender_funded(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)]), vec![AUTHORITY_1], 1, ), ( "a value call past the authority it applies", - funded(), + sender_funded(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)]), vec![AUTHORITY_1], 2, From 54f6c989d9e64847440408c256d314c9308d1529 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 01:49:24 +0800 Subject: [PATCH 435/458] docs(satin): state the created account's charge as behaviour alone --- docs/spec/upgrades/satin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 5bf65fe38..e0fb977b6 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -340,7 +340,7 @@ When each charge is made: - 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 — MUST be given back by it then, before what it makes is charged. 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 (the accounts a value transfer changes from what the transaction loaded; a creation's created account 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 `CREATE` or `CREATE2` MUST charge the created account's record whether or not the creation will make it: the opcode does not know the address a `CREATE2` lands on, and the creation makes no record for an address the transaction has changed already. + A `CREATE` or `CREATE2` MUST charge the created account's record whether or not the creation makes it; it makes none for an address the transaction has changed already. A caller that cannot pay MUST halt with out-of-gas, and the frame MUST NOT start. The price of a record the start takes back — an account the transfer returns to what the transaction loaded — and of a created account's record the creation did not make 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 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. From 2a06b25e0179160fdb118fe9009839397df85072 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:33:23 +0800 Subject: [PATCH 436/458] fix(access): a creation's own account loads are not volatile reads --- AGENTS.md | 1 + crates/mega-evm/src/access/detention.rs | 80 +++++++++-- crates/mega-evm/src/access/mod.rs | 6 + crates/mega-evm/src/evm/host.rs | 5 +- crates/mega-evm/src/evm/instructions.rs | 16 ++- .../mega-evm/tests/system/access_control.rs | 131 +++++++++++++++++- docs/spec/upgrades/satin.md | 4 +- 7 files changed, 220 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index acfd29db1..1835b1cf6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -324,6 +324,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 9bf30e498..b8efa1d23 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -170,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, @@ -213,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; @@ -263,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); } } @@ -293,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. @@ -1236,8 +1258,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"); @@ -1249,10 +1273,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 diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 5d5e53f80..a104f3e6c 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -40,6 +40,12 @@ //! 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 diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 2fa994237..eccb5be91 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -192,7 +192,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, diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 7872e7fe7..2634d68eb 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -17,13 +17,18 @@ //! `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 revm's instruction, 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. //! +//! 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. The revm fork records that gas first, before //! every deduction that fails — an opcode's static gas, which the interpreter's step loop charges @@ -135,9 +140,10 @@ 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 result; } 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/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index e0fb977b6..616de55e0 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -519,7 +519,8 @@ 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 `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 EIP-8037 has the opcode make, 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 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. @@ -581,7 +582,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 | From 2abaee9a878ff6a890cbb9288449c9d4f0f42b6e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:35:28 +0800 Subject: [PATCH 437/458] fix(genesis): read the last copy of a Satin key given twice --- crates/mega-evm/src/block/genesis.rs | 89 ++++++++++++++-------------- docs/spec/upgrades/satin.md | 2 +- 2 files changed, 44 insertions(+), 47 deletions(-) diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index 3fe4ce493..520cc8304 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) } } @@ -527,22 +508,42 @@ 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 @@ -613,9 +614,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/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 616de55e0..48e99739f 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1072,7 +1072,7 @@ 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. The key format is provisional until a network publishes a genesis file carrying it. From 9730cbf10711182d2a4dec3fd69cb940f8e5aa1f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:36:07 +0800 Subject: [PATCH 438/458] docs(satin): state the object form satinTime is also read from --- docs/spec/upgrades/satin.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 48e99739f..9a193b739 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1074,6 +1074,7 @@ A node, a stateless validator and a replay tool must agree on everything below, 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 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. From f17ada434ff1d4ccd1ee4cb40fa361b13dc2543c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:36:26 +0800 Subject: [PATCH 439/458] docs(satin): a witness replay's exports may be a subset of the builder's --- docs/spec/upgrades/satin.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 9a193b739..28921409d 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -980,7 +980,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 From b03ce7a61b92e31c0b61c2b0d4119914cf6a5083 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:36:53 +0800 Subject: [PATCH 440/458] docs(satin): a nonce-refused creation is charged nothing; drop the lane --- docs/spec/upgrades/satin.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 28921409d..14b2f3c9a 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -351,7 +351,7 @@ When each charge is made: 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 is charged as any creation, and the charge MUST come back when its refused start 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: these are the checks EIP-8037 has the creation opcode make before it reads the created address. These MUST NOT pay history gas: @@ -417,7 +417,7 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw 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 on the lane of 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. + 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. 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. @@ -437,7 +437,7 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw - **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 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 and be stopped by no limit; a value the caller cannot fund is charged nothing at its opcode, and the charge for a creation whose creator nonce cannot be bumped comes back (see [History Gas](#7-history-gas)). + 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, lands on the creator, which MUST be held to its limits with it. - **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. From c57bb76f083017e22892c58bdbe544e070fd9357 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:37:22 +0800 Subject: [PATCH 441/458] docs(agents): fee-account writes are records, MSTs pass the packing budget, creation budgets follow the creator record --- AGENTS.md | 6 +++--- crates/mega-evm/src/system/AGENTS.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1835b1cf6..7e4e5627d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,7 +204,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 by the journal's ledger 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: 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 — 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. + 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`). @@ -222,7 +222,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction the block's data-size budget 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. @@ -409,7 +409,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The KV count a node reports is the write-record count; no limit holds it. - **The journal's ledger decides.** `MegaJournal` counts what the transaction's own execution keeps, at the journal's writes: a frame start's records and transfer log inside the start window Satin opens around revm's frame start, a completed write and a deposit's code from the Host's hooks, the body, the hints and the authorities where they are made; revm's checkpoint reverts rewind it, so what the ledger holds is what the journal keeps, whoever reverted what. - Every checkpoint opens a level: a frame level for each frame revm starts — the first checkpoint of a call's start, or a creation's account checkpoint, whose budget and usage are measured from before its creator's nonce record — and a rollback level for any other, a tool's or a precompile's included; a frame level closes only as its frame returns, and a revert that would close one from below trips in debug builds. + Every checkpoint opens a level: a frame level for each frame revm starts — the first checkpoint of a call's start, or a creation's account checkpoint, opened once its creator's nonce record is counted on the creating frame's level, so its budget is taken from what the creator has left after that record and its usage starts after it — and a rollback level for any other, a tool's or a precompile's included; a frame level closes only as its frame returns, and a revert that would close one from below trips in debug builds. The journal's own write methods count nothing, so a tool's or a precompile's writes are not counted. Every verdict is the ledger's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start while its level is open (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return, and the refund of what a caller paid for a start's records, by one formula over what the ledger still holds (`StartSide::refund`): a start's own records when its level was kept, a creator's nonce record unless a revert to before the start took it back. A tool's checkpoint around a frame start that the tool reverts takes the frame's records back with the frame's writes, and the transaction reports what the journal kept. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 5f450ba7b..f217d3970 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -23,7 +23,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 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, its gas and the ledger level a depth-0 call opens, 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 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). From 55bb1da99404e29c5bbe9c46c5f96a35e9f9d1c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 03:41:24 +0800 Subject: [PATCH 442/458] docs(satin): cite revm's creation opcode for the checks a creation makes first --- docs/spec/upgrades/satin.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 14b2f3c9a..5343a2ecd 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -351,7 +351,7 @@ When each charge is made: 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: these are the checks EIP-8037 has the creation opcode make before it reads the created address. +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: @@ -519,7 +519,7 @@ 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, 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 EIP-8037 has the opcode make, 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 `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 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. From e34058cb5bc4bb76dc0e958cd6d84c68d35997c6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 04:57:26 +0800 Subject: [PATCH 443/458] chore: repin revm and op-revm on the byte-pool fork heads Points the twelve revm crates at the local revm fork's byte-pool head (42e4c354) and op-revm at the local op-revm fork's head that settles the first frame through the fork's shared settlement (af071cc2). Both are carry items: local, unpublished commits, repinned to published commits before anything is pushed. The engine is adapted to the changed API and keeps its outcomes: the frame-start hook takes the start mutably, the code-deposit admission is lent the creating frame's tracker, a SELFDESTRUCT's completed write carries the balance it moved, and the frame results Satin builds name the start charge. The pricing table lists the two schedule entries the fork adds. The keyless differential's digests move with the tracker's Debug rendering alone: every case's digest reproduces once the new fields are taken out of the record. --- Cargo.lock | 28 +- Cargo.toml | 26 +- crates/mega-evm/src/evm/context.rs | 6 +- crates/mega-evm/src/evm/execution.rs | 6 + crates/mega-evm/src/evm/frame.rs | 5 + crates/mega-evm/src/evm/host.rs | 2 +- crates/mega-evm/src/evm/journal.rs | 1 + crates/mega-evm/src/evm/precompiles.rs | 3 + crates/mega-evm/src/limit/ledger.rs | 7 +- crates/mega-evm/src/limit/limit.rs | 3 + crates/mega-evm/src/limit/record.rs | 4 +- crates/mega-evm/src/system/oracle.rs | 3 + crates/mega-evm/tests/satin/pricing-table.md | 2 + crates/mega-evm/tests/satin/salt_refund.rs | 3 + .../tests/satin/synthetic_frame_gas.rs | 3 + .../tests/system/keyless/differential.rs | 1 + crates/mega-evm/tests/system/keyless/frame.rs | 3 + .../tests/system/keyless/inspector.rs | 1 + ...erential__keyless_differential_record.snap | 276 +++++++++--------- 19 files changed, 213 insertions(+), 170 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3b4105d0e..eb88ea132 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?tag=v20.0.0-mega.3#58bc98e2fcaffcdea23595b2680fc68daddd7b69" +source = "git+file:///Users/cz/work/op-revm?rev=af071cc255f058bebce27df45a3245332a211dd8#af071cc255f058bebce27df45a3245332a211dd8" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=6147a76d5f5963592359e06dc4aa6c179781e141#6147a76d5f5963592359e06dc4aa6c179781e141" +source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index e8505c0a2..26a085dfe 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 = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-primitives = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-interpreter = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-context = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-context-interface = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-handler = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-database = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-database-interface = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-state = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-bytecode = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-precompile = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } -revm-inspector = { git = "file:///Users/cz/work/mega-revm", rev = "6147a76d5f5963592359e06dc4aa6c179781e141" } +revm = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-primitives = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-interpreter = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-context = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-context-interface = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-handler = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-database = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-database-interface = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-state = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-bytecode = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-precompile = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-inspector = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } [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", tag = "v20.0.0-mega.3" } +op-revm = { git = "file:///Users/cz/work/op-revm", rev = "af071cc255f058bebce27df45a3245332a211dd8" } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 0b2a4ae69..30d0d3b16 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -693,7 +693,11 @@ impl ContextTr for MegaContext) -> Result<(), Bytes> { + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + _gas: &mut revm::context_interface::cfg::gas::GasTracker, + ) -> Result<(), Bytes> { let destroyed = self .journal_ref() .state diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index c5fa12d68..b461d2533 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1497,6 +1497,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: true, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, })) } @@ -1532,6 +1535,9 @@ mod tests { scheme: CallScheme::StaticCall, is_static: true, charged_new_account_state_gas: false, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, })), } } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index f26b53696..3fb3bcc91 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -75,6 +75,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: Default::default(), }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), } @@ -95,6 +96,7 @@ 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: Default::default(), }) } @@ -154,6 +156,9 @@ mod tests { is_static: false, reservoir, charged_new_account_state_gas: charged, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, } } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index eccb5be91..77dce028b 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -378,7 +378,7 @@ impl revm::context_interface::Host /// 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: &FrameStart, gas: &mut GasTracker) -> bool { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { let records = self.journal_ref().start_records(start); if !self.prices_history() { self.additional_limit.stage_frame_charge(records, 0, 0, false); diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs index b54dec109..c617299fb 100644 --- a/crates/mega-evm/src/evm/journal.rs +++ b/crates/mega-evm/src/evm/journal.rs @@ -998,6 +998,7 @@ mod tests { &revm::context_interface::host::CompletedWrite::SelfDestruct { address: from, target: to, + balance: U256::ZERO, result: &SelfDestructResult { had_value: true, ..Default::default() }, }, ) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index c2027fe9a..aeee47ad7 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -306,6 +306,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, } } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 40603ab3b..8f1b27b39 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -1444,7 +1444,12 @@ mod tests { fn test_a_destruction_counts_its_transfer_log_with_its_records() { let moved = SelfDestructResult { had_value: true, ..Default::default() }; let destruction = - |target| CompletedWrite::SelfDestruct { address: CALLEE, target, result: &moved }; + |target| CompletedWrite::SelfDestruct { + address: CALLEE, + target, + balance: alloy_primitives::U256::ZERO, + result: &moved, + }; let mut logging = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); logging.observe_destruction(RecordDelta { added: 2, taken: 0 }); let (check, history) = commit(&mut logging, &destruction(TARGET)); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 8d6d86a7a..1a1197e6d 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -543,6 +543,9 @@ mod tests { is_static: false, reservoir: 0, charged_new_account_state_gas: false, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, } } diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 2ca8c26ac..f88951eec 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -126,7 +126,7 @@ pub(crate) fn write_effect( /// itself, which burns the balance on Satin's base spec. pub(crate) fn write_moves_value(write: &CompletedWrite<'_>) -> bool { match *write { - CompletedWrite::SelfDestruct { address, target, result } => { + CompletedWrite::SelfDestruct { address, target, result, .. } => { result.had_value && target != address } CompletedWrite::Sstore { .. } | CompletedWrite::Log { .. } => false, @@ -165,7 +165,7 @@ mod tests { } fn selfdestruct(result: &SelfDestructResult, target: Address) -> CompletedWrite<'_> { - CompletedWrite::SelfDestruct { address: DESTRUCTED, target, result } + CompletedWrite::SelfDestruct { address: DESTRUCTED, target, balance: U256::ZERO, result } } const RECORD: (LimitUsage, LimitUsage) = (WRITE_RECORD, LimitUsage::ZERO); diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index b63047195..7e9d771a7 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -150,6 +150,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, } } diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index a73acf4fa..c65e36676 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -57,6 +57,8 @@ 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 | +| call_history_allowance | 0 | 0 | 0 | +| bytes_forward_percent | 100 | 100 | 100 | | code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 0d6bad039..19bfbcbec 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -431,6 +431,9 @@ fn charged_call_input(reservoir: u64) -> FrameInput { is_static: false, reservoir, charged_new_account_state_gas: true, + charged_start: Default::default(), + bytes_share: u64::MAX, + history_allowance: 0, })) } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index d2981e802..e1d609ea8 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(), + bytes_share: u64::MAX, + history_allowance: 0, })), } } diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index ebb4e7171..e92158a39 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -956,6 +956,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(), }) } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 780cdbfc2..453672dd5 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -47,6 +47,9 @@ 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(), + bytes_share: u64::MAX, + history_allowance: 0, })), } } diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 554ac26eb..621b0c54b 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -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(), }) } 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 09a811dd2..a6caafe0b 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,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0x32e127d6c4c3d862e527382016152b78430a70faf7ef66fc3b89e8db19fe7fc2", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x5ec2c3380c7c50550621e8e3f4e6184b97627f59e8e0e84ea03f0ead8e756fd9", - "rule: arguments that do not decode @ 50000000 | keccak256=0xfabc9647b618b9b871176f5c368ca06fe88ea60ddfce3d7921dda7513b5b5f70", - "rule: malformed transaction @ 50000000 | keccak256=0x3d7b7cf2cb58e065fd0a393f5964819cfd0bcb223f276326af65b87333fdded2", - "rule: a trailing byte @ 50000000 | keccak256=0x9d8d5b538965ca6ce930be14c371d3fd73c29bbedfccd649bf9a43052588f656", - "rule: not a creation @ 50000000 | keccak256=0x753b01095b0e6b82fe69268face02fc174caec81c4288265db8c10457a0acd4e", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0xbd17be82c15a65317e5b31383d1c191b036d274d42d7078b4986fa8cdc8c734f", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x6513b47dc3fa557c390ade0b18a47021e5ce37e427fba7189fe84f089b650b1b", - "rule: override below the signed gas limit @ 50000000 | keccak256=0xc939cb81da1cbeb80d33d107388f70a052abd126014d6b94da4fd52a7ae0155e", - "rule: invalid signature @ 50000000 | keccak256=0x12f095dd420797ce04e8721d211eb6a7cee720572f81cdc5050fc95077e56e47", - "rule: signer nonce 2 @ 50000000 | keccak256=0xe83367f1d2d95fef8714a65b741ec03ebebcd833d654aef385940d0bc77a5fbc", - "rule: signer with code @ 50000000 | keccak256=0xe76e29fa53120706fc1f14b796fa2178fa403c5defc66ea993db43cf0411d837", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x72cdec61618a4e0459014006d0acfc7928ded0ad2135024f331b90fca368e47b", - "rule: occupied address @ 50000000 | keccak256=0x1cc9153e4cb8f8dd82197405914df3ad6adc78995b6c31e3702425823075195c", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x56876ba1a9dbe188ad837037460c926af84fb67a3ce2b490f7ccc7fb996c29e8", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xbbc37a434deaf690a8998cbdc7645c9b679e79615c43b1201793164a7d4a9e78", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x794a655eaa2553e7894c47c6c02a377ddc5c3d1d1f5ed294a43c8af67b204c30", - "deploys from nonce 1 @ 50000000 | keccak256=0xf6dfd5ad051c64c637309e77da7fb370dee24c6a569b8fef131152767682fed8", - "the address already has a balance @ 50000000 | keccak256=0xe6350edd3c01f3cc5507ef7227d03444d6640add5a7d9ab454ce04ba9c9d677f", - "moves value @ 50000000 | keccak256=0xb7ca4d8f5aac293ab7b4f16bc2821fd0a2ccad360aba7ec815eab6300ec782a0", - "moves value from nonce 1 @ 50000000 | keccak256=0xa508e116c8525b81c4c27cdcd6de310b7261d86beb8e5a61c92c810d5168dfa8", - "the CREATE2 factory @ 50000000 | keccak256=0x9defc54fcea8addd1b41ef5ce2a01b6064a012f2e769f12f051dcbe9e9739c1b", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x20363fe8b2ac7c8a27262c342109378581f998ec6d11b552962e528cc3848fe3", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x7658acefecdb9e68eb1edc8ee3e0a352e729d9d03095e0a8413f0311f371805f", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0x88f6e7d3a3a0e23aca47cc250c88042cc6c9ee2b7f5951fd692a156d0a9daac9", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x8a994094dcc131c0cb43fea37cbcafebb13c49da83c5988206eff35563f2fcff", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x9edeb46f45a2b9ba4bc505e6788a3d316ed5be4ddb3f29fad7ea7c8eb1dab899", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x6ee8ef7bd6a030c1ec50a295a3f2825dc9f5b22166840a645ad29169d3d33cf8", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x090e600aadd82297b31263d204dfc6b8e715890cb6b2085f7c51468eeaf1c34f", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x0646f099491c9d3429c1b22772b70ec343121d4209d18db2d223794b31e92d6e", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0xe4f3abec05741d8c9fa83fac86523bf7f36dde48f26d344e5ac70084647c5a4d", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x0b5a5aa504cd3254a6294f30869b6a8617b8d32430417ca8d5d3302e37161da2", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xecdf635bd46b7552f5f4003d689038426081a6656d4cf6f70fba84f041513c4e", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x81e50cb977f473cebe6189fda1dad77e5451cf084b8e00cb32ba39c1c2acc0eb", - "a constructor out of gas @ 50000000 | keccak256=0x4a2b0a5a139dc4f2deac9cef3c81d0c5dcf1cf16f395723ee1ac2e169027e20c", - "the signer sends it @ 50000000 | keccak256=0xf4b217ee909a34fa24eb33e69e22d991934921666a4b7c09575b408d26a8b649", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x68fc6964cb808234a2d1d33f585fb4c9657f484b0d356ffd331bf6397d41128d", - "a delegated signer @ 50000000 | keccak256=0x7330f3b25240cd042d903a307ceebd468712ab0e0c9bc53956b352a836793277", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xe7d24ab0f4d912f15fb76b088ccecc75ffdf592db8046874805a7cc617effc3c", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xd71d46b795d405e858eef0b6f1d6e6731fe1aa4c8718389b46a8f7c0694303a2", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x37a162d66e66eaef26783bc9561e06aba6dce9824835444dfc73e7034f404684", - "limit: compute, nonce 0 @ 50000000 | keccak256=0xc2631c368e7d21e89e7323514c180d9b25e176ed5f9670dbd34913cd5187eff7", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xebe09eadbe683fa4f548e91770a9464d733d4e0d1a2786c2ad0c9b4bd17e11ab", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0xf4f161f8718555179819b157019d486c1fd6bb5d8817bf63a1bd8494af920311", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x16ef5657b25cfc98fde279c24028149997b65d743364890fdcc5f2a6ededeac6", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfc3ec81976944e9a9a74e281b679e51cb8fa90dd35d22e93d9a7b87051e6be8c", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x2ec14b4f0383ea6b0f12d50f0cd563bc00fa9092e50d22a156ca442852284686", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x28490ec07658b55c1c9fbb116430ee583fef5707812b694ccfb4e546a439b40f", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x04f9a5724edf49c4fec791ab8d222898a565f85efc67f836840ae03ca2138c4a", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xe3e92aa87207f7c32e09845c17a80c911567cfd6938857c8f39e41ec2ceee873", + "rule: value @ 50000000 | keccak256=0xe08d5c11a853f62aefee437420662141db0120bff9ee9601a6d026c415cd42e2", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x5a09b872b7ab1aab123bb581c7cfecbdf94c1f1f4cf526639cb90a4cf5daa8de", + "rule: arguments that do not decode @ 50000000 | keccak256=0xe55555c4007cc686993e358e88184c37d5f28f02965d42e9b7e66ca234d3037a", + "rule: malformed transaction @ 50000000 | keccak256=0xd59eabe5e54fe110b8f34647f3a390e4203e51507912c140ee0a634a4e8387b9", + "rule: a trailing byte @ 50000000 | keccak256=0x545f1457d582396f8dbec1951571441b7500da516a75eb24c1a3886be7df462e", + "rule: not a creation @ 50000000 | keccak256=0x59cda389471b078166acdd49ce5db7258ba0f5dc907d8847a6ec78dd86c1a17e", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x5b16bc64c0c7b5a4f3db5c9696b57c8eae3701d666fae027e13b862b7d624823", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x6c58278252a79bf9ce141d3f59e95883fbbd6cf7c343a0f1f264e8246758dbd2", + "rule: override below the signed gas limit @ 50000000 | keccak256=0x94569cda3f9f71497d65931231777617fdde4535c0a38b7b4e3b8e572ee6dc2d", + "rule: invalid signature @ 50000000 | keccak256=0x4197c988be7ca81330837c660e4158a8a47a5b28ab0f8daa555b0a84f3e3a001", + "rule: signer nonce 2 @ 50000000 | keccak256=0x3c64f81ab2f664531eae546ba8c47348bd4b29f7119bfc56f9e2e265e140d1e5", + "rule: signer with code @ 50000000 | keccak256=0xa9897df9dabe2e14050ab58f0ab01f8f75ed07f4c9842981069df2e9e4ba5893", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x5a8a62e6bf3fb7ff4884d4dd8595426edd777e5e6cc031f739de952803271664", + "rule: occupied address @ 50000000 | keccak256=0xc50907e21260a44080e98a06259905ea58bc269e05d558f2d4d7423b528dab33", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x43c70677007cdd61f038f6734661049f5aed0fdb8485aa693d409af0b823efc1", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xc9e036ca50f734b404cb0d4a1388cf48ec21eb6d453d3650d63e0fa8eaa34bc2", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x0703536a74dac6febfcc32270e1a2f138f7ee2e8432507ab47f321598321131b", + "deploys from nonce 1 @ 50000000 | keccak256=0x62d2aa4c30fe5c05982e9c53e76feea7f952a6af4a709d7342590ada761e495a", + "the address already has a balance @ 50000000 | keccak256=0x62eb6d77f77cd390fa87640e949a495534af010cbaaebb184f8170098faab4e6", + "moves value @ 50000000 | keccak256=0x54de6a78767cfaae5f14de460ecb253e7c01f63bb337f79bc0807a206c72205f", + "moves value from nonce 1 @ 50000000 | keccak256=0x814e9db0b5a0642f7fd0faa63080a523fe91c6ec3dc063f78270704abe9f36e7", + "the CREATE2 factory @ 50000000 | keccak256=0xded0acc143a5a6957c0b60c995cf7456d7821525188bfa4eae207ac51459b889", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0xf0d2fbd0aaa504b147a454687aafefda093f14d67de462991ea595f65dd7cf02", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x3e0b4d0c46a1e10a2a4be8d287e562b315a4d1e88e05ad316fd9bbb1c98ce83c", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xb796edefbeca92977b8296a98e163f6ce2874317551fdfa34f68ece24d3a7a02", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x4a79199b4e4fa90173d320b0f82d3b183122b553826bfadbdc51ec2395609bed", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x76372e8f335e5b5328dbc797b9aa4631cc103b89b259c0e08b85e1698b1aade6", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x20d9d2bbec507184a0c73c414efad6fb9458bb3b93fd3f5d36b64176deb522f4", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x4a12867c38ff561d75fafed049d01ba7b7c2813837e5f781172869c73b6eb741", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x6096bf7f46499fa61be93b942ce794d9366f6b1d9de2a9bd882d129eea7acf36", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x9b1d2c1e151cab97c182f42826e2d7c030c95d1ae8a490104b8ca8a54718b8cd", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xb26f2f17a77f78503786120faf04a6b69114ca9c93f5e1cf67d275240b3b264e", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x84350725b7f63d922e20c939a219d39da049aeb7b1ee5574e3355c0b24b6cd28", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xc04de069fdaedaa94578d0b26e481c221105de0a3e9622fa9eeb18861d75fcaf", + "a constructor out of gas @ 50000000 | keccak256=0x440410ab7678c31790932270569e1ffab0a3f3826bcbc2c6f0dd4654d2107577", + "the signer sends it @ 50000000 | keccak256=0x66a013fa1a11178c230919dc83ffba40bdb631c93bf7b7810e92371df0bf8b77", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x8af244198d5605346b66591f3700b4a442dd78beab01a6afb8dd87665f244b4a", + "a delegated signer @ 50000000 | keccak256=0x8c6adc50e3b0f55f7fde39b7a29d5ad7bbe6ceb9d9358d0b6f3f42a3a9754913", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xd3734a0b376023fca014ecd2178ef794ac6c980f4c2587d20212afa417874e38", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x09f3f4532e7bedf74967ca6ae4d8a6821e20b4c2af048791a427e3d4f5c38105", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x4e57917739c132e7f94e97e42214aa3c511177d21a708f2fb43df099ee23d95a", + "limit: compute, nonce 0 @ 50000000 | keccak256=0xbc5ea5d36da421edc9ac0fb0c1b185c334b6932d52bd2ffe2701223f6e163a0c", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xc5e1e974147e483eb2e59adf9420d4e9bd7fb8e774603558238f15f9efe12129", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0xf0d20c801bfa5db12176f11876c36af0d2ce1066d89bb15e942e7f00a097df28", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x9db440a3067a52613177e664b6b98e2a18fa3b481bb8ab9b6fd95142d8e27bb3", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x81e4e32e9c1a42fddfec6e807f5e97407c3337efb054392c803759d15066cd25", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x255fd223c957aeb8b87bea1a1a8c17e961d6fbc464dac2e095637dd3c99f838d", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x11b1022a2374bdc03dd0df9a6c167d06d4acf539ba17da2f6f6f930c93498f66", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x94382f06999ab6c9322823fe31929d1e40ca0762739b006cc73a4a6f8d02ce0d", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x5058ce0b29dc18f336e7c5c93f634d295d49147c420aaa142e40adc2ac9dad0b", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0xd8fc1b80ef6e59850a033311e764a0c0b324711ab87b7e9f228d81fef2b6e862", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x9d754342c40b514543e0f20d22761b08fb573db9e47e5ab0c37002f08247ffae", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x4b09c30811e005f448c0b99dacb90ed0c821bb69819563758e3835e5950efd80", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xc290bda4152920c918e83ea5e3f59ea87b95b4c38276173fe493e8f3c5e7a55b", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x5bf4131809cf73d80be4dc42e7444e40d52a2216e54fbc9ce64a93dd2cbb2750", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x213fa7e0cf47df7801303f285ad4f1d2671c77850a1acfbb418c0a73581001f8", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xfb0daf3fff5b193acf10c5c4c6e07f56103f8e34bba116c02e0b19816e97d0d7", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x67b1800a5d3d0a89ece8785d2ecbd1440c2f4c2233cbedd130130528a24995e1", - "not dispatched: version() @ 50000000 | keccak256=0x012db0dd4056435f91b578f704d89b2403e5ee8aa546bf5938ee2c8b29302db8", - "not dispatched: no selector @ 50000000 | keccak256=0xa2dd7ce0ac78254d620a50f31df1359066dc31453b857f3f141e02f85dcd495e", - "not dispatched: from a contract @ 50000000 | keccak256=0x9a6219ff6a37c8d7f15944cfa621aecc9ee887836e7c6095d79fe7fa27377ebb", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x7c9e8aba2966417968663ad8a0cf8fe425d1cf768ff2c7d01eb1533c5a302b42", - "no contract code @ 50000000 | keccak256=0xa781ab3fb45d2eb3ce305104a970b9f37e9696b53b9116ceadcf8d2a5dbccc44", - "a system call @ 50000000 | keccak256=0x0c6827dd67a583c406d822bb6be663e1f2181d7169031b788689b69f4df1368d", - "rule: value @ 400000000 | keccak256=0xbf8b1ec960298877fdb19bd98d81c5d12e468e5f0f1ea4b6f6211f056182cf86", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0xa5b782b90fe088899e5f64da600964352b0c15127d5bbcd4b6f0615cd57a7872", - "rule: arguments that do not decode @ 400000000 | keccak256=0x4f62b297a17843c8efb18ca1db2085bc21d5214f1533207bd4b1822cc17383dd", - "rule: malformed transaction @ 400000000 | keccak256=0xbe95f76f8f3110c158bb566e06703c619ce372604ed92edf26566831a7af207a", - "rule: a trailing byte @ 400000000 | keccak256=0xb34fab993aa8b36d8a797878da1efffcd1bbc250e2a61a3d06efa9a4bf11dd3d", - "rule: not a creation @ 400000000 | keccak256=0x7513600f734e60c577538bc669aed90e20c921cf6647399a9cd2cd0da7dfc902", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x48cedb3705954bed9029105fe9f1533547d5fc2906f0622291b9f0fed393b2a2", - "rule: signed at nonce 1 @ 400000000 | keccak256=0xbfa3e0ca7a0b001efdb1984f96db0dc71e000721ef128f3ab1b934906a225885", - "rule: override below the signed gas limit @ 400000000 | keccak256=0xd88431eade0790516f127cc0a1a0708f0e47957eab688073ed4e7ff31f2e9e19", - "rule: invalid signature @ 400000000 | keccak256=0x9f9efe417c783be1664401bef0de138ceffc6153507b0196d2fdc5beb3e06dcc", - "rule: signer nonce 2 @ 400000000 | keccak256=0x52850f08a7f8b5ccbac2abcc15927231eef0c7a5ea1885b6d69a083e2f66f7c4", - "rule: signer with code @ 400000000 | keccak256=0xb43427299f42b4ee56254bdb857544d23ba4da7cf93f1bbd7e7a0659c91d77a3", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xacdcac30a6ec827840cd9af82403d36f904fa6a13c82f1d12eb3c0f0fa5b0e19", - "rule: occupied address @ 400000000 | keccak256=0xbc0dc0d08f77077e23fdf5928ab179afdc08c204dc12f87d4f9fc8f11de63d8f", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x0b3e4a7a6caa16e6dad6eb8bd6073ab811264470bf2ac4d3dbf16247e51e6756", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x9eef5c415b054097f2b05ea81a705f3cc8e2bf63e0c709996c73f8f18fc4448f", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x9d61f6180375c5390d6a20cc1e18e394b83248708835e87f3369bc1dd1413454", - "deploys from nonce 1 @ 400000000 | keccak256=0xd05aad7c48c761c24f143ff3c6ad8e018dadb04aa974c848a3f4f4e74e7b73b9", - "the address already has a balance @ 400000000 | keccak256=0xa46e4d68f4852cdbaa6855f65385a4d74e80cf13294da3a07c9aa5db565f5727", - "moves value @ 400000000 | keccak256=0x14184a1d8be28567f143bfd50f0cffc340514459531a659cbe61da1aa9d374aa", - "moves value from nonce 1 @ 400000000 | keccak256=0xc1f491c7c65cfdac3e955bda5d0e109ae973724214ce10dcbd86d8ab987c42bd", - "the CREATE2 factory @ 400000000 | keccak256=0x593d3f328f4e1c8a5405be9652ce2681c99d7f69bfe578d63f6739fb862ba7a9", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xeaf9df1c39ec19aa926968308c6d4bcf1078c00e15ff55c6ad053b2472bc425a", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x7fccd4eb3f4d9e7d089443c00fd60aef0b5a3156067ea0d9fda1fc6be09dc00b", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0xab285f069bad22c980214cc6f0c48e0905397a307b623adbe0e27d30876d48aa", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xb563c73f2becdd16d894f7b7c365ed2456dd81e49bc53401ae17cbfe8adb7ac9", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x54819c71d7208cd779a459870e9ca6fbb3b4ac15141af5b1a443848479d62b3b", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x98e21e5b40eb07ef81ad46a2bda808a2fbf79a4f2bcf736b2fd9f864ba85510a", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x9f4a7808e3bf06652a83f5b6df4e762a85e6bc4564ef7192f6535fcebfca3aaf", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xf0b3c5d9d151c0add55bd1454d71d0b3d181014e0f6e69167e75b1b177ed7ade", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x3da6beb7b1b7d27328bda18af075c6d6f23dfbe5bc0dcd17078c00c8fd8502ad", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x487530c68a0a31093a7161d5e51b7c044abc39bfaa39619da4080bfb1ae8c10e", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x6d1221ed777d1119fd2cc83e6de1c3e03e8f813d97d6cb3b88cceeb09eddcc58", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x7d102dc0c3d0bea4c3384044a69ddd139229040a72968a7bbef7ea70c86af005", - "a constructor out of gas @ 400000000 | keccak256=0x60db547a068a7d4b1c666aeb6fa67279eb75f6e684083861aa18ee2f5896f77b", - "the signer sends it @ 400000000 | keccak256=0x23d3e43c0591e50bead0e091db67aef632a77f7b789a26ab426cfc7a69814e21", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xa530a2b24e4f4c977e1a73999e343d6230c3372f7467d49901451ab310e9df54", - "a delegated signer @ 400000000 | keccak256=0xe0d591f3e38dda862488a1009602e3f3b24a7ba333a9fbda56fc2f8c0caaa7a7", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x8ef3d795d097ab68240ed2275bc691470ad3c4a72869cb570ad0efc0add5437d", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xad96560f17165fc62cb06d04e4a2ffc2bacb69852fe08b0b1aef0d9dec664690", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x3fda5141c92c11c841821a4754de70393a313b6384e6e0bf8d2606dbe6d03f02", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x02f6f21cfc59e30ec997eaf750e39eba6a2b2cce4844e781dbcf118e2be5a1f1", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x26449cdf1808167f44cbcd787486f5741d7f0e6fde01d26a17f5501c875c4596", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xf141cd7567627de8bf2653832e229ede610b5aabc446163038bfe3549db881f7", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x97e3915f1b9d2e3fe4c473a182b1dd5262fd8143ad765da63a3d20aa6ed5beb6", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x9482d4309b67ed34e4a9cd81480f3ac412dc428b4f8be119c8ce6da847650bf0", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x51b12b6471b58aae1bf288e49fc96363dabad62935fed9e53d5e988f1714f280", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x685e111500442c8884fa6afcc8c5604ebc6b9071e64e62dd98b650664fccb836", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x6bc2427776359900918af73774b1e78be9360ee15982b8eb30d99ff8700ada8b", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xed059de9072084c0cb48a30e520a4cbe621eb6e181f487dda43010e8a4b8e3a8", + "limit: the default limits @ 50000000 | keccak256=0xc5286cfe7e8c22d56ec53bac2e7a224ddf6cc04b52505501f4afeb471840058d", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x2563610ffa9318aeb60b0bcfb4167a9eb31f2f97687f532a8f5435724fcc6ccb", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x47a7201490cc0e99c0417b0bfc5dc39af036d0021015cb12db841856e91f9b7d", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xc581a2020b34fd7f9298dd9ee1ac75b3ecdc209cb592edbcce65896b3d44b535", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x1cbf38af1fe47c1234e498c99a0975bae7a2f84c974c23a47b22c3914d9a9543", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x80448bff277a3f72d6c897f51f25a6662be849beca9d980eac688320d86066c9", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x7fb6ab15e5fbf341d3e1d3870ea6f73bd8ca74dff6b8beb2e96972b6397c4749", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x82bca691c26aacdb312a44ad21c64a87e47df77b6864e82eb79efc58f2e3f666", + "not dispatched: version() @ 50000000 | keccak256=0xee0f650f6791fd685e2656105b93585e08fa330bf01c485023a062ced2909097", + "not dispatched: no selector @ 50000000 | keccak256=0xd45e2aee2869b779c403f3a8e768930dde3ce0dee4feeceec29be249552d9f65", + "not dispatched: from a contract @ 50000000 | keccak256=0x8ebbeab71b3f519f0bd2eb5e67039938a1d2c55fc036734458dde12583d588fd", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x76a0a7bccf4ab00d2b30e0b4818c483a753258e512225968df5cfb249004556b", + "no contract code @ 50000000 | keccak256=0x13bcd1d73b2de8eb1c24f9d33ac665f3d3138305ffc0e0e000940f985faa1a18", + "a system call @ 50000000 | keccak256=0xcae00cf2ae1c9cd8393a3e667027360c3f167eb3bcebd38ad2bfb8b31e95f42b", + "rule: value @ 400000000 | keccak256=0x3922a3db1f22936f578de6cd2ebc59a21b5ab0e2b8923aaec1f9ac75fe8754b4", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xa3077b87c5ad3052d2d72353331e48cad3284a9be2373dcf8c8cf91b0eca5d11", + "rule: arguments that do not decode @ 400000000 | keccak256=0xa330a12e2749576ef722835b5b54e8646be72ac70964a11b76e09ad0e9db90ff", + "rule: malformed transaction @ 400000000 | keccak256=0xa3732d3961a6377f75d95d38655bc6b58699508606d0c1686a9218644d2735a6", + "rule: a trailing byte @ 400000000 | keccak256=0xc8f95911acf41c1227454e2fadb194acd9a20d01bd438ac8b29b6ccd7eed0ee9", + "rule: not a creation @ 400000000 | keccak256=0x095b950bbe9b7fc0e95b96574a7b3054482aed5fb1b94650b3afb175602b7322", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x7168997ea70d91d5e37cc37bbdf40f6e8c1cf3209566f124973b2a363de8f092", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x1352c3f935e83b0ce02cd15dd5b8e9cd424e4e64a8eef8b77d912d31f620adca", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x177bf8926421a6f32cd5f72e85b7ffca3d00a11442e107972bf1884c639638ee", + "rule: invalid signature @ 400000000 | keccak256=0xb5bfdea3c5ad4938b8ec085d865e51179c703f81fa262b9aa19e5a2e4c29682f", + "rule: signer nonce 2 @ 400000000 | keccak256=0x2d91bf7945bfbc243dd77091a7b09743ee51cdbdd962b1e08ef4eaa9242a851d", + "rule: signer with code @ 400000000 | keccak256=0x30f0f71f00bf8ce819eae6e0f644f55ac08949539ec99f028c6bb542774a53d7", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x8e5e36a718119e8a723eae0b7d3f14422f89f8ec09b050afb9df5cea59f9d003", + "rule: occupied address @ 400000000 | keccak256=0xce45a21f6b66c08ba2cc5f62cbef177ee6dea63d1e841fb55f6872586067262c", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x5b176818d9aa4779855cf954713aca6586ee2f26fb4d2e1cda3512307a1e9667", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x592a24a10016a29d65a4391abcd35faaa32a64b53020f7189491e599b6d8fe78", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x37d63f7eb51fa907792cd430ccb3b0d1c69f3d997cc4cec372ccdaf2bfee7e06", + "deploys from nonce 1 @ 400000000 | keccak256=0x82f552474faed9cdebdd488dded67cd05718b54905927ec1f1f627ef389c0b50", + "the address already has a balance @ 400000000 | keccak256=0xab9cf03c7577dbb3d30730e1a7e76111341bd42cc5e3a988bf1d52745bb59df3", + "moves value @ 400000000 | keccak256=0xb3300b4347ee267ffdb245868ba449dec71a1cb738cd2c61aa6a84abf3616ecc", + "moves value from nonce 1 @ 400000000 | keccak256=0x52207a4239fc5c6a70ed8fec7e91048690effd8cd7a3687f194732d6b8c212a1", + "the CREATE2 factory @ 400000000 | keccak256=0x4e116527b62fa8581963beba273363b009997bd6529bcfd179225d8fc1e3dd3a", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x3ea5923db49243150f653046125e736ccb77a5c0c0cc6d8ffcd59df9cc06a989", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x9336a80d7f7be85071d4a70ba9e78ef784954d9f8d4e8e7c0a7bbae7e4545714", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x393cdc3bacb5df6fe898c2612da26aad1c58e227f2dd242aaba388d8fd705c30", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x761f3e0d0cb206f0776585655b586221f766853b17c82a63ce6fce1be38bf30e", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xef3fa9fec87d8419bffe7f3f77277da863510f3954b5a9872e576e5a6bba19d9", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x511a7761645fd502d73b3826a14ca5d586d9d45178ad5db18594c0fcbfc4bdd3", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x88358f956972468609528a953ba9d257f89dba294db62cdd5c03d72aa7c3f834", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x695d8cc6e4bde17769ecd5fbccf6c89715f7e2277e7937e6e72f36196fffd70e", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x94abe8ac217cf241c5969b756ce09d40dca6351cfb9b295574198982d2e5024b", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x878ac261c93e426fa61bb58dffea90a4fa1d1f2261c78aa91427892595d257f4", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xeda90d770f3960abddbc68a9ae08adb9acbbe99d46513925df2634deb33d9ad3", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x5ea889aec6ae2e1b3d58760e2beaa7dcceb4d2d676f60586f4eaf24b9437b7d3", + "a constructor out of gas @ 400000000 | keccak256=0x89c0a44575c806e25d3a8665688d0a2742c5fc931dbeb9d518142e1221285184", + "the signer sends it @ 400000000 | keccak256=0xfc6ea003bcc21839162401a2e0f936c9472f4f0104f3b8ca90ad148e9519ae5b", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xbc7675bf2249c1ce5a52824c9a650f9db1c89bbf0b1644b907697ed9af011cc4", + "a delegated signer @ 400000000 | keccak256=0x33f6c088999ad24a3f97ad47f045741ca00a0201902a3925a430f05978510598", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x73a31ef42c867d557067e96a0e79949a02148294dabeaea50f8e75b458e09dab", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xe24aaf180b4bf444ba01ad9ddf44aec3a0c1a7f52b232af0f5794889bb904fb8", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x2450bf7f26d13f760104617f5134aec8300c96c9f0273368e080cecbbd02cda8", + "limit: compute, nonce 0 @ 400000000 | keccak256=0xd1e24d24cdb678538bc4ac96e2a5c87c48bc464befaaac19dc2208a749f5a600", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xc542291ecf77a6dc64b81659fbde70bb5e71967bf58cda3733020c5dd8818a9c", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x23fc5aa73fd684adc54350aa944c46a3447ec8cb7475449bde2c3ae1cdb65d4b", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x60c838aff27f4229b174514185754485226a2b403157d157007625b8bf3c7cd7", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x3cda6a985d48c8f91bcd9bb751ae6277d2e9c238f72c5538ad576e89283886fd", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x8144d6fd3d845e283f615f92bf0002872f0c7beb4ac373a5f1d0761cb238b987", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xb652c75f2545a42aeaf34311bf62392a0856b616e1b7b3191d8988e7ca775207", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x3532c73382be0923c7e028c397c11501f4f4c318bdfdc8d2a258100edb158e38", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x63d02c91729ac49f2c8c832cc16aba96cf73288991f612a65c78e3cdedd5f904", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xb30a667ac091db1a3cd9ec446b4a07a89c5708d5ef2828142a56116ec8a9b532", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xf1e5506faa79785026d6a61d955ddf0fec8b18266c9b30291b2223e024a8a88a", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x0ba0cd288c2eea3f4dae0aaa76f88e09f30aa3675a76c85b775f7db167cf9305", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xf967b7846d165534ebbba8b4f557549c3428a802ea2d3f6645ba8a11b82df13d", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xd0ba998a740373b278c9758023bf74f6a8c14b8d78e83c3a29b9f237954c6ff8", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0xbc23f753100b78da4dffbb4179682ffde30965fd467c0fa5fff882e8ce492084", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0xacacfe1a26f8f2f960a9a874f882f86efa99ccd93d81052ebe9c3882be7dcdc3", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x93e270afa02f2c36c7ca2c590c8c0b375f276ef56fba8a46749926c956ec96d5", - "not dispatched: version() @ 400000000 | keccak256=0x076ebe076e73f9c816e4a087c552db1c0958aade9e9c8bde0e4f3259ff4d4528", - "not dispatched: no selector @ 400000000 | keccak256=0x9af766c263638d7bda8a38853ace3da20e67197f235f9d046540b219feff51a6", - "not dispatched: from a contract @ 400000000 | keccak256=0xa92e8257fe6dd27b5654ae3784dbea6b76f2a299b5f595c0d858c6a6dcc83de6", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x7c6d8d153d7e970248fd2cfcb8ecbff2fd52176274902baaa905fd52150a83e3", - "no contract code @ 400000000 | keccak256=0x591cbcfdfc6f20a914d9eb7a784d14abdc3fdcbb00598d638b54022fc0500379", - "a system call @ 400000000 | keccak256=0xe64d8b07830e675c4c49f01bbbad5c5d39f6d53fafe9410746d57b83d3caba0d", - "out of gas: the overhead @ 161535 | keccak256=0xc72abadf5209f0081056bed175cc07e3e83a3af77cd91e35c31b2d18eb63502d", - "out of gas: the signer's account @ 162536 | keccak256=0x740a42ebfde771dc0c2e9ed8722599b1bd40e509bf43e7d4e33e45d41e2ffcce", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x1075d3e85809cee95fc0c6aed52a5b240cd70b3981b024a0aa838d9d781a5552", - "out of gas: the creation's charges @ 163024 | keccak256=0xad8555a91355f30b8e442d1701cf3b26b5485feccc9423dfbe73424d1f443715", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x3254c59dbccad8c83e235ff4ff302475c879f1c821be6b5a6ccd5841f952a538", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0x396c7588a13a4c29413037de16e518f10a44b17f8abed0de97303b0c39ff51fc", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x6a1dd7d98b6bf1e7765a8650149bf565dfb0a4a10eea6a2c5120207073419150", - "rule: init code over the limit @ 150000000 | keccak256=0x960eb6e8c4e829af439106007ece5846551074beb2cc3eaac307207d9b40c860", - "rule: init code over the limit @ 2000000000 | keccak256=0x58da5d395d2b47867b957a47072721843bc4fd359f62379c21e38c78965b156c" + "limit: the default limits @ 400000000 | keccak256=0xad4d30ecd3b69b22dd96252e09422f1309de5bfc0142e5198263b89dd2010bf6", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xc4efceebc452bcc77d992cd35b469d302c6336dd14fb2d0b0d7563e4cb9651b6", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xeb826226526c5a5d0e7192f0c042ec198eec7abdc2d19847286d0c2d1bc86ebb", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xc86bc78d010b4a3113976d032eaa8e5132729d70604de4a7cd6aa67447d1e833", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x9581a714c92e5c24aabfbb338bc0b7baa75200abb2c007ffd2745f637c18921e", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x1c1045da7cee360e40ef8b4a923643ef7f0b1ec8bc27539dc33cf60f4d9bc24b", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x2c2d646a715467dc2107fc12b266ca11913a660a110fd42c20c479068f0a83ce", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x59eb1669dda2569995a03c7c2bac26b9dd813d4929c1ccbcdd082c46487926c6", + "not dispatched: version() @ 400000000 | keccak256=0x292bf5788212aa87589c77a2aebf85737bc0ca6b7a95fb35c183910b131b9e2c", + "not dispatched: no selector @ 400000000 | keccak256=0x2a7aeebb83f26482228ee292fd2a971111d29c40040a8ba91e7c26d7c0255c2d", + "not dispatched: from a contract @ 400000000 | keccak256=0x4c447dae19a0d2dd39c801512e0495bba1bb0a264b29c18b1db6d1a52c1e0d9d", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x29bb1e1e870aa7469ea9208c21195473d0309f6eb51a1ea92bd3220f689da71a", + "no contract code @ 400000000 | keccak256=0xa1978cb2b4ae05a9e535c5e3614bd750eaac8ae287112baeebaf78482b316d88", + "a system call @ 400000000 | keccak256=0x9ad23f4f93be819501a8c389210ab517e3d4e6aa36e53d3897f180ec36ac1a1c", + "out of gas: the overhead @ 161535 | keccak256=0xd2b1c6a6a0406e2a5b0bb8a8fff227d1c45489bfa0be343f58ccd01a1a6fa1bb", + "out of gas: the signer's account @ 162536 | keccak256=0x9df1144da6da6dd79ace581960f0bb1f7b009d5ec1d677cba0b7b929294b5859", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x9892528465592e994dfa9e09e128263f445fd19fc47ac4dce9d060c94b535608", + "out of gas: the creation's charges @ 163024 | keccak256=0xa2cf8f8d33b1da3b05c2768ae383b86802934010321d2739ad636fef561a7c31", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x8e7256f46483ac8118dc4133ede63e0140afc4e25b23024d62cbcbbe5de69f90", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x24215a3fcd98c750d7f336e624498326787f8aa5e7f8604de9342326414cdc95", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0xe9b65891ac1ead307efeff7a9c8d5f48e8164a7db38691e4df3678c90fb5274b", + "rule: init code over the limit @ 150000000 | keccak256=0x6838a282dd806d25ccfc1a88020c5accfb1863d7215d4dafd5b1074f98d699ae", + "rule: init code over the limit @ 2000000000 | keccak256=0x7e5ec4fc070585a4076f4dba1bb383c00e19a05c1eb52eaceeef42a5cfd891b5" ], "summary": { - "bytes": 2407306, + "bytes": 2525694, "cases": 139, "lines": 11452, "runs": 556 From 03e0339c4ba0f012121d77bf1b8196363153e136 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 05:33:06 +0800 Subject: [PATCH 444/458] refactor(limit): data size on the byte pool, start charges on revm's carriers A frame's data-size budget is now the byte pool on its gas tracker, which the revm fork forwards and settles as it does the reservoir; the journal-centred ledger and the journal wrapper are gone, and the context runs on revm's own journal. - The transaction's own frame gets what the transaction has left once its body and the authorities' records are counted, under the frame cap; every child the schedule's share of its caller's pool (bytes_forward_percent 98), capped where its caller suspends. - A completed write's record or log is drawn in the write hook, a start's records and transfer log on the started frame once revm decided it, deployed code at the code-deposit admission. A failed draw is the frame's revert-class stop; the transaction's limit is held first, on what the transaction keeps. - The creator's nonce record is drawn on the creator before the share is forwarded, unchecked, and the creator is held to its limits when the creation returns; a creation revm refuses before the bump gives it back. - Write records are computed exactly from current and original info at every start, a creation's created account at its address included; a SELFDESTRUCT's records are rebuilt from the after-write state and the balance it moved. A debug build holds a start's records to what revm's start made of the accounts. - A start's history is declared on FrameStart::charge and refunded by the fork on failure; the first frame's on its input. A kept start's take-back credit is refilled on its result before the merge. - StartSide, the frame-side stack, the top-level refund and the precompile provider copy are deleted; the provider delegates to alloy-evm's. One entry per start revm decided keeps the running counts its failure restores, for the write records and transfer logs the pool cannot carry. - The history allowance is the fork's tracker field, given by the schedule's call_history_allowance; only a log draws it. --- crates/mega-evm/src/evm/context.rs | 87 +- crates/mega-evm/src/evm/execution.rs | 729 ++++---- crates/mega-evm/src/evm/frame.rs | 58 +- crates/mega-evm/src/evm/host.rs | 89 +- crates/mega-evm/src/evm/inspector.rs | 109 +- crates/mega-evm/src/evm/journal.rs | 1026 ----------- crates/mega-evm/src/evm/mod.rs | 4 +- crates/mega-evm/src/evm/precompiles.rs | 119 +- crates/mega-evm/src/evm/schedule.rs | 86 +- crates/mega-evm/src/lib.rs | 4 +- crates/mega-evm/src/limit/ledger.rs | 1529 ----------------- crates/mega-evm/src/limit/limit.rs | 1254 ++++++-------- crates/mega-evm/src/limit/mod.rs | 93 +- crates/mega-evm/src/limit/record.rs | 523 ++++-- .../mega-evm/src/system/keyless/dispatch.rs | 34 +- crates/mega-evm/src/system/keyless/settle.rs | 12 +- crates/mega-evm/src/system/oracle.rs | 8 +- crates/mega-evm/tests/satin/main.rs | 2 +- crates/mega-evm/tests/satin/pricing-table.md | 6 +- crates/mega-evm/tests/satin/pricing_table.rs | 13 +- .../{journal_ledger.rs => tool_writes.rs} | 100 +- ...erential__keyless_differential_record.snap | 276 +-- 22 files changed, 1885 insertions(+), 4276 deletions(-) delete mode 100644 crates/mega-evm/src/evm/journal.rs delete mode 100644 crates/mega-evm/src/limit/ledger.rs rename crates/mega-evm/tests/satin/{journal_ledger.rs => tool_writes.rs} (60%) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 30d0d3b16..5efaf3a63 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -8,10 +8,13 @@ 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, }; @@ -23,21 +26,21 @@ use crate::{ inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - limit::Ledger, + limit::{Accounts, Counted, StartRecords}, system::{ self, keyless::{self, KeylessFrame}, }, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - LimitUsage, MegaJournal, 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 and the Satin journal. +/// transaction type, on revm's own journal. pub(crate) type MegaInnerContext = - Context, DB, MegaJournal, L1BlockInfo>; + Context, DB, Journal, L1BlockInfo>; /// Execution context of the Satin engine. /// @@ -85,6 +88,10 @@ pub struct MegaContext, + /// The records the last frame start's hook charged its caller for, which a debug build holds + /// the start revm then decides to. + #[cfg(debug_assertions)] + pub(crate) charged_records: Option, /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. #[cfg(any(test, feature = "test-utils"))] neutral: bool, @@ -110,9 +117,8 @@ impl MegaContext { ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; - let mut inner: MegaInnerContext = + let inner: MegaInnerContext = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); - inner.journaled_state.ledger_mut().set_limits(limits); Self { inner, cfg, @@ -128,6 +134,8 @@ impl MegaContext { system_call: false, prices_history: true, keyless_frame: None, + #[cfg(debug_assertions)] + charged_records: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -255,11 +263,10 @@ impl MegaContext { self } - /// Holds every transaction from the next one on to `limits`, in the journal's ledger and for - /// gas detention alike. + /// 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); - self.ledger_mut().set_limits(limits); } /// The block hashes execution has read on this context. @@ -308,20 +315,15 @@ impl MegaContext { /// 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; it is read off the journal's ledger, which - /// the next transaction or system call resets. + /// 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.ledger().usage() - } - - /// The journal's ledger of what the running (or last) transaction keeps. - pub(crate) const fn ledger(&self) -> &Ledger { - self.inner.journaled_state.ledger() + self.additional_limit.usage() } - /// The journal's ledger, mutably. - pub(crate) const fn ledger_mut(&mut self) -> &mut Ledger { - self.inner.journaled_state.ledger_mut() + /// 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 @@ -475,8 +477,7 @@ impl MegaContext { } /// Prepares the common execution layer for a transaction or a system call that is, or is not, - /// `system_originated`: the journal's ledger begins it, counting its body, and the frame side - /// is reset. + /// `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. @@ -487,7 +488,6 @@ 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(); let transfer_logs = emits_transfer_logs(&self.inner.cfg); self.bucket_multipliers.reset(); self.oracle_reads.clear(); @@ -497,13 +497,10 @@ impl MegaContext { 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. let body = transaction_body_bytes(self.tx()); - self.ledger_mut().begin_transaction(system_originated, transfer_logs, body); + 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( @@ -575,7 +572,7 @@ impl MegaContext { /// 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.into_revm().database, self.cfg, block) + (journaled_state.database, self.cfg, block) } } @@ -645,7 +642,7 @@ impl ContextTr for MegaContext; type Db = DB; - type Journal = MegaJournal; + type Journal = Journal; type Chain = L1BlockInfo; type Local = LocalContext; @@ -658,7 +655,7 @@ impl ContextTr for MegaContext, &DB, - &MegaJournal, + &Journal, &L1BlockInfo, &LocalContext, ); @@ -668,7 +665,7 @@ impl ContextTr for MegaContext, - &mut MegaJournal, + &mut Journal, &mut L1BlockInfo, &mut LocalContext, ); @@ -676,12 +673,12 @@ impl ContextTr for MegaContext ContextTr for MegaContext, - _gas: &mut revm::context_interface::cfg::gas::GasTracker, + gas: &mut GasTracker, ) -> Result<(), Bytes> { let destroyed = self .journal_ref() @@ -706,7 +703,7 @@ impl ContextTr for MegaContext Result { let authorizations = evm.ctx_ref().tx().authorization_list_len() as u64; - if !evm.ctx_ref().ledger().admits_tx_body(authorizations) { + 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().ledger().body(); + 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); @@ -303,43 +307,54 @@ where 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 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 pool is what the transaction has left of its data-size limit once its body and the + /// records of the authorities it applied are counted, under the frame cap + /// ([`AdditionalLimit::first_frame_pool`](crate::AdditionalLimit)); revm hands the frame the + /// whole of 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 { + gas.set_bytes_remaining(evm.ctx_ref().additional_limit.first_frame_pool()); + 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(), 0); + 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 start's side, 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. + /// 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 the - /// history of it comes back here, at this one site, when the frame did not keep the record — - /// it failed, or it is a success that kept nothing: a creation revm refused on its sender's - /// nonce, a frame an inspector answered or revived — the way EIP-8037 gives back the state gas - /// of the account that frame would have created. The journal's ledger says whether the record - /// is held ([`StartSide::refund`](crate::limit::StartSide)); the refund lands in the pools the - /// charge came from, and a halt burns what of it the regular gas holds. + /// 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: 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 @@ -350,31 +365,16 @@ where frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - let ctx = evm.ctx_mut(); - // The transaction's own frame, answered without returning through `frame_return_result`; - // a transaction whose first frame never reached frame init has no side to pop. - debug_assert!(ctx.additional_limit.starts_open() <= 1, "only the outermost side is left"); - if ctx.additional_limit.starts_open() != 0 { - on_start_return(ctx, 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)?; - let instruction_result = frame_result.instruction_result(); - parent_gas.refill_history(evm.ctx_mut().additional_limit.take_top_level_refund()); - 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 (kept, log_and_code_bytes) = { - let ledger = evm.ctx_ref().ledger(); - (ledger.usage(), ledger.log_and_code_bytes()) - }; 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, kept.write_records, log_and_code_bytes); + layer.settle_history(priced, history); Ok(()) } @@ -463,14 +463,14 @@ impl InspectorHandler for MegaHandler: ContextTr>, - MegaJournal: JournalExt, + MegaContext: ContextTr>, + Journal: JournalExt, EVM: InspectorEvmTr< Context = MegaContext, Frame = EthFrame, Inspector: Inspector, EthInterpreter>, >, - // Implied by `EvmTrError`, but the `ContextTr>` bound above + // Implied by `EvmTrError`, but the `ContextTr>` bound above // stops the compiler from normalizing the context's database type down to `DB`. ERROR: EvmTrError + From @@ -516,23 +516,25 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = self.answered_before_building(&frame_init) { + // What the start's hook left for revm's decision is this start's, whoever decides it. + let creator = self.inner.ctx.additional_limit.take_creator_record(); + #[cfg(debug_assertions)] + let charged = self.inner.ctx.charged_records.take(); + if let Some(result) = call_too_deep(&frame_init) { return Ok(ItemOrResult::Result(result)); } - assert_running_frame(&self.inner.ctx, frame_init.depth); let keyless = keyless::is_dispatched(&self.inner.ctx, &frame_init); let answer = if keyless { keyless::ready(&mut self.inner.ctx, &mut frame_init)? @@ -560,60 +562,73 @@ impl EvmTr for MegaEvm Ok(()), - ItemOrResult::Result(result) => Err(result), - }); - let report = self.inner.ctx.ledger_mut().close_start(); - (decided?, report) + 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.share); + 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; - debug_assert!(!keyless || outcome.is_ok(), "revm builds a keylessDeploy call's frame"); - match outcome { - Ok(()) => { + match decided { + None => { if keyless { ctx.keyless_frame = Some(keyless::KeylessFrame::Built); } - ctx.additional_limit.hold_start(report.verdict); - let built = ctx.ledger().frame_start_rollback(); - debug_assert!(built.is_some(), "a frame revm built has its level open"); - ctx.additional_limit.attach_start(report, built); - Ok(ItemOrResult::Item(self.inner.frame_stack.get())) + ctx.additional_limit.open_start(depth); + 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); + ctx.additional_limit.hold_start(verdict); + #[cfg(debug_assertions)] + start.assert_made(ctx); + Ok(ItemOrResult::Item(frame)) } - Err(mut result) => { + Some(mut result) => { + 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(); - hold_answered_start(ctx, &start, &report, &mut result); - ctx.additional_limit.attach_start(report, None); + // A creation revm answers creates nothing: refused on its creator's account, it + // bumped nothing, and the record its hook counted on the creator comes back with + // its answer; failed onto an occupied address, it is held to nothing at its start, + // and its failure takes its records and transfer log back. + if let Some(record) = creator.filter(|_| !start.bumped(ctx)) { + give_back_creator_record(ctx, &mut result, record); + } + ctx.additional_limit.open_start(depth); + 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.share) + }; + 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); + take_back_a_stopped_answer(ctx, start.mark, succeeded, &result); Ok(ItemOrResult::Result(result)) } } @@ -643,10 +658,6 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - let refund = on_start_return(&mut self.inner.ctx, &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 = 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)?; } + self.inner.ctx.additional_limit.hold_caller(caller.tracker_mut()); Ok(returned) } } @@ -728,9 +751,9 @@ where ) } - /// revm's inspected frame start, with the frame sides kept aligned: a frame the inspector - /// answers itself never reaches [`EvmTr::frame_init`], so a side of its own stands in for it, - /// and its answer settles as a frame that never started ([`answered_by_inspector`]). + /// revm's inspected frame start: a frame the inspector answers itself never reaches + /// [`EvmTr::frame_init`], 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 @@ -748,10 +771,6 @@ where &mut self, mut frame_init: FrameInit, ) -> Result, ContextDbError> { - // A start past the call-stack limit is answered by the depth guard, wherever it comes from. - if frame_init.depth <= CALL_STACK_LIMIT as usize { - assert_running_frame(&self.inner.ctx, frame_init.depth); - } let (ctx, inspector) = self.ctx_inspector(); // What the calling opcode charged upfront, before the inspector's hooks can rewrite the // call it charged for. @@ -762,13 +781,16 @@ where } // The start its charge paid for — the calling opcode's, or the transaction's for its own // frame — may not be the one the inspector lets start. - ctx.additional_limit.waive_start_check(); + #[cfg(debug_assertions)] + { + ctx.charged_records = None; + } 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 = ctx.journal_mut().mark(); - let logs_i = start.position.log_i; + let start = mark(ctx.journal_mut()); + 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 @@ -826,14 +848,10 @@ where instructions.gas_table(), ), }; - if action.is_return() { - // revm closes the frame's level as it processes its return. - ctx.ledger_mut().frame_returning(); - } 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(built_frame_mark(ctx, frame)); + let source = ResultSource::Engine(frame.checkpoint); let upfront = ctx.upfront_records.get(frame.depth).copied().flatten(); frame_end_checked(ctx, inspector, &frame.input, result, source, upfront); frame.set_finished(true); @@ -888,13 +906,14 @@ fn before_frame_run( #[inline] fn after_frame_run( ctx: &mut MegaContext, - frame: &EthFrame, + frame: &mut EthFrame, next: &mut Result>, E>, ) { match next { Ok(ItemOrResult::Item(child)) => { let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth, stipend); + cap_the_share(ctx.additional_limit.frame_cap(), &mut frame.interpreter.gas, child); } Ok(ItemOrResult::Result(result)) => { let instruction_result = result.instruction_result(); @@ -908,6 +927,25 @@ fn after_frame_run( } } +/// Holds the share of its caller's pool the frame `child` starts with to the frame cap, `cap`, +/// and gives what it forwarded above it back to the caller, whose pool `caller` holds: a frame's +/// budget is the schedule's share of what its caller has left, under the cap. +#[inline] +fn cap_the_share(cap: u64, caller: &mut Gas, child: &mut FrameInit) { + let share = match &child.frame_input { + FrameInput::Call(inputs) => inputs.bytes_share, + FrameInput::Create(inputs) => inputs.bytes_share(), + FrameInput::Empty => return, + }; + let Some(excess) = share.checked_sub(cap).filter(|excess| *excess != 0) else { return }; + caller.set_bytes_remaining(caller.bytes_remaining().saturating_add(excess)); + match &mut child.frame_input { + FrameInput::Call(inputs) => inputs.bytes_share = cap, + FrameInput::Create(inputs) => inputs.set_bytes_share(cap), + FrameInput::Empty => {} + } +} + /// Holds a frame answered without running to the compute limit: the answer to a frame of /// `gas_limit` at `depth`, which its caller forwarded. /// @@ -1094,23 +1132,25 @@ 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 a side of its own standing 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_answered_start(frame_init.depth); - } - 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 the journal, and its ledger, 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. +/// 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 +/// 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 @@ -1120,41 +1160,21 @@ impl MegaEvm { /// is all that takes them back. The journal's depth is left as it is. fn take_back_a_stopped_answer( ctx: &mut MegaContext, - start: &Mark, + start: JournalCheckpoint, succeeded: bool, result: &FrameResult, ) { if succeeded && !result.instruction_result().is_ok() { - ctx.journal_mut().revert_to(start); + revert_to(ctx.journal_mut(), start); } } -/// The verdict the journal's ledger gives a call `input` starts had revm made it: the records its -/// transfer would make and take back, as the journal predicts them, and the transfer log of the -/// value it would move, for a start the engine answers without revm deciding it -/// ([`Ledger::hypothetical_start`](crate::limit::Ledger)). -fn hypothetical_start( - ctx: &MegaContext, - input: &FrameInput, -) -> LimitCheck { - let FrameInput::Call(inputs) = input else { - unreachable!("only a call is answered without revm deciding its start") - }; - let value = inputs.value.get(); - let records = ctx.journal_ref().transfer_records(inputs.caller, inputs.target_address, value); - let logged = ctx.ledger().counts_transfer_logs() && - !value.is_zero() && - inputs.target_address != inputs.caller; - ctx.ledger().hypothetical_start(records, logged) -} - /// 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; a side of its own 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`]). +/// past the call-stack limit, 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, @@ -1166,7 +1186,6 @@ where INSP: Inspector, EthInterpreter>, { let mut output = call_too_deep(frame_init).unwrap_or(output); - ctx.additional_limit.push_answered_start(frame_init.depth); let gas_limit = input_gas_limit(&frame_init.frame_input); settle_answer(ctx, frame_init.depth, gas_limit, &mut output); let input = &frame_init.frame_input; @@ -1175,85 +1194,249 @@ where } /// What holding a frame's start to the limits needs of it once revm consumed its input: where the -/// start began and what a stop answering it carries. +/// start began, what it counts and what a stop answering it carries. struct FrameStart { - /// Where the journal and its ledger 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: Mark, - /// What the start is: its depth, its caller, its target or none for a creation, and whether it - /// moves value. - facts: StartFacts, + /// 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 share of its caller's pool the frame starts with: its budget. + share: u64, + /// For a creation, its creator and the creator's nonce before revm decides the start, which + /// says whether revm bumped it. + creator_nonce: Option<(Address, u64)>, + /// 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. + /// The start of the frame `frame_init` asks for, about to be decided by revm: where the + /// journal stands, and the records it makes as the journal's state stands + /// ([`Accounts::start_records`](crate::limit::Accounts)). A creation's creator record is not + /// among them: its start's hook counted it on the creator. fn of( ctx: &mut MegaContext, frame_init: &FrameInit, + creator_counted: bool, + #[cfg(debug_assertions)] hooked: Option, ) -> Self { - let (input, depth) = (&frame_init.frame_input, frame_init.depth); - let (facts, reservoir) = match input { + let accounts = ctx.accounts(); + let (records, charged, reservoir, share, creator_nonce) = match &frame_init.frame_input { FrameInput::Call(inputs) => ( - StartFacts { depth, creation: false, transfers_value: inputs.transfers_value() }, + accounts.transfer_records( + inputs.caller, + inputs.target_address, + inputs.value.transfer().unwrap_or_default(), + ), + inputs.charged_start.history, inputs.reservoir, + inputs.bytes_share, + None, ), - FrameInput::Create(inputs) => ( - StartFacts { depth, creation: true, transfers_value: !inputs.value().is_zero() }, - inputs.reservoir(), - ), + FrameInput::Create(inputs) => { + let nonce = account_nonce(ctx, inputs.caller()); + let created = inputs.created_address(nonce); + ( + accounts.creation_records(inputs.caller(), Some(created), inputs.value()), + inputs.charged_start().history, + inputs.reservoir(), + inputs.bytes_share(), + Some((inputs.caller(), nonce)), + ) + } FrameInput::Empty => unreachable!( "a frame input always names a call or a creation, as revm's frame init asserts" ), }; - Self { mark: ctx.journal_mut().mark(), facts, gas_limit: input_gas_limit(input), reservoir } + 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, creator_counted, hooked); + #[cfg(not(debug_assertions))] + let _ = creator_counted; + Self { + mark: mark(ctx.journal_mut()), + counted: records.counted(), + credit, + gas_limit: input_gas_limit(&frame_init.frame_input), + reservoir, + share, + creator_nonce, + #[cfg(debug_assertions)] + made, + } + } + + /// Whether revm bumped the creator's nonce for the creation this start is, which it does + /// unless it refuses the creation on its creator's account. + fn bumped( + &self, + ctx: &MegaContext, + ) -> bool { + self.creator_nonce.is_some_and(|(creator, nonce)| account_nonce(ctx, creator) != nonce) + } + + /// Asserts revm's start made the records the start was charged for and counted, read off + /// the journal once revm built the frame. + #[cfg(debug_assertions)] + fn assert_made(&self, ctx: &MegaContext) { + self.made.assert_after(ctx); } } -/// Holds `start`, the start of a frame revm answered without building it, to the limits, now that -/// revm decided it: `answer` is revm's answer, or gas detention's to a precompile whose price -/// crosses the compute limit, given without running it. -/// -/// The verdict is the journal's ledger's (`report`), taken while the start's level was open, -/// before revm committed or reverted it — or, for the call gas detention answers, the hypothetical -/// one: a crossing is the stop, which the answer gives way to, on the gas its caller forwarded, -/// untouched, as a frame stopped before it ran, and before gas detention holds 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. -/// -/// A call revm refused to move value for — a value its caller cannot fund — moved nothing and has -/// no verdict. Neither has a creation revm answers, which moved nothing and kept no account: -/// refused on its creator's account — an endowment it cannot fund, a nonce it cannot bump — it -/// bumped nothing and counts nothing; failed after the bump, onto an occupied address, it is held -/// to nothing at its start: its failure takes the created account's record and the transfer log -/// back, and the nonce record, which outlives it, lands on the creator, which is held to its -/// limits with it once the answer returns ([`AdditionalLimit::on_start_return`]). -fn hold_answered_start( +/// The accounts a start writes and whether the transaction had changed each before it, for a debug +/// build to hold the records the start was charged for and counted to what revm's start made of +/// them. +#[cfg(debug_assertions)] +#[derive(Debug)] +struct MadeRecords { + /// The records predicted. + records: StartRecords, + /// The accounts the start writes, each with whether it was changed before the start: a call's + /// sender and recipient, or a creation's created account and creator. + accounts: [(Address, bool); 2], + /// Whether the start is a creation. + creation: bool, + /// Whether the creator's record was counted on it at the start's hook. + creator_counted: bool, +} + +#[cfg(debug_assertions)] +impl MadeRecords { + /// The accounts the start `frame_init` asks for writes, read before revm decides it; and, + /// unless an inspector may rewrite the start between the two, the records the start's hook + /// charged for, which must be those predicted here. + fn before( + ctx: &MegaContext, + frame_init: &FrameInit, + records: StartRecords, + creator_counted: bool, + charged: Option, + ) -> Self { + 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" + ); + } + let (addresses, creation) = match &frame_init.frame_input { + FrameInput::Call(inputs) => ([inputs.caller, inputs.target_address], false), + FrameInput::Create(inputs) => { + let nonce = ctx + .journal_ref() + .state + .get(&inputs.caller()) + .map_or(0, |account| account.info.nonce); + ([inputs.created_address(nonce), inputs.caller()], true) + } + FrameInput::Empty => ([Address::ZERO; 2], false), + }; + let accounts = ctx.accounts(); + let accounts = addresses.map(|address| (address, accounts.is_changed(address))); + Self { records, accounts, creation, creator_counted } + } + + /// 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, + /// and its creator, when the hook counted the creator's record, changed by the bump. + 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)) + }; + let [first, second] = self.accounts; + if !self.creation { + 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"); + return; + } + let created = RecordDelta::of_account(false, self.records.created); + debug_assert_eq!(made(first), created, "a creation made its created account's record"); + if self.creator_counted { + debug_assert_eq!(made(second), RecordDelta::of_account(false, true), "the creator's"); + } + } +} + +/// 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) +} + +/// Gives back the record of its own nonce a creation's start hook counted on its creator, for a +/// creation that never bumped the nonce — revm refused it on its creator's account, after an +/// inspector rewrote it — through `answer`, the creation's failure: what the creator paid for the +/// record, in history and in bytes, joins the start charge its failure gives back. +pub(crate) fn give_back_creator_record( + ctx: &mut MegaContext, + answer: &mut FrameResult, + record: CreatorRecord, +) { + ctx.additional_limit.give_back_creator_record(record); + if let FrameResult::Create(outcome) = answer { + let charge = outcome.charged_start; + outcome.charged_start = + StartCharge::new(charge.history + record.history, charge.bytes + record.drawn); + } +} + +/// 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, - report: &StartReport, answer: &mut FrameResult, + verdict: LimitCheck, ) { - if let Some(stop) = report.verdict.filter(LimitCheck::exceeded_limit) { - let output = ctx.additional_limit.note_frame_stop(&stop); + if verdict.exceeded_limit() { + let output = ctx.additional_limit.note_frame_stop(&verdict); stop_the_answer(answer, start, output); } } /// 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 the call inherited, and no precompile -/// output, as [`synthetic_frame_result`] answers a frame that never started. +/// call's caller forwarded, untouched, with the reservoir and the pool 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 gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + let mut gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + gas.set_bytes_remaining(start.share); + 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(); @@ -1298,68 +1481,9 @@ fn inspect_logs( } } -/// The mark the built frame `frame` is taken back to when an inspector rewrites its success into a -/// failure: the frame's own checkpoint, with what its start's side kept of the counts its level -/// opened with. -fn built_frame_mark( - ctx: &MegaContext, - frame: &EthFrame, -) -> Mark { - let kept = - ctx.additional_limit.running_start().and_then(|side| side.built_mark(frame.checkpoint)); - debug_assert!(kept.is_some(), "a built frame's start side keeps what it is taken back to"); - kept.unwrap_or_else(|| ctx.ledger().mark(frame.checkpoint)) -} - -/// Asserts, as a frame at `depth` starts, that the journal's nearest frame level is the running -/// frame's own: the one its start opened, at the depth above. The frame levels of every frame -/// that started and returned since are closed, whatever rollback levels a tool holds open around -/// them. -fn assert_running_frame( - ctx: &MegaContext, - depth: usize, -) { - let running = ctx.additional_limit.running_start().and_then(|side| side.start()); - let expected = - depth.checked_sub(1).zip(running).map(|(depth, start)| FrameIdentity { depth, start }); - debug_assert!( - ctx.ledger().running_frame() == expected, - "a frame starts from the running frame's own level" - ); -} - -/// Pops the side of the start of the frame `result` returns from, once revm closed the frame's -/// level, and answers the history its caller gets back for the start's records the journal's -/// ledger no longer holds; the caller is held to its limits with what the frame left it -/// ([`AdditionalLimit::on_start_return`](crate::AdditionalLimit)). The transaction's own frame has -/// no caller: its record's refund is kept for the settlement. -/// -/// Asserts the frame's own level, and every level opened inside it, closed: the journal's nearest -/// frame level is the caller's. -fn on_start_return( - ctx: &mut MegaContext, - result: &FrameResult, -) -> u64 { - let ledger = ctx.inner.journaled_state.ledger(); - let Some((side, refund)) = ctx.additional_limit.on_start_return(ledger, result) else { - return 0; - }; - let caller = ctx.additional_limit.running_start().and_then(|side| side.start()); - let expected = side - .depth() - .checked_sub(1) - .zip(caller) - .map(|(depth, start)| FrameIdentity { depth, start }); - debug_assert!( - ctx.ledger().running_frame() == expected, - "a frame returns with its own level closed, into its caller's" - ); - refund -} - -/// 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 creates its caller's account/// 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, and after /// [`validate_env`](Handler::validate_env), which promoted a system-address transaction: a @@ -1391,11 +1515,10 @@ fn charge_created_caller( gas.record_state_cost(state_gas) } -/// 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 -/// 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( +/// 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 applied_authorities( ctx: &mut MegaContext, journal_i: usize, ) -> u64 { @@ -1412,13 +1535,11 @@ fn record_applied_authorities( .collect(); authorities.sort_unstable(); authorities.dedup(); - let applied = authorities.len() as u64; - ctx.ledger_mut().count_authorities(applied); // 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 + authorities.len() as u64 } /// Charges the history of the write records a transaction makes outside any frame: one per @@ -1426,20 +1547,19 @@ fn record_applied_authorities( /// 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 -/// ([`MegaJournal::transfer_records`](crate::MegaJournal)): a recipient that is the sender, or an +/// ([`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, and the ledger counts it. +/// 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 when the -/// frame does not keep the record, and whether it makes one is left for that frame's side to hold -/// the ledger's count to. A first frame revm refuses to start on its sender's account makes no -/// record, and the charge comes back at the settlement as for any frame that kept nothing: among +/// 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. +/// 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, @@ -1450,21 +1570,20 @@ fn charge_records_made_outside_a_frame( return true; } let tx = ctx.tx(); - let records = match tx.kind() { - TxKind::Create => FrameStartRecords { created: true, ..FrameStartRecords::NONE }, + let first_frame = match tx.kind() { + TxKind::Create => 1, TxKind::Call(to) => { - let predicted = ctx.journal_ref().transfer_records(tx.caller(), to, tx.value()); + 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"); - FrameStartRecords::of_transfer(predicted) + predicted.added } }; - let Some((top_level, _)) = - charge_write_records_history(gas, records.added_on_level(), applied_authorities) + let Some((first_frame, _)) = + charge_write_records_history(gas, first_frame, applied_authorities) else { return false; }; - ctx.additional_limit.set_top_level_write_record_gas(top_level); - ctx.additional_limit.stage_top_level_records(records); + ctx.additional_limit.set_first_frame_charge(first_frame); true } @@ -1745,11 +1864,11 @@ mod tests { ] { let case = format!("succeeded {succeeded}, now {result:?}"); let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let start = ctx.journal_mut().mark(); + 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()); - take_back_a_stopped_answer(&mut ctx, &start, succeeded, &answer); + 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}"); } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 3fb3bcc91..797b36116 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -8,13 +8,16 @@ //! 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. +//! gas back on success and revert, the frame's reservoir adopted as the caller's own, and the +//! frame's byte pool 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. +//! the reservoir and the share of the byte pool the frame inherited ([`untouched_call_gas`], +//! [`with_pools_of`]), never `Gas::new(limit)`, which would carry no reservoir and an unlimited +//! pool, billing the sender for the whole reservoir and lifting the caller's budget; 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; [`settle_frame_result`] is that settlement, for a caller //! that settles a result into its own gas outside revm's frame return. @@ -30,26 +33,33 @@ 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 share of its caller's byte pool 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.set_bytes_remaining(inputs.bytes_share); + 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 share of its creator's byte pool 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()) +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.set_bytes_remaining(inputs.bytes_share()); + gas } -/// `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. +/// `gas_limit` of fresh regular gas carrying `source`'s pools: its EIP-8037 reservoir, the state +/// and history gas it charged, the part of those charges that spilled onto regular gas, and its +/// byte pool with what it drew from it. /// /// 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. +/// the caller forwarded): the caller keeps the frame's state and history charges and its byte +/// draws on success and rolls them back on failure, so a rebuilt `Gas` that dropped them would +/// hand the caller an empty reservoir, an unlimited pool 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); @@ -57,12 +67,15 @@ pub const fn with_pools_of(gas_limit: u64, source: &Gas) -> Gas { 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.set_bytes_remaining(source.bytes_remaining()); + gas.set_bytes_spent(source.bytes_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. +/// `output`, the frame's gas untouched, the inherited reservoir and byte share 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,7 +88,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: Default::default(), + charged_start: inputs.charged_start(), }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), } @@ -96,13 +109,14 @@ 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: Default::default(), + 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. +/// the refund refilled into the caller's reservoir, and the start charge the result carries +/// given back when it failed. /// /// `ctx` prices the refund through the same hook the charge went through; a failed lookup is /// the error the hook recorded. @@ -131,6 +145,10 @@ where if let Some(refund) = refund { caller_gas.refill_reservoir(refund); } + if let Some(charge) = result.refundable_start_charge() { + caller_gas.refill_history(charge.history); + caller_gas.refill_bytes(charge.bytes); + } Ok(()) } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 77dce028b..1c4297df1 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -64,7 +64,10 @@ use delegate::delegate; use revm::{ context::ContextTr, context_interface::{ - cfg::{gas::GasTracker, GasId, GasParams, StateGasSite}, + cfg::{ + gas::{GasTracker, StartCharge}, + GasId, GasParams, StateGasSite, + }, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, journaled_state::AccountInfoLoad, @@ -290,10 +293,10 @@ impl revm::context_interface::Host Ok(load) } - /// Commits the record of a write an opcode completed to the running frame's level of the - /// journal's ledger, 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. + /// 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 @@ -322,8 +325,8 @@ impl revm::context_interface::Host CompletedWrite::Log { .. } => (true, false), CompletedWrite::SelfDestruct { .. } => (false, false), }; - let (count, history) = self.ledger().write_count(&write); - let check = self.ledger_mut().count_write(&count); + let (counted, history) = 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)); } @@ -334,12 +337,8 @@ impl revm::context_interface::Host } if appended != 0 { let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; - let drawn = if from_allowance { - self.additional_limit.try_consume_stipend(cost) - } else { - 0 - }; - if !gas.record_history_cost(cost - drawn) { + let cost = if from_allowance { gas.draw_history_allowance(cost) } else { cost }; + if !gas.record_history_cost(cost) { return WriteVerdict::OutOfGas; } } @@ -352,23 +351,24 @@ impl revm::context_interface::Host /// 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 and its creator's nonce — as the journal predicts them from its state - /// ([`MegaJournal::start_records`](crate::MegaJournal)). The created account is charged for - /// every creation: the address a `CREATE2` lands on is not known here, and a creation onto an - /// address the transaction changed already makes no record for it. 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. + /// 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)), and counts the + /// creator's record on the running frame's pool, before the frame's share of it is forwarded. + /// 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. /// /// 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; the frame's side keeps it, and - /// gives back on return what the journal's ledger reports the start did not keep, and the - /// price of the records a transfer returned to what the transaction loaded, once that stands. - /// 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. 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. + /// 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. 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 @@ -379,19 +379,28 @@ impl revm::context_interface::Host /// 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 records = self.journal_ref().start_records(start); - if !self.prices_history() { - self.additional_limit.stage_frame_charge(records, 0, 0, false); - return true; - } - let charged = - charge_write_records_history(gas, records.added_on_level(), u64::from(records.creator)); - let Some((added, creator)) = charged else { - gas.erase_cost(start.forward); - gas.set_failed_charge_remaining(Some(gas.remaining())); - return false; + let records = + self.accounts().start_records(start.kind, start.caller, start.target, start.value); + let on_frame = records.on_frame().added; + let (charge, creator) = if self.prices_history() { + let creator = u64::from(records.creator); + let Some(charged) = charge_write_records_history(gas, on_frame, creator) else { + gas.erase_cost(start.forward); + gas.set_failed_charge_remaining(Some(gas.remaining())); + return false; + }; + charged + } else { + (0, 0) }; - self.additional_limit.stage_frame_charge(records, added, creator, true); + start.charge = StartCharge::new(charge, 0); + if records.creator { + self.additional_limit.count_creator_record(gas, creator); + } + #[cfg(debug_assertions)] + { + self.charged_records = Some(records); + } true } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index b4e208cc1..68ea1c5af 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -32,9 +32,11 @@ //! //! # Block execution //! -//! Block execution admits any inspector: the journal's ledger follows the journal, so a rewrite -//! cannot put the ledger out of step with state, and which inspectors may run on block production -//! is a node's decision, not the engine's. +//! Block execution admits any inspector: which inspectors may run on block production is a node's +//! decision, not the engine's. What the transaction keeps is counted where its own execution +//! writes and taken back with a frame that keeps nothing, so a rewrite that reverts a frame takes +//! back what the frame counted; an inspector that overwrites a frame's gas overwrites its byte +//! pool with it, as it overwrites detention's split (below). //! //! # What a rewrite does not change //! @@ -84,8 +86,10 @@ //! 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 two records of a refused charge are kept from a -//! callback's write. +//! until detention next sets it. The frame's byte pool is in its `Gas` too, and goes back to the +//! snapshot's with it: what the frame wrote in between is counted on the transaction, which is +//! held to its limit, and not drawn from the frame's budget. Only the two records of a refused +//! charge are 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 @@ -95,7 +99,11 @@ use revm::{ context::ContextTr, - context_interface::{cfg::StateGasCharge, Host}, + context_interface::{ + cfg::{gas::StartCharge, StateGasCharge}, + journaled_state::JournalCheckpoint, + Host, + }, handler::FrameResult, inspector::handler::frame_end, interpreter::{ @@ -105,7 +113,7 @@ use revm::{ Database, Inspector, }; -use crate::{limit::Mark, synthetic_frame_result, ExternalEnvTypes, MegaContext}; +use crate::{evm::execution::revert_to, synthetic_frame_result, ExternalEnvTypes, MegaContext}; /// 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. @@ -230,9 +238,8 @@ pub(crate) enum ResultSource { 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 mark: the frame's own - /// checkpoint, or where the journal stood when the start began, with the ledger as it stood - /// there. - Engine(Mark), + /// checkpoint, 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. @@ -277,7 +284,7 @@ pub(crate) fn frame_end_checked( ResultSource::Inspector => true, ResultSource::Engine(mark) => { if before.is_ok() && !frame_result.instruction_result().is_ok() { - context.journal_mut().revert_to(&mark); + revert_to(context.journal_mut(), mark); } false } @@ -299,26 +306,29 @@ pub(crate) fn frame_end_checked( /// /// 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. +/// was built on — `Gas::new(limit)`, which carries no reservoir and no byte pool, or one carrying +/// charges — its state and history charges and its byte draws are rolled back, its refund is +/// dropped, and its reservoir and pool are the ones the frame inherited, so its caller merges back +/// the reservoir and the share of its pool 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; +/// - its state and history charges and its byte draws 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. +/// a frame that restored a slot its caller filled does, and its caller's merge nets it out; +/// - so does the start charge its caller paid for the start's records, which revm's settlement +/// gives back to a failure alone. /// -/// What the frame counted is the journal's ledger's, which the frame's checkpoint took back with -/// the frame's writes, or which never counted the start of a frame the inspector answered: its -/// caller gets back the history it paid for the start's records once the frame returns, and the -/// transaction the history of its own frame's record at the settlement, as for any frame that kept -/// nothing. +/// What the frame counted goes back with its start, which the frame's return closes as one that +/// kept nothing ([`AdditionalLimit::kept_nothing`](crate::AdditionalLimit)); a start the inspector +/// answered was never counted. A creation the inspector answered never bumped its creator's nonce, +/// so the record its start's hook counted on the creator comes back too, with what the creator paid +/// for it. fn settle_kept_nothing( context: &mut MegaContext, input: &FrameInput, @@ -327,6 +337,17 @@ fn settle_kept_nothing( ) { carry_upfront_flags(input, result); let success = result.instruction_result().is_ok(); + // An answer the inspector built carries whatever it was built with; a result the engine made + // carries the charge the engine put on it. + let mut charge = if answered { start_charge(input) } else { carried_start_charge(result) }; + if answered { + if let Some(record) = context.additional_limit.take_creator_record() { + context.additional_limit.give_back_creator_record(record); + charge = StartCharge::new(charge.history + record.history, charge.bytes + record.drawn); + } + } else { + context.additional_limit.kept_nothing(); + } let gas = result.gas_mut(); if answered || success { gas.rollback_state_gas(); @@ -334,10 +355,15 @@ fn settle_kept_nothing( } if answered { gas.set_reservoir(inherited_reservoir(input)); + gas.set_bytes_remaining(inherited_share(input)); } if !success { + set_start_charge(result, charge); return; } + gas.refill_history(charge.history); + gas.refill_bytes(charge.bytes); + set_start_charge(result, StartCharge::default()); // 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()); @@ -346,6 +372,32 @@ fn settle_kept_nothing( result.gas_mut().refill_reservoir(upfront.unwrap_or_default()); } +/// What the caller of the frame `input` starts paid for its start, and the frame's failure gives +/// back: the start charge its input carries. +fn start_charge(input: &FrameInput) -> StartCharge { + match input { + FrameInput::Call(inputs) => inputs.charged_start, + FrameInput::Create(inputs) => inputs.charged_start(), + FrameInput::Empty => StartCharge::default(), + } +} + +/// The start charge `result` carries. +const fn carried_start_charge(result: &FrameResult) -> StartCharge { + match result { + FrameResult::Call(outcome) => outcome.charged_start, + FrameResult::Create(outcome) => outcome.charged_start, + } +} + +/// Sets the start charge `result` carries, which revm's settlement gives back when it fails. +fn set_start_charge(result: &mut FrameResult, charge: StartCharge) { + match result { + FrameResult::Call(outcome) => outcome.charged_start = charge, + FrameResult::Create(outcome) => outcome.charged_start = charge, + } +} + /// 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) { @@ -371,6 +423,15 @@ const fn inherited_reservoir(input: &FrameInput) -> u64 { } } +/// The share of its caller's byte pool the frame `input` starts with. +const fn inherited_share(input: &FrameInput) -> u64 { + match input { + FrameInput::Call(inputs) => inputs.bytes_share, + FrameInput::Create(inputs) => inputs.bytes_share(), + FrameInput::Empty => u64::MAX, + } +} + /// 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 { diff --git a/crates/mega-evm/src/evm/journal.rs b/crates/mega-evm/src/evm/journal.rs deleted file mode 100644 index c617299fb..000000000 --- a/crates/mega-evm/src/evm/journal.rs +++ /dev/null @@ -1,1026 +0,0 @@ -//! The journal of the Satin engine: revm's journal, with the ledger of what the transaction's own -//! execution keeps beside it. -//! -//! [`MegaJournal`] owns revm's [`Journal`] and implements [`JournalTr`] by delegating every method -//! to it. A handful of methods also tell the ledger what they did, under one rule: -//! -//! - **Counted writes.** A call's value transfer (`transfer_loaded`) and a creation's account -//! checkpoint (`create_account_checkpoint`) are counted when revm makes them for a frame start, -//! inside the start window the engine opens around revm's frame start, and only there. A -//! `SELFDESTRUCT`'s move (`selfdestruct`) is observed here and counted by the Host's -//! completed-write hook once the opcode completed. Every other write — `sstore`, `log`, a -//! `transfer`, anything through an account handle — is forwarded and counts nothing: a write an -//! opcode completed reaches the ledger from the Host's completed-write hook, and a write a tool -//! or a precompile makes is not the transaction's own execution. -//! - **What a write counts.** An account's write record follows the net change of its info within -//! the transaction: the journal compares the account's nonce, balance and code hash with what the -//! transaction loaded ([`is_changed`](MegaJournal::is_changed)) before and after each counted -//! write, and tells the ledger which accounts the write changed and which it returned -//! ([`RecordDelta`]). The same prediction, on the journal's state as it stands, is what the -//! frame-start hook charges a start's records from -//! ([`start_records`](MegaJournal::start_records)), but for a creation's created account, which -//! the hook charges for every creation, not knowing the address. -//! - **Levels and the transaction's end.** `checkpoint`, `checkpoint_commit` and -//! `checkpoint_revert` open and close the ledger's levels with revm's checkpoints; `commit_tx`, -//! `discard_tx` and `finalize` close them all. -//! - **Everything else is forwarded**, the configuration switches included: a switch kept at the -//! trait's no-op default would silently turn a journal feature off. The one default kept is -//! `clear`'s, which finalizes through the hooked `finalize`. -//! -//! The impl denies `clippy::missing_trait_methods`, so a method `JournalTr` gains is a lint error -//! here until it is given its rule. -//! -//! [`JournalExt::journal`] hands out revm's own entries, and the journal dereferences to revm's -//! [`Journal`] read-only, so code that reads revm's journal state keeps reading it. There is no -//! mutable dereference: a write that bypassed the methods above could not be seen by the ledger. - -#[cfg(not(feature = "std"))] -use alloc as std; -use core::ops::Deref; -use std::vec::Vec; - -use delegate::delegate; -use revm::{ - context::{ - journaled_state::{ - account::JournaledAccount, AccountInfoLoad, AccountLoad, JournalCheckpoint, - JournalLoadError, TransferError, - }, - JournalTr, - }, - context_interface::{ - context::{SStoreResult, SelfDestructResult, StateLoad}, - host::{FrameStart, FrameStartKind}, - }, - inspector::JournalExt, - primitives::{ - hardfork::SpecId, Address, AddressMap, AddressSet, Bytes, HashSet, Log, StorageKey, - StorageValue, B256, U256, - }, - state::{Account, AccountInfo, Bytecode, EvmState}, - Database, Journal, JournalEntry, -}; - -use crate::limit::{FrameStartRecords, Ledger, Mark, RecordDelta}; - -/// The journal of the Satin engine: revm's journal, and the ledger of what the transaction's own -/// execution keeps. See the module documentation. -/// -/// It is the journal of every [`MegaContext`](crate::MegaContext). A node that names the -/// context's journal type names this one; one that reads revm's journal state reads it through the -/// dereference, and one that writes to it does so through [`JournalTr`]. -#[derive(Clone, Debug)] -pub struct MegaJournal { - /// revm's journal, which holds the state. - revm: Journal, - /// The ledger, kept in step with `revm`'s checkpoints. - ledger: Ledger, -} - -/// 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 -} - -impl MegaJournal { - /// The ledger. - pub(crate) const fn ledger(&self) -> &Ledger { - &self.ledger - } - - /// The ledger, mutably. - pub(crate) const fn ledger_mut(&mut self) -> &mut Ledger { - &mut self.ledger - } - - /// Consumes the journal and returns revm's. - pub(crate) fn into_revm(self) -> Journal { - self.revm - } - - /// Marks where the journal and the ledger stand, without changing the journal's depth. - pub(crate) fn mark(&mut self) -> Mark { - let position = self.revm.checkpoint(); - self.revm.checkpoint_commit(); - self.ledger.mark(position) - } - - /// Takes back every journal entry, log and self-destruct made since `mark`, as revm takes back - /// a frame that fails, and the ledger with them; the journal's depth is left as it is. - pub(crate) fn revert_to(&mut self, mark: &Mark) { - let _ = self.revm.checkpoint(); - self.revm.checkpoint_revert(mark.position); - self.ledger.revert_to(mark); - } - - /// Asserts the ledger holds a level for every checkpoint revm's journal holds open. - #[inline] - fn assert_levels(&self) { - debug_assert!( - self.ledger.depth() == self.revm.depth, - "the ledger holds one level per open checkpoint" - ); - } - - /* What a write changes */ - - /// 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<&Account> { - self.revm - .state - .get(&address) - .filter(|account| account.transaction_id == self.revm.transaction_id) - } - - /// Whether the transaction changed the account at `address` from what it loaded: its nonce, - /// balance or code differs from the account's original info, which revm sets at the account's - /// first load in the transaction. 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 transaction changed the account at `address` from what it loaded, before the - /// nonce bump revm just made on it: the creator of a creation, whose nonce revm bumps before - /// it asks for the creation's account checkpoint. - fn is_changed_before_bump(&self, address: Address) -> bool { - self.loaded(address).is_some_and(|account| { - let before = - AccountInfo { nonce: account.info.nonce.wrapping_sub(1), ..account.info.clone() }; - differs(&before, &account.original_info()) - }) - } - - /// How the record of the account at `address` moves when its balance becomes `balance`: a - /// record when the write changes an account the transaction had not changed, a record back when - /// it returns a changed one to what the transaction loaded. - fn balance_change(&self, address: Address, balance: U256) -> RecordDelta { - let Some(account) = self.loaded(address) else { - // An account the transaction has not loaded is unchanged, and a balance it did not - // hold changes it: what the transaction loads for it will be what the chain holds. - return RecordDelta::of_account(false, balance != U256::ZERO); - }; - let original = account.original_info(); - let after = AccountInfo { balance, ..account.info.clone() }; - RecordDelta::of_account(differs(&account.info, &original), differs(&after, &original)) - } - - /// The current balance of the account at `address`, as the transaction holds it; nothing for - /// one it 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: 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) -> RecordDelta { - if from == to || value.is_zero() { - return RecordDelta::NONE; - } - let Some(from_after) = self.balance(from).checked_sub(value) else { - return RecordDelta::NONE; - }; - let to_after = self.balance(to).saturating_add(value); - self.balance_change(from, from_after).with(self.balance_change(to, to_after)) - } - - /// The records a creation by `creator` with an endowment of `value` may make, for a charge made - /// before revm decides the start: the creator's nonce, when the bump changes an account the - /// transaction had not changed, and the account it creates, counted as a record whatever the - /// address held — the address a `CREATE2` lands on is not known before revm decides the - /// start, and the refund gives back the record when the creation made none. Nothing for an - /// endowment `creator` cannot fund, which revm refuses before it bumps the nonce. - pub(crate) fn creation_records(&self, creator: Address, value: U256) -> FrameStartRecords { - if self.balance(creator) < value { - return FrameStartRecords::NONE; - } - FrameStartRecords { - transfer: RecordDelta::NONE, - created: true, - creator: !self.is_changed(creator), - } - } - - /// The records the frame `start` makes, for the frame-start hook to charge its caller for: a - /// call's value transfer ([`transfer_records`](Self::transfer_records)), a creation's creator - /// nonce and, as an upper bound, its created account - /// ([`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. Nor does a start whose value the caller cannot fund, which revm refuses on the - /// caller's account. - pub(crate) fn start_records(&self, start: &FrameStart) -> FrameStartRecords { - match start.kind { - FrameStartKind::Create | FrameStartKind::Create2 => { - self.creation_records(start.caller, start.value) - } - FrameStartKind::Call | - FrameStartKind::CallCode | - FrameStartKind::DelegateCall | - FrameStartKind::StaticCall => { - FrameStartRecords::of_transfer(start.target.map_or(RecordDelta::NONE, |target| { - self.transfer_records(start.caller, target, start.value) - })) - } - } - } -} - -impl Deref for MegaJournal { - type Target = Journal; - - fn deref(&self) -> &Journal { - &self.revm - } -} - -#[deny(clippy::missing_trait_methods)] -impl JournalTr for MegaJournal { - type Database = DB; - type State = EvmState; - type JournaledAccount<'a> - = JournaledAccount<'a, DB, JournalEntry> - where - DB: 'a; - - fn new(database: DB) -> Self { - Self { revm: Journal::new(database), ledger: Ledger::default() } - } - - // Forwarded: reads, transient storage, the switches, account handles, and the writes the - // ledger does not count here. A write an opcode completed is counted by the Host's - // completed-write hook; any other is not the transaction's own execution. - delegate! { - to self.revm { - fn db_mut(&mut self) -> &mut DB; - fn db(&self) -> &DB; - fn evm_state_mut(&mut self) -> &mut EvmState; - fn evm_state(&self) -> &EvmState; - fn db_and_state(&self) -> (&DB, &EvmState); - fn db_and_state_mut(&mut self) -> (&mut DB, &mut EvmState); - fn sload( - &mut self, - address: Address, - key: StorageKey, - ) -> Result, DB::Error>; - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result, JournalLoadError>; - fn sstore( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - ) -> Result, DB::Error>; - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result, JournalLoadError>; - fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; - fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); - fn log(&mut self, log: Log); - fn take_logs(&mut self) -> Vec; - fn logs(&self) -> &[Log]; - fn warm_access_list(&mut self, access_list: AddressMap>); - fn warm_coinbase_account(&mut self, address: Address); - fn warm_precompiles(&mut self, addresses: &AddressSet); - fn precompile_addresses(&self) -> &AddressSet; - fn set_spec_id(&mut self, spec_id: SpecId); - fn set_eip7708_config(&mut self, disabled: bool, eip8246_delayed_clear_disabled: bool); - fn set_amsterdam_eip7708_enabled(&mut self, enabled: bool); - fn set_legacy_journal_semantics(&mut self, enabled: bool); - fn touch_account(&mut self, address: Address); - // A transfer that is not a frame start's: revm starts frames with `transfer_loaded`. - fn transfer( - &mut self, - from: Address, - to: Address, - balance: U256, - ) -> Result, DB::Error>; - #[allow(deprecated)] - fn caller_accounting_journal_entry( - &mut self, - address: Address, - old_balance: U256, - bump_nonce: bool, - ); - fn balance_incr(&mut self, address: Address, balance: U256) -> Result<(), DB::Error>; - #[allow(deprecated)] - fn nonce_bump_journal_entry(&mut self, address: Address); - fn load_account(&mut self, address: Address) -> Result, DB::Error>; - #[allow(deprecated)] - fn load_account_code( - &mut self, - address: Address, - ) -> Result, DB::Error>; - fn load_account_with_code( - &mut self, - address: Address, - ) -> Result, DB::Error>; - fn load_account_delegated( - &mut self, - address: Address, - ) -> Result, DB::Error>; - fn load_account_mut( - &mut self, - address: Address, - ) -> Result>, DB::Error>; - fn load_account_mut_skip_cold_load( - &mut self, - address: Address, - skip_cold_load: bool, - ) -> Result>, JournalLoadError>; - fn load_account_with_code_mut( - &mut self, - address: Address, - ) -> Result>, DB::Error>; - fn load_account_mut_optional_code( - &mut self, - address: Address, - load_code: bool, - ) -> Result>, DB::Error>; - fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256); - fn set_code(&mut self, address: Address, code: Bytecode); - fn code(&mut self, address: Address) -> Result, DB::Error>; - fn code_hash(&mut self, address: Address) -> Result, DB::Error>; - fn depth(&self) -> usize; - fn load_account_info_skip_cold_load( - &mut self, - address: Address, - load_code: bool, - skip_cold_load: bool, - ) -> Result, JournalLoadError>; - } - } - - /// Counted inside a call's start window: the records the transfer makes and takes back, as - /// the accounts it writes stand before and after it, and its transfer log. - fn transfer_loaded( - &mut self, - from: Address, - to: Address, - balance: U256, - ) -> Option { - let moves = from != to && !balance.is_zero(); - let before = moves.then(|| (self.is_changed(from), self.is_changed(to))); - let logs = self.revm.logs().len(); - let refused = self.revm.transfer_loaded(from, to, balance); - let logged = self.revm.logs().len() > logs; - let records = match before.filter(|_| refused.is_none()) { - Some((from_before, to_before)) => { - RecordDelta::of_account(from_before, self.is_changed(from)) - .with(RecordDelta::of_account(to_before, self.is_changed(to))) - } - None => RecordDelta::NONE, - }; - self.ledger.on_transfer(records, refused.is_some(), logged); - refused - } - - /// Counted inside a creation's start window: the creator's nonce record before the creation's - /// level opens, when the bump revm made changed an account the transaction had not changed, - /// then, on the creation's level, the created account's record, when the creation changes an - /// account the transaction had not changed, and the transfer log. - fn create_account_checkpoint( - &mut self, - caller: Address, - address: Address, - balance: U256, - spec_id: SpecId, - ) -> Result { - let start = self.ledger.before_creation(!self.is_changed_before_bump(caller)); - let created_unchanged = !self.is_changed(address); - let logs = self.revm.logs().len(); - let opened = self.revm.create_account_checkpoint(caller, address, balance, spec_id); - let logged = self.revm.logs().len() > logs; - self.ledger.after_creation(start, opened.ok(), created_unchanged, logged); - self.assert_levels(); - opened - } - - /// Observed for the completed-write hook: the records the destruction makes and takes back, as - /// the destructed account and its beneficiary stand before and after the move. The hook counts - /// them once the opcode completed; the write itself counts nothing here. - fn selfdestruct( - &mut self, - address: Address, - target: Address, - skip_cold_load: bool, - ) -> Result, JournalLoadError> { - let before = (self.is_changed(address), self.is_changed(target)); - let result = self.revm.selfdestruct(address, target, skip_cold_load); - let records = if result.is_ok() { - RecordDelta::of_account(before.0, self.is_changed(address)) - .with(RecordDelta::of_account(before.1, self.is_changed(target))) - } else { - RecordDelta::NONE - }; - self.ledger.observe_destruction(records); - result - } - - fn checkpoint(&mut self) -> JournalCheckpoint { - let checkpoint = self.revm.checkpoint(); - self.ledger.on_checkpoint(checkpoint); - self.assert_levels(); - checkpoint - } - - fn checkpoint_commit(&mut self) { - self.revm.checkpoint_commit(); - self.ledger.on_commit(); - self.assert_levels(); - } - - fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) { - self.revm.checkpoint_revert(checkpoint); - self.ledger.on_revert(checkpoint); - self.assert_levels(); - } - - fn commit_tx(&mut self) { - self.revm.commit_tx(); - self.ledger.on_transaction_end(); - } - - fn discard_tx(&mut self) { - self.revm.discard_tx(); - self.ledger.on_transaction_end(); - } - - fn finalize(&mut self) -> EvmState { - let state = self.revm.finalize(); - self.ledger.on_transaction_end(); - state - } - - /// The trait's own default: it finalizes through the hooked `finalize`. - fn clear(&mut self) { - let _ = self.finalize(); - } -} - -impl JournalExt for MegaJournal { - /// revm's own journal entries. - #[inline] - fn journal(&self) -> &[JournalEntry] { - JournalExt::journal(&self.revm) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - limit::{HistoryBytes, Mark, StartFacts, StartReport, StartSide}, - test_utils::MemoryDatabase, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, - }; - use alloy_primitives::address; - use revm::{ - context_interface::journaled_state::account::JournaledAccountTr, - primitives::Log as PrimitiveLog, - }; - - const SENDER: Address = address!("00000000000000000000000000000000000a0001"); - /// The transaction's own frame. - const A: Address = address!("00000000000000000000000000000000000a0002"); - const B: Address = address!("00000000000000000000000000000000000a0003"); - const C: Address = address!("00000000000000000000000000000000000a0004"); - /// The account a creation makes. - const CREATED: Address = address!("00000000000000000000000000000000000a0005"); - - /// What a start's records and transfer log weigh: `records` write records, and the log when it - /// `moves` value. - const fn start_bytes(records: u64, moves: bool) -> u64 { - records * WRITE_RECORD_SIZE + if moves { TRANSFER_LOG_SIZE } else { 0 } - } - - /// What a caller pays for `records` write records at the history price in effect, as the - /// frame-start hook charges them: nothing at a price of nothing. - fn record_charge(records: u64) -> u64 { - crate::write_record_history_gas(records).unwrap_or(0) - } - - /// The transaction's bytes before any frame: the body. - const fn body() -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } - } - - /// `records` write records and `logs` transfer logs on top of the body. - const fn kept(records: u64, logs: u64) -> LimitUsage { - LimitUsage { - data_size: TX_BODY_SIZE + records * WRITE_RECORD_SIZE + logs * TRANSFER_LOG_SIZE, - write_records: records, - } - } - - /// A journal on Satin's base spec, with transfer logs, every account funded, holding a - /// transaction from [`SENDER`] under `limits`. The sender is changed as validation leaves it: - /// its nonce bumped. - fn journal(limits: EvmTxRuntimeLimits) -> MegaJournal { - let db = [SENDER, A, B, C].into_iter().fold(MemoryDatabase::default(), |db, account| { - db.account_balance(account, U256::from(10)) - }); - let mut journal = MegaJournal::new(db); - journal.set_spec_id(SpecId::OSAKA); - journal.set_amsterdam_eip7708_enabled(true); - for account in [SENDER, A, B, C, CREATED] { - journal.load_account(account).unwrap(); - } - let _ = journal.load_account_mut(SENDER).unwrap().data.bump_nonce(); - journal.ledger_mut().set_limits(limits); - journal.ledger_mut().begin_transaction(false, true, TX_BODY_SIZE); - journal - } - - /// Starts a call from `caller` to `target` at `depth` as revm starts one: its checkpoint, then - /// its value transfer. Returns the frame's checkpoint and what the start counted. - fn start_call( - journal: &mut MegaJournal, - depth: usize, - caller: Address, - target: Address, - value: u64, - ) -> (JournalCheckpoint, StartReport) { - let value = U256::from(value); - let facts = StartFacts { depth, creation: false, transfers_value: !value.is_zero() }; - journal.ledger_mut().open_start(facts); - let checkpoint = journal.checkpoint(); - assert!(journal.transfer_loaded(caller, target, value).is_none()); - (checkpoint, journal.ledger_mut().close_start()) - } - - /// Starts a creation of `created` from `creator` at `depth` as revm starts one: the nonce - /// bump, then the account checkpoint. - fn start_creation( - journal: &mut MegaJournal, - depth: usize, - creator: Address, - created: Address, - value: u64, - ) -> (JournalCheckpoint, StartReport) { - let value = U256::from(value); - let facts = StartFacts { depth, creation: true, transfers_value: !value.is_zero() }; - journal.ledger_mut().open_start(facts); - let _ = journal.load_account_mut(creator).unwrap().data.bump_nonce(); - let checkpoint = - journal.create_account_checkpoint(creator, created, value, SpecId::OSAKA).unwrap(); - (checkpoint, journal.ledger_mut().close_start()) - } - - /// Returns from the running frame as revm does: its level closes, committed or reverted to - /// `failed`'s checkpoint. - fn end_frame(journal: &mut MegaJournal, failed: Option) { - journal.ledger_mut().frame_returning(); - match failed { - Some(checkpoint) => journal.checkpoint_revert(checkpoint), - None => journal.checkpoint_commit(), - } - } - - /// The journal's own write methods count nothing, inside a frame start's window and outside - /// it: a write an opcode completed is counted by the Host's completed-write hook, and any other - /// is not the transaction's own execution. A `SELFDESTRUCT` is observed for that hook, and - /// counts nothing until the hook counts it. - #[test] - fn test_the_journals_own_writes_count_nothing() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let writes = |journal: &mut MegaJournal| { - journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); - journal.sstore_skip_cold_load(A, U256::from(2), U256::from(1), false).unwrap(); - journal.log(PrimitiveLog::new_unchecked(A, Vec::new(), Bytes::new())); - assert_eq!(journal.transfer(A, B, U256::from(1)).unwrap(), None); - journal.selfdestruct(C, B, false).unwrap(); - }; - let _ = start_call(&mut journal, 0, SENDER, A, 0); - writes(&mut journal); - assert_eq!(journal.ledger().usage(), body(), "outside a start's window"); - - journal.ledger_mut().open_start(StartFacts { - depth: 1, - creation: false, - transfers_value: false, - }); - let _ = journal.checkpoint(); - writes(&mut journal); - let _ = journal.ledger_mut().close_start(); - assert_eq!(journal.ledger().usage(), body(), "inside a start's window"); - assert!(!journal.logs().is_empty(), "the writes reached revm's journal"); - } - - /// Every configuration switch reaches revm's journal: a switch kept at the trait's no-op - /// default would turn a journal feature off without a word. - #[test] - fn test_the_switches_reach_revms_journal() { - let mut mega = MegaJournal::new(MemoryDatabase::default()); - let mut plain: Journal = Journal::new(MemoryDatabase::default()); - let precompiles = AddressSet::from_iter([A]); - let access_list = AddressMap::from_iter([(B, HashSet::from_iter([U256::from(1)]))]); - for (spec, flag) in [(SpecId::OSAKA, true), (SpecId::CANCUN, false)] { - mega.set_spec_id(spec); - plain.set_spec_id(spec); - mega.set_eip7708_config(flag, !flag); - plain.set_eip7708_config(flag, !flag); - mega.set_amsterdam_eip7708_enabled(flag); - plain.set_amsterdam_eip7708_enabled(flag); - mega.set_legacy_journal_semantics(flag); - plain.set_legacy_journal_semantics(flag); - mega.warm_coinbase_account(C); - plain.warm_coinbase_account(C); - mega.warm_precompiles(&precompiles); - plain.warm_precompiles(&precompiles); - mega.warm_access_list(access_list.clone()); - plain.warm_access_list(access_list.clone()); - assert_eq!(mega.inner.cfg, plain.inner.cfg, "{spec:?}"); - assert_eq!(mega.inner.warm_addresses, plain.inner.warm_addresses, "{spec:?}"); - assert_eq!(mega.precompile_addresses(), plain.precompile_addresses()); - } - } - - /// `JournalExt::journal` hands out revm's own entries, the ones an inspector reads after a - /// write. - #[test] - fn test_the_journal_extension_hands_out_revms_entries() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); - let entries = JournalExt::journal(&journal); - assert!(!entries.is_empty()); - assert_eq!(entries, JournalExt::journal(&*journal), "revm's own"); - } - - /// An ordinary method call on the journal is the journal's own trait method, not one of revm's - /// journal reached through the dereference: a checkpoint opened and reverted with method syntax - /// opens and closes a level of the ledger, and the extension's entries are revm's. - #[test] - fn test_an_ordinary_method_call_is_the_journals_own() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let checkpoint = journal.checkpoint(); - assert_eq!(journal.ledger().depth(), 1, "the ledger saw the checkpoint"); - journal.sstore(A, U256::from(1), U256::from(1)).unwrap(); - assert_eq!(journal.journal().len(), journal.revm.journal.len()); - journal.checkpoint_revert(checkpoint); - assert_eq!((journal.ledger().depth(), journal.depth()), (0, 0)); - } - - /// The ledger holds a level for every checkpoint revm's journal holds open: a commit closes - /// one and keeps what was counted inside it, a revert closes one and takes it back, and - /// `clear`, the trait's default, closes them all through `finalize`. - #[test] - fn test_the_levels_follow_revms_checkpoints() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let (checkpoint, _) = start_call(&mut journal, 1, A, B, 1); - assert_eq!((journal.ledger().depth(), journal.depth()), (2, 2)); - assert_eq!(journal.ledger().usage(), kept(2, 1), "B's record, A's, and the transfer log"); - end_frame(&mut journal, Some(checkpoint)); - assert_eq!((journal.ledger().depth(), journal.depth()), (1, 1)); - assert_eq!(journal.ledger().usage(), body(), "the revert takes the start back"); - - let _ = start_call(&mut journal, 1, A, B, 1); - end_frame(&mut journal, None); - assert_eq!(journal.ledger().usage(), kept(2, 1), "the commit keeps it"); - let _ = journal.checkpoint(); - journal.clear(); - assert_eq!((journal.ledger().depth(), journal.depth()), (0, 0)); - assert_eq!(journal.ledger().usage(), kept(2, 1), "readable until the next transaction"); - } - - /// An account is changed once its nonce, balance or code differs from what the transaction - /// loaded, and unchanged again once a write returns it; one the transaction has not loaded is - /// unchanged. The sender is changed from the start, by the nonce validation bumped. - #[test] - fn test_an_account_is_changed_while_its_info_differs_from_what_was_loaded() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - assert!(journal.is_changed(SENDER), "validation bumped its nonce"); - assert!(!journal.is_changed(A)); - assert!( - !journal.is_changed(address!("00000000000000000000000000000000000a00ff")), - "not loaded" - ); - assert_eq!(journal.transfer(A, B, U256::from(3)).unwrap(), None); - assert!(journal.is_changed(A) && journal.is_changed(B)); - assert_eq!(journal.transfer(B, A, U256::from(3)).unwrap(), None); - assert!(!journal.is_changed(A) && !journal.is_changed(B), "both returned"); - let _ = journal.load_account_mut(A).unwrap().data.bump_nonce(); - assert!(journal.is_changed(A), "a nonce bump changes it"); - assert!(!journal.is_changed_before_bump(A), "but not before the bump"); - journal.set_code(B, Bytecode::new_raw(Bytes::from_static(&[0x00]))); - assert!(journal.is_changed(B), "code changes it"); - } - - /// The records a transfer makes are predicted from the journal's state as the hook sees it and - /// counted as revm makes the transfer, and the two agree: a transfer that changes both - /// accounts, one whose sender the transaction changed, one that returns an account, and the - /// moves that make none — to the same account, of nothing, of more than the sender holds. - #[test] - fn test_the_records_predicted_for_a_transfer_are_the_records_counted() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let none = RecordDelta::NONE; - let both = RecordDelta { added: 2, taken: 0 }; - let recipient = RecordDelta { added: 1, taken: 0 }; - assert_eq!(journal.transfer_records(A, A, U256::from(1)), none, "to itself"); - assert_eq!(journal.transfer_records(A, B, U256::ZERO), none, "of nothing"); - assert_eq!(journal.transfer_records(A, B, U256::from(11)), none, "unfunded"); - assert_eq!(journal.transfer_records(SENDER, B, U256::from(1)), recipient, "the sender"); - assert_eq!(journal.transfer_records(A, B, U256::from(1)), both); - - let (_, report) = start_call(&mut journal, 1, A, B, 1); - assert_eq!(report.records.transfer, both, "counted as predicted"); - end_frame(&mut journal, None); - assert_eq!( - journal.transfer_records(B, A, U256::from(1)), - RecordDelta { added: 0, taken: 2 }, - "the return takes both back" - ); - assert_eq!( - journal.transfer_records(B, C, U256::from(1)), - RecordDelta { added: 1, taken: 1 }, - "B returns, C changes" - ); - let (_, report) = start_call(&mut journal, 1, B, A, 1); - assert_eq!(report.records.transfer, RecordDelta { added: 0, taken: 2 }); - assert_eq!(journal.ledger().usage(), kept(0, 2), "the records went, the logs stay"); - } - - /// A tool's checkpoint around a call's start — opened before the start, closed after the frame - /// returned — is a rollback level the frame's level sits above. Committed, it changes nothing: - /// the frame's records stand, its refund is none, and its caller's account stays changed, so a - /// later value call from it records only its recipient. Reverted, it takes back what the frame - /// kept: the records and the frame's refund all go back to before the start, and the later - /// call finds the caller unchanged and records it again. - /// - /// The caller paid for the start's two records at the price in effect, as the frame-start hook - /// charges them, so the refund holds at any history byte price, a price of nothing included. - #[test] - fn test_a_tool_checkpoint_around_a_call_closes_in_order() { - let charge = record_charge(2); - for reverted in [false, true] { - let case = if reverted { "reverted" } else { "committed" }; - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let tool = journal.checkpoint(); - let (_, report) = start_call(&mut journal, 1, A, B, 1); - assert_eq!( - (report.records.transfer, report.transfer_log), - (RecordDelta { added: 2, taken: 0 }, true), - "{case}: B's record, A's, and the log" - ); - end_frame(&mut journal, None); - let mut side = StartSide::new(1, charge, 0, true, None); - side.attach(report, None); - if reverted { - journal.checkpoint_revert(tool); - } else { - journal.checkpoint_commit(); - } - let refund = if reverted { charge } else { 0 }; - assert_eq!(side.refund(journal.ledger()), refund, "{case}: B's refund"); - assert_eq!(journal.ledger().usage(), if reverted { body() } else { kept(2, 1) }); - - let (_, later) = start_call(&mut journal, 1, A, C, 1); - let records = if reverted { 2 } else { 1 }; - assert_eq!(later.records.transfer.added, records, "{case}: A's account"); - end_frame(&mut journal, None); - let records = if reverted { 2 } else { 3 }; - assert_eq!(journal.ledger().usage(), kept(records, if reverted { 1 } else { 2 })); - } - } - - /// A tool's checkpoint around a creation's start closes in order as one around a call does, and - /// a revert of it takes back the creator's nonce record with the rest, which the creation's own - /// failure leaves: the creator's caller gets back the charge for that record too, and the - /// creator's account is unchanged again, so its next creation records it. - /// - /// The caller paid one record's price for the created account and one for the creator's nonce, - /// at the price in effect, as the frame-start hook charges them, so the refunds hold at any - /// history byte price, a price of nothing included. - #[test] - fn test_a_tool_checkpoint_around_a_creation_takes_its_creators_record_back() { - let (created, creator) = (record_charge(1), record_charge(1)); - for (case, failed, reverted, refund, creator_changed) in [ - ("a creation that succeeds, the tool's checkpoint committed", false, false, 0, true), - ("a creation that fails, the tool's checkpoint committed", true, false, created, true), - ( - "a creation that succeeds, the tool's checkpoint reverted", - false, - true, - created + creator, - false, - ), - ( - "a creation that fails, the tool's checkpoint reverted", - true, - true, - created + creator, - false, - ), - ] { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let _ = start_call(&mut journal, 1, A, B, 0); - let tool = journal.checkpoint(); - let (checkpoint, report) = start_creation(&mut journal, 2, B, CREATED, 1); - assert!(report.records.creator, "{case}: B's nonce record is the start's"); - end_frame(&mut journal, failed.then_some(checkpoint)); - let mut side = StartSide::new(2, created, creator, true, None); - side.attach(report, None); - if reverted { - journal.checkpoint_revert(tool); - } else { - journal.checkpoint_commit(); - } - assert_eq!(side.refund(journal.ledger()), refund, "{case}: the refund"); - let (_, later) = start_creation(&mut journal, 2, B, C, 0); - assert_eq!(!later.records.creator, creator_changed, "{case}: B's account"); - } - } - - /// A revert that would close a level from below — a checkpoint taken before a frame started, - /// reverted while the frame still runs — is not supported, and trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "a revert closes the latest level")] - fn test_a_revert_below_a_running_frame_trips() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let tool = journal.checkpoint(); - let _ = start_call(&mut journal, 1, A, B, 1); - journal.checkpoint_revert(tool); - } - - /// A creation's creator nonce record is the creating frame's, counted on its level before the - /// creation's budget is taken from what it has left: with `R` bytes left to an unchanged - /// creator, the record leaves it `R − 40`, the creation gets `(R − 40) − ⌈(R − 40) / 50⌉`, and - /// starts with the created account's record alone, 40 bytes. At 81 bytes that is a budget of - /// 40, which the start fills exactly; at 100, a budget of 58, which leaves the creation 18 - /// bytes. An endowment adds its transfer log to the start. - /// - /// Before the creator's record moved to the creating frame, the creation's budget was taken - /// from `R` and its usage was measured from before the record: a budget of 79 against 80 bytes - /// at 81, which the start crossed, and of 98 against 80 at 100, the same 18 bytes left. - #[test] - fn test_a_creation_is_budgeted_after_its_creators_record() { - let log = TRANSFER_LOG_SIZE; - for (left, value, budget) in - [(81, 0, 40), (100, 0, 58), (81 + log, 1, 196), (100 + log, 1, 215)] - { - let start = start_bytes(1, value != 0); - let limits = - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + left); - let mut journal = journal(limits); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let (_, report) = start_creation(&mut journal, 1, A, CREATED, value); - let case = format!("{left} bytes left, value {value}"); - assert!(report.records.creator, "{case}: the creator's record is the start's"); - let used = LimitUsage { data_size: start, write_records: 1 }; - assert_eq!(journal.ledger().running_budget(), Some((budget, used)), "{case}"); - assert_eq!( - journal.ledger().usage(), - kept(2, u64::from(value != 0)), - "{case}: the creator's record is counted, below the creation's level" - ); - let verdict = if start > budget { - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: budget, - used: start, - frame_local: true, - } - } else { - LimitCheck::WithinLimit - }; - assert_eq!(report.verdict, Some(verdict), "{case}"); - } - } - - /// A creation records the account it creates as every counted write records an account: when - /// the creation changes an account the transaction had not changed. An address a transfer - /// funded is changed already, and the creation adds no record for it, however it then changes - /// it. The records the frame-start hook charges from count the account for every creation, the - /// address not being known there. - #[test] - fn test_a_creation_records_its_account_by_the_net_change() { - for funded in [false, true] { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - if funded { - let _ = start_call(&mut journal, 1, A, CREATED, 1); - end_frame(&mut journal, None); - } - let charged = journal.creation_records(B, U256::from(1)); - assert_eq!( - charged, - FrameStartRecords { transfer: RecordDelta::NONE, created: true, creator: true }, - "funded {funded}: charged for the created account and B's nonce" - ); - let (_, report) = start_creation(&mut journal, 1, B, CREATED, 1); - assert_eq!( - report.records, - FrameStartRecords { transfer: RecordDelta::NONE, created: !funded, creator: true }, - "funded {funded}: the created account is counted where the creation changed it" - ); - let (records, logs) = if funded { (3, 2) } else { (2, 1) }; - assert_eq!(journal.ledger().usage(), kept(records, logs), "funded {funded}"); - assert!(journal.is_changed(CREATED), "funded {funded}: the creation changed it"); - } - } - - /// A creation's start mark is its level's opening, after the creator's record: a creation - /// rewritten into a failure is taken back to it, and keeps its creator's record, as a creation - /// that fails does, the creator's nonce standing. - #[test] - fn test_a_creations_start_mark_keeps_its_creators_record() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let (checkpoint, _) = start_creation(&mut journal, 1, A, CREATED, 1); - let mark: Mark = journal.ledger().frame_start_mark().expect("the creation's level is open"); - assert_eq!(mark.position, checkpoint, "the creation's own checkpoint"); - end_frame(&mut journal, None); - assert_eq!(journal.ledger().usage(), kept(2, 1)); - - journal.revert_to(&mark); - assert_eq!(journal.ledger().usage(), kept(1, 0), "the creator's record stays"); - let (_, later) = start_creation(&mut journal, 1, A, C, 0); - assert!(!later.records.creator, "A stays changed"); - } - - /// The hypothetical start a call gas detention answers without running is held to the limits - /// as the start revm would have made: the same records, the transfer log of the value it moves, - /// the same budget. - #[test] - fn test_a_hypothetical_start_is_held_as_the_start_revm_makes() { - // A value call one frame down records its recipient and its caller; the transaction's own - // frame records its recipient alone. - let (below, own) = (start_bytes(2, true), start_bytes(1, true)); - for (depth, value, room) in - [(1, 1, below - 1), (1, 1, below), (1, 0, 0), (0, 1, own - 1), (0, 1, own)] - { - let limits = - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + room); - let mut journal = journal(limits); - let caller = if depth == 0 { - SENDER - } else { - let _ = start_call(&mut journal, 0, SENDER, A, 0); - A - }; - let records = journal.transfer_records(caller, B, U256::from(value)); - let logged = journal.ledger().counts_transfer_logs() && value != 0; - let hypothetical = journal.ledger().hypothetical_start(records, logged); - let (_, report) = start_call(&mut journal, depth, caller, B, value); - assert_eq!(Some(hypothetical), report.verdict, "depth {depth}, value {value}, {room}"); - } - } - - /// A `SELFDESTRUCT` is observed for the completed-write hook as its move leaves the two - /// accounts: the destructed account, whose balance it clears, and the beneficiary. A - /// beneficiary the transaction gave its balance is returned by the move; a destruction to - /// itself, of an account the transaction did not create, moves nothing. - #[test] - fn test_a_destruction_is_observed_for_the_hook() { - let mut journal = journal(EvmTxRuntimeLimits::no_limits()); - let _ = start_call(&mut journal, 0, SENDER, A, 0); - let records = |journal: &mut MegaJournal, from, to| { - journal.selfdestruct(from, to, false).unwrap(); - journal.ledger().write_count( - &revm::context_interface::host::CompletedWrite::SelfDestruct { - address: from, - target: to, - balance: U256::ZERO, - result: &SelfDestructResult { had_value: true, ..Default::default() }, - }, - ) - }; - let (count, history) = records(&mut journal, A, B); - assert_eq!( - count.added, - LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 2 } - ); - assert_eq!(count.taken, LimitUsage::ZERO); - assert_eq!(history, HistoryBytes { appended: 2 * WRITE_RECORD_SIZE, taken: 0 }); - - // C gives three of its ten to an account that holds nothing, which destructs back to C: - // both are as the transaction loaded them again. - assert_eq!(journal.transfer(C, CREATED, U256::from(3)).unwrap(), None); - let (count, history) = records(&mut journal, CREATED, C); - assert_eq!(count.added, LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }); - assert_eq!(count.taken, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); - assert_eq!(history, HistoryBytes { appended: 0, taken: 2 * WRITE_RECORD_SIZE }); - - let (count, _) = records(&mut journal, C, C); - assert_eq!(count.added, LimitUsage::ZERO, "a destruction to itself moves nothing"); - assert_eq!(count.taken, LimitUsage::ZERO); - } -} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 4d60c1f36..b43f79e7d 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -13,7 +13,6 @@ mod history; mod host; mod inspector; mod instructions; -mod journal; mod precompiles; mod prices; mod result; @@ -27,7 +26,6 @@ pub use execution::*; pub use factory::*; pub use frame::*; pub use history::*; -pub use journal::*; pub use precompiles::*; pub use prices::*; pub use result::*; @@ -258,7 +256,7 @@ 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 journal's ledger counted, the limit + /// 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( diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index aeee47ad7..1e4cc758b 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -46,19 +46,16 @@ #[cfg(not(feature = "std"))] use alloc as std; -use std::{ - string::{String, ToString}, - sync::Arc, -}; +use std::{string::String, sync::Arc}; use alloy_evm::{ - precompiles::{DynPrecompile, Precompile as _, PrecompileInput, PrecompilesMap}, - Database, EvmInternals, + precompiles::{DynPrecompile, Precompile as _, PrecompilesMap}, + Database, }; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ - context::{BlockEnv, CfgEnv, ContextTr}, - handler::{precompile_output_to_interpreter_result, PrecompileProvider}, + context::{BlockEnv, CfgEnv}, + handler::PrecompileProvider, interpreter::{CallInputs, InterpreterResult}, precompile::Precompiles, primitives::{Address, AddressSet, HashMap, OnceLock}, @@ -191,18 +188,16 @@ pub mod kzg_point_evaluation { .with_required_gas(required_gas); } -/// The plain revm context over revm's own journal, the one alloy-evm implements the provider for. -type RevmJournalContext = +/// 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`]. -/// -/// alloy-evm implements the provider for revm's plain context over revm's own journal, and the -/// context [`MegaContext`] wraps runs on the Satin journal ([`MegaJournal`](crate::MegaJournal)), -/// so `run` is alloy-evm's own, on that journal: the precompile gets the call's input and an -/// [`EvmInternals`] over the journal, and its output is turned into the call's result the way -/// revm turns any precompile's. A precompile's writes through [`EvmInternals`] reach the journal -/// as any tool's do, and the journal counts none of them. +/// 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 { @@ -221,36 +216,19 @@ impl PrecompileProvider, inputs: &CallInputs, ) -> Result, String> { - let Some(precompile) = self.get(&inputs.bytecode_address) else { - return Ok(None); - }; - let (block, tx, cfg, journal, _, local) = context.inner.all_mut(); - let output = precompile - .call(PrecompileInput { - data: inputs.input.as_bytes_local(local).as_ref(), - gas: inputs.gas_limit, - reservoir: inputs.reservoir, - caller: inputs.caller, - value: inputs.call_value(), - is_static: inputs.is_static, - internals: EvmInternals::new(journal, block, cfg, tx), - target_address: inputs.target_address, - bytecode_address: inputs.bytecode_address, - }) - .map_err(|error| error.to_string())?; - Ok(Some(precompile_output_to_interpreter_result(output, inputs.gas_limit))) + 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) } } @@ -322,71 +300,6 @@ mod tests { .expect("the address is a precompile") } - /// The provider on the Satin journal runs a precompile as alloy-evm's provider runs it on - /// revm's own journal: for every entry of the Satin set, and for a node's own precompiles that - /// succeed, log, write through `EvmInternals`, revert and fail fatally, and for an address with - /// no precompile, the two give the same answer and leave the same logs and the same state. - #[test] - fn test_the_provider_runs_a_precompile_as_alloy_evms_does() { - use alloy_primitives::{address, Log, LogData}; - use revm::{context::JournalTr, precompile::PrecompileError}; - const SUCCEEDS: Address = address!("00000000000000000000000000000000000e0001"); - const LOGS: Address = address!("00000000000000000000000000000000000e0002"); - const WRITES: Address = address!("00000000000000000000000000000000000e0003"); - const REVERTS: Address = address!("00000000000000000000000000000000000e0004"); - const FATAL: Address = address!("00000000000000000000000000000000000e0005"); - const MISSING: Address = address!("00000000000000000000000000000000000e00ff"); - let own = |address: Address| { - DynPrecompile::new(PrecompileId::Custom("own".into()), move |mut input| { - let ok = |gas| Ok(PrecompileOutput::new(gas, Bytes::from_static(b"ok"), 0)); - match address { - SUCCEEDS => ok(10), - LOGS => { - let data = LogData::new_unchecked(Vec::new(), input.data.to_vec().into()); - input.internals.log(Log { address, data }); - ok(20) - } - WRITES => { - input.internals.sstore(address, U256::from(1), U256::from(2)).unwrap(); - ok(30) - } - REVERTS => Ok(PrecompileOutput::revert(5, Bytes::from_static(b"no"), 0)), - _ => Err(PrecompileError::Fatal("broken".into())), - } - }) - }; - let mut map = satin_precompiles_map(); - for address in [SUCCEEDS, LOGS, WRITES, REVERTS, FATAL] { - map.apply_precompile(&address, |_| Some(own(address))); - } - let addresses = satin_precompiles() - .addresses() - .copied() - .chain([SUCCEEDS, LOGS, WRITES, REVERTS, FATAL, MISSING]); - for address in addresses { - for input in [Bytes::new(), Bytes::from(std::vec![1; 192])] { - let inputs = inputs(address, input, 1_000_000); - let mut mega = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let mut plain: RevmJournalContext = - Context::new(MemoryDatabase::default(), OpSpecId::KARST) - .with_cfg(mega.cfg().clone()); - let ours = map.clone().run(&mut mega, &inputs); - let theirs = PrecompileProvider::>::run( - &mut map.clone(), - &mut plain, - &inputs, - ); - assert_eq!(ours, theirs, "{address}: the answer"); - assert_eq!(mega.journal_ref().logs(), plain.journal_ref().logs(), "{address}"); - assert_eq!(mega.journal_ref().state, plain.journal_ref().state, "{address}"); - } - } - assert_eq!( - PrecompileProvider::>::warm_addresses(&map), - PrecompileProvider::>::warm_addresses(&map), - ); - } - /// A valid proof costs the `MegaETH` price and returns the field parameters. #[test] fn test_kzg_precompile_sufficient_gas() { diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 793908eac..0d84db3ca 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,14 +2,19 @@ //! //! 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 three 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 [`STORAGE_CALL_STIPEND_BYTES`]; +//! 3. the share of its caller's data-size budget a frame starts with +//! ([`FRAME_BYTES_FORWARD_PERCENT`]): upstream forwards the whole byte pool, and Satin forwards +//! 98 per cent of what the caller has left. //! //! 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 @@ -37,7 +42,13 @@ use revm::{ primitives::{eip8037, hardfork::SpecId, OnceLock}, }; -use crate::evm::prices::{active_satin_prices, SatinPrices}; +use crate::{ + evm::{ + history::STORAGE_CALL_STIPEND_BYTES, + prices::{active_satin_prices, SatinPrices}, + }, + limit::{FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR}, +}; /// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte /// price. @@ -62,7 +73,21 @@ 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 ([`storage_call_stipend`](crate::storage_call_stipend)). +pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[ + (GasId::code_deposit_history_gas, 1), + (GasId::call_history_allowance, STORAGE_CALL_STIPEND_BYTES), +]; + +/// The share of its caller's byte pool, in per cent, a frame starts with: its data-size budget, +/// [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what the caller has left. +/// revm's forward of the pool rounds the share down, as the budget's rule does. +pub(crate) const FRAME_BYTES_FORWARD_PERCENT: u64 = + FRAME_DATA_SHARE_NUMERATOR * 100 / FRAME_DATA_SHARE_DENOMINATOR; +const _: () = + assert!((FRAME_DATA_SHARE_NUMERATOR * 100).is_multiple_of(FRAME_DATA_SHARE_DENOMINATOR)); /// The Satin gas schedule at the prices in effect. /// @@ -87,7 +112,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 +136,7 @@ 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::bytes_forward_percent(), FRAME_BYTES_FORWARD_PERCENT)]); params } @@ -143,7 +169,8 @@ 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::bytes_forward_percent(); if rebuilt { continue; } @@ -218,22 +245,50 @@ 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 budget, which + /// revm forwards at every frame start as the schedule's share of the byte pool, 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_pool() { + let satin = satin_gas_params(); + assert_eq!(satin.get(GasId::bytes_forward_percent()), 98); + assert_eq!(amsterdam().get(GasId::bytes_forward_percent()), 100); + 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.bytes_forward_share(pool), floor, "{pool}"); + } + } + + /// The history allowance a value-transferring call gives the frame it starts is + /// [`STORAGE_CALL_STIPEND_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_storage_call_stipend() { + let id = GasId::call_history_allowance(); + assert_eq!(satin_gas_params().get(id), crate::storage_call_stipend()); + 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 +339,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/lib.rs b/crates/mega-evm/src/lib.rs index 7b7c5cb87..3fb541f9d 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -52,8 +52,8 @@ pub use evm::{ 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, DynPrecompilesBuilder, EthSpecId, IntrinsicGas, - MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, MegaJournal, - MegaSpecId, MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, + MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, MegaSpecId, + MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, SatinPriceError, SatinPrices, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, SYSTEM_CALL_REGULAR_GAS_LIMIT, diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs deleted file mode 100644 index 8f1b27b39..000000000 --- a/crates/mega-evm/src/limit/ledger.rs +++ /dev/null @@ -1,1529 +0,0 @@ -//! The journal's ledger: what the transaction's own execution keeps, counted at the journal's -//! writes and rewound with the journal's checkpoints. -//! -//! The ledger lives in [`MegaJournal`](crate::MegaJournal), beside revm's journal, and keeps one -//! level per checkpoint revm's journal holds open. A revert restores the counts the level saw when -//! it opened, so what the ledger holds is what the journal keeps, whoever reverted what: revm for a -//! frame that fails, Satin for a stop, a tool for a checkpoint of its own. -//! -//! # Frame levels and rollback levels -//! -//! A checkpoint opens one of two kinds of level: -//! -//! - a **frame level**, for each frame revm starts: the first checkpoint revm opens while it -//! decides a call's start, or the one a creation's account checkpoint returns. Only the engine's -//! start window ([`open_start`](Ledger::open_start)) opens one. It carries the frame's data-size -//! budget; -//! - a **rollback level**, for every other checkpoint: the pre-execution phase's, a system call's, -//! a precompile's, a tool's. It carries what its revert restores and nothing else. -//! -//! Budgets and the running frame's check use the nearest frame level. A rollback level may enclose -//! a frame start (a tool's checkpoint opened before a call and closed after it) as long as the two -//! close in order. A revert that would close a level from below — a checkpoint reverted while a -//! level opened after it is still open — is not supported, and trips in debug builds. -//! -//! # What is counted where -//! -//! An account's write record follows the net change of its info within the transaction: the -//! journal tells the ledger, at each write, which accounts the write changed from what the -//! transaction loaded and which it returned to that ([`RecordDelta`]), and the ledger counts a -//! record for the first and takes one back for the second. A storage slot's record follows the -//! slot's original value the same way. So: -//! -//! - the body and the Oracle hints, as the ledger's base, which no revert takes back; -//! - the records of the applied EIP-7702 authorities, inside the pre-execution level; -//! - a frame start's records and its transfer log, inside the start window, at the two writes revm -//! makes for the start: a call's value transfer, and a creation's account checkpoint. A -//! creation's creator nonce record is the creating frame's: counted on its level before the -//! creation's budget is taken from what it has left, so the creation's failure leaves it with the -//! creator, and the creator is held to its own budget with it; -//! - a completed write's record, on the running frame's level, fed by the Host's completed-write -//! hook; -//! - deployed code, on the creation's level before revm commits it. -//! -//! Nothing a tool or a precompile writes through the journal is counted: the journal's own write -//! methods count nothing, and the start window is open only while revm decides a start. -//! -//! The ledger takes every decision: the counts, the frame budgets, the start verdicts, the -//! refunds of the history a caller paid for a start's records, and the check of a caller its child -//! returns into. Satin's side of each frame start ([`StartSide`]) — what its caller paid for its -//! records, the history allowance the frame was granted, a built frame's mark — lives beside it on -//! [`AdditionalLimit`](crate::AdditionalLimit), one side per frame result revm returns. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use revm::context_interface::{host::CompletedWrite, journaled_state::JournalCheckpoint}; - -use super::{ - record::{write_effect, write_moves_value, HistoryBytes, RecordDelta, WriteCount}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, -}; -use crate::write_record_history_gas; - -/// What the ledger counts that the journal rewinds: additions and refunds, kept apart so that a -/// frame's own usage saturates at zero on its own — a child can take back a slot its parent -/// dirtied — and the log and code bytes history counts beside the write records. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct Counts { - /// What was counted. - used: LimitUsage, - /// What was taken back: a slot written back to its original value, an account returned to - /// what the transaction loaded. - refund: LimitUsage, - /// The log and code bytes among [`used`](Self::used). - log_and_code_bytes: u64, -} - -/// A frame start's number in its transaction, in the order the starts were handed to revm. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] -pub(crate) struct StartId(u64); - -/// Who a frame level's frame is: its depth, and the start that opened the level. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct FrameIdentity { - /// The frame's depth. - pub(crate) depth: usize, - /// The frame's start. - pub(crate) start: StartId, -} - -/// A frame level's frame: who it is, and what it may keep. Kept beside the levels, the running -/// frame's last, so that the running frame and its caller are found without a scan. -#[derive(Clone, Copy, Debug)] -struct FrameLevel { - /// The frame's level: its index among the open levels. - level: usize, - /// The frame's start. - start: StartId, - /// The frame's depth. - depth: usize, - /// The most data-size bytes the frame may keep. - budget: u64, - /// Whether the frame is returning, so revm may close its level. - returning: bool, -} - -/// One open checkpoint of revm's journal. -#[derive(Clone, Copy, Debug)] -struct Level { - /// The checkpoint revm's journal opened it at, which its revert reverts to. - opened_at: JournalCheckpoint, - /// The counts its revert restores. - at_open: Counts, - /// The start the next frame start would be when it opened: a start at or after it began - /// inside it. - next_start_at_open: StartId, - /// Whether it is a frame level, whose frame is the last of the frames when it is the latest - /// level; a rollback level otherwise. - frame: bool, -} - -/// What the engine tells the ledger about a frame start it is about to hand revm. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct StartFacts { - /// The frame's depth. - pub(crate) depth: usize, - /// Whether the start is a creation; a call otherwise. - pub(crate) creation: bool, - /// Whether the start transfers value: a call carrying a non-zero transfer, or a creation with - /// an endowment. - pub(crate) transfers_value: bool, -} - -/// 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 { - /// The records a call's value transfer makes and takes back on the frame's own level, which - /// its failure takes back: the accounts it changes from what the transaction loaded, and those - /// it returns to that. - pub(crate) transfer: RecordDelta, - /// Whether the start records the account a creation creates, on the frame's own level, which - /// its failure takes back. The ledger counts it when the creation changed an account the - /// transaction had not changed; a charge made before revm decides the start counts it for - /// every creation, the address a `CREATE2` lands on not being known there, and the refund - /// gives back what the count fell short of. - pub(crate) created: bool, - /// Whether the start writes its creator's nonce record, on the creating frame, which the - /// creation's failure leaves there. - pub(crate) creator: bool, -} - -impl FrameStartRecords { - /// No record at all. - pub(crate) const NONE: Self = - Self { transfer: RecordDelta::NONE, created: false, creator: false }; - - /// The records of a call's value transfer, which makes and takes back `records`. - pub(crate) const fn of_transfer(records: RecordDelta) -> Self { - Self { transfer: records, ..Self::NONE } - } - - /// The records the start adds on the frame's own level: the accounts a transfer changes, and - /// the created account. - pub(crate) const fn added_on_level(self) -> u64 { - self.transfer.added + self.created as u64 - } - - /// Whether a charge computed from `self` paid for the records `counted`: the same records, - /// but for the created account, which the charge counts for every creation and the ledger only - /// where the creation changed it. - #[cfg(debug_assertions)] - fn covers(self, counted: Self) -> bool { - self.transfer == counted.transfer && - self.creator == counted.creator && - (self.created || !counted.created) - } -} - -/// The start window, open while revm decides one frame start. -#[derive(Clone, Copy, Debug)] -struct Window { - facts: StartFacts, - /// The start the window is open for. - start: StartId, - /// Whether the start's frame level opened. - opened: bool, - /// Whether the start's write — a call's transfer, a creation's account checkpoint — was seen. - counted: bool, -} - -/// What a frame start counted, as the ledger saw it while revm decided the start. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct StartReport { - /// The start, once revm decided it in a start window; `None` for a start answered before. - pub(crate) start: Option, - /// The records the start counted: on its own level, and its creator's below it. - pub(crate) records: FrameStartRecords, - /// Whether the start counted the transfer log revm journaled for it. - pub(crate) transfer_log: bool, - /// The verdict on the start, held to the limits while its level was open; `None` when nothing - /// was held: a refused transfer, a creation that failed before its level opened, a start revm - /// never decided. - pub(crate) verdict: Option, -} - -/// What became of the last start revm decided: whether its level was kept — committed, and not -/// taken back since — and whether anything it counted is still held, which a revert to before the -/// start takes back, a creator's nonce record included. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Fate { - start: StartId, - level_kept: bool, - start_kept: bool, -} - -/// What a revert of the ledger restores: the counts and the levels open. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Rollback { - /// The counts. - counts: Counts, - /// The number of levels open: a revert finds at most these. - levels: usize, -} - -/// A point the ledger and revm's journal can be taken back to together -/// ([`MegaJournal::revert_to`](crate::MegaJournal)). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Mark { - /// Where revm's journal stood. - pub(crate) position: JournalCheckpoint, - /// What the ledger goes back to. - rollback: Rollback, - /// The start the next frame start would be: a start at or after it is taken back with the - /// mark. - next_start: StartId, - /// For a built frame's own mark, its start, whose creator record the mark keeps. - own_start: Option, -} - -/// The facts of a creation's start, taken as its creator's nonce record is counted. -#[derive(Clone, Copy, Debug)] -pub(crate) struct CreationStart { - /// The creation's budget, from what its creator has left after its nonce record. - budget: u64, - /// Whether the creator's nonce record was counted. - creator_record: bool, - /// The creation's depth. - depth: usize, -} - -/// The ledger. See the module documentation. -#[derive(Clone, Debug, Default)] -pub(crate) struct Ledger { - counts: Counts, - /// The body's data-size bytes. - body: u64, - /// The Oracle hints' data-size bytes. - hints: u64, - /// One level per checkpoint revm's journal holds open, the latest last. - levels: Vec, - /// The frames whose levels are open, the running frame last. - frames: Vec, - /// The start window, while one is open. - window: Option, - /// What the start of the window counted. - last_start: Option, - /// What became of the last start revm decided. - last_decided: Option, - /// The next frame start. - next_start: StartId, - /// The records the journal saw the last `SELFDESTRUCT` make and take back, for the - /// completed-write hook to count once the opcode completed. - destruction: RecordDelta, - /// Whether a value movement journals an EIP-7708 transfer log. - transfer_logs: bool, - limits: EvmTxRuntimeLimits, - /// Whether the transaction is held to no limit. - exempt: bool, -} - -/// `counted`, with the transfer log revm journaled for the value it moved when `logged`. -const fn with_transfer_log(counted: LimitUsage, logged: bool) -> LimitUsage { - if logged { - counted.saturating_add(TRANSFER_LOG) - } else { - counted - } -} - -impl Ledger { - /// Holds every transaction from the next one on to `limits`. - pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { - self.limits = limits; - } - - /// Starts a transaction, held to the limits or to none when `exempt`, whose body weighs `body` - /// bytes and whose value movements journal transfer logs or not. - pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { - self.counts = Counts::default(); - self.body = body; - self.hints = 0; - self.levels.clear(); - self.frames.clear(); - self.window = None; - self.last_start = None; - self.last_decided = None; - self.next_start = StartId::default(); - self.destruction = RecordDelta::NONE; - self.transfer_logs = transfer_logs; - self.exempt = exempt; - } - - /* What the ledger holds */ - - /// What the transaction keeps so far: its data-size bytes and write records. - pub(crate) fn usage(&self) -> LimitUsage { - LimitUsage { data_size: self.body.saturating_add(self.hints), write_records: 0 } - .saturating_add(self.counts.used) - .saturating_sub(self.counts.refund) - } - - /// The history bytes the transaction keeps beside its write records: its logs and the code it - /// deposited. - pub(crate) const fn log_and_code_bytes(&self) -> u64 { - self.counts.log_and_code_bytes - } - - /// The data-size bytes of the transaction's body, which the transaction counts before any - /// frame and no revert takes back. - pub(crate) const fn body(&self) -> u64 { - self.body - } - - /// 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 { - self.exempt || - !LimitUsage { data_size: self.body, write_records: 0 } - .saturating_add(WRITE_RECORD.times(authorizations)) - .exceeds_data_size(self.limits.tx_data_size_limit) - } - - /// The number of levels open, which is revm's journal depth. - pub(crate) fn depth(&self) -> usize { - self.levels.len() - } - - /// The running frame's level: the nearest frame level. - fn frame_level(&self) -> Option<&FrameLevel> { - self.frames.last() - } - - /// The running frame's level, mutably. - fn frame_level_mut(&mut self) -> Option<&mut FrameLevel> { - self.frames.last_mut() - } - - /// What `frame` keeps so far, the children it kept included: what was counted since its level - /// opened. - fn frame_usage(&self, frame: &FrameLevel) -> LimitUsage { - let at_open = &self.levels[frame.level].at_open; - self.counts - .used - .saturating_sub(at_open.used) - .saturating_sub(self.counts.refund.saturating_sub(at_open.refund)) - } - - /// The data-size bytes `frame` may still keep. - fn frame_remaining(&self, frame: &FrameLevel) -> u64 { - frame.budget.saturating_sub(self.frame_usage(frame).data_size) - } - - /// Who the running frame is: the identity its level was opened with. - pub(crate) fn running_frame(&self) -> Option { - self.frame_level().map(|level| FrameIdentity { depth: level.depth, start: level.start }) - } - - /// Whether the transaction's value movements journal EIP-7708 transfer logs, which the ledger - /// counts where the value moves. - pub(crate) const fn counts_transfer_logs(&self) -> bool { - self.transfer_logs - } - - /// The running frame's budget and what it keeps so far. - #[cfg(test)] - pub(crate) fn running_budget(&self) -> Option<(u64, LimitUsage)> { - self.frame_level().map(|frame| (frame.budget, self.frame_usage(frame))) - } - - /// What became of `start`, which must be the last start revm decided: whether its level was - /// kept, and whether what it counted below its level — a creator's nonce record — is still - /// held. - pub(crate) fn fate(&self, start: StartId) -> (bool, bool) { - let fate = self.last_decided.filter(|fate| fate.start == start); - debug_assert!(fate.is_some(), "a start's fate is read as its frame returns"); - fate.map_or((false, false), |fate| (fate.level_kept, fate.start_kept)) - } - - /* Verdicts */ - - /// The verdict on `used` crossing a data-size `limit`, a frame budget when `frame_local`: - /// within, whatever it crossed, for an exempt transaction. - const fn crossed(&self, limit: u64, used: u64, frame_local: bool) -> LimitCheck { - if self.exempt { - return LimitCheck::WithinLimit; - } - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local } - } - - /// Holds what the transaction keeps to its limit, then what the running frame keeps to its - /// budget. - pub(crate) fn check(&self) -> LimitCheck { - let (kept, limit) = (self.usage(), self.limits.tx_data_size_limit); - if kept.exceeds_data_size(limit) { - return self.crossed(limit, kept.data_size, false); - } - if let Some(frame) = self.frame_level() { - let used = self.frame_usage(frame); - if used.exceeds_data_size(frame.budget) { - return self.crossed(frame.budget, used.data_size, true); - } - } - LimitCheck::WithinLimit - } - - /// The budget of a frame starting now: a share of what the running frame has left, or, for - /// the transaction's own frame, what the transaction has left, under the frame cap. - fn child_budget(&self) -> u64 { - let forwarded = match self.frame_level() { - Some(parent) => share_of_remaining(self.frame_remaining(parent)), - None => self.limits.tx_data_size_limit.saturating_sub(self.usage().data_size), - }; - forwarded.min(self.limits.frame_data_size_limit) - } - - /// 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: the records its value transfer would - /// make and take back (`records`, as the journal predicts them) and the transfer log of the - /// value it would move (`logged`), held to the transaction's limit and to the budget its frame - /// would get. Nothing is counted. - pub(crate) fn hypothetical_start(&self, records: RecordDelta, logged: bool) -> LimitCheck { - let added = with_transfer_log(WRITE_RECORD.times(records.added), logged); - let taken = WRITE_RECORD.times(records.taken); - let (kept, limit) = ( - self.usage().saturating_add(added).saturating_sub(taken), - self.limits.tx_data_size_limit, - ); - if kept.exceeds_data_size(limit) { - return self.crossed(limit, kept.data_size, false); - } - let (budget, used) = (self.child_budget(), added.saturating_sub(taken)); - if used.exceeds_data_size(budget) { - return self.crossed(budget, used.data_size, true); - } - LimitCheck::WithinLimit - } - - /* What the transaction counts outside the journal's writes */ - - /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts - /// other than the transaction's sender. Inside the pre-execution level, whose revert takes - /// them back. - /// - /// 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 count_authorities(&mut self, authorities: u64) { - self.counts.used = self.counts.used.saturating_add(WRITE_RECORD.times(authorities)); - debug_assert!( - 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" - ); - } - - /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and - /// never taken back once counted. - pub(crate) fn admit_hint(&mut self, bytes: u64) -> LimitCheck { - let hint = LimitUsage { data_size: bytes, write_records: 0 }; - let (reached, limit) = (self.usage().saturating_add(hint), self.limits.tx_data_size_limit); - if reached.exceeds_data_size(limit) { - let stop = self.crossed(limit, reached.data_size, false); - if stop.exceeded_limit() { - return stop; - } - } - self.hints = self.hints.saturating_add(bytes); - LimitCheck::WithinLimit - } - - /// Notes the records the journal saw a `SELFDESTRUCT` make and take back, for the - /// completed-write hook to count once the opcode completed; a `SELFDESTRUCT` whose opcode - /// then fails leaves them for the next one to overwrite. - pub(crate) const fn observe_destruction(&mut self, records: RecordDelta) { - self.destruction = records; - } - - /// What `write`, which the running opcode completed, keeps and takes back, and the history - /// bytes it appends and takes back: what [`count_write`](Self::count_write) counts, and what - /// the Host's completed-write hook charges and refills. - /// - /// A `SELFDESTRUCT` that moved value to another account also keeps the EIP-7708 transfer log - /// revm journaled for the move, with the records its move made. The log is the running - /// frame's, as the move is: the frame's own journal checkpoint takes both back when the frame - /// fails. It is data size and nothing else — no write record, and no history: the bytes - /// reported are the records' alone. - pub(crate) fn write_count(&self, write: &CompletedWrite<'_>) -> (WriteCount, HistoryBytes) { - let (added, taken) = write_effect(write, self.destruction); - let history = HistoryBytes { appended: added.data_size, taken: taken.data_size }; - // A log's bytes are history beside the write records; a record's are counted as one. - let log_bytes = match write { - CompletedWrite::Log { .. } => added.data_size, - CompletedWrite::Sstore { .. } | CompletedWrite::SelfDestruct { .. } => 0, - }; - let added = with_transfer_log(added, self.transfer_logs && write_moves_value(write)); - (WriteCount { added, taken, log_bytes }, history) - } - - /// Counts what a completed write keeps on the running frame's level: what it takes back, then - /// what it adds. The verdict is the check after an addition; a write that adds nothing holds - /// nothing. - pub(crate) fn count_write(&mut self, count: &WriteCount) -> LimitCheck { - if count.taken != LimitUsage::ZERO { - self.counts.refund = self.counts.refund.saturating_add(count.taken); - } - self.counts.log_and_code_bytes = - self.counts.log_and_code_bytes.saturating_add(count.log_bytes); - if count.added == LimitUsage::ZERO { - return LimitCheck::WithinLimit; - } - self.counts.used = self.counts.used.saturating_add(count.added); - self.check() - } - - /// Counts `bytes` of code a creation deposits, on the creation's level before revm commits it. - pub(crate) fn count_code(&mut self, bytes: u64) -> LimitCheck { - if bytes == 0 { - return LimitCheck::WithinLimit; - } - let code = LimitUsage { data_size: bytes, write_records: 0 }; - self.counts.used = self.counts.used.saturating_add(code); - self.counts.log_and_code_bytes = self.counts.log_and_code_bytes.saturating_add(bytes); - self.check() - } - - /// Takes back one write record on the running frame's level, for an account a write outside - /// the journal's counted writes returned to what the transaction loaded: a `keylessDeploy` - /// call's signer, whose nonce the settlement sets back. - pub(crate) fn take_back_record(&mut self) { - self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD); - } - - /* The start window */ - - /// Opens the start window for the start `facts` describes, which revm decides next. - pub(crate) fn open_start(&mut self, facts: StartFacts) { - debug_assert!(self.window.is_none(), "start windows do not nest"); - let start = self.next_start; - self.next_start = StartId(start.0 + 1); - self.last_start = Some(StartReport { start: Some(start), ..Default::default() }); - self.window = Some(Window { facts, start, opened: false, counted: false }); - } - - /// Closes the start window once revm decided the start, and reports what the start counted. A - /// start whose level never opened is decided here. - pub(crate) fn close_start(&mut self) -> StartReport { - if let Some(window) = self.window.take().filter(|window| !window.opened) { - self.last_decided = - Some(Fate { start: window.start, level_kept: false, start_kept: true }); - } - self.last_start.take().unwrap_or_default() - } - - /// The start report of the open window. - fn report_mut(&mut self) -> &mut StartReport { - self.last_start.get_or_insert_with(StartReport::default) - } - - /* Levels */ - - /// Opens a level at `opened_at`, a frame level when `frame`. - fn open_level(&mut self, opened_at: JournalCheckpoint, frame: bool) { - self.levels.push(Level { - opened_at, - at_open: self.counts, - next_start_at_open: self.next_start, - frame, - }); - } - - /// Opens the frame level of the window's start at `opened_at`, under `budget`: the frame the - /// window's start builds. - fn open_frame_level(&mut self, opened_at: JournalCheckpoint, budget: u64) { - let Some(window) = &mut self.window else { - unreachable!("a frame level opens inside its start's window") - }; - window.opened = true; - let (start, depth) = (window.start, window.facts.depth); - self.open_level(opened_at, true); - self.frames.push(FrameLevel { - level: self.levels.len() - 1, - start, - depth, - budget, - returning: false, - }); - } - - /// revm's journal opened a checkpoint at `opened_at`: the frame level of a call whose start the - /// window is open for, when it is the first checkpoint of the window; a rollback level - /// otherwise. - pub(crate) fn on_checkpoint(&mut self, opened_at: JournalCheckpoint) { - let Some(window) = self.window.filter(|window| !window.opened) else { - return self.open_level(opened_at, false); - }; - if window.facts.creation { - // A creation's frame level is the one its account checkpoint opens. - return self.open_level(opened_at, false); - } - self.open_frame_level(opened_at, self.child_budget()); - // A start that moves value is held once its transfer is counted (`on_transfer`); any - // other has nothing of its own to count, and is held now. - if !window.facts.transfers_value { - let verdict = self.check(); - self.report_mut().verdict = Some(verdict); - } - } - - /// revm moved the value of the call whose start the window is open for (`refused` when it - /// could not), changing and returning the accounts `records` says, and journaled a transfer - /// log or not (`logged`): counts the records on the call's level, then holds the start to the - /// limits. - pub(crate) fn on_transfer(&mut self, records: RecordDelta, refused: bool, logged: bool) { - let Some(window) = &mut self.window else { return }; - if window.counted || !window.opened || window.facts.creation { - return; - } - window.counted = true; - if refused { - self.report_mut().verdict = None; - return; - } - if !window.facts.transfers_value { - return; - } - let added = with_transfer_log(WRITE_RECORD.times(records.added), logged); - self.counts.used = self.counts.used.saturating_add(added); - self.counts.refund = self.counts.refund.saturating_add(WRITE_RECORD.times(records.taken)); - let verdict = self.check(); - let report = self.report_mut(); - report.records = FrameStartRecords::of_transfer(records); - report.transfer_log = logged; - report.verdict = Some(verdict); - } - - /// revm is about to open a creation's account checkpoint for the start of the window, having - /// bumped its creator's nonce: counts the creator's nonce record on the creating frame's level - /// when the bump changed an account the transaction had not changed (`creator_unchanged`), - /// then takes the creation's budget from what the creator has left. The transaction's own - /// creation writes its sender's nonce, which the body counts. `None` outside a creation's - /// start window. - /// - /// The record is the creator's to keep within its budget, not the creation's: it lands on the - /// creator unchecked, and the creator is held to its limits with it as the creation returns. - pub(crate) fn before_creation(&mut self, creator_unchanged: bool) -> Option { - let window = self.window.as_mut()?; - if window.counted || !window.facts.creation { - return None; - } - window.counted = true; - let depth = window.facts.depth; - let creator_record = depth > 0 && creator_unchanged; - if creator_record { - self.counts.used = self.counts.used.saturating_add(WRITE_RECORD); - } - let budget = self.child_budget(); - Some(CreationStart { budget, creator_record, depth }) - } - - /// revm opened (`Some`) or failed to open (`None`) the account checkpoint of a creation, and - /// journaled a transfer log or not (`logged`): opens the creation's frame level, counts on it - /// the created account's record when the creation changed an account the transaction had not - /// changed (`created_unchanged`), and the log, then holds the start to the limits. A creation - /// sets the account's nonce to one, so it leaves the account changed, and never returns it to - /// what the transaction loaded. The creator's nonce record is below the creation's level; its - /// revert keeps it. - /// - /// A checkpoint opened outside a creation's start window opens a rollback level. - pub(crate) fn after_creation( - &mut self, - start: Option, - opened: Option, - created_unchanged: bool, - logged: bool, - ) { - let Some(start) = start else { - if let Some(opened_at) = opened { - self.open_level(opened_at, false); - } - return; - }; - self.report_mut().records.creator = start.creator_record; - let Some(opened_at) = opened else { return }; - debug_assert!(start.depth == self.window.map_or(start.depth, |window| window.facts.depth)); - self.open_frame_level(opened_at, start.budget); - let created = WRITE_RECORD.times(u64::from(created_unchanged)); - self.counts.used = self.counts.used.saturating_add(with_transfer_log(created, logged)); - let verdict = self.check(); - let report = self.report_mut(); - report.records.created = created_unchanged; - report.transfer_log = logged; - report.verdict = Some(verdict); - } - - /// The running frame is returning: revm closes its level next, committing or reverting it. - pub(crate) fn frame_returning(&mut self) { - if let Some(level) = self.frame_level_mut() { - level.returning = true; - } - } - - /// Asserts a frame level closes as revm closes one: while its start is being decided, or once - /// its frame is returning. A frame level any other checkpoint closes — a tool's checkpoint - /// reverted while a frame opened after it still runs — would leave the frame running without - /// its level. - fn assert_frame_closes(&self, frame: &FrameLevel) { - debug_assert!( - self.window.is_some() || frame.returning, - "a revert closes the latest level: a frame's level closes only when the frame returns" - ); - } - - /// revm's journal committed its latest checkpoint: the level closes, and what it counted stays - /// with the level below. - pub(crate) fn on_commit(&mut self) { - let Some(level) = self.levels.pop() else { return }; - if !level.frame { - return; - } - let frame = self.pop_frame(); - self.assert_frame_closes(&frame); - self.last_decided = Some(Fate { start: frame.start, level_kept: true, start_kept: true }); - } - - /// revm's journal reverted to `checkpoint`: the latest level, which must be the one opened - /// there, closes, and the counts are what they were when it opened. - /// - /// A frame level's revert keeps what its start counted below it, a creator's nonce record. A - /// rollback level a start began inside — a tool's checkpoint around a call — takes everything - /// the start counted back with it. - pub(crate) fn on_revert(&mut self, checkpoint: JournalCheckpoint) { - let Some(level) = self.levels.pop() else { return }; - debug_assert!( - level.opened_at == checkpoint, - "a revert closes the latest level: a revert below a level still open is not supported" - ); - let frame = level.frame.then(|| self.pop_frame()); - self.counts = level.at_open; - match frame { - Some(frame) => { - self.assert_frame_closes(&frame); - self.last_decided = - Some(Fate { start: frame.start, level_kept: false, start_kept: true }); - } - None => self.take_back_starts_from(level.next_start_at_open, None), - } - } - - /// Pops the frame of the frame level just popped. - fn pop_frame(&mut self) -> FrameLevel { - let frame = self.frames.pop().expect("a frame level has its frame"); - debug_assert!(frame.level == self.levels.len(), "the frames follow the frame levels"); - frame - } - - /// Notes that the last start decided is taken back when it is `start` or later: its level is no - /// longer kept, and, unless it is `own_start`, nothing it counted is. - fn take_back_starts_from(&mut self, start: StartId, own_start: Option) { - if let Some(fate) = &mut self.last_decided { - if fate.start >= start { - fate.level_kept = false; - fate.start_kept &= own_start == Some(fate.start); - } - } - } - - /// revm's journal ended the transaction: every level closes. What was counted stays readable - /// until the next transaction begins. - pub(crate) fn on_transaction_end(&mut self) { - self.levels.clear(); - self.frames.clear(); - self.window = None; - } - - /* Marks */ - - /// A mark at `position`, where revm's journal stands now. - pub(crate) fn mark(&self, position: JournalCheckpoint) -> Mark { - Mark { - position, - rollback: Rollback { counts: self.counts, levels: self.levels.len() }, - next_start: self.next_start, - own_start: None, - } - } - - /// What a frame revm just built is taken back to when it is rewritten into a failure, with its - /// start: the counts its level opened with, after a creation's creator record. The frame's - /// side keeps it past the level's commit, for the mark the rewrite reverts to - /// ([`StartSide::built_mark`]). - pub(crate) fn frame_start_rollback(&self) -> Option<(StartId, Rollback)> { - let level = self.levels.last()?; - if !level.frame { - return None; - } - let frame = self.frames.last()?; - let rollback = Rollback { counts: level.at_open, levels: self.levels.len() - 1 }; - Some((frame.start, rollback)) - } - - /// The mark a frame revm just built is taken back to when it is rewritten into a failure - /// ([`frame_start_rollback`](Self::frame_start_rollback), at the frame's own checkpoint). - #[cfg(test)] - pub(crate) fn frame_start_mark(&self) -> Option { - let (start, rollback) = self.frame_start_rollback()?; - Some(Mark::of_built(self.levels.last()?.opened_at, start, rollback)) - } - - /// Takes the ledger back to `mark`, which revm's journal is being reverted to: the counts, and - /// what became of the last start decided. - pub(crate) fn revert_to(&mut self, mark: &Mark) { - debug_assert!( - self.levels.len() <= mark.rollback.levels, - "a revert to a mark finds every level opened since closed" - ); - self.counts = mark.rollback.counts; - self.take_back_starts_from(mark.next_start, mark.own_start); - } -} - -impl Mark { - /// The mark of a frame revm built at `position`, its own checkpoint: `rollback` is what its - /// level opened with, and `start` the frame's, whose creator record the mark keeps. - const fn of_built(position: JournalCheckpoint, start: StartId, rollback: Rollback) -> Self { - Self { position, rollback, next_start: start, own_start: Some(start) } - } -} - -/// The history gas `records` write records cost; nothing for a count with no price, which no -/// charge was made for. -fn records_history_gas(records: u64) -> u64 { - write_record_history_gas(records).unwrap_or(0) -} - -/// Satin's side of one frame start: what its caller paid for the records it makes, what the -/// ledger saw it count, the history allowance the frame was granted, and, for a frame revm built, -/// what it is taken back to when it is rewritten into a failure. One per frame result revm will -/// return. -#[derive(Clone, Copy, Debug)] -pub(crate) struct StartSide { - /// The frame's depth. - depth: usize, - /// What the caller paid for the records the start adds on the frame's own level. - added_charge: u64, - /// What the caller paid for the record of its own nonce, for a creation. - creator_charge: u64, - /// Whether the transaction prices history, so that a record the start took back is history - /// the caller gets back. - priced: bool, - /// What is left of the history allowance the 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. - stipend: u64, - /// The start, once revm decided it; `None` for a start answered before, which counted nothing. - start: Option, - /// The records the ledger saw the start count. - counted: FrameStartRecords, - /// What a frame revm built is taken back to when it is rewritten into a failure. - rollback: Option, - /// The records the charge was computed from, when the charge was made from one and nothing - /// could rewrite the start between the two: what a debug build holds the ledger's count to. - #[cfg(debug_assertions)] - charged: Option, -} - -impl StartSide { - /// The side of a start at `depth` whose caller paid `added_charge` and `creator_charge` for - /// the records `charged`, when the charge was computed from them, in a transaction that - /// prices history or not (`priced`). - pub(crate) const fn new( - depth: usize, - added_charge: u64, - creator_charge: u64, - priced: bool, - charged: Option, - ) -> Self { - #[cfg(not(debug_assertions))] - let _ = charged; - Self { - depth, - added_charge, - creator_charge, - priced, - stipend: 0, - start: None, - counted: FrameStartRecords::NONE, - rollback: None, - #[cfg(debug_assertions)] - charged, - } - } - - /// Attaches what the ledger saw the start count and, for a frame revm built, what it is taken - /// back to, and holds the count to the records the start's charge was computed from. - /// - /// The two are separate answers to one question, asked at two points: the charge at the - /// opcode, on the journal's state as revm's instruction hands the frame-start hook the start — - /// or before execution, on the transaction, for its own frame; or at a `keylessDeploy` call's - /// first run, on the creation it starts — and the count, on the writes revm made for the - /// start. They agree because the start revm makes carries the caller, target and value the - /// charge was computed from, and nothing between the two changes it or the accounts it - /// writes: an interceptor answers a frame or lets it start as it is, and a creation reaches - /// none. A divergence trips in a debug build rather than mis-charging the caller and - /// mis-splitting the refund its failure gets back. An inspector that may rewrite the start - /// runs between the two, and can split them: under one the start is not checked. Only a start - /// revm made and held to the limits is checked: one it refused, or failed before its level - /// opened, counted nothing, and the charge comes back. - /// - /// The one record the charge may count where the ledger does not is a creation's created - /// account ([`FrameStartRecords::created`]): the charge cannot tell the address a `CREATE2` - /// lands on, and counts it for every creation; the refund gives back what it paid for a record - /// the ledger did not count. - pub(crate) fn attach(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { - self.start = report.start; - self.counted = report.records; - self.rollback = built.map(|(start, rollback)| { - debug_assert!(report.start == Some(start), "a built frame's rollback is its start's"); - rollback - }); - #[cfg(debug_assertions)] - if let Some(charged) = - self.charged.filter(|_| report.start.is_some() && report.verdict.is_some()) - { - debug_assert!( - charged.covers(report.records), - "the records a frame's start makes changed after its caller was charged for them: \ - charged {charged:?}, counted {:?}", - report.records, - ); - } - } - - /// The frame's depth. - pub(crate) const fn depth(&self) -> usize { - self.depth - } - - /// Grants the frame a history allowance of `amount`. - pub(crate) const fn grant_stipend(&mut self, amount: u64) { - self.stipend = amount; - } - - /// Draws up to `amount` from the frame's history allowance and reports what it gave; the frame - /// pays the rest out of its gas. - pub(crate) const fn consume_stipend(&mut self, amount: u64) -> u64 { - let drawn = if self.stipend < amount { self.stipend } else { amount }; - self.stipend -= drawn; - drawn - } - - /// The start, once revm decided it. - pub(crate) const fn start(&self) -> Option { - self.start - } - - /// The mark a frame revm built is taken back to when it is rewritten into a failure, at - /// `position`, the frame's own checkpoint; `None` for a frame revm did not build. - pub(crate) fn built_mark(&self, position: JournalCheckpoint) -> Option { - let (start, rollback) = self.start.zip(self.rollback)?; - Some(Mark::of_built(position, start, rollback)) - } - - /// The history gas the caller gets back once the frame returned: what it paid for the start's - /// records less the price of those `ledger` holds, and the price of the records the start took - /// back, when it stands. - /// - /// The records on the start's own level are held when that level was kept — committed, and not - /// taken back since — and so is what the start took back there: the caller then gets back the - /// price of every record the start returned to what the transaction loaded, which nobody paid - /// for again, and of a created account's record it paid for and the ledger did not count, the - /// account having been changed before. A creator's nonce record, counted below the creation's - /// level, is held unless a revert to before the start took it back. So a start answered before - /// revm decided it, or refused before its writes, gets everything back; a call answered with a - /// success keeps its records; a failed precompile, and a frame that fails, give theirs back, a - /// creator's surviving record aside, and give back nothing for a take-back their failure - /// undid. - pub(crate) fn refund(&self, ledger: &Ledger) -> u64 { - let (level_kept, start_kept) = - self.start.map_or((false, false), |start| ledger.fate(start)); - let mut refund = if level_kept { - let kept = records_history_gas(self.counted.added_on_level()); - let taken = - if self.priced { records_history_gas(self.counted.transfer.taken) } else { 0 }; - self.added_charge.saturating_sub(kept).saturating_add(taken) - } else { - self.added_charge - }; - if !(start_kept && self.counted.creator) { - refund = refund.saturating_add(self.creator_charge); - } - refund - } -} - -/// `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) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, Address}; - use revm::context_interface::context::SelfDestructResult; - - const SENDER: Address = address!("00000000000000000000000000000000000f0001"); - const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); - const TARGET: Address = address!("00000000000000000000000000000000000f0003"); - - /// Two records added: a value transfer between two accounts the transaction has not changed. - const BOTH: RecordDelta = RecordDelta { added: 2, taken: 0 }; - /// One record added: a transfer whose sender the transaction changed already. - const ONE: RecordDelta = RecordDelta { added: 1, taken: 0 }; - - /// A ledger holding a transaction with a body of `body` bytes under `limits`, exempt or not, - /// whose value movements journal transfer logs when `transfer_logs`. - fn ledger(limits: EvmTxRuntimeLimits, exempt: bool, transfer_logs: bool, body: u64) -> Ledger { - let mut ledger = Ledger::default(); - ledger.set_limits(limits); - ledger.begin_transaction(exempt, transfer_logs, body); - ledger - } - - /// 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) - } - - /// A checkpoint of revm's journal as the ledger sees one: distinct per open level. - fn checkpoint(ledger: &Ledger) -> JournalCheckpoint { - JournalCheckpoint { log_i: 0, journal_i: ledger.depth(), selfdestructed_i: 0 } - } - - /// Starts a call at `depth` as revm starts one, moving `value` to another account, which - /// changes and returns the accounts `records` says, and journaling a transfer log for it when - /// the ledger's transaction does; reports what the start counted. - fn start_call( - ledger: &mut Ledger, - depth: usize, - value: u64, - records: RecordDelta, - ) -> StartReport { - let facts = StartFacts { depth, creation: false, transfers_value: value != 0 }; - ledger.open_start(facts); - ledger.on_checkpoint(checkpoint(ledger)); - let logged = ledger.transfer_logs && value != 0; - ledger.on_transfer(if value == 0 { RecordDelta::NONE } else { records }, false, logged); - ledger.close_start() - } - - /// Returns from the running frame as revm does: its level closes, committed or reverted. - fn end_frame(ledger: &mut Ledger, failed: bool) { - ledger.frame_returning(); - let opened_at = ledger.levels.last().expect("a frame is running").opened_at; - if failed { - ledger.on_revert(opened_at); - } else { - ledger.on_commit(); - } - } - - /// The stop of a data-size crossing. - const fn stop(limit: u64, used: u64, frame_local: bool) -> LimitCheck { - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local } - } - - #[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}"); - } - } - - /// 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 mut held = ledger(limits, false, false, 40); - assert_eq!(held.admit_hint(59), LimitCheck::WithinLimit); - assert_eq!(held.usage().data_size, 99); - assert_eq!(held.admit_hint(2), stop(100, 101, false), "two more bytes cross"); - assert_eq!(held.usage().data_size, 99, "the hint that crossed is not counted"); - assert_eq!(held.admit_hint(1), LimitCheck::WithinLimit, "one more fits exactly"); - assert_eq!(held.usage().data_size, 100, "and is counted"); - - let mut exempt = ledger(limits, true, false, 40); - assert_eq!(exempt.admit_hint(61), LimitCheck::WithinLimit); - assert_eq!(exempt.usage().data_size, 101, "an exempt transaction's hint is counted"); - } - - /// 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 limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(10_000); - let mut ledger = ledger(limits, false, false, 310); - let budget = |ledger: &Ledger| ledger.running_budget().expect("a frame is running").0; - - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - let first = 10_000 - 310; - assert_eq!(budget(&ledger), first); - - start_call(&mut ledger, 1, 0, RecordDelta::NONE); - let child = share_of_remaining(first); - assert_eq!(child, 9_496); - assert_eq!(budget(&ledger), child); - - start_call(&mut ledger, 2, 0, RecordDelta::NONE); - let grandchild = share_of_remaining(child); - assert_eq!(budget(&ledger), grandchild); - - start_call(&mut ledger, 3, 0, RecordDelta::NONE); - assert_eq!( - budget(&ledger), - 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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); - let mut ledger = ledger(limits, false, false, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(100)); - start_call(&mut ledger, 1, 0, RecordDelta::NONE); - assert_eq!(ledger.running_budget().map(|(budget, _)| budget), Some(98)); - } - - /// A transaction that is not exempt is stopped wherever it crosses a limit: 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. An exempt transaction is stopped by no - /// limit, at the transaction or at a frame, and what it uses is counted all the same. - #[test] - fn test_a_transaction_is_stopped_where_it_crosses_unless_exempt() { - for exempt in [false, true] { - let mut ledger = ledger(zero_limits(), exempt, false, TX_BODY_SIZE); - let first = start_call(&mut ledger, 0, 0, RecordDelta::NONE); - let second = start_call(&mut ledger, 1, 1, BOTH); - let verdicts = (first.verdict, second.verdict, ledger.check()); - let expected = if exempt { - ( - Some(LimitCheck::WithinLimit), - Some(LimitCheck::WithinLimit), - LimitCheck::WithinLimit, - ) - } else { - let records = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE; - ( - Some(stop(0, TX_BODY_SIZE, false)), - Some(stop(0, records, false)), - stop(0, records, false), - ) - }; - assert_eq!(verdicts, expected, "exempt {exempt}"); - assert_eq!( - ledger.usage(), - LimitUsage { data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 }, - "exempt {exempt}: counted all the same" - ); - } - } - - /// 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 limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE); - let mut ledger = ledger(limits, false, false, TX_BODY_SIZE); - ledger.count_authorities(2); - } - - /// Applied authorities are recorded for an exempt transaction, whatever they cross. - #[test] - fn test_an_exempt_transaction_records_its_authorities() { - let mut ledger = ledger(zero_limits(), true, false, 0); - ledger.count_authorities(2); - assert_eq!(ledger.usage(), WRITE_RECORD.times(2)); - } - - /// A transfer log is data size and nothing else: no write record, and no history byte beside - /// the records — 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 ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, TX_BODY_SIZE); - start_call(&mut ledger, 0, 1, ONE); - start_call(&mut ledger, 1, 1, ONE); - assert_eq!( - ledger.usage(), - LimitUsage { - data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE, - write_records: 2, - }, - "the recipient of each move — the inner one's sender is the outer one's recipient — \ - and two logs", - ); - assert_eq!(ledger.log_and_code_bytes(), 0, "no history byte beside the records"); - } - - /// 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 ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - start_call(&mut ledger, 1, 1, BOTH); - assert_eq!(ledger.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); - end_frame(&mut ledger, true); - assert_eq!(ledger.usage(), LimitUsage::ZERO); - } - - /// A transfer that returns an account to what the transaction loaded takes its record back on - /// the call's level: the usage falls by the record, the frame's own usage saturates at nothing, - /// and the call's failure puts the record back with the rest. - #[test] - fn test_a_transfer_that_returns_an_account_takes_its_record_back() { - let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); - start_call(&mut ledger, 0, 1, ONE); - assert_eq!(ledger.usage(), LimitUsage { data_size: 40 + 160, write_records: 1 }); - // The recipient hands the value back: its own record goes, the sender's is the body's. - let report = start_call(&mut ledger, 1, 1, RecordDelta { added: 0, taken: 1 }); - assert_eq!(report.records.transfer, RecordDelta { added: 0, taken: 1 }); - assert_eq!(report.verdict, Some(LimitCheck::WithinLimit)); - assert_eq!( - ledger.usage(), - LimitUsage { data_size: 2 * TRANSFER_LOG_SIZE, write_records: 0 }, - "the record went; both logs stay" - ); - assert_eq!( - ledger.running_budget().map(|(_, used)| used), - Some(LimitUsage { data_size: TRANSFER_LOG_SIZE - WRITE_RECORD_SIZE, write_records: 0 }), - "the returning frame's own usage is its log less the record it took back, and its \ - record count saturates at nothing" - ); - end_frame(&mut ledger, true); - assert_eq!( - ledger.usage(), - LimitUsage { data_size: 40 + 160, write_records: 1 }, - "the failed return puts the record back" - ); - } - - /// A frame start whose transfer log crosses a limit is stopped at its start, 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; - // 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 limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap); - let mut ledger = ledger(limits, false, true, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - let report = start_call(&mut ledger, 1, 1, BOTH); - let expected = - if fits { LimitCheck::WithinLimit } else { stop(needs - 1, needs, true) }; - assert_eq!(report.verdict, Some(expected), "a cap of {cap}"); - } - - // The transaction's own value: one record, the recipient's, and the log. - let needs = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit); - let mut ledger = ledger(limits, false, true, 0); - let report = start_call(&mut ledger, 0, 1, ONE); - let expected = - if fits { LimitCheck::WithinLimit } else { stop(tx_limit, needs, false) }; - assert_eq!(report.verdict, Some(expected), "a limit of {tx_limit}"); - } - } - - /// A child's return holds its caller to the ledger's check with what the child left it, every - /// time: a failed creation's nonce record lands on the creator unchecked, and the creator is - /// stopped before it runs on when the record puts it over its budget; a success hands its - /// caller no more than the share it gave, and the caller runs on. - #[test] - fn test_a_childs_return_holds_its_caller_to_what_it_left() { - // A frame cap of 100: the transaction's own frame gets 100, a child 98. - let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); - for (case, left, failed, stopped) in [ - ("a success within its share", 98, false, false), - ("a failed creation's nonce record, within", 60, true, false), - ("a failed creation's nonce record, over the budget", 61, true, true), - ] { - let mut ledger = ledger(limits, false, false, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - // What the caller kept of its own before the start. - let count = WriteCount { - added: LimitUsage { data_size: left, write_records: 0 }, - ..WriteCount::NONE - }; - assert_eq!(ledger.count_write(&count), LimitCheck::WithinLimit, "{case}"); - if failed { - ledger.open_start(StartFacts { depth: 1, creation: true, transfers_value: false }); - let start = ledger.before_creation(true); - ledger.after_creation(start, Some(checkpoint(&ledger)), true, false); - let _ = ledger.close_start(); - } else { - start_call(&mut ledger, 1, 0, RecordDelta::NONE); - } - end_frame(&mut ledger, failed); - let check = ledger.check(); - assert_eq!(check.exceeded_limit(), stopped, "{case}: {check:?}"); - if stopped { - assert_eq!(check, stop(100, left + WRITE_RECORD_SIZE, true), "{case}"); - } - } - } - - /// A creation's creator record is the creating frame's, counted when the bump changed an - /// account the transaction had not changed, and never for the transaction's own creation, - /// whose creator is the sender, whom the body counts. The created account's record is the - /// creation's own, counted on its level when the creation changed an account the transaction - /// had not changed, at any depth. - #[test] - fn test_a_creators_record_is_counted_below_the_creations_level() { - for (depth, creator_unchanged, expected) in - [(1, true, true), (1, false, false), (0, true, false), (0, false, false)] - { - for created_unchanged in [true, false] { - let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); - if depth > 0 { - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - } - ledger.open_start(StartFacts { depth, creation: true, transfers_value: false }); - let start = ledger.before_creation(creator_unchanged); - ledger.after_creation(start, Some(checkpoint(&ledger)), created_unchanged, false); - let report = ledger.close_start(); - let case = format!( - "depth {depth}, creator unchanged {creator_unchanged}, created account \ - unchanged {created_unchanged}" - ); - assert_eq!(report.records.creator, expected, "{case}"); - assert_eq!(report.records.created, created_unchanged, "{case}"); - assert_eq!(report.records.transfer, RecordDelta::NONE, "{case}"); - let records = u64::from(created_unchanged) + u64::from(expected); - assert_eq!(ledger.usage(), WRITE_RECORD.times(records), "{case}"); - end_frame(&mut ledger, true); - assert_eq!( - ledger.usage(), - WRITE_RECORD.times(u64::from(expected)), - "{case}: the creator's record survives the creation's failure" - ); - } - } - } - - /// 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 = TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE; - let at = body + 2 * WRITE_RECORD_SIZE; - let under = |limit: u64, exempt: bool| { - ledger( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - exempt, - false, - body, - ) - }; - assert!(under(at, false).admits_tx_body(2), "at the limit"); - assert!(!under(at - 1, false).admits_tx_body(2), "one byte over it"); - assert!(under(at - 1, false).admits_tx_body(1), "one record fewer"); - assert!(!under(body - 1, false).admits_tx_body(0), "the body alone over it"); - assert!(under(0, true).admits_tx_body(2), "an exempt transaction"); - assert_eq!(under(at, false).body(), body); - assert_eq!(under(at, false).usage().data_size, body, "the body is counted"); - } - - /// Counts `write` on `ledger` as the completed-write hook does, and reports the verdict and - /// the history bytes. - fn commit(ledger: &mut Ledger, write: &CompletedWrite<'_>) -> (LimitCheck, HistoryBytes) { - let (count, history) = ledger.write_count(write); - (ledger.count_write(&count), history) - } - - /// A `SELFDESTRUCT` that moved value to another account counts the records the journal saw its - /// move make and take back, with its transfer log, in one check, and reports the records' - /// history alone: appended for a record made, taken for one taken back. Where the move - /// changes nothing — a beneficiary that is the sender, whose account the transaction changed, - /// and a destructed account the transaction gave its balance — it is the log alone, and the - /// log alone can cross; and nothing counts a log when the transaction's value movements - /// journal none. - #[test] - fn test_a_destruction_counts_its_transfer_log_with_its_records() { - let moved = SelfDestructResult { had_value: true, ..Default::default() }; - let destruction = - |target| CompletedWrite::SelfDestruct { - address: CALLEE, - target, - balance: alloy_primitives::U256::ZERO, - result: &moved, - }; - let mut logging = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); - logging.observe_destruction(RecordDelta { added: 2, taken: 0 }); - let (check, history) = commit(&mut logging, &destruction(TARGET)); - assert_eq!(check, LimitCheck::WithinLimit); - assert_eq!(history, HistoryBytes { appended: 2 * WRITE_RECORD_SIZE, taken: 0 }); - assert_eq!( - logging.usage(), - LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 2 }, - ); - - let mut returning = ledger(EvmTxRuntimeLimits::no_limits(), false, true, 0); - returning.count_authorities(1); - returning.observe_destruction(RecordDelta { added: 1, taken: 1 }); - let (check, history) = commit(&mut returning, &destruction(TARGET)); - assert_eq!(check, LimitCheck::WithinLimit); - assert_eq!(history, HistoryBytes { appended: WRITE_RECORD_SIZE, taken: WRITE_RECORD_SIZE }); - assert_eq!( - returning.usage(), - LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, - "one record made, one taken back, and the log" - ); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1); - let mut tight = ledger(limits, false, true, 0); - tight.observe_destruction(RecordDelta::NONE); - let (check, history) = commit(&mut tight, &destruction(SENDER)); - assert_eq!(history, HistoryBytes::default()); - 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 silent = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); - silent.observe_destruction(RecordDelta { added: 1, taken: 0 }); - let _ = commit(&mut silent, &destruction(TARGET)); - assert_eq!(silent.usage(), WRITE_RECORD, "no log, no bytes"); - } - - /// The hypothetical start a call gas detention answers without running counts the records - /// its transfer would make and take back and the log it would journal, against the - /// transaction's limit and the budget its frame would get, and counts nothing. - #[test] - fn test_a_hypothetical_start_counts_what_its_transfer_would() { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(WRITE_RECORD_SIZE); - let mut ledger = ledger(limits, false, true, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - assert_eq!( - ledger.hypothetical_start(BOTH, true), - stop(WRITE_RECORD_SIZE, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, false) - ); - assert_eq!( - ledger.hypothetical_start(RecordDelta { added: 1, taken: 1 }, false), - LimitCheck::WithinLimit, - "a record taken back pays for one made" - ); - assert_eq!(ledger.usage(), LimitUsage::ZERO, "nothing was counted"); - } - - /// A record taken back outside the journal's counted writes — a `keylessDeploy` signer's nonce - /// set back — is a refund on the running frame's level, which its failure puts back. - #[test] - fn test_a_record_taken_back_by_hand_goes_with_the_level() { - let mut ledger = ledger(EvmTxRuntimeLimits::no_limits(), false, false, 0); - start_call(&mut ledger, 0, 0, RecordDelta::NONE); - ledger.count_authorities(1); - ledger.take_back_record(); - assert_eq!(ledger.usage(), LimitUsage::ZERO); - end_frame(&mut ledger, true); - assert_eq!(ledger.usage(), LimitUsage::ZERO, "the record and its take-back went together"); - } -} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 1a1197e6d..c3a0bbcdd 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,9 +1,8 @@ -//! The per-transaction state of the common execution layer beside the journal's ledger. +//! The per-transaction state of the common execution layer. use alloy_primitives::Bytes; use revm::{ - handler::FrameResult, - interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, + context_interface::cfg::gas::GasTracker, handler::FrameResult, interpreter::InstructionResult, }; #[cfg(not(feature = "std"))] @@ -11,52 +10,71 @@ use alloc as std; use std::vec::Vec; use super::{ - ledger::{FrameStartRecords, Ledger, Rollback, StartId, StartSide}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, StartReport, WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; -use crate::storage_call_stipend; -/// What the common execution layer tracks for the running transaction beside the journal's -/// ledger ([`Ledger`]), which counts what the transaction keeps and holds it to the data-size -/// limit: Satin's side of each frame start ([`StartSide`]), the stops its frames return, whether -/// it is exempt from every limit, and the figures the settled transaction reports. +/// What the common execution layer tracks for the running transaction: what it keeps of the +/// data-size limit and 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 reset before each transaction and -/// system call, and is driven by the Host's frame-start hook (the charge of a frame's start) and -/// the frame lifecycle (the frame sides, the stops). +/// 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 data size +/// +/// 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: the transaction's own frame gets what the transaction has +/// left once its body and the records made before it are counted +/// ([`first_frame_pool`](Self::first_frame_pool)), every child the schedule's share of what its +/// caller has left (98/100, `GasId::bytes_forward_percent`) under the frame cap, a failing frame's +/// draws go back to its pool and a successful one hands what it kept to its caller. A byte 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 +/// pool before the creation's share is forwarded +/// ([`count_creator_record`](Self::count_creator_record)). +/// +/// The transaction's limit is 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)). A pool is one +/// figure, the bytes; the write-record count and the transfer logs the transaction reports apart +/// from the bytes are kept beside them, and restored with them. /// /// # 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 its level of the ledger, 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 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 +/// 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 of two places — the ledger's verdict for the data size, -/// [`crossed`](Self::crossed) for gas detention's compute stop — and both answer an exempt -/// transaction with [`LimitCheck::WithinLimit`] whatever it crossed. What the transaction uses is -/// counted all the same, so its usage is reported as any other transaction's is. +/// 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 { 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, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, /// The stop the frame about to run must return instead of running: the one a frame revm built /// returns on its first run when its start crossed a limit ([`hold_start`](Self::hold_start)), /// or the one a frame a child returned into returns when what the child left it put it over a - /// limit ([`on_start_return`](Self::on_start_return)). + /// limit ([`hold_caller`](Self::hold_caller)). pending_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 @@ -65,39 +83,121 @@ 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, - /// 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, + /// 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 record of its own nonce the last creation's start hook charged its creator for, until + /// a frame start takes it. + pending_creator: Option, + /// Whether the result returning next kept nothing, whatever it says: an inspector revived a + /// frame that failed. + kept_nothing: bool, + /// 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 does not keep the record. - 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 the frame's side to hold the ledger's count to. 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 side to be pushed. - pending_frame_charge: FrameCharge, - /// The history gas the transaction's own frame's start gets back, kept once that frame - /// returned for the settlement to give back - /// ([`take_top_level_refund`](Self::take_top_level_refund)). - top_level_refund: u64, + /// 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, /// The EIP-8037 reservoir the settled transaction left unspent. reservoir_remaining: u64, - /// Satin's side of every frame start, one per frame result revm will return: what the start's - /// caller paid for its records, what the journal's ledger saw the start count, the history - /// allowance the frame was granted, and the mark a frame revm built is taken back to when it - /// is rewritten into a failure. - starts: Vec, +} + +/// What a transaction's frames keep: the data-size bytes they drew from their pools, and, among +/// them, the write records and the EIP-7708 transfer logs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Kept { + /// Data-size bytes. + bytes: u64, + /// Write records. + records: u64, + /// EIP-7708 transfer logs. + transfer_logs: u64, +} + +/// What one write, or one frame start, adds to what a frame keeps and takes back from it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counted { + /// Data-size bytes added: records, a log's bytes, deployed code, a transfer log. + pub(crate) added: u64, + /// Data-size bytes taken back: the records of accounts and slots returned to what the + /// transaction loaded. + pub(crate) taken: u64, + /// Write records added. + pub(crate) records_added: u64, + /// Write records taken back. + pub(crate) records_taken: u64, + /// Whether an EIP-7708 transfer log is among the bytes added. + pub(crate) transfer_log: bool, +} + +impl Counted { + /// Nothing counted. + pub(crate) const NONE: Self = + Self { added: 0, taken: 0, records_added: 0, records_taken: 0, transfer_log: false }; + + /// `added` write records made and `taken` taken back, with an EIP-7708 transfer log when + /// `transfer_log`. + 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: WRITE_RECORD_SIZE.saturating_mul(added).saturating_add(log), + taken: WRITE_RECORD_SIZE.saturating_mul(taken), + records_added: added, + records_taken: taken, + transfer_log, + } + } + + /// `bytes` bytes that are no write record: a log's, or deployed code. + pub(crate) const fn bytes(bytes: u64) -> Self { + Self { added: bytes, ..Self::NONE } + } + + /// Whether it adds nothing and takes nothing back. + const fn is_none(&self) -> bool { + self.added == 0 && self.taken == 0 + } +} + +/// 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, + /// The bytes of a creator's nonce record the frame's own pool could not pay when the frame + /// created, which it owes until the creation returns into it. + overdraft: u64, +} + +/// The record of its own nonce a creation's start hook charged its creator for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct CreatorRecord { + /// The history gas it cost. + pub(crate) history: u64, + /// The bytes it drew from the creator's pool. + pub(crate) drawn: u64, + /// The bytes the creator's pool could not pay, which the creator owes. + pub(crate) overdraft: u64, } impl AdditionalLimit { @@ -116,22 +216,361 @@ impl AdditionalLimit { self.limits = limits; } - /// Clears the state for a new transaction, keeping allocations and the limits. - pub(crate) fn reset(&mut self) { - self.exempt = false; + /// 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. + /// + /// 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.pending_stop = None; self.frame_stop = None; self.limit_exceeded = None; + self.body = body; + self.hints = 0; + self.authorities = 0; + self.kept = Kept::default(); + self.decided.clear(); + self.pending_creator = None; + self.kept_nothing = false; 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.top_level_refund = 0; + self.first_frame_charge = 0; self.history_gas_spent = 0; self.history_bytes = 0; self.reservoir_remaining = 0; - self.starts.clear(); + } + + /* What the transaction keeps */ + + /// What the transaction keeps so far: its data-size bytes and write records, every running + /// frame counted as if it succeeds. + pub(crate) const fn usage(&self) -> LimitUsage { + LimitUsage { + data_size: self + .body + .saturating_add(self.hints) + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) + .saturating_add(self.kept.bytes), + write_records: self.authorities.saturating_add(self.kept.records), + } + } + + /// 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 + } + + /// 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 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) const fn admits_tx_body(&self, authorizations: u64) -> bool { + self.exempt || + self.body.saturating_add(WRITE_RECORD_SIZE.saturating_mul(authorizations)) <= + self.limits.tx_data_size_limit + } + + /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts + /// other than the transaction's sender, 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 count_authorities(&mut self, authorities: u64) { + self.authorities = authorities; + debug_assert!( + 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" + ); + } + + /// Takes back the authorities' records, 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; + } + + /// The pool of the transaction's own frame: what the transaction has left of its data-size + /// limit once its body and the records made before the frame are counted, under the frame + /// cap; unlimited for an exempt transaction. + pub(crate) const fn first_frame_pool(&self) -> u64 { + let left = self.limits.tx_data_size_limit.saturating_sub(self.usage().data_size); + let cap = self.frame_cap(); + if self.exempt { + u64::MAX + } else if left < cap { + left + } else { + cap + } + } + + /// The most a frame's pool may start with: the frame cap, and nothing for an exempt + /// transaction. + pub(crate) const fn frame_cap(&self) -> u64 { + if self.exempt { + u64::MAX + } else { + self.limits.frame_data_size_limit + } + } + + /* 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. + /// + /// 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 } + } + + /// The verdict on the transaction keeping `counted` more: its data-size limit crossed, or + /// within. + const fn check_transaction(&self, counted: &Counted) -> LimitCheck { + let used = + self.usage().data_size.saturating_sub(counted.taken).saturating_add(counted.added); + if used > self.limits.tx_data_size_limit { + return self.crossed(LimitKind::DataSize, self.limits.tx_data_size_limit, used, false); + } + LimitCheck::WithinLimit + } + + /// The verdict on a frame budget crossed by `added` bytes the pool `gas` holds could not pay: + /// 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 `added` in. + fn budget_crossed(&self, gas: &GasTracker, added: u64) -> LimitCheck { + let budget = gas.bytes_remaining().saturating_add_signed(gas.bytes_spent()); + let used = gas.bytes_spent().saturating_add_unsigned(added).max(0).unsigned_abs(); + self.crossed(LimitKind::DataSize, budget, used, true) + } + + /// Counts what the frame whose pool `gas` holds keeps of `counted`, held to the transaction's + /// limit, then to the frame's budget: the bytes `counted` takes back go back to the pool + /// first, and the bytes it adds are drawn; a draw the pool cannot pay is the frame's budget + /// crossed. A crossing counts nothing and draws nothing, and is the stop the frame reverts + /// with. A count that adds nothing holds nothing. + pub(crate) fn draw(&mut self, gas: &mut GasTracker, counted: &Counted) -> LimitCheck { + if counted.is_none() { + return LimitCheck::WithinLimit; + } + if counted.added != 0 { + let check = self.check_transaction(counted); + if check.exceeded_limit() { + return check; + } + } + gas.refill_bytes(counted.taken); + if !gas.record_bytes(counted.added) { + gas.clear_bytes_crossing(); + let check = self.budget_crossed(gas, counted.added); + let drew = gas.record_bytes(counted.taken); + debug_assert!(drew, "what was given back can be drawn again"); + return check; + } + self.count(counted); + LimitCheck::WithinLimit + } + + /// Adds `counted` to what the frames keep. + fn count(&mut self, counted: &Counted) { + let kept = &mut self.kept; + debug_assert!( + kept.bytes >= counted.taken && kept.records >= counted.records_taken, + "a frame takes back only what the transaction's frames keep" + ); + kept.bytes = kept.bytes.saturating_sub(counted.taken).saturating_add(counted.added); + kept.records = kept + .records + .saturating_sub(counted.records_taken) + .saturating_add(counted.records_added); + 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 the transaction's limit and to `budget`, the + /// pool its frame would start with. Nothing is counted. + pub(crate) const fn hypothetical_start(&self, counted: &Counted, budget: u64) -> LimitCheck { + let check = self.check_transaction(counted); + if check.exceeded_limit() { + return check; + } + let used = counted.added.saturating_sub(counted.taken); + if used > budget { + return self.crossed(LimitKind::DataSize, budget, used, true); + } + LimitCheck::WithinLimit + } + + /// 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.check_transaction(&Counted::bytes(bytes)); + if check.within_limit() { + self.hints = self.hints.saturating_add(bytes); + } + check + } + + /* A frame's start */ + + /// Counts the record of a creator's own nonce, which a creation's start makes on the creating + /// frame, whose pool `gas` holds, before the frame's share is forwarded: the creation's budget + /// is taken from what the creator has left once the record is counted. It lands on the creator + /// unchecked, and the creator is held to its limits with it once the creation returns + /// ([`hold_caller`](Self::hold_caller)); a pool that cannot pay it is drained, and the creator + /// owes the rest until then. `history` is what the creator paid for it. + pub(crate) fn count_creator_record(&mut self, gas: &mut GasTracker, history: u64) { + self.count(&Counted::records(1, 0, false)); + let drawn = WRITE_RECORD_SIZE.min(gas.bytes_remaining()); + let drew = gas.record_bytes(drawn); + debug_assert!(drew, "the draw is what the pool holds"); + let overdraft = WRITE_RECORD_SIZE - drawn; + if overdraft != 0 { + if let Some(running) = self.decided.last_mut() { + running.overdraft += overdraft; + } + } + self.pending_creator = Some(CreatorRecord { history, drawn, overdraft }); + } + + /// The record of its own nonce the last creation's start hook charged its creator for, which + /// the start's decision takes: revm deciding it keeps it, an inspector answering in its place + /// gives it back ([`give_back_creator_record`](Self::give_back_creator_record)). + pub(crate) const fn take_creator_record(&mut self) -> Option { + self.pending_creator.take() + } + + /// Takes back the record of its own nonce a creation's start counted on its creator, for a + /// creation an inspector answered in revm's place: the start never bumped the nonce. What the + /// creator paid for it goes back through the creation's answer. + pub(crate) fn give_back_creator_record(&mut self, record: CreatorRecord) { + self.count(&Counted::records(0, 1, false)); + if let Some(running) = self.decided.last_mut() { + running.overdraft -= record.overdraft; + } + } + + /// 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)). + pub(crate) fn open_start(&mut self, depth: usize) { + self.decided.push(Decided { depth, at_start: self.kept, credit: 0, overdraft: 0 }); + } + + /// Holds the start revm just decided, whose frame's pool `gas` holds, to the limits, and counts + /// `counted`, the records and transfer log it made, on that pool ([`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. + pub(crate) fn count_start( + &mut self, + gas: &mut GasTracker, + counted: &Counted, + credit: u64, + ) -> LimitCheck { + let check = self.draw(gas, counted); + if check.within_limit() { + if let Some(start) = self.decided.last_mut() { + start.credit = credit; + } + } + check + } + + /// Notes that the result returning next kept nothing, whatever it says: an inspector revived + /// a frame that failed. + pub(crate) const fn kept_nothing(&mut self) { + self.kept_nothing = true; + } + + /// Closes the start of the frame whose result returns at `depth`, `kept` or not, and answers + /// the history its caller gets back for it: a frame that kept nothing — it failed, or an + /// inspector revived it — has what the frames keep restored to what they kept when its start + /// began, and its caller gets nothing back; one that kept its start, the start's credit. + /// + /// A result revm did not decide the start of — the depth guard's, an interceptor's, an + /// inspector's — has no start to close: what its caller paid comes back with its start charge. + pub(crate) fn close_start(&mut self, depth: usize, kept: bool) -> u64 { + let kept_nothing = core::mem::take(&mut self.kept_nothing); + let kept = kept && !kept_nothing; + let Some(&start) = self.decided.last().filter(|start| start.depth == depth) else { + return 0; + }; + self.decided.pop(); + if kept { + start.credit + } else { + self.kept = start.at_start; + 0 + } + } + + /// Holds the frame a child just returned into, whose pool `gas` holds, to its limits with what + /// it now keeps: a creation's nonce record, which outlives the creation, lands on its creator + /// unchecked ([`count_creator_record`](Self::count_creator_record)), and a crossing is the stop + /// the creator returns before it runs on ([`stop_before_run`](Self::stop_before_run)). The + /// transaction's limit is held first. A record the creator's pool could not pay is drawn now if + /// the pool can pay it; a creator still owing it crossed its budget. + /// + /// Any other return leaves the caller within its limits — a failure hands it nothing, and a + /// success no more than the share it gave — and clears a stop it had. + pub(crate) fn hold_caller(&mut self, gas: &mut GasTracker) { + let check = self.check_transaction(&Counted::NONE); + self.pending_stop = check.exceeded_limit().then_some(check); + if self.pending_stop.is_some() { + return; + } + let Some(running) = self.decided.last_mut() else { return }; + let overdraft = running.overdraft; + if overdraft == 0 { + return; + } + if gas.record_bytes(overdraft) { + running.overdraft = 0; + return; + } + gas.clear_bytes_crossing(); + let stop = self.budget_crossed(gas, overdraft); + self.pending_stop = stop.exceeded_limit().then_some(stop); + } + + /// Takes back one write record of the running frame, whose pool `gas` holds, for an account a + /// write outside the hooks returned to what the transaction loaded: a `keylessDeploy` call's + /// signer, whose nonce the settlement sets back. A record the frame still owes is forgiven + /// first. + pub(crate) fn take_back_record(&mut self, gas: &mut GasTracker) { + let forgiven = self.decided.last_mut().map_or(0, |running| { + let forgiven = running.overdraft.min(WRITE_RECORD_SIZE); + running.overdraft -= forgiven; + forgiven + }); + gas.refill_bytes(WRITE_RECORD_SIZE - forgiven); + self.count(&Counted::records(0, 1, false)); } /* The stops and the exemption */ @@ -155,87 +594,88 @@ impl AdditionalLimit { /// 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_start_return`](Self::on_start_return) takes it, and the transaction's when that frame - /// is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). + /// 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() } + /// 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)); + } + } + /// 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; the journal's ledger begins the transaction exempt alongside. - /// 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. - /// - /// Gas detention's compute stop comes from here, as the data-size stops come from the - /// ledger's own verdict, so this is where the exemption applies to it: 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 } - } - /// The stop the running frame returns instead of running another instruction: the one its own /// start left it ([`hold_start`](Self::hold_start)), or the one - /// [`on_start_return`](Self::on_start_return) left for a caller its child put over a limit. - /// Taking it clears it, which stops one frame. + /// [`hold_caller`](Self::hold_caller) 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.pending_stop.take() } - /// Holds the start of the frame revm just built to `verdict`, the journal's ledger's on what - /// the start counted while the frame's level was open: a crossing is the stop the frame + /// Holds the start of the frame revm just built to `verdict`: a crossing is the stop the frame /// returns on its first run, before any instruction /// ([`stop_before_run`](Self::stop_before_run)). revm moved the value, journaled the transfer /// log and, for a creation, bumped its creator's nonce; the stop is a revert of the frame, so /// its journal checkpoint takes the move and the log back, and the nonce, bumped before the /// checkpoint, stays, with its record on the creator. #[inline] - pub(crate) fn hold_start(&mut self, verdict: Option) { - if let Some(stop) = verdict.filter(LimitCheck::exceeded_limit) { + pub(crate) fn hold_start(&mut self, verdict: LimitCheck) { + if verdict.exceeded_limit() { debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); - self.pending_stop = Some(stop); + self.pending_stop = Some(verdict); } } - /// Holds the running frame to `check`, the journal's ledger's, once what it keeps changed - /// outside its own instructions — a child returned into it, or a record a child left it was - /// taken back: a crossing is the stop it returns before it runs on, and anything else clears a - /// stop it had. - pub(crate) fn hold_running_frame(&mut self, check: LimitCheck) { - self.pending_stop = check.exceeded_limit().then_some(check); - } - /// Whether the running frame has a stop to return before it runs another instruction /// ([`stop_before_run`](Self::stop_before_run)). pub(crate) const fn has_stop_before_run(&self) -> bool { self.pending_stop.is_some() } + /* What the transaction pays before its first frame */ + + /// 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 + } + + /// 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; + } + + /// 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; + } + + /// 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 + } + /* What the settled transaction reports */ /// The history gas the last settled transaction spent. @@ -243,11 +683,6 @@ impl AdditionalLimit { 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; - } - /// 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 @@ -261,22 +696,6 @@ impl AdditionalLimit { self.reservoir_remaining = reservoir; } - /// 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 @@ -285,195 +704,20 @@ impl AdditionalLimit { self.history_bytes } - /// Settles [`history_bytes`](Self::history_bytes) from what the transaction kept — its - /// `write_records` and its `log_and_code_bytes`, as the journal's ledger holds them once the - /// transaction's own frame returned: `priced` is whether it pays history at all. - pub(crate) const fn settle_history_bytes( - &mut self, - priced: bool, - write_records: u64, - log_and_code_bytes: u64, - ) { + /// 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(write_records)) - .saturating_add(log_and_code_bytes) + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) + .saturating_add(self.kept.bytes) + .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) } else { 0 }; } - - /* The charges a frame start is paid for */ - - /// Records 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 does not keep the record gets it back at the settlement, with the rest of what the - /// frame did not keep. - 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 that frame's side to hold the ledger's count to once revm - /// decided the start ([`attach_start`](Self::attach_start)). - /// - /// Only a transaction that pays history is charged, and so leaves one. - pub(crate) const fn stage_top_level_records(&mut self, records: FrameStartRecords) { - self.pending_top_level_records = Some(records); - } - - /// Leaves the history gas the running opcode just charged its frame for the records the frame - /// it starts will make: `added` for the records that frame's failure takes back, `creator` for - /// the record of the creator's own nonce, and `records`, the answer the charge was computed - /// from, for the frame's side to hold the ledger's count to; `priced` says whether the - /// transaction prices history at all, so that a record the start takes back is history the - /// caller gets back. - /// - /// The next side pushed takes it, whether that is the frame's own or that of a frame answered - /// without running. - #[inline] - pub(crate) const fn stage_frame_charge( - &mut self, - records: FrameStartRecords, - added: u64, - creator: u64, - priced: bool, - ) { - self.pending_frame_charge = FrameCharge { records: Some(records), added, creator, priced }; - } - - /// Leaves the frame about to start unchecked against the answer its charge was computed from - /// — its caller's at the opcode, or the transaction's before execution for the transaction's - /// own frame: an inspector that may rewrite the frame's input runs between the charge and the - /// count. - pub(crate) const fn waive_start_check(&mut self) { - self.pending_frame_charge.records = None; - self.pending_top_level_records = None; - } - - /// 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.starts.last_mut().map_or(0, |side| side.consume_stipend(amount)) - } - - /* The frame side */ - - /// Pushes Satin's side of the start of the frame `input` asks for at `depth`, which revm - /// decides next: what its caller paid for the records the start makes, and, for a - /// value-transferring `CALL` or `CALLCODE` below the transaction's own frame, the history - /// allowance the frame is granted ([`storage_call_stipend`](crate::storage_call_stipend)). - /// What the ledger then sees the start count is attached once revm decided it - /// ([`attach_start`](Self::attach_start)). - pub(crate) fn push_start(&mut self, input: &FrameInput, depth: usize) { - self.push_side(depth); - if let FrameInput::Call(inputs) = input { - if depth > 0 && grants_stipend(inputs) { - if let Some(side) = self.starts.last_mut() { - side.grant_stipend(storage_call_stipend()); - } - } - } - } - - /// Pushes the side of a frame at `depth` answered without revm deciding its start — by the - /// depth guard, an interceptor or an inspector — which keeps the frame sides aligned with the - /// results revm returns. Such a frame makes none of the records its caller paid for, so the - /// whole charge comes back when its side is popped, whatever the answer was. - pub(crate) fn push_answered_start(&mut self, depth: usize) { - self.push_side(depth); - } - - /// Pushes a side at `depth` carrying the charge waiting for it: the opcode's for a frame below - /// the transaction's own, and, for the transaction's own frame, what was charged before - /// execution for the write record it makes. - fn push_side(&mut self, depth: usize) { - let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - let side = if depth == 0 { - // The transaction's own frame takes no record back: before it, the transaction changed - // only its sender, to which no value moves, and the authorities it applied, which - // differ by a nonce no transfer returns. - let records = self.pending_top_level_records.take(); - StartSide::new(depth, self.top_level_write_record_gas, 0, false, records) - } else { - StartSide::new(depth, charge.added, charge.creator, charge.priced, charge.records) - }; - self.starts.push(side); - } - - /// Attaches what the journal's ledger saw the latest start count, and what a frame revm built - /// is taken back to, to that start's side, and holds the count to the records the start's - /// charge was computed from ([`StartSide::attach`]). - pub(crate) fn attach_start(&mut self, report: StartReport, built: Option<(StartId, Rollback)>) { - if let Some(side) = self.starts.last_mut() { - side.attach(report, built); - } - } - - /// The side of the running frame's start, or of the start just answered. - pub(crate) fn running_start(&self) -> Option<&StartSide> { - self.starts.last() - } - - /// The number of starts whose frames have not returned yet. - pub(crate) fn starts_open(&self) -> usize { - self.starts.len() - } - - /// Pops the side of the start of the frame `result` returns from, once revm closed the frame's - /// level, and settles what the start and the frame leave behind, as the journal's `ledger` - /// holds them: - /// - /// - the history the caller paid for the start's records, less the price of those the ledger - /// still holds ([`StartSide::refund`]), which the caller gets back once the frame merged into - /// it. The transaction's own frame was paid for before execution: its refund is kept for the - /// settlement ([`take_top_level_refund`](Self::take_top_level_refund)); - /// - the caller, held to its limits with what it now holds: a failed creation's nonce record, - /// which outlives the creation, lands on its creator, and a crossing is the stop the caller - /// returns before it runs on ([`stop_before_run`](Self::stop_before_run)). Any other return - /// leaves the caller within its limits — a failure hands it nothing, and a success no more - /// than the share it gave — and is held all the same; - /// - the crossing the result is made of, the stop noted for the frame - /// ([`note_frame_stop`](Self::note_frame_stop)), which 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 side, and the history its caller gets back. - pub(crate) fn on_start_return( - &mut self, - ledger: &Ledger, - result: &FrameResult, - ) -> Option<(StartSide, u64)> { - let noted = self.frame_stop.take(); - // 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 side = self.starts.pop()?; - let refund = side.refund(ledger); - if side.depth() == 0 { - self.limit_exceeded = noted.filter(|stop| is_the_revert_of(result, stop)); - self.top_level_refund = refund; - return Some((side, 0)); - } - self.hold_running_frame(ledger.check()); - Some((side, refund)) - } - - /// The history gas the transaction's own frame's start gets back, once that frame returned - /// ([`on_start_return`](Self::on_start_return)): what the transaction paid before execution - /// for the write record that frame makes, unless the frame kept it. The settlement takes it - /// and gives it back; a transaction whose own frame never started gets nothing back, having - /// paid nothing that stands. - pub(crate) const fn take_top_level_refund(&mut self) -> u64 { - let refund = self.top_level_refund; - self.top_level_refund = 0; - refund - } } /// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the @@ -483,159 +727,16 @@ fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { result.result == InstructionResult::Revert && result.output == stop.revert_data() } -/// 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 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. - records: Option, - /// What the records the start adds on the frame's own level cost. - added: u64, - /// What the record of the creator's own nonce cost. - creator: u64, - /// Whether the transaction prices history. - priced: bool, -} - -impl FrameCharge { - /// Nothing charged. - const NONE: Self = Self { records: None, added: 0, creator: 0, priced: false }; -} - #[cfg(test)] mod tests { use super::*; - use crate::{ - limit::{RecordDelta, StartFacts}, - test_utils::MemoryDatabase, - MegaContext, MegaSpecId, - }; - use alloy_primitives::{address, Address, Bytes, U256}; - use revm::{ - context::{ContextTr, JournalTr}, - interpreter::{CallInput, CallValue}, - }; - - const SENDER: Address = address!("00000000000000000000000000000000000f0001"); - const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); - const TARGET: Address = address!("00000000000000000000000000000000000f0003"); - - 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, - charged_start: Default::default(), - bytes_share: u64::MAX, - history_allowance: 0, - } - } - - /// 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) - })) - } - - /// What the ledger reports of a start revm made and held to the limits: `records`. - fn report(records: FrameStartRecords) -> StartReport { - StartReport { - start: Some(StartId::default()), - records, - transfer_log: false, - verdict: Some(LimitCheck::WithinLimit), - } - } - - /// `added` records a call's value transfer makes on the frame's level. - const fn transfer(added: u64) -> FrameStartRecords { - FrameStartRecords::of_transfer(RecordDelta { added, taken: 0 }) - } - - /// A creation's records: its created account's on the frame's level (`created`), and its - /// creator's own below it (`creator`). - const fn creation(created: bool, creator: bool) -> FrameStartRecords { - FrameStartRecords { transfer: RecordDelta::NONE, created, creator } - } - /// 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"); - } - } - - /// The allowance is the started frame's, below the transaction's own frame: its side draws on - /// it, and nothing is left once the side is popped. The transaction's own frame is granted - /// none, however it was started. At a history price of nothing the allowance is nothing, and - /// there is nothing to draw. - #[test] - fn test_the_allowance_is_granted_to_the_frame_a_value_call_starts() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let ledger = ctx.ledger(); - let stipend = storage_call_stipend(); - if stipend == 0 { - crate::test_utils::note_price_guard("MEGA_SATIN_CPHB prices a history byte at nothing"); - return; - } - let mut limit = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - assert_eq!(limit.try_consume_stipend(1), 0, "the transaction's own frame has none"); - limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - assert_eq!(limit.try_consume_stipend(stipend - 1), stipend - 1); - assert_eq!(limit.try_consume_stipend(5), 1, "what is left of it"); - assert_eq!(limit.try_consume_stipend(5), 0); - let result = crate::synthetic_frame_result( - &call_from_to(CALLEE, TARGET, U256::from(1)), - InstructionResult::Stop, - Bytes::new(), - ); - let _ = limit.on_start_return(ledger, &result); - assert_eq!(limit.try_consume_stipend(5), 0, "the caller's own frame has none"); - } - - /// An exempt layer answers every crossing of gas detention's as within the limits, in any - /// dimension and at the transaction or at a frame; a reset ends the exemption, and the next - /// transaction is held to its limits again. + /// 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_the_exemption_answers_every_crossing_and_lasts_one_transaction() { let mut limit = AdditionalLimit::default(); - limit.exempt(); + limit.begin_transaction(true, false, 0); assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { @@ -643,7 +744,7 @@ mod tests { assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); } } - limit.reset(); + limit.begin_transaction(false, false, 0); assert!(!limit.is_exempt()); assert_eq!( limit.crossed(LimitKind::ComputeGas, 0, 1, false), @@ -653,242 +754,7 @@ mod tests { used: 1, frame_local: false }, - "after a reset the transaction is held to its limits" + "the next transaction is held to its limits" ); } - - /// The records the ledger counts for a start are the records its caller was charged for: a - /// value transfer records the caller's account and the recipient's, the two the charge was - /// computed from, and a creation the created account and its creator's nonce. The charge counts - /// the created account for every creation, the address not being known at the opcode, so a - /// creation onto an account the transaction changed already counts less than it was charged - /// for. A start revm refused, or failed before its level opened, counted nothing and is not - /// held to the charge. - #[test] - fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { - let mut limit = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - for (charged, counted) in [ - (transfer(2), transfer(2)), - (creation(true, true), creation(true, true)), - (creation(true, true), creation(false, true)), - (creation(true, false), creation(false, false)), - ] { - limit.stage_frame_charge(charged, 2, 0, true); - limit.push_start(&inner, 1); - limit.attach_start(report(counted), None); - } - - limit.stage_frame_charge(transfer(2), 2, 0, true); - limit.push_start(&inner, 1); - let refused = StartReport { verdict: None, ..report(FrameStartRecords::NONE) }; - limit.attach_start(refused, None); - } - - /// Attaches to a value call's side, charged for `charged`, a start the ledger counted - /// `counted` for: what the check below holds every start to. - fn attach_counted_against_charged(charged: FrameStartRecords, counted: FrameStartRecords) { - let mut limit = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_frame_charge(charged, 0, 0, true); - limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(counted), None); - } - - /// Every record but a creation's created account is held to the charge exactly: a transfer - /// that counts one record fewer than its caller was charged for trips, as one that counts more - /// does. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_transfer_counting_fewer_records_than_charged_trips() { - attach_counted_against_charged(transfer(2), transfer(1)); - } - - /// A creator's nonce record the ledger counted where none was charged trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_creator_record_not_charged_trips() { - attach_counted_against_charged(creation(true, false), creation(true, true)); - } - - /// A created account's record the ledger counted where none was charged trips: the charge may - /// count it where the ledger does not, never the reverse. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_created_account_not_charged_trips() { - attach_counted_against_charged(creation(false, false), creation(true, false)); - } - - /// 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 = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); - limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(transfer(2)), None); - } - - /// The transaction's own frame is held to the records its history was charged for before - /// execution: its value's recipient, or the account a creation makes. - #[test] - fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { - for records in [transfer(0), transfer(1), creation(true, false)] { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(records); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(records), None); - } - } - - /// A transaction's own frame that makes another record than its history paid for trips the - /// check, rather than counting data size no history matches or keeping history no data size - /// matches. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_top_level_record_its_history_did_not_pay_for_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(transfer(0)); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(transfer(1)), None); - } - - /// Under an inspector that may rewrite a start, the check is waived: the start its charge paid - /// for may not be the one revm made. - #[test] - fn test_a_waived_start_is_not_held_to_its_charge() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(transfer(0)); - limit.waive_start_check(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); - limit.attach_start(report(transfer(1)), None); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0, true); - limit.waive_start_check(); - limit.push_start(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - limit.attach_start(report(transfer(2)), None); - } - - /// 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: the whole - /// charge comes back when its side is popped, and the caller it returns into is held to the - /// ledger's check. - /// - /// 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_gives_the_whole_charge_back() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let ledger = ctx.ledger(); - for answer in - [InstructionResult::CallTooDeep, InstructionResult::Revert, InstructionResult::Stop] - { - let mut limit = AdditionalLimit::default(); - limit.push_start(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(creation(true, true), 1_000, 2_000, true); - limit.push_answered_start(1); - let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); - let (_, refund) = limit.on_start_return(ledger, &result).expect("the side"); - assert_eq!(refund, 3_000, "{answer:?}: all of it back"); - assert_eq!(limit.stop_before_run(), None, "{answer:?}: the caller runs on"); - assert_eq!(limit.starts_open(), 1, "{answer:?}: the caller's side is left"); - } - } - - /// The transaction's own frame's side keeps what was charged before execution for the write - /// record the frame makes, and gives it to the settlement when the frame did not keep the - /// record: a frame that failed, and a frame answered before revm decided it. A frame that kept - /// its record gives nothing back, and a transaction whose first frame never started has - /// nothing to give back. - /// - /// The record's history is charged at the price in effect, as pre-execution charges it, so the - /// refunds hold at any history byte price, a price of nothing included. - #[test] - fn test_the_top_level_record_comes_back_once_at_the_settlement() { - let charge = crate::write_record_history_gas(1).unwrap_or(0); - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let outer = call_from_to(SENDER, CALLEE, U256::from(1)); - let ended = |result| crate::synthetic_frame_result(&outer, result, Bytes::new()); - // The start kept: a level revm committed. - for (case, failed, refund) in [("kept", false, 0), ("failed", true, charge)] { - let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(charge); - limit.push_start(&outer, 0); - ctx.ledger_mut().begin_transaction(false, false, 0); - ctx.ledger_mut().open_start(StartFacts { - depth: 0, - creation: false, - transfers_value: true, - }); - let checkpoint = ctx.journal_mut().checkpoint(); - ctx.ledger_mut().on_transfer(RecordDelta { added: 1, taken: 0 }, false, false); - let report = ctx.ledger_mut().close_start(); - limit.attach_start(report, None); - ctx.ledger_mut().frame_returning(); - if failed { - ctx.journal_mut().checkpoint_revert(checkpoint); - } else { - ctx.journal_mut().checkpoint_commit(); - } - let result = - ended(if failed { InstructionResult::Revert } else { InstructionResult::Stop }); - let (side, caller) = limit.on_start_return(ctx.ledger(), &result).expect("the side"); - assert_eq!(side.depth(), 0, "{case}"); - assert_eq!(caller, 0, "{case}: the transaction's own frame has no caller to refund"); - assert_eq!(limit.take_top_level_refund(), refund, "{case}"); - assert_eq!(limit.take_top_level_refund(), 0, "{case}: taken once"); - } - - // Answered before revm decided it: nothing counted, everything back. - let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(charge); - limit.push_answered_start(0); - let _ = limit.on_start_return(ctx.ledger(), &ended(InstructionResult::Stop)); - assert_eq!(limit.take_top_level_refund(), charge); - - // Never started: no side, nothing back. - let mut limit = AdditionalLimit::default(); - limit.set_top_level_write_record_gas(charge); - assert!(limit.on_start_return(ctx.ledger(), &ended(InstructionResult::OutOfGas)).is_none()); - assert_eq!(limit.take_top_level_refund(), 0); - } - - /// The stop the transaction reports is the crossing its own frame's result is made of, read as - /// that frame returns, and only while the result is still the stop's revert. - #[test] - fn test_limit_exceeded_is_the_stop_the_own_frames_result_is_made_of() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let outer = call_from_to(SENDER, CALLEE, U256::ZERO); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 3, - used: 4, - frame_local: false, - }; - for (case, output, result, reported) in [ - ("the stop's revert", stop.revert_data(), InstructionResult::Revert, Some(stop)), - ("another output", Bytes::new(), InstructionResult::Revert, None), - ("a success", stop.revert_data(), InstructionResult::Return, None), - ] { - let mut limit = AdditionalLimit::default(); - limit.push_start(&outer, 0); - let data = limit.note_frame_stop(&stop); - assert_eq!(data, stop.revert_data(), "{case}"); - let result = crate::synthetic_frame_result(&outer, result, output); - let _ = limit.on_start_return(ctx.ledger(), &result); - assert_eq!(limit.limit_exceeded().copied(), reported, "{case}"); - } - } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 2d4d26619..9988d500d 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -6,19 +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 ledger -//! counts, and it holds a frame to the cap with the gas the frame may spend. It stops the frame +//! [`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`]). //! -//! What the data-size limit meters — data-size bytes and write records — is counted by the -//! journal's ledger ([`MegaJournal`](crate::MegaJournal), `ledger.rs`), on one level per open -//! checkpoint of revm's journal, at the journal's writes and from the Host's hooks, and revm's -//! checkpoint reverts rewind it: what the ledger holds is what the journal keeps, whoever reverted -//! what. A write an opcode makes is counted once the opcode completed, in the Host's -//! completed-write hook, which revm calls after every charge the opcode makes. Beside the ledger, -//! [`AdditionalLimit`] keeps Satin's side of each frame start, the stops and the settled figures. +//! 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 //! @@ -42,7 +43,7 @@ //! - the records a frame's start makes, when the frame starts; //! - 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 level before the creation is committed, so a crossing leaves +//! - 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; @@ -51,19 +52,22 @@ //! moves: with the records of the frame start that moves it — the transaction's own value, a //! 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 -//! level of the frame whose journal checkpoint holds the move, so the failure that takes the move +//! 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 as the frame starts and held to the limits once revm decided it, on -//! what revm then did. 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, gets back what its caller paid for -//! its records, and no limit stops it. A creation revm fails after it bumped its creator's nonce, -//! onto an occupied address, is held to nothing at its start: its failure discards its records and -//! transfer log, but for the nonce record, which lands on the creator. +//! 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, gets back +//! what its caller paid for its records, and no limit stops it. A creation revm fails after it +//! bumped its creator's nonce, onto an occupied address, is held to nothing at its start: its +//! failure discards its records and transfer log, but for the nonce record, which lands on the +//! creator. //! //! 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 @@ -79,14 +83,14 @@ //! //! # Write records //! -//! The write-record count the ledger 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 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 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 //! @@ -134,16 +138,13 @@ //! 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 ledger; #[allow(clippy::module_inception)] mod limit; mod record; -#[cfg(test)] -pub(crate) use ledger::StartSide; -pub(crate) use ledger::{FrameIdentity, FrameStartRecords, Ledger, Mark, StartFacts, StartReport}; pub use limit::AdditionalLimit; -pub(crate) use record::{HistoryBytes, RecordDelta}; +pub(crate) use limit::{Counted, CreatorRecord}; +pub(crate) use record::{Accounts, HistoryBytes, RecordDelta, StartRecords}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; @@ -332,14 +333,6 @@ 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 }; @@ -545,8 +538,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 @@ -597,14 +588,12 @@ 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); - assert_eq!( - WRITE_RECORD.saturating_add(WRITE_RECORD).saturating_sub(WRITE_RECORD), - WRITE_RECORD - ); + let record = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; + assert_eq!(max.saturating_add(record), max); + assert_eq!(LimitUsage::ZERO.saturating_sub(record), LimitUsage::ZERO); + assert_eq!(record.times(3), LimitUsage { data_size: 120, write_records: 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`. diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index f88951eec..4db299970 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -1,22 +1,27 @@ -//! What a write an opcode completed counts. +//! What a write counts: the write records it makes and takes back, by the net change of what it +//! writes, and its other bytes. //! -//! revm hands the Host the facts of every write `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` -//! complete, once the write is in the journal and every charge the opcode makes has been made -//! ([`Host::write_completed`](revm::context_interface::Host::write_completed)). A failed opcode -//! offers nothing, so nothing here is counted for a write its failure takes back. +//! 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. -use revm::context_interface::host::CompletedWrite; +use revm::{ + context_interface::host::{CompletedWrite, FrameStartKind}, + primitives::{Address, U256}, + state::{Account, AccountInfo, EvmState, TransactionId}, + Journal, +}; -use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; +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. -/// -/// A value transfer moves at most one record per side, and a `SELFDESTRUCT` one per account it -/// writes. A creation's records are kept apart from this delta -/// ([`FrameStartRecords`](super::FrameStartRecords)): its created account, which the creation -/// leaves changed and never returns, and its creator's nonce bump, which lands on the creating -/// frame. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct RecordDelta { /// Records created. @@ -46,103 +51,256 @@ impl RecordDelta { } } -/// 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. +/// 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 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. - pub(crate) taken: u64, +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. + 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) + } } -/// What a completed write keeps, as the journal's ledger counts it: what it adds, what it takes -/// back, and the log bytes among what it adds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct WriteCount { - /// What the write adds: records, a log's bytes, a transfer log. - pub(crate) added: LimitUsage, - /// What the write takes back: the records of accounts and slots returned to what the - /// transaction loaded. - pub(crate) taken: LimitUsage, - /// The bytes of [`added`](Self::added) that are a log's. - pub(crate) log_bytes: u64, +/// 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, + transaction_id: TransactionId, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, } -impl WriteCount { - /// Nothing kept. - #[cfg(test)] - pub(crate) const NONE: Self = - Self { added: LimitUsage::ZERO, taken: LimitUsage::ZERO, log_bytes: 0 }; +/// 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 } -/// What committing the write `write` counts, per site, as records added and taken back and as -/// bytes appended and taken 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`: `destruction`, the records of the accounts the move changed and returned, -/// which the journal observed as it made the write: the beneficiary, and the destructed account -/// whose balance the move clears. -pub(crate) fn write_effect( - write: &CompletedWrite<'_>, - destruction: RecordDelta, -) -> (LimitUsage, LimitUsage) { - match *write { - CompletedWrite::Sstore { result: slot, .. } => { - if slot.is_original_eq_present() { - if slot.is_original_eq_new() { - (LimitUsage::ZERO, LimitUsage::ZERO) - } else { - (WRITE_RECORD, LimitUsage::ZERO) - } - } else if slot.is_original_eq_new() { - (LimitUsage::ZERO, WRITE_RECORD) - } else { - (LimitUsage::ZERO, LimitUsage::ZERO) +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, transaction_id: journal.transaction_id, transfer_logs } + } + + /// 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 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, } - CompletedWrite::Log { topics, data_len, .. } => ( - LimitUsage { - data_size: log_history_bytes(u64::from(topics), data_len), - write_records: 0, - }, - LimitUsage::ZERO, - ), - CompletedWrite::SelfDestruct { .. } => { - (WRITE_RECORD.times(destruction.added), WRITE_RECORD.times(destruction.taken)) + } + + /// 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 } } -} -/// Whether the write 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) fn write_moves_value(write: &CompletedWrite<'_>) -> bool { - match *write { - CompletedWrite::SelfDestruct { address, target, result, .. } => { - result.had_value && target != address + /// 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 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)), } - CompletedWrite::Sstore { .. } | CompletedWrite::Log { .. } => false, + } + + /// 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, and the history bytes it appends and takes 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, 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. + pub(crate) fn write_counted(&self, write: &CompletedWrite<'_>) -> (Counted, HistoryBytes) { + let counted = match *write { + CompletedWrite::Sstore { result: slot, .. } => { + if slot.is_original_eq_present() { + if slot.is_original_eq_new() { + Counted::NONE + } else { + Counted::records(1, 0, false) + } + } else if slot.is_original_eq_new() { + Counted::records(0, 1, false) + } else { + Counted::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; + Counted::records(records.added, records.taken, logged) + } + }; + let log = if counted.transfer_log { TRANSFER_LOG_SIZE } else { 0 }; + (counted, HistoryBytes { appended: counted.added - log, taken: counted.taken }) } } +/// 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. + pub(crate) taken: u64, +} + #[cfg(test)] mod tests { use super::*; - use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE}; - use alloy_primitives::{address, Address, U256}; - use revm::context_interface::context::{SStoreResult, SelfDestructResult}; + use crate::{test_utils::MemoryDatabase, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; + use alloy_primitives::address; + use revm::{ + context::JournalTr, + context_interface::context::{SStoreResult, SelfDestructResult}, + }; 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 slot(original: u64, present: u64, new: u64) -> SStoreResult { SStoreResult { @@ -152,73 +310,111 @@ mod tests { } } - fn sstore(slot: &SStoreResult) -> CompletedWrite<'_> { - CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: slot } - } - - const fn log(topics: u8, data_len: u64) -> CompletedWrite<'static> { - CompletedWrite::Log { address: OTHER, topics, data_len } - } - - fn destruction(had_value: bool) -> SelfDestructResult { - SelfDestructResult { had_value, target_exists: true, previously_destroyed: false } + /// 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 } - fn selfdestruct(result: &SelfDestructResult, target: Address) -> CompletedWrite<'_> { - CompletedWrite::SelfDestruct { address: DESTRUCTED, target, balance: U256::ZERO, result } + /// 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, + } } - const RECORD: (LimitUsage, LimitUsage) = (WRITE_RECORD, LimitUsage::ZERO); - const TAKEN: (LimitUsage, LimitUsage) = (LimitUsage::ZERO, WRITE_RECORD); - const NOTHING: (LimitUsage, LimitUsage) = (LimitUsage::ZERO, LimitUsage::ZERO); - /// 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() { - let effect = |original, present, new| { - write_effect(&sstore(&slot(original, present, new)), RecordDelta::NONE) + let journal = journal(); + let accounts = Accounts::of(&journal, false); + let counted = |original, present, new| { + let slot = slot(original, present, new); + let write = CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: &slot }; + accounts.write_counted(&write).0 }; - assert_eq!(effect(0, 0, 1), RECORD); - assert_eq!(effect(5, 5, 0), RECORD); - assert_eq!(effect(0, 1, 0), TAKEN); - assert_eq!(effect(0, 1, 2), NOTHING); - assert_eq!(effect(3, 3, 3), NOTHING); - assert_eq!(effect(3, 4, 4), NOTHING); + assert_eq!(counted(0, 0, 1), Counted::records(1, 0, false)); + assert_eq!(counted(5, 5, 0), Counted::records(1, 0, false)); + assert_eq!(counted(0, 1, 0), Counted::records(0, 1, false)); + assert_eq!(counted(0, 1, 2), Counted::NONE); + assert_eq!(counted(3, 3, 3), Counted::NONE); + assert_eq!(counted(3, 4, 4), Counted::NONE); } - /// 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 effect = |topics, data_len| write_effect(&log(topics, data_len), RecordDelta::NONE); - assert_eq!( - effect(0, 0), - (LimitUsage { data_size: 32, write_records: 0 }, LimitUsage::ZERO) - ); + let journal = journal(); + let accounts = Accounts::of(&journal, false); + let counted = |topics, data_len| { + accounts.write_counted(&CompletedWrite::Log { address: OTHER, topics, data_len }) + }; + 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.added, TRANSFER_LOG_SIZE); + assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, TRANSFER_LOG_SIZE); + } + + /// 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_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!( - effect(4, 100), - (LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }, LimitUsage::ZERO) + 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!( - effect(1, u64::MAX), - (LimitUsage { data_size: u64::MAX, write_records: 0 }, LimitUsage::ZERO) + Accounts::of(&funded, false).write_counted(&destruction(OTHER, 7)).0, + Counted::records(1, 0, false), + "the beneficiary's record alone" ); - } - /// A `SELFDESTRUCT` counts the records the journal saw its move make and take back, whatever - /// the beneficiary: the sender is told apart by its account, which the transaction changed, - /// not by its address. - #[test] - fn test_selfdestruct_counts_the_records_the_journal_observed() { - let moved = destruction(true); - let effect = |target, delta| write_effect(&selfdestruct(&moved, target), delta); + // A pre-existing account destructing to itself keeps its balance: nothing changes. + let to_itself = journal(); assert_eq!( - effect(OTHER, RecordDelta { added: 2, taken: 0 }), - (WRITE_RECORD.times(2), LimitUsage::ZERO) + Accounts::of(&to_itself, true).write_counted(&destruction(DESTRUCTED, 5)).0, + Counted::NONE ); - assert_eq!(effect(OTHER, RecordDelta { added: 1, taken: 1 }), (WRITE_RECORD, WRITE_RECORD)); - assert_eq!(effect(SENDER, RecordDelta { added: 1, taken: 0 }), RECORD); - assert_eq!(effect(DESTRUCTED, RecordDelta::NONE), NOTHING); } /// An account's delta: a record when a write changes it, a record back when a write returns @@ -235,25 +431,48 @@ mod tests { ); } - /// 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. + /// 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_only_a_destruction_to_another_account_moves_value() { - let moves = - |had_value, target| write_moves_value(&selfdestruct(&destruction(had_value), target)); - assert!(moves(true, OTHER)); - assert!(moves(true, SENDER), "the body's record is not the log"); - assert!(!moves(true, DESTRUCTED), "a destruction to itself burns"); - assert!(!moves(false, OTHER), "nothing to move"); - assert!(!write_moves_value(&sstore(&slot(0, 0, 1)))); - assert!(!write_moves_value(&log(3, 32))); - } + 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); - /// 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!(write_effect(&log(3, 32), RecordDelta::NONE).0, crate::limit::TRANSFER_LOG,); - assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, crate::limit::TRANSFER_LOG.data_size); + // 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!( + 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" + ); } } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index d13c90138..8eaf6734f 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -11,7 +11,7 @@ use alloy_sol_types::SolCall; use revm::{ context::{Cfg, ContextError, ContextTr, JournalTr}, context_interface::{ - cfg::{GasId, StateGasCharge, StateGasSite}, + cfg::{gas::StartCharge, GasId, StateGasCharge, StateGasSite}, Host, }, handler::{EthFrame, FrameResult}, @@ -25,7 +25,7 @@ use revm::{ use crate::{ charge_write_records_history, - limit::FrameStartRecords, + limit::StartRecords, synthetic_call_result, system::{ intercept::peek_selector, @@ -206,7 +206,7 @@ pub(crate) fn run( /// /// 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 level runs as the signer, whose +/// its forward and the reservoir it inherits. The call's frame 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( @@ -224,13 +224,7 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - let (added, creator) = deployment.record_charges.unwrap_or((0, 0)); - ctx.additional_limit.stage_frame_charge( - deployment.records, - added, - creator, - deployment.record_charges.is_some(), - ); + let (on_frame, creator) = deployment.record_charges.unwrap_or((0, 0)); let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, @@ -241,6 +235,20 @@ fn start( ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); + // The creation's start charge, which its failure gives back, and its creator's record, which + // the call keeps: counted on the call's pool before the creation's share of it is + // forwarded, as a `CREATE` opcode's start does. + create.set_charged_start(StartCharge::new(on_frame, 0)); + if deployment.records.creator { + ctx.additional_limit.count_creator_record(gas.tracker_mut(), creator); + } + #[cfg(debug_assertions)] + { + ctx.charged_records = Some(deployment.records); + } + let share = ctx.gas_params().bytes_forward_share(gas.bytes_remaining()); + gas.tracker_mut().forward_bytes(share); + create.set_bytes_share(share); ctx.keyless_frame = Some(KeylessFrame::Deploying(Started { deploy_address: deployment.deploy_address, signer: deployment.signer, @@ -266,7 +274,7 @@ struct Deployment { /// Whether the call was charged the created account. charged_create_state_gas: bool, /// The records the creation's start makes. - records: FrameStartRecords, + records: StartRecords, /// What the call paid for them: the created account's, and the signer's nonce. `None` when /// the transaction pays no history. record_charges: Option<(u64, u64)>, @@ -429,11 +437,11 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } - let records = ctx.journal_ref().creation_records(signer, tx.value); + 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.added_on_level(), + records.on_frame().added, u64::from(records.creator), ); if charged.is_none() { diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index d16e87f54..2d7607808 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -248,14 +248,12 @@ fn take_back_bump( gas: &mut Gas, started: &Started, ) -> Result<(), ContextError> { - let changed = ctx.journal_ref().is_changed(started.signer); + let changed = ctx.accounts().is_changed(started.signer); ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); - if changed && !ctx.journal_ref().is_changed(started.signer) { - ctx.ledger_mut().take_back_record(); - // A stop the record left the call, by putting it over a limit, goes with it: the call is - // held to its limits again without the record. - let check = ctx.ledger().check(); - ctx.additional_limit.hold_running_frame(check); + if changed && !ctx.accounts().is_changed(started.signer) { + // A stop the record would leave the call, by putting it over a limit, goes with it: the + // call is held to its limits without the record once it is settled. + ctx.additional_limit.take_back_record(gas.tracker_mut()); gas.refill_history(started.signer_record_charge); } Ok(()) diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 7e9d771a7..fc94e65a9 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -67,9 +67,9 @@ 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 (the journal's -/// ledger admits it, `Ledger::admit_hint`), so trailing bytes an ABI -/// decoder ignores are paid for; a payload that would cross the transaction's limit is neither +/// The payload is counted toward the transaction's data size before it is decoded +/// ([`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.ledger_mut().admit_hint(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)); diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index a13bc1531..789526736 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -25,7 +25,6 @@ mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; -mod journal_ledger; mod limit_exemption; mod limit_stop; mod neutral; @@ -52,6 +51,7 @@ 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/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index c65e36676..f59aa3072 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 data-size budget; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those three applies. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -57,8 +57,8 @@ 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 | -| call_history_allowance | 0 | 0 | 0 | -| bytes_forward_percent | 100 | 100 | 100 | +| call_history_allowance | 0 | 0 | 14080 | +| bytes_forward_percent | 100 | 100 | 98 | | 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..c82533a20 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -141,9 +141,10 @@ 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 data-size budget; the `Satin` column \ + differs from `Amsterdam` in exactly the entries where one of those three applies.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -307,11 +308,11 @@ 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 is the frame's share of the byte pool, which upstream forwards whole. assert_eq!( differing, - ["code_deposit_history_gas"], + ["call_history_allowance", "bytes_forward_percent", "code_deposit_history_gas"], "the entries Satin prices differently from Amsterdam" ); } diff --git a/crates/mega-evm/tests/satin/journal_ledger.rs b/crates/mega-evm/tests/satin/tool_writes.rs similarity index 60% rename from crates/mega-evm/tests/satin/journal_ledger.rs rename to crates/mega-evm/tests/satin/tool_writes.rs index c4bc04233..9446502ef 100644 --- a/crates/mega-evm/tests/satin/journal_ledger.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -1,12 +1,9 @@ -//! The journal's ledger on the writes made by anything but the transaction's own execution, and on -//! a tool's checkpoints. +//! The data size of the writes made by anything but the transaction's own execution. //! -//! The ledger counts what the transaction's own execution keeps, at the journal's writes, and the -//! journal's checkpoints rewind it. A precompile's writes through `EvmInternals` and an -//! inspector's are not the transaction's own execution, and neither is counted. A tool's -//! checkpoint around a call is a level of the journal like any other: committed, it changes -//! nothing; reverted, it takes back what the call kept, and the transaction reports what the -//! journal holds. +//! 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}; @@ -16,11 +13,9 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::STOP, - context::{ContextTr, JournalTr}, - context_interface::journaled_state::JournalCheckpoint, handler::FrameResult, interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, + interpreter::EthInterpreter, CallOutcome, FrameInput, Gas, InstructionResult, InterpreterResult, }, precompile::{PrecompileId, PrecompileOutput}, @@ -103,89 +98,6 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { assert_eq!(outcome.usage, records_and_moves(2, 1), "the call's start alone is counted"); } -/// An inspector that opens a checkpoint when a call to `target` starts, and commits it or reverts -/// it when the call ends: a tool's checkpoint around a frame start. -struct Encloses { - target: Address, - revert: bool, - open: Vec, -} - -impl Inspector, EthInterpreter> for Encloses { - fn call( - &mut self, - context: &mut MegaContext, - inputs: &mut CallInputs, - ) -> Option { - if inputs.target_address == self.target { - self.open.push(context.journal_mut().checkpoint()); - } - None - } - - fn call_end( - &mut self, - context: &mut MegaContext, - inputs: &CallInputs, - _outcome: &mut CallOutcome, - ) { - if inputs.target_address != self.target { - return; - } - let checkpoint = self.open.pop().expect("opened when the call started"); - if self.revert { - context.journal_mut().checkpoint_revert(checkpoint); - } else { - context.journal_mut().checkpoint_commit(); - } - } -} - -/// A tool's checkpoint opened as a value call to [`RECEIVER`] starts and closed as it ends, before -/// [`CONTRACT`] makes a second value call, to [`PAYEE`]. -/// -/// Committed, it changes nothing: both calls keep their starts — the two recipients' records, -/// `CONTRACT`'s own, once, and the two transfer logs. -/// -/// Reverted, it takes back what the first call kept, its value and its transfer log included, so -/// the receipt carries the second call's log alone; the ledger takes back the first call's records -/// and `CONTRACT`'s flag with it, so the second call records `CONTRACT` again, and the transaction -/// reports what the journal kept: two records and one log. -#[test] -fn test_a_tool_checkpoint_around_a_call_closes_with_it() { - for revert in [false, true] { - let case = if revert { "reverted" } else { "committed" }; - let code = BytecodeBuilder::default() - .call(RECEIVER, U256::from(VALUE)) - .call(PAYEE, U256::from(VALUE)) - .stop() - .build(); - let db = MemoryDatabase::default() - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(2 * VALUE)) - .account_code(RECEIVER, Bytes::from_static(&[STOP])); - let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); - let inspector = Encloses { target: RECEIVER, revert, open: Vec::new() }; - let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); - let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - let paid = transfer_log(CONTRACT, PAYEE, U256::from(VALUE)); - if revert { - assert_eq!(outcome.result.logs(), [paid], "{case}: the second call's log alone"); - assert_eq!( - outcome.state.get(&RECEIVER).map(|account| account.info.balance), - Some(U256::ZERO), - "{case}: the first call's value went back" - ); - assert_eq!(outcome.usage, records_and_moves(2, 1), "{case}: what the journal kept"); - } else { - let received = transfer_log(CONTRACT, RECEIVER, U256::from(VALUE)); - assert_eq!(outcome.result.logs(), [received, paid], "{case}"); - assert_eq!(outcome.usage, records_and_moves(3, 2), "{case}"); - } - } -} - /// An inspector that answers, in `frame_start`, the call to `target` with a success on the gas /// the call was given. struct AnswersAtFrameStart { 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 a6caafe0b..4b6621e03 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,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xe08d5c11a853f62aefee437420662141db0120bff9ee9601a6d026c415cd42e2", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x5a09b872b7ab1aab123bb581c7cfecbdf94c1f1f4cf526639cb90a4cf5daa8de", - "rule: arguments that do not decode @ 50000000 | keccak256=0xe55555c4007cc686993e358e88184c37d5f28f02965d42e9b7e66ca234d3037a", - "rule: malformed transaction @ 50000000 | keccak256=0xd59eabe5e54fe110b8f34647f3a390e4203e51507912c140ee0a634a4e8387b9", - "rule: a trailing byte @ 50000000 | keccak256=0x545f1457d582396f8dbec1951571441b7500da516a75eb24c1a3886be7df462e", - "rule: not a creation @ 50000000 | keccak256=0x59cda389471b078166acdd49ce5db7258ba0f5dc907d8847a6ec78dd86c1a17e", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0x5b16bc64c0c7b5a4f3db5c9696b57c8eae3701d666fae027e13b862b7d624823", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x6c58278252a79bf9ce141d3f59e95883fbbd6cf7c343a0f1f264e8246758dbd2", - "rule: override below the signed gas limit @ 50000000 | keccak256=0x94569cda3f9f71497d65931231777617fdde4535c0a38b7b4e3b8e572ee6dc2d", - "rule: invalid signature @ 50000000 | keccak256=0x4197c988be7ca81330837c660e4158a8a47a5b28ab0f8daa555b0a84f3e3a001", - "rule: signer nonce 2 @ 50000000 | keccak256=0x3c64f81ab2f664531eae546ba8c47348bd4b29f7119bfc56f9e2e265e140d1e5", - "rule: signer with code @ 50000000 | keccak256=0xa9897df9dabe2e14050ab58f0ab01f8f75ed07f4c9842981069df2e9e4ba5893", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x5a8a62e6bf3fb7ff4884d4dd8595426edd777e5e6cc031f739de952803271664", - "rule: occupied address @ 50000000 | keccak256=0xc50907e21260a44080e98a06259905ea58bc269e05d558f2d4d7423b528dab33", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x43c70677007cdd61f038f6734661049f5aed0fdb8485aa693d409af0b823efc1", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xc9e036ca50f734b404cb0d4a1388cf48ec21eb6d453d3650d63e0fa8eaa34bc2", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x0703536a74dac6febfcc32270e1a2f138f7ee2e8432507ab47f321598321131b", - "deploys from nonce 1 @ 50000000 | keccak256=0x62d2aa4c30fe5c05982e9c53e76feea7f952a6af4a709d7342590ada761e495a", - "the address already has a balance @ 50000000 | keccak256=0x62eb6d77f77cd390fa87640e949a495534af010cbaaebb184f8170098faab4e6", - "moves value @ 50000000 | keccak256=0x54de6a78767cfaae5f14de460ecb253e7c01f63bb337f79bc0807a206c72205f", - "moves value from nonce 1 @ 50000000 | keccak256=0x814e9db0b5a0642f7fd0faa63080a523fe91c6ec3dc063f78270704abe9f36e7", - "the CREATE2 factory @ 50000000 | keccak256=0xded0acc143a5a6957c0b60c995cf7456d7821525188bfa4eae207ac51459b889", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0xf0d2fbd0aaa504b147a454687aafefda093f14d67de462991ea595f65dd7cf02", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x3e0b4d0c46a1e10a2a4be8d287e562b315a4d1e88e05ad316fd9bbb1c98ce83c", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xb796edefbeca92977b8296a98e163f6ce2874317551fdfa34f68ece24d3a7a02", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x4a79199b4e4fa90173d320b0f82d3b183122b553826bfadbdc51ec2395609bed", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x76372e8f335e5b5328dbc797b9aa4631cc103b89b259c0e08b85e1698b1aade6", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x20d9d2bbec507184a0c73c414efad6fb9458bb3b93fd3f5d36b64176deb522f4", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x4a12867c38ff561d75fafed049d01ba7b7c2813837e5f781172869c73b6eb741", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x6096bf7f46499fa61be93b942ce794d9366f6b1d9de2a9bd882d129eea7acf36", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x9b1d2c1e151cab97c182f42826e2d7c030c95d1ae8a490104b8ca8a54718b8cd", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xb26f2f17a77f78503786120faf04a6b69114ca9c93f5e1cf67d275240b3b264e", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x84350725b7f63d922e20c939a219d39da049aeb7b1ee5574e3355c0b24b6cd28", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xc04de069fdaedaa94578d0b26e481c221105de0a3e9622fa9eeb18861d75fcaf", - "a constructor out of gas @ 50000000 | keccak256=0x440410ab7678c31790932270569e1ffab0a3f3826bcbc2c6f0dd4654d2107577", - "the signer sends it @ 50000000 | keccak256=0x66a013fa1a11178c230919dc83ffba40bdb631c93bf7b7810e92371df0bf8b77", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x8af244198d5605346b66591f3700b4a442dd78beab01a6afb8dd87665f244b4a", - "a delegated signer @ 50000000 | keccak256=0x8c6adc50e3b0f55f7fde39b7a29d5ad7bbe6ceb9d9358d0b6f3f42a3a9754913", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xd3734a0b376023fca014ecd2178ef794ac6c980f4c2587d20212afa417874e38", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x09f3f4532e7bedf74967ca6ae4d8a6821e20b4c2af048791a427e3d4f5c38105", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x4e57917739c132e7f94e97e42214aa3c511177d21a708f2fb43df099ee23d95a", - "limit: compute, nonce 0 @ 50000000 | keccak256=0xbc5ea5d36da421edc9ac0fb0c1b185c334b6932d52bd2ffe2701223f6e163a0c", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xc5e1e974147e483eb2e59adf9420d4e9bd7fb8e774603558238f15f9efe12129", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0xf0d20c801bfa5db12176f11876c36af0d2ce1066d89bb15e942e7f00a097df28", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x9db440a3067a52613177e664b6b98e2a18fa3b481bb8ab9b6fd95142d8e27bb3", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x81e4e32e9c1a42fddfec6e807f5e97407c3337efb054392c803759d15066cd25", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x255fd223c957aeb8b87bea1a1a8c17e961d6fbc464dac2e095637dd3c99f838d", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x11b1022a2374bdc03dd0df9a6c167d06d4acf539ba17da2f6f6f930c93498f66", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x94382f06999ab6c9322823fe31929d1e40ca0762739b006cc73a4a6f8d02ce0d", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x5058ce0b29dc18f336e7c5c93f634d295d49147c420aaa142e40adc2ac9dad0b", + "rule: value @ 50000000 | keccak256=0x6be2c4a9e04b8cee42b1568a07dfc761f3625d225e1479f331f6898b873f7f43", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0xdb4cd2ecbbdc0409018a90520dfbe2fd4dfcd3228fe6918019701639fda73cb9", + "rule: arguments that do not decode @ 50000000 | keccak256=0x8a813b8ae24856b4670ed7c432e3f56d86a8fb94616b65b79f7aa5505c37ef8a", + "rule: malformed transaction @ 50000000 | keccak256=0x14d8b7934f5ffc986bf3ca9c62b683f0aa8cc6a81962fc4ecaca891ea8c09a43", + "rule: a trailing byte @ 50000000 | keccak256=0x5e2b8c4e1f373bdc071255c53792e3eeea4e33aea1483d461780e58a7a2bbc7c", + "rule: not a creation @ 50000000 | keccak256=0xd7f99061cfe84b1fc116b335579639fe83f72e30f559319b77040dda8294c4e3", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x54e4035bd71deb715fdfcc17be3d9d64e85270ea83f26ed7f5b83b4ac37f2bee", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x4bd17b02bb35de5672fdd9b4380664f5bbb81a223eb4e7e7df754b988ec35e26", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xa0d0ffa69a340796adf3fb60e4f23a78a358f0deb799ac4fb92b87790be106a6", + "rule: invalid signature @ 50000000 | keccak256=0x561b100463b72a94f271bb0827444f11ccd93c1040fd2f0735a0e678b03a40cf", + "rule: signer nonce 2 @ 50000000 | keccak256=0x2e3d79aa7d471bdb32dd53ae4a7ceb0e772cf42da9dae2d546eb3f5ae3f824de", + "rule: signer with code @ 50000000 | keccak256=0xf829b9a8e15c4516b260bcca3b6a5b4c5fc575c4d53fe8b72fbcde086fec6cd9", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x2b6a69e0ecd0cdacbaedbde179e9d2924c30793240c49d19de0e110d1eb22811", + "rule: occupied address @ 50000000 | keccak256=0xbe9f719ec43f447863b3228891ddf7cb67cc24943f826a733619ada658036ee8", + "rule: value the signer cannot fund @ 50000000 | keccak256=0xebfd7e580f06f4ce7173806ab4b07fe8d2f14779296c587134e45932d3cbedc9", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x48c202dde80bc36473bdad805104396592772162d4c1c0cac69957a6e7f87b91", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xbb1464b44b11119c689e90f7202032706d3a5bf99cc989449f1f77c4a6f3ad13", + "deploys from nonce 1 @ 50000000 | keccak256=0x58586ebdf3651fcdb6851c51672f8b9894f98f7241e0ed8e782ce587325b0585", + "the address already has a balance @ 50000000 | keccak256=0xc6f304d2539cf7f36aa9641180c7ac1eb2ef384208699307d4aa2e89de21ab3a", + "moves value @ 50000000 | keccak256=0x7791ff6b94b87d5190ceb3755aad4444dad6fd8990cc462e853883420cb98251", + "moves value from nonce 1 @ 50000000 | keccak256=0xc61f6eb4c373e8a0e26129ea81d3d650c19051b662283fc11d8a54563b226605", + "the CREATE2 factory @ 50000000 | keccak256=0x7257f5422ca230d3552cec8593662688d1e2bb8a66eb03826534cefb9825c68d", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x67e5c21d36073d3b2207faf6a8bb0e7077a8a8e7abcafc232d5f1e50ac27048a", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x734ed0efea72d4ad1653e96f333c25822faa0f6b31ab2b4df1227167ba0a147b", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xed92061138d839808c496c1b3a1880fd420c72fd56abee07bf654fcf54c170e9", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x792fcb2363c740a91e68bdc061b7c8bbaf98cbe1aff749e8dbdfbe9736d71207", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x0f44f2d81f3b8c26ddca17526eab2cd3eb52137bc9ecfed8f24bcae5a1a98ce5", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x9c6b93134642dbc82a216e8d1a0c4a86fd735529b6c2e87fa6e55f61282c7c55", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf254ed0372774046b90e9785fc3b9b7cc2e53c9724f963b381bb82bcd7570ae8", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x584ce5096b24c9af8af54fc81c58c8eb251b032c0a651ecf86c3c9fc4e82f8f7", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x4cf8709413710aaa0b36400ccb07610a80282f9f4328d592621162188ecc37b1", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xa891e7c22dd52bc557a741ba5cb73cc453f88fb645c6764076d655edd9f1d794", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xb56bb82c7e82d2bec5d78c97140fd962419bd4dd84661cd6441844f67a55d3b2", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xdc0eeec20ae5509fbc1f8fdcbfa3e551ed77cdbd2daf7ddf828005ab3026d246", + "a constructor out of gas @ 50000000 | keccak256=0x5d9e9859c6783124d05749d7d8d18080d2f3b85f9c6d59c653f6d03ee1432e00", + "the signer sends it @ 50000000 | keccak256=0xb86e75c9de01d038cc31626c50bbfb899cd9bc1aff693e832adf6d895fe0c0b8", + "the signer sends it, and it reverts @ 50000000 | keccak256=0xdbfbc4870331b30af5e411392cc7a3d3ff9fd70e32632d703b1095713e2bdfba", + "a delegated signer @ 50000000 | keccak256=0x615fe64c9175edc760269e3b34bb0acd09924c3a93eaf361ab60e0b81e5c1a18", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x57f1733c301bdcddb35328a6b05d88b4f9f7f148a1d3d69c31531804fd5cb6ff", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xa4badbe971db28ab8130cafb1b6b1ccaf35df75e748e531424b79071f747d4bc", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x421d276d9b66b743508f39a2f16df0c67d316c0424234548cbf6ab890f0e269a", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x23b69940d238186cc2e474800bdd4505c3530a1b046950a35519e5f802db89f6", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x8f2cb657a8bc784c170b06958359d8d2cb6feb0e11fbe801c2e3f831f861e07e", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x8afa218026e3cd07dbe01cc2d5271b3e98d1a7d62f5e09caf56616f63c4f032b", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x8d7670e2a640e39ce62efe8a7a41d1a72fb781bb28f962c5c4a2b849a2e8047c", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xcf2f3d5e3b39aeca817a3052f5c7463fee70e19db014a1db450e3e1f4685e891", + "limit: compute, nonce 1 @ 50000000 | keccak256=0xb244a6e11c3b6f793159f9122aa1e0968de07920514f1d2cf3fa02d8d9693fa8", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xa6c90f9773d5434dfbf73f4fb6cd782f96509138441219f0f45304e76fe0a4a8", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x2d4d3cc36f54cfa8e1f3c8c20b274bfa95c6b6f7e9d0dbe8c4a9898523276ad2", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x6d8111208239652510ab44b66c7d5b63d50d00797a459bec6a32f68fb044f3df", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0xc5286cfe7e8c22d56ec53bac2e7a224ddf6cc04b52505501f4afeb471840058d", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x2563610ffa9318aeb60b0bcfb4167a9eb31f2f97687f532a8f5435724fcc6ccb", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x47a7201490cc0e99c0417b0bfc5dc39af036d0021015cb12db841856e91f9b7d", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xc581a2020b34fd7f9298dd9ee1ac75b3ecdc209cb592edbcce65896b3d44b535", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x1cbf38af1fe47c1234e498c99a0975bae7a2f84c974c23a47b22c3914d9a9543", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x80448bff277a3f72d6c897f51f25a6662be849beca9d980eac688320d86066c9", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x7fb6ab15e5fbf341d3e1d3870ea6f73bd8ca74dff6b8beb2e96972b6397c4749", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x82bca691c26aacdb312a44ad21c64a87e47df77b6864e82eb79efc58f2e3f666", - "not dispatched: version() @ 50000000 | keccak256=0xee0f650f6791fd685e2656105b93585e08fa330bf01c485023a062ced2909097", - "not dispatched: no selector @ 50000000 | keccak256=0xd45e2aee2869b779c403f3a8e768930dde3ce0dee4feeceec29be249552d9f65", - "not dispatched: from a contract @ 50000000 | keccak256=0x8ebbeab71b3f519f0bd2eb5e67039938a1d2c55fc036734458dde12583d588fd", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x76a0a7bccf4ab00d2b30e0b4818c483a753258e512225968df5cfb249004556b", - "no contract code @ 50000000 | keccak256=0x13bcd1d73b2de8eb1c24f9d33ac665f3d3138305ffc0e0e000940f985faa1a18", - "a system call @ 50000000 | keccak256=0xcae00cf2ae1c9cd8393a3e667027360c3f167eb3bcebd38ad2bfb8b31e95f42b", - "rule: value @ 400000000 | keccak256=0x3922a3db1f22936f578de6cd2ebc59a21b5ab0e2b8923aaec1f9ac75fe8754b4", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0xa3077b87c5ad3052d2d72353331e48cad3284a9be2373dcf8c8cf91b0eca5d11", - "rule: arguments that do not decode @ 400000000 | keccak256=0xa330a12e2749576ef722835b5b54e8646be72ac70964a11b76e09ad0e9db90ff", - "rule: malformed transaction @ 400000000 | keccak256=0xa3732d3961a6377f75d95d38655bc6b58699508606d0c1686a9218644d2735a6", - "rule: a trailing byte @ 400000000 | keccak256=0xc8f95911acf41c1227454e2fadb194acd9a20d01bd438ac8b29b6ccd7eed0ee9", - "rule: not a creation @ 400000000 | keccak256=0x095b950bbe9b7fc0e95b96574a7b3054482aed5fb1b94650b3afb175602b7322", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x7168997ea70d91d5e37cc37bbdf40f6e8c1cf3209566f124973b2a363de8f092", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x1352c3f935e83b0ce02cd15dd5b8e9cd424e4e64a8eef8b77d912d31f620adca", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x177bf8926421a6f32cd5f72e85b7ffca3d00a11442e107972bf1884c639638ee", - "rule: invalid signature @ 400000000 | keccak256=0xb5bfdea3c5ad4938b8ec085d865e51179c703f81fa262b9aa19e5a2e4c29682f", - "rule: signer nonce 2 @ 400000000 | keccak256=0x2d91bf7945bfbc243dd77091a7b09743ee51cdbdd962b1e08ef4eaa9242a851d", - "rule: signer with code @ 400000000 | keccak256=0x30f0f71f00bf8ce819eae6e0f644f55ac08949539ec99f028c6bb542774a53d7", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x8e5e36a718119e8a723eae0b7d3f14422f89f8ec09b050afb9df5cea59f9d003", - "rule: occupied address @ 400000000 | keccak256=0xce45a21f6b66c08ba2cc5f62cbef177ee6dea63d1e841fb55f6872586067262c", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x5b176818d9aa4779855cf954713aca6586ee2f26fb4d2e1cda3512307a1e9667", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x592a24a10016a29d65a4391abcd35faaa32a64b53020f7189491e599b6d8fe78", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x37d63f7eb51fa907792cd430ccb3b0d1c69f3d997cc4cec372ccdaf2bfee7e06", - "deploys from nonce 1 @ 400000000 | keccak256=0x82f552474faed9cdebdd488dded67cd05718b54905927ec1f1f627ef389c0b50", - "the address already has a balance @ 400000000 | keccak256=0xab9cf03c7577dbb3d30730e1a7e76111341bd42cc5e3a988bf1d52745bb59df3", - "moves value @ 400000000 | keccak256=0xb3300b4347ee267ffdb245868ba449dec71a1cb738cd2c61aa6a84abf3616ecc", - "moves value from nonce 1 @ 400000000 | keccak256=0x52207a4239fc5c6a70ed8fec7e91048690effd8cd7a3687f194732d6b8c212a1", - "the CREATE2 factory @ 400000000 | keccak256=0x4e116527b62fa8581963beba273363b009997bd6529bcfd179225d8fc1e3dd3a", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x3ea5923db49243150f653046125e736ccb77a5c0c0cc6d8ffcd59df9cc06a989", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x9336a80d7f7be85071d4a70ba9e78ef784954d9f8d4e8e7c0a7bbae7e4545714", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x393cdc3bacb5df6fe898c2612da26aad1c58e227f2dd242aaba388d8fd705c30", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x761f3e0d0cb206f0776585655b586221f766853b17c82a63ce6fce1be38bf30e", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xef3fa9fec87d8419bffe7f3f77277da863510f3954b5a9872e576e5a6bba19d9", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x511a7761645fd502d73b3826a14ca5d586d9d45178ad5db18594c0fcbfc4bdd3", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x88358f956972468609528a953ba9d257f89dba294db62cdd5c03d72aa7c3f834", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x695d8cc6e4bde17769ecd5fbccf6c89715f7e2277e7937e6e72f36196fffd70e", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x94abe8ac217cf241c5969b756ce09d40dca6351cfb9b295574198982d2e5024b", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x878ac261c93e426fa61bb58dffea90a4fa1d1f2261c78aa91427892595d257f4", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xeda90d770f3960abddbc68a9ae08adb9acbbe99d46513925df2634deb33d9ad3", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x5ea889aec6ae2e1b3d58760e2beaa7dcceb4d2d676f60586f4eaf24b9437b7d3", - "a constructor out of gas @ 400000000 | keccak256=0x89c0a44575c806e25d3a8665688d0a2742c5fc931dbeb9d518142e1221285184", - "the signer sends it @ 400000000 | keccak256=0xfc6ea003bcc21839162401a2e0f936c9472f4f0104f3b8ca90ad148e9519ae5b", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xbc7675bf2249c1ce5a52824c9a650f9db1c89bbf0b1644b907697ed9af011cc4", - "a delegated signer @ 400000000 | keccak256=0x33f6c088999ad24a3f97ad47f045741ca00a0201902a3925a430f05978510598", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x73a31ef42c867d557067e96a0e79949a02148294dabeaea50f8e75b458e09dab", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xe24aaf180b4bf444ba01ad9ddf44aec3a0c1a7f52b232af0f5794889bb904fb8", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x2450bf7f26d13f760104617f5134aec8300c96c9f0273368e080cecbbd02cda8", - "limit: compute, nonce 0 @ 400000000 | keccak256=0xd1e24d24cdb678538bc4ac96e2a5c87c48bc464befaaac19dc2208a749f5a600", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xc542291ecf77a6dc64b81659fbde70bb5e71967bf58cda3733020c5dd8818a9c", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x23fc5aa73fd684adc54350aa944c46a3447ec8cb7475449bde2c3ae1cdb65d4b", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x60c838aff27f4229b174514185754485226a2b403157d157007625b8bf3c7cd7", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x3cda6a985d48c8f91bcd9bb751ae6277d2e9c238f72c5538ad576e89283886fd", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x8144d6fd3d845e283f615f92bf0002872f0c7beb4ac373a5f1d0761cb238b987", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xb652c75f2545a42aeaf34311bf62392a0856b616e1b7b3191d8988e7ca775207", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x3532c73382be0923c7e028c397c11501f4f4c318bdfdc8d2a258100edb158e38", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x63d02c91729ac49f2c8c832cc16aba96cf73288991f612a65c78e3cdedd5f904", + "limit: the default limits @ 50000000 | keccak256=0xd7487619833b3a89ec79d8c60f3e28058bc75f3aaba41636e80427944717be1d", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xd9d5aa4fe8ee4b858316adb50837a13dd3ec46c0a1b297c54551fffad5aef8e9", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x1b5bf70dd810bdbfa173abfc9bb651675def4d7009432485953c1348540cdb52", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x887eaa144b558fec53eacc9a7b67ebb840bf5c004f3b059868d67e2d5acb3c4e", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xb95346d264a4b219c08125f67413bb662ae31f91c3d898b21e86ea5629e51f8c", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x29395f62de1af080571f9173e19a164073e1b3915372ca32a5b0905db17d1776", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x7973e1fd3dc2e403960a81da78403d1c407569742c9bd4a3075ac6a878b91c35", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x013d06a21e951b01c385b47689137dac5c4f9d79a3c581c197be0daa14988065", + "not dispatched: version() @ 50000000 | keccak256=0x71b5f865bd3661322761b71fc4309da6208266782e81dbaf4fd603052eef0d13", + "not dispatched: no selector @ 50000000 | keccak256=0xbdd2f3a556c32236687fbd2c77b0dcd6b043149ad44562ab57c414de832a446b", + "not dispatched: from a contract @ 50000000 | keccak256=0x60def043245e382daab29836061360a339f0ed239fb0968391b466df61e229ce", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x86cff0e90a7dde446fc895e574b925799e65cc12b85771d6ff6bb16c16746063", + "no contract code @ 50000000 | keccak256=0x95de965c9dbee87d5a5abad6d3664d1c78528dce8eee432e7b9756682b21eb7c", + "a system call @ 50000000 | keccak256=0x39fed9f75314afb72adb029216af30534218ecf119b1738e50e821f73c96e654", + "rule: value @ 400000000 | keccak256=0x6621fff65c743a2795883489d013835a24b226a2b04df466978c950578193cff", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x403ab771ff977d1722d04d2256374a6bb81da23243a35f44d6214ade1c739959", + "rule: arguments that do not decode @ 400000000 | keccak256=0x953f0b00aaf0cb0c3828f8e1d898f34c4420908e4217b3bcfa97bcd27f63d1d8", + "rule: malformed transaction @ 400000000 | keccak256=0xfe1a1d713f9ba4fd3ee9a05c42f7bb8566b3e63ae85ab3db0c0a0ed17b652e57", + "rule: a trailing byte @ 400000000 | keccak256=0xc0f5106b1c89842f0173f57016bb3c7a1ed0c738fe1c2ebd9e4d48f66f392040", + "rule: not a creation @ 400000000 | keccak256=0x54f9544b6408475fb4307cde34fd6a54f02e45379d4a344ccac017e3be4b4066", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x112674d77e25ae333275a87088503d7334955992b3ce4ad1e6527eabf436ce86", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x1b9f2d4b41f900f726fa88f5db019e02ee4364c4bdaf54c98a38ff1305c54855", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x224d3c5e43f9d5323fe6b9f9bbd781fd2fa46f3f6763c26a68f29c7efe766eae", + "rule: invalid signature @ 400000000 | keccak256=0xa7c33a1a4839d113bf94afa1d8d5caae218b1d6b5a4c4d3ecbf19d63cc664dd1", + "rule: signer nonce 2 @ 400000000 | keccak256=0x36a94b5c8d88f0fa7854c48731a14077110271be7988492e5e6715f939b40bb4", + "rule: signer with code @ 400000000 | keccak256=0x12ceffc3e9bb891411bd6defbdaee189a9224e76671abb6c712f26851e4225c8", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xee84ab770836481c0d2b9f0f3fda578f366e10eafacfb6539872c76e22b0c6bd", + "rule: occupied address @ 400000000 | keccak256=0x15097e3e99676ea1dbc2b9ddf62930b551bec694a48311de72e73f0c0c09eefd", + "rule: value the signer cannot fund @ 400000000 | keccak256=0xd421efd34bb65e29f6fb1235cb8a12f2b998db4df186b05ce35537df7ee03992", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x848b0d734b52f41c15a8ea7e07818deb93a83c8fda8f2f5e4d00c55f55442ed9", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x62cb4df0295fe698a4bedf30f9891e09baf6f39d937873b00076906ca2a73a33", + "deploys from nonce 1 @ 400000000 | keccak256=0xcebe8a59449392e3d21bea17eb6768676c277af25bcbc6e68460c3e1676a7d44", + "the address already has a balance @ 400000000 | keccak256=0x36ccff4608574dba9a464ed028b47fb58d39533e34199b8f80f158cee221f283", + "moves value @ 400000000 | keccak256=0xfcaf2dd354f9db199d3d19e8ae0197824c9ad3671439df9d5d91fa8703ac4b9e", + "moves value from nonce 1 @ 400000000 | keccak256=0x86b54cf0da28ddbc6c13f0b13f4b3546400d8a21ec0773e00205f38762ec6275", + "the CREATE2 factory @ 400000000 | keccak256=0xd2572ebcf5c6cd0478ce3a8fb99daba77c43ea02e8be1a16d285847be3b1e12b", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x7d79966d2586bb18d0f3cd975617220b026ed14a7fc11bd985a3095edab36ab1", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xa7a2bed3e11fd77bac02885b4974d05d4e1a0333f115b68de02629dabb86bc0d", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0xaeb851f138d0aec9ff33d2c4349bfa936175e9bb2187892923ec8620c2273f0c", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xab5569c4a6209d9e854036f767b38fcdac1a65bd1616c4a9e0937b33aa8f9994", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe288cb34e9909960113b6e3cdb1e02be2d0a62efc15bf60e87c584476d2d3923", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0xe4ea5b03b83a33e8cdeca1788c7a46cce01c2d7ec2183d051acfba1cb9fe703b", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x217851801f9fd7fcf13aeb97d16923646e8561f3f4c998ff5d58b4926b5b13f5", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x7a8ba7478366ef8e3817763f9ed36ee748e65fe733d7443009a45de6484041b4", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0xf2ce34640bff1a53ddfb714e1f9bd6b25c35fac5f512fb58facdc0a1692182d0", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xd7b919e0f1753b880a1fff9cfaf36b21ab2e3884debc041616395f095cbd1202", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x4078316eada64a6161caec29df05c407e4c5f1ef1a20faff8f0d382816ebfdcf", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x6b8a101e66ef4010835fc3da00c74e610c23db0021eb6eba90b93eaf273f2f25", + "a constructor out of gas @ 400000000 | keccak256=0xac5a841f99f78b0e21076a347e60c48ae83555ec3bdefa5b8df4b862d99e618b", + "the signer sends it @ 400000000 | keccak256=0x55ee191f25b9ff082b5734bf12ca6a8e0d2d1766d39881a75c94bdc550a23e77", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xf8fa9c7e63710003664c34c12ffef4140efa5366930e795d7484837d22d7edf2", + "a delegated signer @ 400000000 | keccak256=0x1e6d8f5bde5cac9791e0bdd02c1d4880c1d22d08e496990a205964855a0e9a90", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xb1ac9749392dc3156f389a1b603ae5e69c9d08937bb4308cb7488ed61701c055", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x924a2702ff5ad4301372d7cff03137f759467b9ff7153eb6e143f1cebcc95397", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xe4dbf743f422c6726384de3115d2dc7f6079ea79723b3290d91aae49381ff779", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x185d095dc4ea9d189687a13fa993c28a8ad81b734c3fcd5da8e573aa5daf30cf", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x189bf4dad92f38af3fc108ab7e2946bf941520252ea42e03089efd29b213d93c", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xaa9e603ace266be85412fc48f16cf054cb4c8ae59a0261bacf2699c10f8c4e0d", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xffbeade2e2586b013d7cd68ba729d8e7cc6bc61439565ab2ef27fd4039b7bd42", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x84dbf201e6ceab370961d5fe7a37cea63d51618fc38e1614060f56bbbc5f8561", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x5014b568b4ae5d95ade79311955e48ebe07068cb47fa5461515c2aab7213fcdb", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x8ccb6d71d3af3a757525e928562dc212025eadd1f29d3eef90d5e75d09af28d6", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xace6753de34dd4fbfcbbdcc989ba0b9f5b04259776b3c833beba77f1d2c44f7c", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xf36763d00fe5507de7ba782c73f37cb52d18790eb95b5b3f9820181d02d735a9", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xad4d30ecd3b69b22dd96252e09422f1309de5bfc0142e5198263b89dd2010bf6", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xc4efceebc452bcc77d992cd35b469d302c6336dd14fb2d0b0d7563e4cb9651b6", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xeb826226526c5a5d0e7192f0c042ec198eec7abdc2d19847286d0c2d1bc86ebb", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xc86bc78d010b4a3113976d032eaa8e5132729d70604de4a7cd6aa67447d1e833", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x9581a714c92e5c24aabfbb338bc0b7baa75200abb2c007ffd2745f637c18921e", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x1c1045da7cee360e40ef8b4a923643ef7f0b1ec8bc27539dc33cf60f4d9bc24b", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x2c2d646a715467dc2107fc12b266ca11913a660a110fd42c20c479068f0a83ce", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x59eb1669dda2569995a03c7c2bac26b9dd813d4929c1ccbcdd082c46487926c6", - "not dispatched: version() @ 400000000 | keccak256=0x292bf5788212aa87589c77a2aebf85737bc0ca6b7a95fb35c183910b131b9e2c", - "not dispatched: no selector @ 400000000 | keccak256=0x2a7aeebb83f26482228ee292fd2a971111d29c40040a8ba91e7c26d7c0255c2d", - "not dispatched: from a contract @ 400000000 | keccak256=0x4c447dae19a0d2dd39c801512e0495bba1bb0a264b29c18b1db6d1a52c1e0d9d", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x29bb1e1e870aa7469ea9208c21195473d0309f6eb51a1ea92bd3220f689da71a", - "no contract code @ 400000000 | keccak256=0xa1978cb2b4ae05a9e535c5e3614bd750eaac8ae287112baeebaf78482b316d88", - "a system call @ 400000000 | keccak256=0x9ad23f4f93be819501a8c389210ab517e3d4e6aa36e53d3897f180ec36ac1a1c", - "out of gas: the overhead @ 161535 | keccak256=0xd2b1c6a6a0406e2a5b0bb8a8fff227d1c45489bfa0be343f58ccd01a1a6fa1bb", - "out of gas: the signer's account @ 162536 | keccak256=0x9df1144da6da6dd79ace581960f0bb1f7b009d5ec1d677cba0b7b929294b5859", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x9892528465592e994dfa9e09e128263f445fd19fc47ac4dce9d060c94b535608", - "out of gas: the creation's charges @ 163024 | keccak256=0xa2cf8f8d33b1da3b05c2768ae383b86802934010321d2739ad636fef561a7c31", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x8e7256f46483ac8118dc4133ede63e0140afc4e25b23024d62cbcbbe5de69f90", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0x24215a3fcd98c750d7f336e624498326787f8aa5e7f8604de9342326414cdc95", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0xe9b65891ac1ead307efeff7a9c8d5f48e8164a7db38691e4df3678c90fb5274b", - "rule: init code over the limit @ 150000000 | keccak256=0x6838a282dd806d25ccfc1a88020c5accfb1863d7215d4dafd5b1074f98d699ae", - "rule: init code over the limit @ 2000000000 | keccak256=0x7e5ec4fc070585a4076f4dba1bb383c00e19a05c1eb52eaceeef42a5cfd891b5" + "limit: the default limits @ 400000000 | keccak256=0xef704d7bc2fce3e18a1da2af57ec8a2a53b98c4a180c3ec9cb776d24540c4852", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x042438c94d0621ae8a2f19c02ac3f04e76eb4e4a06a78979ace089a255440176", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xdd3b0907d4c6c127470d7ccb6124f0204603155431d5ba8daea66a1d2f0bcac9", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x143d38c359b8a8bbbbb25c51c937f0a1489fd237f6c171b4e3cbd223c5aa0061", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xed8375b46dc371b2031b4628fb78d08239fa9ee263815ea3d4f194f97feeea31", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x68ad51797ae01a1d145d2a59af9a0d39c2f1b874b0fc87b871dcacfb35980e0d", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x21490e3a5958ebc22af5cbbcb52b644ed09b709764bfb2598d5e541d07051b97", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x08c04c0bbed8559bf465611bb8d95c4c2a1b41003c103e9b79436feb53b321e2", + "not dispatched: version() @ 400000000 | keccak256=0xb0697f813fcf0b76481275f2fd8a71f3c313708da0b3968985003c5b622d7e42", + "not dispatched: no selector @ 400000000 | keccak256=0x75fe0bf0713bc6c078a16bac52359e7d3a89938d8337309c8ed301ea0f82eee0", + "not dispatched: from a contract @ 400000000 | keccak256=0xc1d016f94b74d3107a876c74f03b6d6e7b1503ead5d4b4bb82b3309c99680c96", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0xa27b66fb90ece2b8b19071bd98e27f6ab83f3a239058f22bd9b0df4b300dd8d4", + "no contract code @ 400000000 | keccak256=0x207f8e449c8da45440b71acbddc1796dd88e5adf27b2777372a45607c225c5dd", + "a system call @ 400000000 | keccak256=0xbc7901dc1b60b4c891850d89708756c04cc648058e8bce964e59c72ba9192aab", + "out of gas: the overhead @ 161535 | keccak256=0x9e5fa941ba924cb9ec361e5cff34ccb0655c61440dfba72525cf32bce4a0e324", + "out of gas: the signer's account @ 162536 | keccak256=0x1b10a06299a9c84eeff3f3a80bd672c3c89c8a04040c73b8e0b4abe9ad529be4", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x91244c305f19041671325d1f781e6f7119f34ef45c1f5b42312f6137d473f791", + "out of gas: the creation's charges @ 163024 | keccak256=0x6ad1b06738836db19511c6232f82e08f5148b1bbc5240ff4f59d2cb11f1d29c5", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0xa81c6721ab647bfc0dbed1d24a304344906c7ece94c08552a935bfd00bf772e6", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x45a89392882dcc35e679fcd79e54fd30ff593f981d0e7172b906e4f2ecfbd061", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x1493c0d5815ef90d4b4ab4fb32569f119b7370e6765292497afc21f10b602572", + "rule: init code over the limit @ 150000000 | keccak256=0xdb26152222c6f33e3e4b11646593374057eb3619c2ee6ecf30af45f9602dfc75", + "rule: init code over the limit @ 2000000000 | keccak256=0xf7055f08d140f0e730be867a1240128308297c023ca11b8e05fd20b6f18d7bab" ], "summary": { - "bytes": 2525694, + "bytes": 2523500, "cases": 139, "lines": 11452, "runs": 556 From 00cef4526a570b4e1239548a4b7301efae0062ce Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 05:42:54 +0800 Subject: [PATCH 445/458] fix(limit): hold every start to the transaction's limit, a creation counting nothing included The creator's nonce record lands on the creator unchecked, and the creation's start is where the transaction first meets it: a start is held to the transaction's limit whatever it counts. Pinned by a creation onto an address the transaction funded, whose creator's record crosses the limit. --- crates/mega-evm/src/limit/limit.rs | 9 ++++ crates/mega-evm/tests/satin/data_size.rs | 61 +++++++++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index c3a0bbcdd..aa90610db 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -487,12 +487,21 @@ impl AdditionalLimit { /// `counted`, the records and transfer log it made, on that pool ([`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 limit whatever it counts, nothing included: a + /// creation's creator record lands on the creator unchecked + /// ([`count_creator_record`](Self::count_creator_record)), and the creation's start is where + /// the transaction first meets it. pub(crate) fn count_start( &mut self, gas: &mut GasTracker, counted: &Counted, credit: u64, ) -> LimitCheck { + let check = self.check_transaction(counted); + if check.exceeded_limit() { + return check; + } let check = self.draw(gas, counted); if check.within_limit() { if let Some(start) = self.decided.last_mut() { diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 102b27219..ecb9a87e9 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -10,7 +10,7 @@ //! when revm would deposit it. use alloy_evm::Evm; -use alloy_primitives::{address, keccak256, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::SolError; use mega_evm::{ constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, @@ -1629,3 +1629,62 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { } } } + +/// A creation's start is held to the transaction's limit even when it counts nothing: the record of +/// its creator's nonce lands on the creator unchecked, and the creation's start is where the +/// transaction first meets it. +/// +/// `A` funds `X`, the address `B`'s empty `CREATE2` lands on, keeping two records and the transfer +/// log, and then calls `B`. `B`'s creation records nothing of its own — `X` is changed already, and +/// it carries no endowment — but the record of `B`'s nonce puts the transaction one byte over its +/// limit: the creation returns the stop before its first instruction, `B` returns it once the +/// creation returned into it, its nonce and its record going with its revert, and `A` resumes and +/// keeps what it kept. +#[test] +fn test_a_creation_counting_nothing_is_stopped_by_its_creators_record() { + 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; + let stop = + Bytes::from(MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.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 }, + "inspect {inspect}: A's transfer alone", + ); + 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, + vec![(InstructionResult::Revert, stop.clone())], + "the creation returns the transaction's stop before its first instruction", + ); + assert!( + probe.calls.contains(&(B, InstructionResult::Revert, stop.clone())), + "B returns it once the creation returned into it: {:?}", + probe.calls, + ); + } + } +} From 4a5825777c0e740ea931e673fdbc2c2aea213bb6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 05:43:00 +0800 Subject: [PATCH 446/458] refactor(handler): charge the body's history in tx_gas, not in the intrinsic state slot The body's history gas is charged on the transaction's tracker where revm builds it, reservoir first and as no spill, as EIP-8037's intrinsic state gas is; revm's runtime out-of-gas fallback rebuilds the gas through the same phase, so a transaction that runs out of gas before its first frame keeps it charged. It no longer rides in InitialAndFloorGas's state slot, so post-execution no longer takes it back out, and the settled history gas is the tracker's. Pinned above the execution cap, where a charge the rebuild dropped would leave the reservoir whole. --- crates/mega-evm/src/evm/execution.rs | 68 +++++++++---------- crates/mega-evm/src/evm/validation.rs | 5 +- .../mega-evm/tests/satin/history_reservoir.rs | 41 ++++++++++- 3 files changed, 75 insertions(+), 39 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9dc812c87..e5820c3ad 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -230,21 +230,15 @@ where 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 @@ -265,7 +259,7 @@ 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); } @@ -282,15 +276,23 @@ 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 transaction-level gas, with 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. + /// 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 @@ -299,6 +301,13 @@ where /// 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); @@ -356,9 +365,9 @@ where /// [`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: 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. + /// 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, @@ -370,21 +379,15 @@ where layer.take_frame_stop(frame_result, true); self.op.last_frame_result(evm, frame_result, 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.settle_history(priced, history); + 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. - /// - /// The reservoir the transaction leaves unspent is 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. + /// 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, @@ -393,9 +396,6 @@ where eip7702_gas_refund: i64, ) -> Result { self.settled_reservoir.set(Some(exec_result.gas().reservoir())); - 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) } 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/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 9de582130..2680c1659 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -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"); @@ -306,3 +310,36 @@ 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 }); +} From afda2c63060ec8b82b46388175b3c18b90e9b2ff Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 05:46:26 +0800 Subject: [PATCH 447/458] docs: the byte pool and the start charge in AGENTS.md; a creation is charged exactly its records AGENTS.md describes the data size on the frames' byte pools, the start charge on revm's carriers, revm's own journal and the per-start entry, in place of the journal's ledger, the start window and the frame sides; the fork-pin lines name the byte-pool carry items. The spec drops the interim rule that a creation is charged its created account's record whether or not it makes it: a creation is charged exactly the records it makes, as every other start is, keyless deployment's step 14 included. --- AGENTS.md | 87 ++++++++++---------- crates/mega-evm/src/system/AGENTS.md | 2 +- crates/mega-evm/tests/block/inspector.rs | 5 +- crates/mega-evm/tests/satin/write_records.rs | 5 +- docs/spec/upgrades/satin.md | 39 +++++---- 5 files changed, 69 insertions(+), 69 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e4e5627d..09e18a352 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,11 +107,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 fork pins at the commit that adds the instruction hooks on top of its mega.6 release (megaeth-labs/revm#75), until the mega.7 tag is cut. +- The fork pins at the head of its byte-pool branch, a local carry item repinned to a published commit before anything is pushed, and op-revm at the commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), also a local carry item. + The byte-pool branch carries a data-size budget on every frame's gas tracker (`GasTracker::record_bytes`, `refill_bytes`, `bytes_remaining`, `bytes_spent`), forwarded at every start as the schedule's share (`GasId::bytes_forward_percent`) and settled as the reservoir is; 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`). mega.6 no longer splits a system call's gas or reports 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 @@ -130,22 +131,22 @@ 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`; `MegaJournal`, the context's journal: revm's journal behind a wrapper that delegates every method, with the journal's ledger beside it, the start window revm decides a frame start in, and the marks Satin takes the journal back to (`journal.rs`); `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, 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, held to the limits and charged its history, and a frame start's records, charged to the caller after the forward — 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 on the Satin journal, alloy-evm's own (`precompiles.rs`); synthetic frame results (`frame.rs`); 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 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 hold of a frame's start to the limits once revm decided it (`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`; `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`; the journal's ledger: the data-size bytes, write records and the log and code bytes of the history byte count, counted at the journal's writes and rewound with its checkpoints — frame and rollback levels, the frame budgets, the start reports and verdicts, the marks, the creation rule, the refund formula, the body, deployed code and the EIP-7708 transfer logs (`ledger.rs`); what a completed write counts (`record.rs`); `AdditionalLimit`: Satin's side of each frame start (`StartSide`: the start charge, the history allowance, a built frame's mark), 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 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 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, 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, and a frame start's records, charged to the caller after the forward and declared on the start, the creator's record drawn on the creator — 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`); 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 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 the caller's hold when a child returns (`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`; `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`; the write records 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 (`record.rs`); `AdditionalLimit`: the draws on a frame's byte pool and the transaction's limit held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records 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 creator's unpaid record — 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 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. - Its journal is `MegaJournal`: revm's journal, delegated to method by method, with the ledger of what the transaction's own execution keeps beside it (see the journal's ledger below); a node that names the context's journal type names `MegaJournal`, and reads revm's journal through its read-only dereference. + 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, 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. @@ -173,9 +174,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 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. + 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. @@ -188,20 +189,21 @@ 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 level of the frame whose journal checkpoint holds the move: a frame start's log with its records; 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 is counted by the ledger as revm makes it, inside the start window, and held to the limits while the frame's level is open, in `MegaEvm::frame_init` (`AdditionalLimit::hold_start`, `hold_answered_start` in `evm/execution.rs`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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` and a creation it answers before bumping its creator's nonce count nothing and have no verdict, their level never having opened; the call 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, and the creation gets back the history its caller paid. + 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`, `hold_start`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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 answers before bumping its creator's nonce — an endowment an inspector raised past the creator's balance — gives back the creator's record its hook counted, with what the creator paid for it. 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 lands on the creator, which is held to its limits with it. 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. - The ledger counts the log revm journaled for a start, not a prediction of 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. + 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. + A frame's budget is the byte pool on its gas tracker: the transaction's tracker starts with what the body and the authorities' records leave (`AdditionalLimit::first_frame_pool`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::bytes_forward_percent` = 98), capped where the caller suspends (`cap_the_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`), the transaction limit before the frame budget. 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 by the journal's ledger with a transaction limit and frame budgets, and compute gas (2), gas detention's stop. +- A limit stop names one of two runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), drawn from the frames' byte pools under a transaction limit, 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: 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 — and the count is still 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. @@ -264,7 +266,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 level of the ledger is the one any depth-0 call opens, 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 drawn on its pool before the share is forwarded, as a `CREATE` opcode's start does. 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. @@ -389,44 +391,43 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 commits the record to the running frame's level of the journal's ledger and holds it to the limits first — 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. + It counts the record's bytes on the running frame's pool (`AdditionalLimit::draw`) and holds it to the limits first — the transaction's limit, then the frame's budget; 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 for the records the start makes, so the frame's budget carries none of them, and leaves the charge on the frame's side (`StartSide`), which gives back on return what the ledger reports the start did not keep. + 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; a creator's nonce record is drawn on the caller's pool there, before revm forwards the frame its share, and is not declared, outliving the creation. revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. 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, asked at the opcode and counted by the ledger as revm makes the start; a debug build holds the count to the charge for every start revm made and held to the limits, except under an inspector that may rewrite the frame's input between them, exactly but for a creation's created account, which the hook charges for every creation — it cannot tell the address a `CREATE2` lands on — and whose record the refund gives back where the creation did not make it. + 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 the hook's records to those, except under an inspector that may rewrite the frame's input between them, and both to what revm's start made of the accounts, exactly for every record. - **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, 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 (`MegaJournal::is_changed`): the journal compares the accounts a counted write touches before and after it — a value transfer's two sides, 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), a `SELFDESTRUCT`'s beneficiary and the account it clears — and tells the ledger the records the write makes and takes back (`RecordDelta`), the frame-start hook predicts the same from the journal's state to charge the caller (`MegaJournal::start_records`), and 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 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 frame's level of the journal's ledger: a commit keeps them for the caller, a revert takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its level once the nonce was bumped and before the creation's budget is taken from what the creator has left, so it survives the creation's failure and is held to the creator's budget, not the creation's. - That record lands on the creator unchecked, so the creator is held to its budget with it as the creation returns, before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_start_return`). + 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, drawn on its pool at the creation's hook before the creation's share is forwarded, so it survives the creation's failure and is held to the creator's budget, not the creation's. + That record lands on the creator unchecked — a pool that cannot pay it is drained and owes the rest — so the creation's start is held to the transaction's limit with it, and the creator to its budget as the creation returns, before it runs on, reverting alone if it crossed (`AdditionalLimit::hold_caller`). The KV count a node reports is the write-record count; no limit holds it. -- **The journal's ledger decides.** - `MegaJournal` counts what the transaction's own execution keeps, at the journal's writes: a frame start's records and transfer log inside the start window Satin opens around revm's frame start, a completed write and a deposit's code from the Host's hooks, the body, the hints and the authorities where they are made; revm's checkpoint reverts rewind it, so what the ledger holds is what the journal keeps, whoever reverted what. - Every checkpoint opens a level: a frame level for each frame revm starts — the first checkpoint of a call's start, or a creation's account checkpoint, opened once its creator's nonce record is counted on the creating frame's level, so its budget is taken from what the creator has left after that record and its usage starts after it — and a rollback level for any other, a tool's or a precompile's included; a frame level closes only as its frame returns, and a revert that would close one from below trips in debug builds. - The journal's own write methods count nothing, so a tool's or a precompile's writes are not counted. - Every verdict is the ledger's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start while its level is open (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return, and the refund of what a caller paid for a start's records, by one formula over what the ledger still holds (`StartSide::refund`): a start's own records when its level was kept, a creator's nonce record unless a revert to before the start took it back. - A tool's checkpoint around a frame start that the tool reverts takes the frame's records back with the frame's writes, and the transaction reports what the journal kept. -- **The frame side stays aligned with frames.** - `frame_init` pushes one side (`StartSide`) per frame result revm will return — what the caller paid for the start's records, the history allowance, and, once revm built the frame, what the ledger saw the start count and the frame's own mark — one for a frame answered without running too (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 side any depth-0 call has, and its creation's side is pushed above it as any child's. +- **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 creator's record its pool could not pay. + 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 is given them where it settles (`settle_kept_nothing`). + 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)` (the ledger's verdict for the data size, `AdditionalLimit::crossed` for gas detention's compute stop, both answering the exemption), what it counted goes with its level, and its caller resumes as after any revert. + 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, 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 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. A frame returns a stop before running another instruction in two cases (`AdditionalLimit::stop_before_run`, `before_frame_run`): on its first run, when its own start crossed a limit once revm built it; and on a resume, when a child left it one — 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; the history charged before execution for that frame's write record comes back at the settlement, at one site, whenever the frame did not keep the record. + 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). 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 `Ledger::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`). + 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 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. @@ -440,7 +441,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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`). - **Inspectors in block execution.** - Block execution admits any inspector: the journal's ledger follows the journal, so a rewrite cannot put the ledger out of step with state, and which inspectors may run on block production is a node's decision, not the engine's. + 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 module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase. `test_utils::ReadOnlyObserver` wraps an inspector that is meant to write nothing back and proves it in debug builds, for tests. @@ -449,7 +450,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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 journal's ledger holds none, the frame's level having been reverted or its start never made, and the history its caller paid for the start's records comes back by the ledger's formula — 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, at the settlement. + 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, no byte draw and no refund, no write record — what the frame counted goes back with its start, or was never counted, and the history its caller paid for the start's records comes back with its start charge — 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, at the settlement. 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`. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index f217d3970..652929f88 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -23,7 +23,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 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 ledger level a depth-0 call opens, 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 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 `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 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). diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index da525507e..7d500b0bf 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -238,9 +238,8 @@ where /// An inspector that answers the calls below the transaction's own frame rewrites what execution /// produces. Block execution does not refuse it, and on the EVM alike its answer stands in for the -/// frame: a side of its own keeps the frame sides aligned -/// with the frames, the answered call ends as every call does, and the transaction settles as one -/// whose nested call never ran. +/// 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(); diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index c7e9bde5a..4581ae769 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1460,8 +1460,9 @@ impl Inspector, EthInterpreter> for ChangedBeforeT /// 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 frame's side builds on that, giving back no price -/// for a record taken back; this holds it for every transaction shape, in the release build too. +/// 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)); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 5343a2ecd..55a805c71 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -339,10 +339,9 @@ When each charge is made: 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 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 — MUST be given back by it then, before what it makes is charged. 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 (the accounts a value transfer changes from what the transaction loaded; a creation's created account 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 `CREATE` or `CREATE2` MUST charge the created account's record whether or not the creation makes it; it makes none for an address the transaction has changed already. +- 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. - The price of a record the start takes back — an account the transfer returns to what the transaction loaded — and of a created account's record the creation did not make MUST be given back to the caller once the frame returned with its start kept. + 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 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)). @@ -646,23 +645,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 transaction 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)` | +| 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. From 0479760461a85d48003f587c3f684039bb86dcd2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 06:20:12 +0800 Subject: [PATCH 448/458] test: pin a creation's exact start charge and trip the start checks A creation onto an account the transaction already changed charges its creator one record: given 64 times its price after its charges, the creator starts the creation, and one gas less it does not. A debug build now holds the history a start declares to the price of the records predicted for it, beside the records themselves, and both checks, with the authority-records check the ledger's test pinned, have a test that trips them. A creation past the depth limit takes no address, so its hook counts nothing; the depth guard asserts it. Two doc lines are mended. --- crates/mega-evm/src/evm/execution.rs | 50 ++++++++++++++++-- crates/mega-evm/src/evm/host.rs | 7 +-- crates/mega-evm/src/limit/limit.rs | 14 +++++ crates/mega-evm/tests/satin/history_gas.rs | 60 ++++++++++++++++++++-- 4 files changed, 121 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index e5820c3ad..bba3f63bd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -552,6 +552,10 @@ impl EvmTr for MegaEvm( } } -/// Whether executing this transaction creates its caller's account/// 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 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, and after /// [`validate_env`](Handler::validate_env), which promoted a system-address transaction: a @@ -1622,6 +1637,35 @@ mod tests { })) } + /// A debug build holds the records a start's hook charged its caller for to those predicted + /// once revm is about to decide the start: a start whose records changed in between trips, + /// since its charge and the refund its failure gets back would both be wrong. `CALLER` holds + /// nothing, so the value call makes no record; its hook was charged for a transfer log. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "changed after its caller was charged for them")] + fn test_a_start_whose_records_changed_after_its_charge_trips() { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let init = FrameInit { depth: 1, memory: SharedMemory::new(), frame_input: value_call() }; + let charged = StartRecords { transfer_log: true, ..StartRecords::NONE }; + let _ = FrameStart::of(&mut ctx, &init, false, Some(charged)); + } + + /// A debug build holds the history a start declares to the price of the records predicted for + /// it: a start whose hook charged another price trips. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "a start's charge is the price of the records it makes on its frame")] + fn test_a_start_charged_another_price_trips() { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let mut frame_input = value_call(); + if let FrameInput::Call(inputs) = &mut frame_input { + inputs.charged_start = StartCharge::new(1, 0); + } + let init = FrameInit { depth: 1, memory: SharedMemory::new(), frame_input }; + let _ = FrameStart::of(&mut ctx, &init, false, Some(StartRecords::NONE)); + } + /// 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 { diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 1c4297df1..0e8307931 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -366,9 +366,10 @@ impl revm::context_interface::Host /// 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. 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. + /// 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 diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index aa90610db..1217b03c7 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -766,4 +766,18 @@ mod tests { "the next transaction is held to its limits" ); } + + /// 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 limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); + let mut limit = AdditionalLimit::new(limits); + limit.begin_transaction(false, false, crate::TX_BODY_SIZE); + limit.count_authorities(2); + } } diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index d3636200d..428f672ff 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}, @@ -12,13 +12,16 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLCODE, CREATE, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STATICCALL, - STOP, + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, 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, runs_at_measurement_prices, +}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const CALLEE: Address = address!("0000000000000000000000000000000000200001"); @@ -228,6 +231,55 @@ 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 a 64th of what is left, keeping that +/// 64th to pay the start's records with. Given 64 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 + 64 * 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 + 64 * 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 From 932e8c77acaf559bbdba13cdea3e7ad97b5ad272 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 06:27:37 +0800 Subject: [PATCH 449/458] docs: the start's declared charge is held to its records' price in debug builds --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 09e18a352..eb0dd4b53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -398,7 +398,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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; a creator's nonce record is drawn on the caller's pool there, before revm forwards the frame its share, and is not declared, outliving the creation. revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. 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 the hook's records to those, except under an inspector that may rewrite the frame's input between them, and both to what revm's start made of the accounts, exactly for every record. + 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 the hook's records to those, and the history it declared to their price, except under an inspector that may rewrite the frame's input between them, and both to what revm's start made of the accounts, exactly for every record. - **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. From 92cf6f38730a6509bfe0095517c8713f1197959c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 07:20:43 +0800 Subject: [PATCH 450/458] fix(inspector): an answered start's charged records go with it, and every transaction starts without them --- crates/mega-evm/src/evm/context.rs | 5 +++++ crates/mega-evm/src/evm/execution.rs | 11 +++++----- crates/mega-evm/tests/satin/tool_writes.rs | 24 ++++++++++++++++++++++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 5efaf3a63..e5041d143 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -494,6 +494,11 @@ impl MegaContext { // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call // unanswered. self.keyless_frame = None; + // A start an inspector answered left the records its hook charged for. + #[cfg(debug_assertions)] + { + self.charged_records = None; + } self.system_originated = system_originated; let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; self.set_history_exempt(exempt); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index bba3f63bd..762a273b3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -779,16 +779,17 @@ where // 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)); - } // The start its charge paid for — the calling opcode's, or the transaction's for its own - // frame — may not be the one the inspector lets start. + // frame — may not be the one the inspector lets start, and one it answers never reaches + // revm: either way the records go with this start. #[cfg(debug_assertions)] { ctx.charged_records = None; } + 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 diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs index 9446502ef..8ab315fc0 100644 --- a/crates/mega-evm/tests/satin/tool_writes.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -148,3 +148,27 @@ fn test_a_value_call_answered_at_frame_start_counts_nothing() { assert_eq!(outcome.usage, records_and_moves(0, 0), "{case}"); } } + +/// The records a start's hook charged its caller for are that start's alone: a start an inspector +/// answers in `frame_start` leaves none of them to the next transaction on the same EVM, which a +/// debug build would otherwise hold its first frame's start to once the inspector is disabled. +#[test] +fn test_a_start_answered_at_frame_start_leaves_its_records_with_its_transaction() { + let code = BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])); + let mut evm = + MegaEvm::new(context(db)).with_inspector(AnswersAtFrameStart { target: RECEIVER }); + let answered = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); + let outcome = evm.execute_transaction(answered).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage, records_and_moves(0, 0), "the answered value call counts nothing"); + + alloy_evm::Evm::set_inspector_enabled(&mut evm, false); + let plain = call(CALLER, RECEIVER, U256::ZERO, value_call_room()); + let outcome = evm.execute_transaction(plain).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage, records_and_moves(0, 0), "a call without value makes no record"); +} From 03354570eafc83c399d326e7053107543f8a19ca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 07:20:43 +0800 Subject: [PATCH 451/458] docs(test): a creation is charged its created account's record only when the transaction had not changed it --- crates/mega-evm/tests/satin/write_records.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 4581ae769..672315bd0 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -482,10 +482,10 @@ impl Creation { /// The creator's nonce adds no record either where the transfer that funded the address changed /// the creator already. /// -/// The caller pays the created account's history at the opcode, which cannot tell the address a -/// `CREATE2` lands on, and gets it back when the creation recorded nothing — and, with everything -/// else the creation made, when it fails: the history the transaction pays is its body's and the -/// records it keeps, at the prices in effect. +/// 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 From fd1bce61e899cf3dcc3a341b98899b3c8bacfd7f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 07:31:49 +0800 Subject: [PATCH 452/458] docs(context): the per-transaction reset of a start's charged records names the rule it holds --- crates/mega-evm/src/evm/context.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e5041d143..a08c76019 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -494,7 +494,8 @@ impl MegaContext { // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call // unanswered. self.keyless_frame = None; - // A start an inspector answered left the records its hook charged for. + // The records a start's hook charged for are that start's, and no start outlives its + // transaction. #[cfg(debug_assertions)] { self.charged_records = None; From a1053311bfa4a394215f56694a30523a6f1ae5ec Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 09:52:48 +0800 Subject: [PATCH 453/458] chore(deps): pin the revm and op-revm forks by rev on their public repositories The twelve revm crates move to megaeth-labs/revm at 42e4c354 (the code of megaeth-labs/revm#76) and op-revm to megaeth-labs/op-revm at e33fb15b (the head of megaeth-labs/op-revm#8). The revm commit is the one the local checkout was pinned at; the op-revm commit differs from the local one only in op-revm's own revm pin, so its crate sources are the same. --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 26 +++++++++++++------------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eb88ea132..50efdaefb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+file:///Users/cz/work/op-revm?rev=af071cc255f058bebce27df45a3245332a211dd8#af071cc255f058bebce27df45a3245332a211dd8" +source = "git+https://github.com/megaeth-labs/op-revm?rev=e33fb15b416008ac9d45c52a2b1edd0a286ff521#e33fb15b416008ac9d45c52a2b1edd0a286ff521" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" 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+file:///Users/cz/work/mega-revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +source = "git+https://github.com/megaeth-labs/revm?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index 26a085dfe..14a720e5a 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 = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-primitives = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-interpreter = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-context = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-context-interface = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-handler = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-database = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-database-interface = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-state = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-bytecode = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-precompile = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-inspector = { git = "file:///Users/cz/work/mega-revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } [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 = "file:///Users/cz/work/op-revm", rev = "af071cc255f058bebce27df45a3245332a211dd8" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "e33fb15b416008ac9d45c52a2b1edd0a286ff521" } From 720ad2435d4293d5c89c4f95cee41b93ca08ee12 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 09:53:04 +0800 Subject: [PATCH 454/458] docs: name the fork commits the patch blocks pin by rev The overview names the revm and op-revm commits and their pull requests in place of release tags, AGENTS.md states the rev-pin rule and drops the carry-item and release-name wording, and the review notes and the execution-spec workflows' comments speak of a pinned commit rather than a tag. --- .claude/skills/satin-review/SKILL.md | 2 +- .github/workflows/exec-spec-satin.yml | 2 +- .github/workflows/exec-spec.yml | 2 +- AGENTS.md | 7 ++++--- REVIEW.md | 2 +- docs/spec/overview.md | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index ff3ee7b6c..19f6756e7 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -21,7 +21,7 @@ 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 at the commits the patch blocks pin by `rev` (megaeth-labs/revm#76, megaeth-labs/op-revm#8) 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. diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index caa593fb0..ac97d0f17 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -144,7 +144,7 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - # A release tag, or a release's commit until its tag is cut. + # The fork's tag or `rev`, and the commit the lock resolved it to. 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 diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 0f9c545b1..015883e09 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -60,7 +60,7 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - # A release tag, or a release's commit until its tag is cut. + # The fork's tag or `rev`, and the commit the lock resolved it to. 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 diff --git a/AGENTS.md b/AGENTS.md index eb0dd4b53..7f0cba40b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,12 +104,13 @@ 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. + Both forks are pinned by `rev`, a full commit hash, and not by tag until the line is final; `docs/spec/overview.md` names the pinned commits, and a repin updates it. - 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 fork pins at the head of its byte-pool branch, a local carry item repinned to a published commit before anything is pushed, and op-revm at the commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), also a local carry item. - The byte-pool branch carries a data-size budget on every frame's gas tracker (`GasTracker::record_bytes`, `refill_bytes`, `bytes_remaining`, `bytes_spent`), forwarded at every start as the schedule's share (`GasId::bytes_forward_percent`) and settled as the reservoir is; 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`). - mega.6 no longer splits a system call's gas or reports 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`). +- The revm fork is pinned at the code of megaeth-labs/revm#76, the instruction hooks and the per-frame byte pool, and op-revm at the head of megaeth-labs/op-revm#8, which settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`). + That revm commit carries a data-size budget on every frame's gas tracker (`GasTracker::record_bytes`, `refill_bytes`, `bytes_remaining`, `bytes_spent`), forwarded at every start as the schedule's share (`GasId::bytes_forward_percent`) and settled as the reservoir is; 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 revm fork no longer splits a system call's gas or reports 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, lending it the creating frame's tracker, whose pool the code's bytes are drawn from. diff --git a/REVIEW.md b/REVIEW.md index 09251868f..f5fbee410 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -184,7 +184,7 @@ These checks guard every change to the Satin engine. - 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 and suppression hygiene. - - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. + - `exec-spec.yml`: the execution-spec fixtures at the pinned fork commit. - `doc-audit.yml`: the documentation audit of `satin`'s docs. - `price-grid.yml`: the whole byte-price grid. diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 3e98d1c88..ab3d9746b 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.6`; until that tag is cut, its release commit `7bc0c664`), 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 [`42e4c354`](https://github.com/megaeth-labs/revm/commit/42e4c3543af170ca911cbb52e68de1ecd8cd443e) ([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 [`e33fb15b`](https://github.com/megaeth-labs/op-revm/commit/e33fb15b416008ac9d45c52a2b1edd0a286ff521) ([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 5c0147bd3917a74d802232574d661ab6e86fa538 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 10:42:35 +0800 Subject: [PATCH 455/458] fix(build): gate the imports only debug checks use, so a release build does not warn --- crates/mega-evm/src/evm/context.rs | 4 +++- crates/mega-evm/src/evm/execution.rs | 4 +++- crates/mega-evm/src/limit/mod.rs | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index a08c76019..005762118 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -19,6 +19,8 @@ use revm::{ Database, }; +#[cfg(debug_assertions)] +use crate::limit::StartRecords; use crate::{ constants, evm::{ @@ -26,7 +28,7 @@ use crate::{ inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - limit::{Accounts, Counted, StartRecords}, + limit::{Accounts, Counted}, system::{ self, keyless::{self, KeylessFrame}, diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 762a273b3..4f50598d7 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -49,12 +49,14 @@ use revm::{ Inspector, }; +#[cfg(debug_assertions)] +use crate::limit::StartRecords; use crate::{ access::ComputeStop, charge_write_records_history, evm::inspector::{frame_end_checked, ResultSource, StepGuard, UpfrontRecord}, history_gas, - limit::{Counted, CreatorRecord, StartRecords}, + limit::{Counted, CreatorRecord}, synthetic_frame_result, system::keyless, write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 9988d500d..e94b4c24d 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -144,7 +144,9 @@ mod record; pub use limit::AdditionalLimit; pub(crate) use limit::{Counted, CreatorRecord}; -pub(crate) use record::{Accounts, HistoryBytes, RecordDelta, StartRecords}; +#[cfg(debug_assertions)] +pub(crate) use record::RecordDelta; +pub(crate) use record::{Accounts, HistoryBytes, StartRecords}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; From 9c1909a613711bc7716d6e4abead864e02ebaee5 Mon Sep 17 00:00:00 2001 From: William Cheung Date: Wed, 21 Oct 2026 21:39:21 +0800 Subject: [PATCH 456/458] fix: restore coverage uploads and large PR reviews (#406) (cherry picked from commit 821577dc28f683b15ec6e747c7ea24fbbda69aad) Conflict resolution: - .github/workflows/claude.yml: main's version, unchanged. - .github/workflows/coverage.yml: this branch's version, which already uploads over OIDC with fail_ci_if_error, continue-on-error and a warning step, and triggers on satin; main's persist-credentials: false is added to its checkout step. --- .github/workflows/claude.yml | 5 +++-- .github/workflows/coverage.yml | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 8416c48ed..25710daab 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -80,7 +80,7 @@ jobs: # Review under the CI app identity rather than the job token: it is what # lets the action resolve stale review threads (the shared action gates # --resolve-threads on github_identity_token being non-empty). - - uses: actions/create-github-app-token@v3 + - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 id: app-token with: client-id: ${{ vars.MEGA_MAXWELL_CLIENT_ID }} @@ -96,7 +96,8 @@ jobs: submodules: recursive fetch-depth: 1 - - uses: megaeth-labs/.github/.github/actions/claude-pr-review@main + # Includes the large-PR diff fallback and App identity forwarding (.github#48). + - uses: megaeth-labs/.github/.github/actions/claude-pr-review@eb44b85d2d0f02ab70452935912948e4b2b29cf0 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} github_identity_token: ${{ steps.app-token.outputs.token }} diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 6b596ed2f..75e83d6d6 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -28,6 +28,7 @@ jobs: - uses: actions/checkout@v4 with: submodules: recursive + persist-credentials: false - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1 From 2038ced1baf6aca56fdd59d0026a86d8c7729a42 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 08:39:48 +0800 Subject: [PATCH 457/458] feat(satin): restore KV and state-growth limits, run on revm's lifecycles, count the creator record at the return and add the destruction table - Restore the KV-update and state-growth limits per transaction, per frame (98/100 shares) and per block; a crossing is a revert-class limit stop of the frame that crosses it, ordered data size, KV updates, state growth, the frame budget named first. - Forward the reservoir and regular gas at 98/100 on the forks' pools, and replace the storage-gas stipend with a 160-byte history allowance. - Run frames on revm's own plain and inspected lifecycles through the forks' loop hooks; no inspector-specific code remains in the engine. - Count a creator's nonce record on the creator when the creation returns with the nonce bumped; the creation's budget is the share taken before it. - Give back what a transaction made of an account its first effective destruction removes (the same-transaction destruction table), read from the journal. - Read an account's absence at a transaction's start from that transaction's journal. - Pin the forks at revm 2fc8edf33b2ffddb195cebc17be9adabfd95417c and op-revm f599efdabc3e5b36a280f1aa72978751bd64c160. - Accept a limits file of the first published shape; pack mega-evme's recorded block fixtures into one archive; specification, implementation notes and the review guide updated to the final engine. --- .claude/skills/satin-review/SKILL.md | 387 ++-- .github/workflows/claude.yml | 5 +- .github/workflows/coverage.yml | 1 - .github/workflows/exec-spec-satin.yml | 2 +- .github/workflows/exec-spec.yml | 2 +- AGENTS.md | 197 +- Cargo.lock | 44 +- Cargo.toml | 26 +- REVIEW.md | 17 +- 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/common/outcome.rs | 11 +- 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 | 47 +- crates/mega-evm/benches/transact.rs | 16 +- crates/mega-evm/src/access/detention.rs | 76 +- crates/mega-evm/src/access/mod.rs | 2 +- crates/mega-evm/src/block/eips.rs | 41 +- crates/mega-evm/src/block/executor.rs | 36 +- crates/mega-evm/src/block/genesis.rs | 16 +- 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 | 66 +- crates/mega-evm/src/evm/execution.rs | 1174 +++++------ crates/mega-evm/src/evm/factory.rs | 8 +- crates/mega-evm/src/evm/frame.rs | 168 +- crates/mega-evm/src/evm/history.rs | 16 +- crates/mega-evm/src/evm/host.rs | 214 +- crates/mega-evm/src/evm/inspector.rs | 505 ----- crates/mega-evm/src/evm/mod.rs | 119 +- crates/mega-evm/src/evm/precompiles.rs | 2 +- crates/mega-evm/src/evm/result.rs | 3 +- crates/mega-evm/src/evm/schedule.rs | 129 +- crates/mega-evm/src/lib.rs | 38 +- crates/mega-evm/src/limit/limit.rs | 737 ++++--- crates/mega-evm/src/limit/mod.rs | 239 ++- crates/mega-evm/src/limit/record.rs | 565 +++++- crates/mega-evm/src/system/AGENTS.md | 8 +- .../mega-evm/src/system/keyless/dispatch.rs | 119 +- crates/mega-evm/src/system/keyless/mod.rs | 28 +- crates/mega-evm/src/system/keyless/settle.rs | 94 +- crates/mega-evm/src/system/limit_control.rs | 2 +- crates/mega-evm/src/system/oracle.rs | 2 +- .../mega-evm/src/system/sequencer_registry.rs | 39 +- crates/mega-evm/tests/block/counters.rs | 53 +- crates/mega-evm/tests/block/eips.rs | 113 +- crates/mega-evm/tests/block/factory.rs | 16 +- crates/mega-evm/tests/block/inspector.rs | 2 +- crates/mega-evm/tests/block/limits.rs | 274 ++- 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 | 20 +- 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 | 4 +- crates/mega-evm/tests/fuzz/gen/world.rs | 98 +- crates/mega-evm/tests/fuzz/properties.rs | 187 +- crates/mega-evm/tests/fuzz/regressions.rs | 63 +- crates/mega-evm/tests/satin/common.rs | 46 +- 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 | 613 ++++-- .../mega-evm/tests/satin/data_size_counts.rs | 23 +- crates/mega-evm/tests/satin/deposit_charge.rs | 57 +- .../tests/satin/detained_transfers.rs | 206 +- crates/mega-evm/tests/satin/detention.rs | 125 +- crates/mega-evm/tests/satin/equivalence.rs | 51 +- 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} | 41 +- crates/mega-evm/tests/satin/history_bytes.rs | 53 +- .../mega-evm/tests/satin/history_exemption.rs | 4 +- crates/mega-evm/tests/satin/history_gas.rs | 84 +- .../mega-evm/tests/satin/history_reservoir.rs | 19 +- .../mega-evm/tests/satin/inherited_costs.rs | 113 +- crates/mega-evm/tests/satin/inspector.rs | 62 +- .../tests/satin/inspector_cheatcodes.rs | 63 +- .../mega-evm/tests/satin/inspector_limits.rs | 130 +- .../tests/satin/inspector_settlement.rs | 912 +++++---- crates/mega-evm/tests/satin/kv_updates.rs | 285 +++ .../mega-evm/tests/satin/limit_exemption.rs | 88 +- .../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 | 7 +- 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 | 19 +- .../mega-evm/tests/satin/reservoir_drain.rs | 1751 +++++++++++++++++ .../mega-evm/tests/satin/reservoir_share.rs | 200 ++ crates/mega-evm/tests/satin/salt_refund.rs | 127 +- crates/mega-evm/tests/satin/schedule.rs | 8 +- ...atin__corpus__corpus_outcomes_and_gas.snap | 2 +- crates/mega-evm/tests/satin/spec_numbers.rs | 89 +- crates/mega-evm/tests/satin/state_growth.rs | 824 +++++++- crates/mega-evm/tests/satin/stops.rs | 527 +++-- crates/mega-evm/tests/satin/strategic_stop.rs | 66 +- .../tests/satin/synthetic_frame_gas.rs | 100 +- crates/mega-evm/tests/satin/system_call.rs | 162 +- crates/mega-evm/tests/satin/tool_writes.rs | 32 +- crates/mega-evm/tests/satin/transfer_logs.rs | 269 +-- crates/mega-evm/tests/satin/withheld_gas.rs | 61 +- crates/mega-evm/tests/satin/write_records.rs | 218 +- .../mega-evm/tests/system/keyless/charges.rs | 50 + .../mega-evm/tests/system/keyless/deploy.rs | 85 +- .../tests/system/keyless/detention.rs | 10 +- .../tests/system/keyless/differential.rs | 5 +- crates/mega-evm/tests/system/keyless/frame.rs | 17 +- .../tests/system/keyless/inspector.rs | 98 +- .../mega-evm/tests/system/keyless/limits.rs | 156 +- crates/mega-evm/tests/system/keyless/rules.rs | 2 +- ...erential__keyless_differential_record.snap | 276 +-- crates/mega-evm/tests/system/oracle.rs | 6 +- crates/mega-evm/tests/system/system_tx.rs | 12 +- crates/mega-evm/tests/tracers/harness.rs | 8 +- crates/mega-evm/tests/tracers/scenarios.rs | 39 +- ...first_frame_start_stop__call_with_log.snap | 2 +- ...p_caught_by_the_parent__call_with_log.snap | 2 +- crates/mega-state-test/README.md | 2 +- crates/mega-state-test/src/digest.rs | 12 +- crates/mega-state-test/tests/runner.rs | 3 +- crates/state-test/README.md | 2 +- crates/state-test/src/main.rs | 19 +- crates/state-test/tests/cli.rs | 2 + .../mega-evme/configuration/chain-and-spec.md | 14 +- docs/spec/glossary.md | 38 + docs/spec/hardfork-spec.md | 6 +- docs/spec/overview.md | 4 +- docs/spec/upgrades/overview.md | 2 +- docs/spec/upgrades/satin.md | 626 +++++- 199 files changed, 16642 insertions(+), 4424 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 create mode 100644 crates/mega-evm/tests/satin/gas_forward.rs rename crates/mega-evm/tests/satin/{storage_call_stipend.rs => history_allowance.rs} (96%) 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 diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 76b51aa72..5f6088b08 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 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) 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 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. 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,7 +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 at the commits the patch blocks pin by `rev` (megaeth-labs/revm#76, megaeth-labs/op-revm#8) are pinned dependencies with their own review; their diff is not part of this pull request. +- 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. @@ -41,32 +42,124 @@ 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. +#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. +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 @@ -78,35 +171,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 @@ -114,65 +213,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`, the effect of a completed write in `record.rs`), `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:** - - A write is counted in the Host's completed-write hook, 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 frame start's records are charged in the Host's frame-start hook, after the forward and before revm builds the frame's input; a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. + - 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. + - 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 ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited. + - 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`. @@ -180,64 +296,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; @@ -253,50 +389,60 @@ 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`). +- **`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. @@ -305,12 +451,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. -- **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. +- **`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. diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 25710daab..8416c48ed 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -80,7 +80,7 @@ jobs: # Review under the CI app identity rather than the job token: it is what # lets the action resolve stale review threads (the shared action gates # --resolve-threads on github_identity_token being non-empty). - - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 + - uses: actions/create-github-app-token@v3 id: app-token with: client-id: ${{ vars.MEGA_MAXWELL_CLIENT_ID }} @@ -96,8 +96,7 @@ jobs: submodules: recursive fetch-depth: 1 - # Includes the large-PR diff fallback and App identity forwarding (.github#48). - - uses: megaeth-labs/.github/.github/actions/claude-pr-review@eb44b85d2d0f02ab70452935912948e4b2b29cf0 + - uses: megaeth-labs/.github/.github/actions/claude-pr-review@main with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} github_identity_token: ${{ steps.app-token.outputs.token }} diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 75e83d6d6..6b596ed2f 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -28,7 +28,6 @@ jobs: - uses: actions/checkout@v4 with: submodules: recursive - persist-credentials: false - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1 diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index ac97d0f17..caa593fb0 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -144,7 +144,7 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - # The fork's tag or `rev`, and the commit the lock resolved it to. + # 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 diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 015883e09..0f9c545b1 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -60,7 +60,7 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - # The fork's tag or `rev`, and the commit the lock resolved it to. + # 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 diff --git a/AGENTS.md b/AGENTS.md index 7f0cba40b..6f106e02d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,13 +104,14 @@ 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. - Both forks are pinned by `rev`, a full commit hash, and not by tag until the line is final; `docs/spec/overview.md` names the pinned commits, and a repin updates it. - 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 revm fork is pinned at the code of megaeth-labs/revm#76, the instruction hooks and the per-frame byte pool, and op-revm at the head of megaeth-labs/op-revm#8, which settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`). - That revm commit carries a data-size budget on every frame's gas tracker (`GasTracker::record_bytes`, `refill_bytes`, `bytes_remaining`, `bytes_spent`), forwarded at every start as the schedule's share (`GasId::bytes_forward_percent`) and settled as the reservoir is; 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 revm fork no longer splits a system call's gas or reports 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`). +- 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, lending it the creating frame's tracker, whose pool the code's bytes are drawn from. @@ -132,17 +133,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 | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `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, 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, and a frame start's records, charged to the caller after the forward and declared on the start, the creator's record drawn on the creator — 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`); 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 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 the caller's hold when a child returns (`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`; `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`; the write records 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 (`record.rs`); `AdditionalLimit`: the draws on a frame's byte pool and the transaction's limit held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records 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 creator's unpaid record — 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 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 @@ -156,7 +157,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. @@ -166,6 +167,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 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. @@ -191,41 +193,61 @@ 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`, `hold_start`), with a journal mark at every start: a frame revm built returns the stop on its first run, before any instruction, 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 answers before bumping its creator's nonce — an endowment an inspector raised past the creator's balance — gives back the creator's record its hook counted, with what the creator paid for it. - 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 lands on the creator, which is held to its limits with it. + 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. - A frame's budget is the byte pool on its gas tracker: the transaction's tracker starts with what the body and the authorities' records leave (`AdditionalLimit::first_frame_pool`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::bytes_forward_percent` = 98), capped where the caller suspends (`cap_the_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`), the transaction limit before the frame budget. + 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), drawn from the frames' byte pools under a transaction limit, 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: 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 — and the count is still reported, in the outcome's usage and the block's. +- 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 the block's data-size budget 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 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. @@ -235,8 +257,9 @@ 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`). `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. @@ -262,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. - 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 drawn on its pool before the share is forwarded, as a `CREATE` opcode's start does. + 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. @@ -297,16 +320,16 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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`). @@ -323,6 +346,7 @@ 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.** @@ -339,32 +363,39 @@ Detention caps how much a transaction may still compute once it read such data ( 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`, in the completed-write hook, 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 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. + 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: 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. @@ -373,7 +404,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 is not the frame's: `StepGuard` puts the record back around each callback, so a later halt that records nothing of its own is not read off it. + 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`. @@ -392,14 +423,18 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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's bytes on the running frame's pool (`AdditionalLimit::draw`) and holds it to the limits first — the transaction's limit, then the frame's budget; 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. + 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; a creator's nonce record is drawn on the caller's pool there, before revm forwards the frame its share, and is not declared, outliving the creation. - revm copies the caller's reservoir into the frame's input after the hook, so a built frame and an answered start both inherit the reservoir the charge left. + 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 the hook's records to those, and the history it declared to their price, except under an inspector that may rewrite the frame's input between them, and both to what revm's start made of the accounts, exactly for every record. + 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. @@ -407,22 +442,25 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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, drawn on its pool at the creation's hook before the creation's share is forwarded, so it survives the creation's failure and is held to the creator's budget, not the creation's. - That record lands on the creator unchecked — a pool that cannot pay it is drained and owes the rest — so the creation's start is held to the transaction's limit with it, and the creator to its budget as the creation returns, before it runs on, reverting alone if it crossed (`AdditionalLimit::hold_caller`). - The KV count a node reports is the write-record count; no limit holds 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 creator's record its pool could not pay. + 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 is given them where it settles (`settle_kept_nothing`). + 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`, 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, 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 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. - A frame returns a stop before running another instruction in two cases (`AdditionalLimit::stop_before_run`, `before_frame_run`): on its first run, when its own start crossed a limit once revm built it; and on a resume, when a child left it one — a failed creation's nonce record, which lands on its creator unchecked, putting the creator over a limit. + 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`). @@ -433,32 +471,32 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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`). + 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 module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase. + 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: 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. + 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, no byte draw and no refund, no write record — what the frame counted goes back with its start, or was never counted, and the history its caller paid for the start's records comes back with its start charge — 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, at the settlement. - 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, and `initialize_interp` at a frame's start, see the inspector through `StepGuard`, which puts back the withheld-part crossing and the failed-charge record such a refusal leaves, 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. @@ -470,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. @@ -524,7 +564,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te 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. @@ -542,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. @@ -630,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 50efdaefb..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?rev=e33fb15b416008ac9d45c52a2b1edd0a286ff521#e33fb15b416008ac9d45c52a2b1edd0a286ff521" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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?rev=42e4c3543af170ca911cbb52e68de1ecd8cd443e#42e4c3543af170ca911cbb52e68de1ecd8cd443e" +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 14a720e5a..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", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "42e4c3543af170ca911cbb52e68de1ecd8cd443e" } +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 pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "e33fb15b416008ac9d45c52a2b1edd0a286ff521" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "f599efdabc3e5b36a280f1aa72978751bd64c160" } diff --git a/REVIEW.md b/REVIEW.md index f5fbee410..d04b1ce12 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -27,24 +27,25 @@ 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. 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. @@ -184,7 +185,7 @@ These checks guard every change to the Satin engine. - 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 and suppression hygiene. - - `exec-spec.yml`: the execution-spec fixtures at the pinned fork commit. + - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. - `doc-audit.yml`: the documentation audit of `satin`'s docs. - `price-grid.yml`: the whole byte-price grid. 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/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/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 33f33cbb3..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: 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,11 +134,13 @@ 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, whatever charge it could not pay, an opcode's static gas included. @@ -158,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,13 +208,14 @@ let (evm, result) = executor.finish_with_counters()?; ``` 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. -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. +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 4e245fad3..81a7def05 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -5,8 +5,8 @@ //! //! - `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 completed-write -//! hook. +//! 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`'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 @@ -555,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 b8efa1d23..e8b8723fd 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -448,10 +448,14 @@ impl Detention { /// (`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, @@ -466,14 +470,17 @@ impl Detention { return None; } self.figures.on_frame_end(depth); - if let Some(limit) = self.stop(gas) { - return Some(ComputeStop { limit, used: self.compute(gas.tracker()) }); + 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 = gas.failed_charge_remaining().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 } @@ -487,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 @@ -571,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 @@ -753,6 +760,19 @@ 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] @@ -860,6 +880,38 @@ mod tests { } } + /// 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"); + } + } + /// 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] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index a104f3e6c..613c9161a 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -69,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 205ceb9f4..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: @@ -35,29 +36,15 @@ use revm::context::{ Block, ContextTr, DBErrorMarker, }; -use crate::{ExternalEnvTypes, MegaEvm, 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`]). +/// 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 @@ -82,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 eb929b555..92e174a38 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -78,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 @@ -384,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 } @@ -609,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 @@ -1052,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()); } @@ -1076,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)), diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index 520cc8304..c50facd36 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -304,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::()?; } @@ -547,8 +550,9 @@ mod tests { } /// 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| { @@ -564,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"); 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 005762118..7dd04b1b6 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,9 +1,5 @@ //! 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::{ @@ -19,20 +15,14 @@ use revm::{ Database, }; -#[cfg(debug_assertions)] -use crate::limit::StartRecords; use crate::{ constants, evm::{ history::transaction_body_bytes, - inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, limit::{Accounts, Counted}, - system::{ - self, - keyless::{self, KeylessFrame}, - }, + system::{self, keyless}, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, LimitUsage, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, @@ -68,9 +58,6 @@ pub struct MegaContext>, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, @@ -87,13 +74,9 @@ pub struct MegaContext, - /// The records the last frame start's hook charged its caller for, which a debug build holds - /// the start revm then decides to. - #[cfg(debug_assertions)] - pub(crate) charged_records: Option, + /// 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, @@ -127,7 +110,6 @@ impl MegaContext { external_envs, 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(), @@ -135,9 +117,7 @@ impl MegaContext { system_originated: false, system_call: false, prices_history: true, - keyless_frame: None, - #[cfg(debug_assertions)] - charged_records: None, + keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -478,6 +458,20 @@ impl MegaContext { 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`: the layer begins it, counting its body. /// @@ -493,15 +487,9 @@ impl MegaContext { 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; - // The records a start's hook charged for are that start's, and no start outlives its - // transaction. - #[cfg(debug_assertions)] - { - self.charged_records = 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); @@ -703,12 +691,10 @@ impl ContextTr for MegaContext, gas: &mut GasTracker, ) -> 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) { + // 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()); } let check = self.additional_limit.draw(gas, &Counted::bytes(deposit.code.len() as u64)); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 4f50598d7..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,7 +16,7 @@ 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::{ @@ -24,8 +27,8 @@ use revm::{ }, context_interface::{ cfg::{ - gas::{GasTracker, StartCharge}, - GasId, StateGasCharge, StateGasSite, + gas::{GasTracker, PoolAmounts, PoolId, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, }, journaled_state::{entry::JournalEntry, JournalCheckpoint}, Host, @@ -33,36 +36,33 @@ use revm::{ 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, Gas, - 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}, Inspector, }; -#[cfg(debug_assertions)] -use crate::limit::StartRecords; use crate::{ access::ComputeStop, - charge_write_records_history, - evm::inspector::{frame_end_checked, ResultSource, StepGuard, UpfrontRecord}, - history_gas, - limit::{Counted, CreatorRecord}, + charge_write_records_history, history_gas, + limit::{Counted, CreatorBefore}, synthetic_frame_result, system::keyless, 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; @@ -74,11 +74,6 @@ pub const SYSTEM_CALL_REGULAR_GAS_LIMIT: u64 = 30_000_000; #[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 @@ -91,11 +86,7 @@ pub struct MegaHandler { impl MegaHandler { /// Creates a handler. pub fn new() -> Self { - Self { - op: OpHandler::new(), - deposit_creates_caller: Cell::new(false), - settled_reservoir: Cell::new(None), - } + Self { op: OpHandler::new(), settled_reservoir: Cell::new(None) } } } @@ -172,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, @@ -185,20 +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 = 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); + evm.ctx_mut().additional_limit.count_authorities(applied, created); Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -217,18 +223,12 @@ 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) } @@ -324,16 +324,17 @@ where /// to the beneficiary: revm resolves that delegate through the journal, where the Host does /// not see it. /// - /// The pool is what the transaction has left of its data-size limit once its body and the - /// records of the authorities it applied are counted, under the frame cap - /// ([`AdditionalLimit::first_frame_pool`](crate::AdditionalLimit)); revm hands the frame the - /// whole of 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> { - gas.set_bytes_remaining(evm.ctx_ref().additional_limit.first_frame_pool()); + 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 @@ -346,7 +347,10 @@ where evm.ctx_mut().additional_limit.take_back_authorities(); return Ok(None); }; - let charge = StartCharge::new(evm.ctx_ref().additional_limit.first_frame_charge(), 0); + 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), @@ -451,13 +455,29 @@ where /// halted, as for any transaction that halts. Any other error refuses the transaction, and the /// 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.settled_reservoir.take(); - self.op.catch_error(evm, error) + 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 } } @@ -511,55 +531,73 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - // What the start's hook left for revm's decision is this start's, whoever decides it. - let creator = self.inner.ctx.additional_limit.take_creator_record(); - #[cfg(debug_assertions)] - let charged = self.inner.ctx.charged_records.take(); + // 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) { - debug_assert!( - creator.is_none(), - "a creation past the depth limit takes no address, and its hook counts nothing" - ); 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)? @@ -572,10 +610,7 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Some(result), }; let ctx = &mut self.inner.ctx; - match decided { - None => { - if keyless { - ctx.keyless_frame = Some(keyless::KeylessFrame::Built); - } - ctx.additional_limit.open_start(depth); - 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); - ctx.additional_limit.hold_start(verdict); - #[cfg(debug_assertions)] - start.assert_made(ctx); - Ok(ItemOrResult::Item(frame)) - } - Some(mut result) => { - 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, and the record its hook counted on the creator comes back with - // its answer; failed onto an occupied address, it is held to nothing at its start, - // and its failure takes its records and transfer log back. - if let Some(record) = creator.filter(|_| !start.bumped(ctx)) { - give_back_creator_record(ctx, &mut result, record); - } - ctx.additional_limit.open_start(depth); - 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.share) - }; - stop_the_answer_at(ctx, &start, &mut result, verdict); + 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)); } - settle_answer(ctx, depth, gas_limit, &mut result); - take_back_a_stopped_answer(ctx, start.mark, succeeded, &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 start's, when - /// it crossed a limit once revm built the frame, or the one a child left it, when what the - /// 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() } - /// Returns the result to the caller as revm does, once 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. The caller is then held - /// to its limits with what the frame left it ([`AdditionalLimit::hold_caller`]( - /// crate::AdditionalLimit)). + /// 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(()) + } + + /// 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, @@ -696,7 +752,7 @@ impl EvmTr for MegaEvm (0, true), }; let layer = &mut self.inner.ctx.additional_limit; - let credit = layer.close_start(depth, result.instruction_result().is_ok()); + let (credit, creator) = layer.close_start(depth, result.instruction_result().is_ok()); if credit != 0 { result.gas_mut().refill_history(credit); } @@ -706,12 +762,29 @@ impl EvmTr for MegaEvm { + 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) } } @@ -756,199 +829,150 @@ where &mut evm.inspector, ) } +} - /// revm's inspected frame start: a frame the inspector answers itself never reaches - /// [`EvmTr::frame_init`], 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. - /// - /// A frame whose start crossed a limit returns the stop before it runs: the inspector sees it - /// start and end with the stop, and is told neither of an interpreter nor of the logs its - /// start journaled, which the stop takes back — what it sees of a call answered with the stop. - #[inline] - fn inspect_frame_init( - &mut self, - mut frame_init: FrameInit, - ) -> Result, ContextDbError> { - 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); - // The start its charge paid for — the calling opcode's, or the transaction's for its own - // frame — may not be the one the inspector lets start, and one it answers never reaches - // revm: either way the records go with this start. - #[cfg(debug_assertions)] - { - ctx.charged_records = None; - } - 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 = mark(ctx.journal_mut()); - 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, 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); - // A frame whose start crossed a limit returns the stop before it runs, which takes back - // what its start journaled, as for a call answered with the stop. - let stopped = ctx.additional_limit.has_stop_before_run(); - if !stopped && ctx.journal().logs().len() != logs_i { - inspect_logs(ctx, inspector, logs_i); - } - if !keyless::runs(ctx, frame) && !stopped { - StepGuard(&mut *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`], as `initialize_interp` does at the frame's - /// start, 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, 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 on a first run -/// is the frame's own start, which crossed a limit once revm built the frame: its revert takes -/// back what the start moved. A stop on a resume is the child's doing: 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, with the stipend revm gives a value call's -/// child, which the frame did not forward; 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: &mut EthFrame, - next: &mut Result>, E>, + result: &mut FrameResult, + depth: usize, ) { - match next { - Ok(ItemOrResult::Item(child)) => { - let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); - ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth, stipend); - cap_the_share(ctx.additional_limit.frame_cap(), &mut frame.interpreter.gas, child); - } - 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); } } -/// Holds the share of its caller's pool the frame `child` starts with to the frame cap, `cap`, -/// and gives what it forwarded above it back to the caller, whose pool `caller` holds: a frame's -/// budget is the schedule's share of what its caller has left, under the cap. +/// 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, + 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_share(cap: u64, caller: &mut Gas, child: &mut FrameInit) { - let share = match &child.frame_input { - FrameInput::Call(inputs) => inputs.bytes_share, - FrameInput::Create(inputs) => inputs.bytes_share(), +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 Some(excess) = share.checked_sub(cap).filter(|excess| *excess != 0) else { return }; - caller.set_bytes_remaining(caller.bytes_remaining().saturating_add(excess)); + 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.bytes_share = cap, - FrameInput::Create(inputs) => inputs.set_bytes_share(cap), + FrameInput::Call(inputs) => inputs.pool_shares = shares, + FrameInput::Create(inputs) => inputs.set_pool_shares(shares), FrameInput::Empty => {} } } @@ -1176,30 +1200,6 @@ fn take_back_a_stopped_answer( } } -/// 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, 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); - let gas_limit = input_gas_limit(&frame_init.frame_input); - settle_answer(ctx, frame_init.depth, gas_limit, &mut output); - let input = &frame_init.frame_input; - frame_end_checked(ctx, inspector, input, &mut output, ResultSource::Inspector, upfront); - output -} - /// 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 { @@ -1218,11 +1218,12 @@ struct FrameStart { gas_limit: u64, /// The reservoir the frame inherits. reservoir: u64, - /// The share of its caller's pool the frame starts with: its budget. - share: u64, - /// For a creation, its creator and the creator's nonce before revm decides the start, which - /// says whether revm bumped it. - creator_nonce: Option<(Address, 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, @@ -1230,37 +1231,53 @@ struct FrameStart { impl FrameStart { /// The start of the frame `frame_init` asks for, about to be decided by revm: where the - /// journal stands, and the records it makes as the journal's state stands - /// ([`Accounts::start_records`](crate::limit::Accounts)). A creation's creator record is not - /// among them: its start's hook counted it on the creator. + /// 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, - creator_counted: bool, - #[cfg(debug_assertions)] hooked: Option, - ) -> Self { + ) -> 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, charged, reservoir, share, creator_nonce) = match &frame_init.frame_input { - FrameInput::Call(inputs) => ( - accounts.transfer_records( - inputs.caller, - inputs.target_address, - inputs.value.transfer().unwrap_or_default(), - ), - inputs.charged_start.history, - inputs.reservoir, - inputs.bytes_share, - None, - ), + 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 nonce = account_nonce(ctx, inputs.caller()); - let created = inputs.created_address(nonce); + 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.bytes_share(), - Some((inputs.caller(), nonce)), + inputs.pool_shares(), ) } FrameInput::Empty => unreachable!( @@ -1268,17 +1285,6 @@ impl FrameStart { ), }; let on_frame = records.on_frame(); - // The hook, or a keyless deployment's start, charged the price of the records it predicted, - // which a debug build holds to those predicted here unless an inspector may have rewritten - // the start since. - #[cfg(debug_assertions)] - if hooked.is_some() && ctx.prices_history() { - debug_assert_eq!( - Some(charged), - write_record_history_gas(on_frame.added), - "a start's charge is the price of the records it makes on its 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)) @@ -1286,94 +1292,77 @@ impl FrameStart { 0 }; #[cfg(debug_assertions)] - let made = MadeRecords::before(ctx, frame_init, records, creator_counted, hooked); - #[cfg(not(debug_assertions))] - let _ = creator_counted; - Self { + let made = MadeRecords::before(ctx, frame_init, records); + Ok(Self { mark: mark(ctx.journal_mut()), - counted: records.counted(), + counted: records.counted().with_growth(growth, 0), credit, gas_limit: input_gas_limit(&frame_init.frame_input), reservoir, - share, - creator_nonce, + shares, + creator, #[cfg(debug_assertions)] made, - } - } - - /// Whether revm bumped the creator's nonce for the creation this start is, which it does - /// unless it refuses the creation on its creator's account. - fn bumped( - &self, - ctx: &MegaContext, - ) -> bool { - self.creator_nonce.is_some_and(|(creator, nonce)| account_nonce(ctx, creator) != nonce) + }) } - /// Asserts revm's start made the records the start was charged for and counted, read off - /// the journal once revm built the frame. + /// 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 writes and whether the transaction had changed each before it, for a debug -/// build to hold the records the start was charged for and counted to what revm's start made of -/// them. +/// 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 the start writes, each with whether it was changed before the start: a call's - /// sender and recipient, or a creation's created account and creator. - accounts: [(Address, bool); 2], - /// Whether the start is a creation. - creation: bool, - /// Whether the creator's record was counted on it at the start's hook. - creator_counted: bool, + /// 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, - /// unless an inspector may rewrite the start between the two, the records the start's hook - /// charged for, which must be those predicted here. + /// 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, - creator_counted: bool, - charged: Option, ) -> Self { - 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" - ); - } - let (addresses, creation) = match &frame_init.frame_input { - FrameInput::Call(inputs) => ([inputs.caller, inputs.target_address], false), + 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 = ctx - .journal_ref() - .state - .get(&inputs.caller()) - .map_or(0, |account| account.info.nonce); - ([inputs.created_address(nonce), inputs.caller()], true) + let nonce = account_nonce(ctx, inputs.caller()); + MadeOn::Creation(read(inputs.created_address(nonce))) } - FrameInput::Empty => ([Address::ZERO; 2], false), + FrameInput::Empty => MadeOn::Call([read(Address::ZERO); 2]), }; - let accounts = ctx.accounts(); - let accounts = addresses.map(|address| (address, accounts.is_changed(address))); - Self { records, accounts, creation, creator_counted } + 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, - /// and its creator, when the hook counted the creator's record, changed by the bump. + /// returned as its transfer's records say, a creation's created account as its record says. fn assert_after( &self, ctx: &MegaContext, @@ -1383,20 +1372,23 @@ impl MadeRecords { let made = |(address, before): (Address, bool)| { RecordDelta::of_account(before, accounts.is_changed(address)) }; - let [first, second] = self.accounts; - if !self.creation { - 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"); - return; - } - let created = RecordDelta::of_account(false, self.records.created); - debug_assert_eq!(made(first), created, "a creation made its created account's record"); - if self.creator_counted { - debug_assert_eq!(made(second), RecordDelta::of_account(false, true), "the creator's"); + 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" + ); + } } } } @@ -1409,23 +1401,6 @@ fn account_nonce( ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) } -/// Gives back the record of its own nonce a creation's start hook counted on its creator, for a -/// creation that never bumped the nonce — revm refused it on its creator's account, after an -/// inspector rewrote it — through `answer`, the creation's failure: what the creator paid for the -/// record, in history and in bytes, joins the start charge its failure gives back. -pub(crate) fn give_back_creator_record( - ctx: &mut MegaContext, - answer: &mut FrameResult, - record: CreatorRecord, -) { - ctx.additional_limit.give_back_creator_record(record); - if let FrameResult::Create(outcome) = answer { - let charge = outcome.charged_start; - outcome.charged_start = - StartCharge::new(charge.history + record.history, charge.bytes + record.drawn); - } -} - /// 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 @@ -1443,7 +1418,7 @@ fn stop_the_answer_at( } /// 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 pool the call inherited, and no +/// 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)] @@ -1452,7 +1427,7 @@ fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) 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.set_bytes_remaining(start.share); + 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); @@ -1460,6 +1435,112 @@ fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) 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, + frame_init: &FrameInit, +) -> 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)) +} + +/// 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. +/// +/// 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, +) -> 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; + } + 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 /// with `CallTooDeep`, its gas untouched and its reservoir carried — the answer revm gives it. /// @@ -1471,8 +1552,8 @@ fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) /// 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( @@ -1483,41 +1564,23 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } -/// 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 @@ -1533,31 +1596,53 @@ fn charge_created_caller( gas.record_state_cost(state_gas) } -/// 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. +/// 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. +/// +/// 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 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(); + 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); } - authorities.len() as u64 + 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 @@ -1635,40 +1720,11 @@ mod tests { is_static: false, charged_new_account_state_gas: true, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: PoolAmounts::UNLIMITED, history_allowance: 0, })) } - /// A debug build holds the records a start's hook charged its caller for to those predicted - /// once revm is about to decide the start: a start whose records changed in between trips, - /// since its charge and the refund its failure gets back would both be wrong. `CALLER` holds - /// nothing, so the value call makes no record; its hook was charged for a transfer log. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_start_whose_records_changed_after_its_charge_trips() { - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let init = FrameInit { depth: 1, memory: SharedMemory::new(), frame_input: value_call() }; - let charged = StartRecords { transfer_log: true, ..StartRecords::NONE }; - let _ = FrameStart::of(&mut ctx, &init, false, Some(charged)); - } - - /// A debug build holds the history a start declares to the price of the records predicted for - /// it: a start whose hook charged another price trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "a start's charge is the price of the records it makes on its frame")] - fn test_a_start_charged_another_price_trips() { - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let mut frame_input = value_call(); - if let FrameInput::Call(inputs) = &mut frame_input { - inputs.charged_start = StartCharge::new(1, 0); - } - let init = FrameInit { depth: 1, memory: SharedMemory::new(), frame_input }; - let _ = FrameStart::of(&mut ctx, &init, false, Some(StartRecords::NONE)); - } - /// 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 { @@ -1702,7 +1758,7 @@ mod tests { is_static: true, charged_new_account_state_gas: false, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: PoolAmounts::UNLIMITED, history_allowance: 0, })), } 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 797b36116..e2dc505d1 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -1,31 +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, and the -//! frame's byte pool absorbed into the caller's; +//! 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 and the share of the byte pool the frame inherited ([`untouched_call_gas`], -//! [`with_pools_of`]), never `Gas::new(limit)`, which would carry no reservoir and an unlimited -//! pool, billing the sender for the whole reservoir and lifting the caller's budget; 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; [`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, @@ -33,47 +30,27 @@ use revm::{ }; /// The gas of a call result built without running the callee: the call's whole gas limit -/// unspent, the reservoir the call inherited, and the share of its caller's byte pool it was -/// given, undrawn. +/// 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 { let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); - gas.set_bytes_remaining(inputs.bytes_share); + 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, the reservoir the creation inherited, and the share of its creator's byte pool it was +/// unspent, the reservoir the creation inherited, and the shares of its creator's pools it was /// given, undrawn. #[inline] 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.set_bytes_remaining(inputs.bytes_share()); - gas -} - -/// `gas_limit` of fresh regular gas carrying `source`'s pools: its EIP-8037 reservoir, the state -/// and history gas it charged, the part of those charges that spilled onto regular gas, and its -/// byte pool with what it drew from it. -/// -/// 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 and its byte -/// draws on success and rolls them back on failure, so a rebuilt `Gas` that dropped them would -/// hand the caller an empty reservoir, an unlimited pool 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.set_bytes_remaining(source.bytes_remaining()); - gas.set_bytes_spent(source.bytes_spent()); + 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, the inherited reservoir and byte share carried, and the +/// `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( @@ -113,50 +90,11 @@ pub fn synthetic_call_result( }) } -/// 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, and the start charge the result carries -/// given back when it failed. -/// -/// `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); - } - if let Some(charge) = result.refundable_start_charge() { - caller_gas.refill_history(charge.history); - caller_gas.refill_bytes(charge.bytes); - } - 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"); @@ -175,7 +113,7 @@ mod tests { reservoir, charged_new_account_state_gas: charged, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: PoolAmounts::UNLIMITED, history_allowance: 0, } } @@ -191,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] @@ -226,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 0e8307931..dc40bdfa2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -52,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. @@ -65,8 +78,8 @@ use revm::{ context::ContextTr, context_interface::{ cfg::{ - gas::{GasTracker, StartCharge}, - GasId, GasParams, StateGasSite, + gas::{GasTracker, PoolAmounts, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, }, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, @@ -77,8 +90,10 @@ use revm::{ }; use crate::{ - charge_write_records_history, history_gas, limit::HistoryBytes, - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, + charge_write_records_history, history_gas, + limit::{DestroyedParts, HistoryBytes}, + system::ORACLE_CONTRACT_ADDRESS, + ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -220,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. + /// lands on ([`priced_state_gas`](MegaContext::priced_state_gas)). /// - /// `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`. + /// 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`]). /// - /// 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. + /// [`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. @@ -306,7 +302,7 @@ impl revm::context_interface::Host /// 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 ([`storage_call_stipend`](crate::storage_call_stipend)): a write record is the + /// 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 @@ -315,6 +311,15 @@ impl revm::context_interface::Host /// 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. @@ -325,16 +330,29 @@ impl revm::context_interface::Host CompletedWrite::Log { .. } => (true, false), CompletedWrite::SelfDestruct { .. } => (false, false), }; - let (counted, history) = self.accounts().write_counted(&write); + 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 }; @@ -352,11 +370,13 @@ impl revm::context_interface::Host /// 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)), and counts the - /// creator's record on the running frame's pool, before the frame's share of it is forwarded. - /// 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. + /// 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 @@ -380,33 +400,106 @@ impl revm::context_interface::Host /// 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 records = - self.accounts().start_records(start.kind, start.caller, start.target, start.value); - let on_frame = records.on_frame().added; - let (charge, creator) = if self.prices_history() { + 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(charged) = charge_write_records_history(gas, on_frame, creator) else { + 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; }; - charged + charge } else { - (0, 0) + 0 }; - start.charge = StartCharge::new(charge, 0); - if records.creator { - self.additional_limit.count_creator_record(gas, creator); - } - #[cfg(debug_assertions)] - { - self.charged_records = Some(records); - } + 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] @@ -514,14 +607,15 @@ mod tests { assert!(destructed.data.had_value); assert_eq!(ctx.limit_usage(), LimitUsage::ZERO, "the Host counts nothing"); - // The hook is what counts: the slot's first change is one write record. + // 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.limit_usage(), - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 } + 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 68ea1c5af..000000000 --- a/crates/mega-evm/src/evm/inspector.rs +++ /dev/null @@ -1,505 +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. -//! -//! # Block execution -//! -//! Block execution admits any inspector: which inspectors may run on block production is a node's -//! decision, not the engine's. What the transaction keeps is counted where its own execution -//! writes and taken back with a frame that keeps nothing, so a rewrite that reverts a frame takes -//! back what the frame counted; an inspector that overwrites a frame's gas overwrites its byte -//! pool with it, as it overwrites detention's split (below). -//! -//! # 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, and an opcode's failed charge records what the frame had, which detention reads as -//! what its halt burned; the refusal of an inspector's charge is neither, 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. The frame's byte pool is in its `Gas` too, and goes back to the -//! snapshot's with it: what the frame wrote in between is counted on the transaction, which is -//! held to its limit, and not drawn from the frame's budget. Only the two records of a refused -//! charge are 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, - context_interface::{ - cfg::{gas::StartCharge, StateGasCharge}, - journaled_state::JournalCheckpoint, - Host, - }, - handler::FrameResult, - inspector::handler::frame_end, - interpreter::{ - gas::WithheldCrossing, FrameInput, Gas, InstructionResult, Interpreter, InterpreterTypes, - }, - primitives::{Address, Bytes, Log, U256}, - Database, Inspector, -}; - -use crate::{evm::execution::revert_to, synthetic_frame_result, ExternalEnvTypes, MegaContext}; - -/// 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 leaves two records: the -/// regular gas the frame had before it, which gas detention reads as what a halting frame burned, -/// and, when the part detention withholds would have paid it, 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 records are the frame's end. An inspector's does not: the interpreter -/// never sees it fail and the frame runs on, and a halt that no failed charge records — a cold -/// access the frame cannot pay — keeps a record already there. So both records a callback leaves -/// are put back to what they were before the callback, and the frame ends on the charges it made -/// itself; a record an opcode's own failure left before the callback stays. -/// -/// It stands in for the inspector in revm's instruction loop (`inspect_instructions`), which makes -/// four of the callbacks forwarded here and no other, and for the one callback a frame's start -/// hands the interpreter to before the loop, `initialize_interp`; the rest of 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 initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let records = gas_records(&interp.gas); - self.0.initialize_interp(interp, context); - restore_gas_records(&mut interp.gas, records); - } - - #[inline] - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let records = gas_records(&interp.gas); - self.0.step(interp, context); - restore_gas_records(&mut interp.gas, records); - } - - #[inline] - fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let records = gas_records(&interp.gas); - self.0.step_end(interp, context); - restore_gas_records(&mut interp.gas, records); - } - - #[inline] - fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let records = gas_records(&interp.gas); - self.0.log_full(interp, context, log); - restore_gas_records(&mut interp.gas, records); - } - - #[inline] - fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { - self.0.selfdestruct(contract, target, value); - } -} - -/// A frame's two records of a refused regular charge: the crossing of its withheld gas and the -/// regular gas it had before the charge. -type GasRecords = (Option, Option); - -/// The records of a refused charge `gas` holds before a callback runs. -#[inline] -const fn gas_records(gas: &Gas) -> GasRecords { - (gas.withheld_crossing(), gas.failed_charge_remaining()) -} - -/// Puts the records [`gas_records`] read back on `gas`, over whatever the callback left. -#[inline] -const fn restore_gas_records(gas: &mut Gas, (crossing, failed): GasRecords) { - gas.set_withheld_crossing(crossing); - gas.set_failed_charge_remaining(failed); -} - -/// 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 mark: the frame's own - /// checkpoint, 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, - 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(mark) => { - if before.is_ok() && !frame_result.instruction_result().is_ok() { - revert_to(context.journal_mut(), mark); - } - false - } - }; - if answered || !before.is_ok() { - settle_kept_nothing(context, frame_input, frame_result, answered); - } -} - -/// Settles the result of a frame 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 and no byte pool, or one carrying -/// charges — its state and history charges and its byte draws are rolled back, its refund is -/// dropped, and its reservoir and pool are the ones the frame inherited, so its caller merges back -/// the reservoir and the share of its pool 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 and its byte draws 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; -/// - so does the start charge its caller paid for the start's records, which revm's settlement -/// gives back to a failure alone. -/// -/// What the frame counted goes back with its start, which the frame's return closes as one that -/// kept nothing ([`AdditionalLimit::kept_nothing`](crate::AdditionalLimit)); a start the inspector -/// answered was never counted. A creation the inspector answered never bumped its creator's nonce, -/// so the record its start's hook counted on the creator comes back too, with what the creator paid -/// for it. -fn settle_kept_nothing( - context: &mut MegaContext, - input: &FrameInput, - result: &mut FrameResult, - answered: bool, -) { - carry_upfront_flags(input, result); - let success = result.instruction_result().is_ok(); - // An answer the inspector built carries whatever it was built with; a result the engine made - // carries the charge the engine put on it. - let mut charge = if answered { start_charge(input) } else { carried_start_charge(result) }; - if answered { - if let Some(record) = context.additional_limit.take_creator_record() { - context.additional_limit.give_back_creator_record(record); - charge = StartCharge::new(charge.history + record.history, charge.bytes + record.drawn); - } - } else { - context.additional_limit.kept_nothing(); - } - let gas = result.gas_mut(); - if answered || success { - gas.rollback_state_gas(); - gas.set_refunded(0); - } - if answered { - gas.set_reservoir(inherited_reservoir(input)); - gas.set_bytes_remaining(inherited_share(input)); - } - if !success { - set_start_charge(result, charge); - return; - } - gas.refill_history(charge.history); - gas.refill_bytes(charge.bytes); - set_start_charge(result, StartCharge::default()); - // 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)); - result.gas_mut().refill_reservoir(upfront.unwrap_or_default()); -} - -/// What the caller of the frame `input` starts paid for its start, and the frame's failure gives -/// back: the start charge its input carries. -fn start_charge(input: &FrameInput) -> StartCharge { - match input { - FrameInput::Call(inputs) => inputs.charged_start, - FrameInput::Create(inputs) => inputs.charged_start(), - FrameInput::Empty => StartCharge::default(), - } -} - -/// The start charge `result` carries. -const fn carried_start_charge(result: &FrameResult) -> StartCharge { - match result { - FrameResult::Call(outcome) => outcome.charged_start, - FrameResult::Create(outcome) => outcome.charged_start, - } -} - -/// Sets the start charge `result` carries, which revm's settlement gives back when it fails. -fn set_start_charge(result: &mut FrameResult, charge: StartCharge) { - match result { - FrameResult::Call(outcome) => outcome.charged_start = charge, - FrameResult::Create(outcome) => outcome.charged_start = charge, - } -} - -/// 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 share of its caller's byte pool the frame `input` starts with. -const fn inherited_share(input: &FrameInput) -> u64 { - match input { - FrameInput::Call(inputs) => inputs.bytes_share, - FrameInput::Create(inputs) => inputs.bytes_share(), - FrameInput::Empty => u64::MAX, - } -} - -/// 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() -} - -#[cfg(test)] -mod tests { - use super::*; - use revm::interpreter::interpreter::EthInterpreter; - - /// Charges `amount` of regular gas from every callback that holds the interpreter, and - /// ignores whether the frame could pay it. - struct Charges(u64); - - impl Inspector<(), EthInterpreter> for Charges { - fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut ()) { - let _ = interp.gas.record_regular_cost(self.0); - } - - fn step(&mut self, interp: &mut Interpreter, _: &mut ()) { - let _ = interp.gas.record_regular_cost(self.0); - } - - fn step_end(&mut self, interp: &mut Interpreter, _: &mut ()) { - let _ = interp.gas.record_regular_cost(self.0); - } - - fn log_full(&mut self, interp: &mut Interpreter, _: &mut (), _: Log) { - let _ = interp.gas.record_regular_cost(self.0); - } - } - - /// Runs `callback` of [`StepGuard`] around `inspector` on `interp`. - fn guarded(callback: &str, inspector: &mut Charges, interp: &mut Interpreter) { - let mut guard = StepGuard(inspector); - match callback { - "initialize_interp" => guard.initialize_interp(interp, &mut ()), - "step" => guard.step(interp, &mut ()), - "step_end" => guard.step_end(interp, &mut ()), - "log_full" => guard.log_full(interp, &mut (), Log::default()), - _ => unreachable!(), - } - } - - /// A charge a callback cannot pay is refused and leaves no failed-charge record behind: the - /// frame did not fail, and a record left there would be read as what the frame had when a - /// later halt that records nothing of its own ended it. A record an opcode's own failed charge - /// left before the callback stays as it was, whatever the callback's charge did. - #[test] - fn test_a_callback_leaves_the_failed_charge_record_as_it_was() { - for callback in ["initialize_interp", "step", "step_end", "log_full"] { - let mut interp = Interpreter { gas: Gas::new(1_000), ..Default::default() }; - guarded(callback, &mut Charges(1_001), &mut interp); - assert_eq!(interp.gas.remaining(), 1_000, "{callback}: the charge took nothing"); - assert_eq!(interp.gas.failed_charge_remaining(), None, "{callback}: no record"); - - // An opcode's charge failed with 1,000 left, and its halt zeroed the frame's gas: a - // callback after it fails its own charge on nothing left. - assert!(!interp.gas.record_regular_cost(1_500)); - interp.gas.spend_all(); - guarded(callback, &mut Charges(1), &mut interp); - assert_eq!( - interp.gas.failed_charge_remaining(), - Some(1_000), - "{callback}: the opcode's record" - ); - } - } -} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index b43f79e7d..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; @@ -114,7 +146,7 @@ impl 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). The engine + /// 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 { @@ -359,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, @@ -389,27 +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. What the call - /// left of its reservoir is + /// 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`]: crate::SYSTEM_CALL_REGULAR_GAS_LIMIT - pub fn transact_system_call_with_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))) } @@ -703,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!( - evm.ctx().additional_limit().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!(evm.ctx().additional_limit().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(); diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 1e4cc758b..954fdde2c 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -285,7 +285,7 @@ mod tests { is_static: false, charged_new_account_state_gas: false, charged_start: Default::default(), - bytes_share: u64::MAX, + 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 3758e2f83..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. diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 0d84db3ca..f4c1da8b2 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,7 +2,7 @@ //! //! 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 three 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 @@ -11,12 +11,19 @@ //! 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 [`STORAGE_CALL_STIPEND_BYTES`]; -//! 3. the share of its caller's data-size budget a frame starts with -//! ([`FRAME_BYTES_FORWARD_PERCENT`]): upstream forwards the whole byte pool, and Satin forwards -//! 98 per cent of what the caller has left. +//! 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 @@ -44,10 +51,13 @@ use revm::{ use crate::{ evm::{ - history::STORAGE_CALL_STIPEND_BYTES, + history::HISTORY_ALLOWANCE_BYTES, prices::{active_satin_prices, SatinPrices}, }, - limit::{FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR}, + 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 @@ -75,20 +85,26 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ /// history charge is made by the engine, which prices its own byte counts (the `history` module). /// 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 ([`storage_call_stipend`](crate::storage_call_stipend)). +/// 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, STORAGE_CALL_STIPEND_BYTES), + (GasId::call_history_allowance, HISTORY_ALLOWANCE_BYTES), ]; -/// The share of its caller's byte pool, in per cent, a frame starts with: its data-size budget, -/// [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what the caller has left. -/// revm's forward of the pool rounds the share down, as the budget's rule does. -pub(crate) const FRAME_BYTES_FORWARD_PERCENT: u64 = - FRAME_DATA_SHARE_NUMERATOR * 100 / FRAME_DATA_SHARE_DENOMINATOR; +/// 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. /// /// See the module documentation for what it changes; [`satin_gas_params_at`] is the same schedule @@ -136,7 +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::bytes_forward_percent(), FRAME_BYTES_FORWARD_PERCENT)]); + 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 } @@ -170,7 +192,11 @@ mod tests { let id = GasId::new(slot); let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) || - id == GasId::bytes_forward_percent(); + 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; } @@ -262,27 +288,72 @@ mod tests { } } - /// A frame starts with 98 per cent of what its caller has left of its data-size budget, which - /// revm forwards at every frame start as the schedule's share of the byte pool, rounded down as - /// the budget's rule is; upstream forwards the whole pool. + /// 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_frame_is_forwarded_98_percent_of_its_callers_pool() { + fn test_a_call_forwards_at_most_98_percent_of_its_callers_regular_gas() { let satin = satin_gas_params(); - assert_eq!(satin.get(GasId::bytes_forward_percent()), 98); - assert_eq!(amsterdam().get(GasId::bytes_forward_percent()), 100); - 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.bytes_forward_share(pool), floor, "{pool}"); + 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 - /// [`STORAGE_CALL_STIPEND_BYTES`] at the cost per history byte, the same figure the engine + /// [`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_storage_call_stipend() { + fn test_a_value_call_is_given_the_history_allowance() { let id = GasId::call_history_allowance(); - assert_eq!(satin_gas_params().get(id), crate::storage_call_stipend()); + 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); diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 3fb541f9d..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,17 +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, DynPrecompilesBuilder, EthSpecId, IntrinsicGas, - MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, MegaSpecId, - MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, - SatinPriceError, SatinPrices, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, - LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, - SYSTEM_CALL_REGULAR_GAS_LIMIT, + 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::{ @@ -79,7 +77,9 @@ 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, MegaInstructions, PricedPrecompiles}; +pub(crate) use evm::{ + charge_write_records_history, hold_creator, MegaInstructions, PricedPrecompiles, +}; /* Re-export of upstream crates, so consumers build against the exact versions used here */ pub use alloy_consensus; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 1217b03c7..4e772df15 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -2,7 +2,9 @@ use alloy_primitives::Bytes; use revm::{ - context_interface::cfg::gas::GasTracker, handler::FrameResult, interpreter::InstructionResult, + context_interface::cfg::gas::{GasTracker, PoolAmounts, PoolId}, + handler::FrameResult, + interpreter::InstructionResult, }; #[cfg(not(feature = "std"))] @@ -10,44 +12,53 @@ use alloc as std; use std::vec::Vec; use super::{ - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, COUNTED, DATA_SIZE_POOL, + KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; /// What the common execution layer tracks for the running transaction: what it keeps of the -/// data-size limit and the frame budgets, the stops its frames return, whether it is exempt from -/// every limit, and the figures the settled transaction reports. +/// 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 data size +/// # The three counted dimensions /// -/// 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: the transaction's own frame gets what the transaction has -/// left once its body and the records made before it are counted -/// ([`first_frame_pool`](Self::first_frame_pool)), every child the schedule's share of what its -/// caller has left (98/100, `GasId::bytes_forward_percent`) under the frame cap, a failing frame's -/// draws go back to its pool and a successful one hands what it kept to its caller. A byte 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 -/// pool before the creation's share is forwarded -/// ([`count_creator_record`](Self::count_creator_record)). +/// 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. /// -/// The transaction's limit is held beside the pools, on what the transaction keeps +/// 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)). A pool is one -/// figure, the bytes; the write-record count and the transfer logs the transaction reports apart -/// from the bytes are kept beside them, and restored with them. +/// 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 @@ -71,11 +82,6 @@ pub struct AdditionalLimit { exempt: bool, /// Whether a value movement journals an EIP-7708 transfer log. transfer_logs: bool, - /// The stop the frame about to run must return instead of running: the one a frame revm built - /// returns on its first run when its start crossed a limit ([`hold_start`](Self::hold_start)), - /// or the one a frame a child returned into returns when what the child left it put it over a - /// limit ([`hold_caller`](Self::hold_caller)). - pending_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. @@ -89,16 +95,19 @@ pub struct AdditionalLimit { 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 record of its own nonce the last creation's start hook charged its creator for, until - /// a frame start takes it. - pending_creator: Option, - /// Whether the result returning next kept nothing, whatever it says: an inspector revived a - /// frame that failed. - kept_nothing: bool, /// The history gas of the transaction's body, part of /// [`history_gas_spent`](Self::history_gas_spent). intrinsic_history_gas: u64, @@ -116,30 +125,36 @@ pub struct AdditionalLimit { reservoir_remaining: u64, } -/// What a transaction's frames keep: the data-size bytes they drew from their pools, and, among -/// them, the write records and the EIP-7708 transfer logs. +/// 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 { - /// Data-size bytes. - bytes: u64, - /// Write records. - records: u64, + /// 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, } -/// What one write, or one frame start, adds to what a frame keeps and takes back from it. +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, + } + } +} + +/// 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 { - /// Data-size bytes added: records, a log's bytes, deployed code, a transfer log. - pub(crate) added: u64, - /// Data-size bytes taken back: the records of accounts and slots returned to what the - /// transaction loaded. - pub(crate) taken: u64, - /// Write records added. - pub(crate) records_added: u64, - /// Write records taken back. - pub(crate) records_taken: u64, + /// 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, } @@ -147,29 +162,75 @@ pub(crate) struct Counted { impl Counted { /// Nothing counted. pub(crate) const NONE: Self = - Self { added: 0, taken: 0, records_added: 0, records_taken: 0, transfer_log: false }; + Self { added: PoolAmounts::ZERO, taken: PoolAmounts::ZERO, transfer_log: false }; /// `added` write records made and `taken` taken back, with an EIP-7708 transfer log when - /// `transfer_log`. + /// `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: WRITE_RECORD_SIZE.saturating_mul(added).saturating_add(log), - taken: WRITE_RECORD_SIZE.saturating_mul(taken), - records_added: added, - records_taken: taken, + 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, } } + /// 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, + } + } + /// `bytes` bytes that are no write record: a log's, or deployed code. pub(crate) const fn bytes(bytes: u64) -> Self { - Self { added: bytes, ..Self::NONE } + Self { added: PoolAmounts::ZERO.with(DATA_SIZE_POOL, bytes), ..Self::NONE } + } + + /// 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 } + } + + /// 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 data-size bytes it adds. + pub(crate) const fn bytes_added(&self) -> u64 { + self.added.get(DATA_SIZE_POOL) + } + + /// The data-size bytes it takes back. + pub(crate) const fn bytes_taken(&self) -> u64 { + self.taken.get(DATA_SIZE_POOL) } /// Whether it adds nothing and takes nothing back. const fn is_none(&self) -> bool { - self.added == 0 && self.taken == 0 + self.added.is_zero() && self.taken.is_zero() + } + + /// 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 } } @@ -184,20 +245,9 @@ struct Decided { /// the price of the records the start took back, less what the caller paid for records the /// start did not make. credit: u64, - /// The bytes of a creator's nonce record the frame's own pool could not pay when the frame - /// created, which it owes until the creation returns into it. - overdraft: u64, -} - -/// The record of its own nonce a creation's start hook charged its creator for. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct CreatorRecord { - /// The history gas it cost. - pub(crate) history: u64, - /// The bytes it drew from the creator's pool. - pub(crate) drawn: u64, - /// The bytes the creator's pool could not pay, which the creator owes. - pub(crate) overdraft: 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, } impl AdditionalLimit { @@ -225,16 +275,16 @@ impl AdditionalLimit { pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { self.exempt = exempt; self.transfer_logs = transfer_logs; - self.pending_stop = None; 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.pending_creator = None; - self.kept_nothing = false; self.intrinsic_history_gas = 0; self.intrinsic_history_bytes = 0; self.first_frame_charge = 0; @@ -245,16 +295,43 @@ impl AdditionalLimit { /* What the transaction keeps */ - /// What the transaction keeps so far: its data-size bytes and write records, every running - /// frame counted as if it succeeds. + /// 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: self - .body - .saturating_add(self.hints) - .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) - .saturating_add(self.kept.bytes), - write_records: self.authorities.saturating_add(self.kept.records), + data_size: positive(self.net(LimitKind::DataSize)), + write_records: positive(self.net(LimitKind::KvUpdate)), + state_growth: positive(self.net(LimitKind::StateGrowth)), + } + } + + /// 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, + }; + outside + frames + } + + /// 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, } } @@ -283,49 +360,120 @@ impl AdditionalLimit { } /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts - /// other than the transaction's sender, made before the first frame. An out-of-gas before the - /// first frame takes them back ([`take_back_authorities`](Self::take_back_authorities)). + /// 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 count_authorities(&mut self, authorities: u64) { + /// 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.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" + ); } - /// Takes back the authorities' records, which an out-of-gas before the first frame takes back - /// with the authorizations. + /// 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; + } + + /// 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; + } + + /// 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 check; + } + self.transaction_crossed(LimitKind::StateGrowth, &counted, false) } - /// The pool of the transaction's own frame: what the transaction has left of its data-size - /// limit once its body and the records made before the frame are counted, under the frame + /// 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); + } + + /// 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 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_pool(&self) -> u64 { - let left = self.limits.tx_data_size_limit.saturating_sub(self.usage().data_size); - let cap = self.frame_cap(); + pub(crate) const fn first_frame_pools(&self) -> PoolAmounts { if self.exempt { - u64::MAX - } else if left < cap { - left - } else { - cap + 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; } + pools } - /// The most a frame's pool may start with: the frame cap, and nothing for an exempt - /// transaction. - pub(crate) const fn frame_cap(&self) -> u64 { + /// 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 { - u64::MAX - } else { - self.limits.frame_data_size_limit + return PoolAmounts::UNLIMITED; } + PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, self.limits.frame_data_size_limit) } /* Verdicts */ @@ -349,88 +497,144 @@ impl AdditionalLimit { LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// The verdict on the transaction keeping `counted` more: its data-size limit crossed, or - /// within. - const fn check_transaction(&self, counted: &Counted) -> LimitCheck { - let used = - self.usage().data_size.saturating_sub(counted.taken).saturating_add(counted.added); - if used > self.limits.tx_data_size_limit { - return self.crossed(LimitKind::DataSize, self.limits.tx_data_size_limit, used, false); + /// 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) + } + + /// 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 } - /// The verdict on a frame budget crossed by `added` bytes the pool `gas` holds could not pay: - /// 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 `added` in. - fn budget_crossed(&self, gas: &GasTracker, added: u64) -> LimitCheck { - let budget = gas.bytes_remaining().saturating_add_signed(gas.bytes_spent()); - let used = gas.bytes_spent().saturating_add_unsigned(added).max(0).unsigned_abs(); - self.crossed(LimitKind::DataSize, budget, used, true) + /// 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; + } + } + LimitCheck::WithinLimit + } + + /// 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))) } - /// Counts what the frame whose pool `gas` holds keeps of `counted`, held to the transaction's - /// limit, then to the frame's budget: the bytes `counted` takes back go back to the pool - /// first, and the bytes it adds are drawn; a draw the pool cannot pay is the frame's budget - /// crossed. A crossing counts nothing and draws nothing, and is the stop the frame reverts - /// with. A count that adds nothing holds nothing. + /// 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; } - if counted.added != 0 { - let check = self.check_transaction(counted); - if check.exceeded_limit() { - return check; - } - } - gas.refill_bytes(counted.taken); - if !gas.record_bytes(counted.added) { - gas.clear_bytes_crossing(); - let check = self.budget_crossed(gas, counted.added); - let drew = gas.record_bytes(counted.taken); - debug_assert!(drew, "what was given back can be drawn again"); + 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 } + /// 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!( + drew || gas.pool_remaining(pool) == u64::MAX, + "the checks admit the draw" + ); + if !drew { + gas.clear_pool_crossing(pool); + } + } + } + /// Adds `counted` to what the frames keep. + /// + /// 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.bytes >= counted.taken && kept.records >= counted.records_taken, + 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.bytes = kept.bytes.saturating_sub(counted.taken).saturating_add(counted.added); - kept.records = kept - .records - .saturating_sub(counted.records_taken) - .saturating_add(counted.records_added); 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 the transaction's limit and to `budget`, the - /// pool its frame would start with. Nothing is counted. - pub(crate) const fn hypothetical_start(&self, counted: &Counted, budget: u64) -> LimitCheck { - let check = self.check_transaction(counted); - if check.exceeded_limit() { - return check; - } - let used = counted.added.saturating_sub(counted.taken); - if used > budget { - return self.crossed(LimitKind::DataSize, budget, used, true); - } - LimitCheck::WithinLimit + /// 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 { - let check = self.check_transaction(&Counted::bytes(bytes)); + let check = self.transaction_crossed(LimitKind::DataSize, &Counted::bytes(bytes), false); if check.within_limit() { self.hints = self.hints.saturating_add(bytes); } @@ -439,147 +643,88 @@ impl AdditionalLimit { /* A frame's start */ - /// Counts the record of a creator's own nonce, which a creation's start makes on the creating - /// frame, whose pool `gas` holds, before the frame's share is forwarded: the creation's budget - /// is taken from what the creator has left once the record is counted. It lands on the creator - /// unchecked, and the creator is held to its limits with it once the creation returns - /// ([`hold_caller`](Self::hold_caller)); a pool that cannot pay it is drained, and the creator - /// owes the rest until then. `history` is what the creator paid for it. - pub(crate) fn count_creator_record(&mut self, gas: &mut GasTracker, history: u64) { - self.count(&Counted::records(1, 0, false)); - let drawn = WRITE_RECORD_SIZE.min(gas.bytes_remaining()); - let drew = gas.record_bytes(drawn); - debug_assert!(drew, "the draw is what the pool holds"); - let overdraft = WRITE_RECORD_SIZE - drawn; - if overdraft != 0 { - if let Some(running) = self.decided.last_mut() { - running.overdraft += overdraft; - } - } - self.pending_creator = Some(CreatorRecord { history, drawn, overdraft }); - } - - /// The record of its own nonce the last creation's start hook charged its creator for, which - /// the start's decision takes: revm deciding it keeps it, an inspector answering in its place - /// gives it back ([`give_back_creator_record`](Self::give_back_creator_record)). - pub(crate) const fn take_creator_record(&mut self) -> Option { - self.pending_creator.take() - } - - /// Takes back the record of its own nonce a creation's start counted on its creator, for a - /// creation an inspector answered in revm's place: the start never bumped the nonce. What the - /// creator paid for it goes back through the creation's answer. - pub(crate) fn give_back_creator_record(&mut self, record: CreatorRecord) { - self.count(&Counted::records(0, 1, false)); - if let Some(running) = self.decided.last_mut() { - running.overdraft -= record.overdraft; - } - } - /// 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)). - pub(crate) fn open_start(&mut self, depth: usize) { - self.decided.push(Decided { depth, at_start: self.kept, credit: 0, overdraft: 0 }); + /// ([`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 }); } - /// Holds the start revm just decided, whose frame's pool `gas` holds, to the limits, and counts - /// `counted`, the records and transfer log it made, on that pool ([`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. + /// 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 limit whatever it counts, nothing included: a - /// creation's creator record lands on the creator unchecked - /// ([`count_creator_record`](Self::count_creator_record)), and the creation's start is where - /// the transaction first meets it. + /// 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 check = self.check_transaction(counted); + let (remaining, spent) = Self::pools_of(gas); + let check = self.check(remaining, spent, counted, true); if check.exceeded_limit() { return check; } - let check = self.draw(gas, counted); - if check.within_limit() { - if let Some(start) = self.decided.last_mut() { - start.credit = credit; - } + Self::apply(gas, counted); + self.count(counted); + if let Some(start) = self.decided.last_mut() { + start.credit = credit; } - check - } - - /// Notes that the result returning next kept nothing, whatever it says: an inspector revived - /// a frame that failed. - pub(crate) const fn kept_nothing(&mut self) { - self.kept_nothing = true; + LimitCheck::WithinLimit } /// Closes the start of the frame whose result returns at `depth`, `kept` or not, and answers - /// the history its caller gets back for it: a frame that kept nothing — it failed, or an - /// inspector revived it — has what the frames keep restored to what they kept when its start - /// began, and its caller gets nothing back; one that kept its start, the start's credit. + /// 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: what its caller paid comes back with its start charge. - pub(crate) fn close_start(&mut self, depth: usize, kept: bool) -> u64 { - let kept_nothing = core::mem::take(&mut self.kept_nothing); - let kept = kept && !kept_nothing; + /// 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; + return (0, None); }; self.decided.pop(); if kept { - start.credit + (start.credit, start.creator) } else { self.kept = start.at_start; - 0 + (0, start.creator) } } - /// Holds the frame a child just returned into, whose pool `gas` holds, to its limits with what - /// it now keeps: a creation's nonce record, which outlives the creation, lands on its creator - /// unchecked ([`count_creator_record`](Self::count_creator_record)), and a crossing is the stop - /// the creator returns before it runs on ([`stop_before_run`](Self::stop_before_run)). The - /// transaction's limit is held first. A record the creator's pool could not pay is drawn now if - /// the pool can pay it; a creator still owing it crossed its budget. + /// 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. /// - /// Any other return leaves the caller within its limits — a failure hands it nothing, and a - /// success no more than the share it gave — and clears a stop it had. - pub(crate) fn hold_caller(&mut self, gas: &mut GasTracker) { - let check = self.check_transaction(&Counted::NONE); - self.pending_stop = check.exceeded_limit().then_some(check); - if self.pending_stop.is_some() { - return; - } - let Some(running) = self.decided.last_mut() else { return }; - let overdraft = running.overdraft; - if overdraft == 0 { - return; - } - if gas.record_bytes(overdraft) { - running.overdraft = 0; - return; + /// 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); + } } - gas.clear_bytes_crossing(); - let stop = self.budget_crossed(gas, overdraft); - self.pending_stop = stop.exceeded_limit().then_some(stop); - } - - /// Takes back one write record of the running frame, whose pool `gas` holds, for an account a - /// write outside the hooks returned to what the transaction loaded: a `keylessDeploy` call's - /// signer, whose nonce the settlement sets back. A record the frame still owes is forgiven - /// first. - pub(crate) fn take_back_record(&mut self, gas: &mut GasTracker) { - let forgiven = self.decided.last_mut().map_or(0, |running| { - let forgiven = running.overdraft.min(WRITE_RECORD_SIZE); - running.overdraft -= forgiven; - forgiven - }); - gas.refill_bytes(WRITE_RECORD_SIZE - forgiven); - self.count(&Counted::records(0, 1, false)); + None } /* The stops and the exemption */ @@ -628,34 +773,6 @@ impl AdditionalLimit { self.exempt } - /// The stop the running frame returns instead of running another instruction: the one its own - /// start left it ([`hold_start`](Self::hold_start)), or the one - /// [`hold_caller`](Self::hold_caller) 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.pending_stop.take() - } - - /// Holds the start of the frame revm just built to `verdict`: a crossing is the stop the frame - /// returns on its first run, before any instruction - /// ([`stop_before_run`](Self::stop_before_run)). revm moved the value, journaled the transfer - /// log and, for a creation, bumped its creator's nonce; the stop is a revert of the frame, so - /// its journal checkpoint takes the move and the log back, and the nonce, bumped before the - /// checkpoint, stays, with its record on the creator. - #[inline] - pub(crate) fn hold_start(&mut self, verdict: LimitCheck) { - if verdict.exceeded_limit() { - debug_assert!(self.pending_stop.is_none(), "a frame starts from a caller that ran"); - self.pending_stop = Some(verdict); - } - } - - /// Whether the running frame has a stop to return before it runs another instruction - /// ([`stop_before_run`](Self::stop_before_run)). - pub(crate) const fn has_stop_before_run(&self) -> bool { - self.pending_stop.is_some() - } - /* What the transaction pays before its first frame */ /// The history gas of the transaction's body: the bytes the transaction carries and the write @@ -721,7 +838,7 @@ impl AdditionalLimit { self.history_bytes = if priced { self.intrinsic_history_bytes .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) - .saturating_add(self.kept.bytes) + .saturating_add(positive(self.kept.net(LimitKind::DataSize) as i128)) .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) } else { 0 @@ -729,6 +846,17 @@ impl AdditionalLimit { } } +/// `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 { @@ -740,6 +868,29 @@ fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { 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_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 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] @@ -778,6 +929,6 @@ mod tests { .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut limit = AdditionalLimit::new(limits); limit.begin_transaction(false, false, crate::TX_BODY_SIZE); - limit.count_authorities(2); + limit.count_authorities(2, 0); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index e94b4c24d..d29dcc328 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -28,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 @@ -63,11 +68,21 @@ //! 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, gets back -//! what its caller paid for its records, and no limit stops it. A creation revm fails after it -//! bumped its creator's nonce, onto an occupied address, is held to nothing at its start: its -//! failure discards its records and transfer log, but for the nonce record, which lands on the -//! creator. +//! 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 @@ -88,22 +103,42 @@ //! 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 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. +//! 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 //! @@ -111,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. //! @@ -143,14 +179,32 @@ mod limit; mod record; pub use limit::AdditionalLimit; -pub(crate) use limit::{Counted, CreatorRecord}; +pub(crate) use limit::Counted; +pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes}; #[cfg(debug_assertions)] -pub(crate) use record::RecordDelta; -pub(crate) use record::{Accounts, HistoryBytes, StartRecords}; +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. @@ -222,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 { @@ -233,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. /// @@ -261,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, @@ -281,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. @@ -303,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, @@ -315,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; @@ -337,34 +432,37 @@ impl EvmTxRuntimeLimits { 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), } } } @@ -382,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 { @@ -398,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, } } @@ -406,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. @@ -475,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. @@ -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,11 +711,15 @@ mod tests { #[test] fn test_limit_usage_arithmetic_saturates() { - let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; - let record = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; + 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!(record.times(3), LimitUsage { data_size: 120, write_records: 3 }); + assert_eq!( + 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); } @@ -624,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()), @@ -637,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}"); } } @@ -647,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 4db299970..fd43e9c3a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -9,11 +9,36 @@ //! //! 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. +//! 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. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; use revm::{ - context_interface::host::{CompletedWrite, FrameStartKind}, - primitives::{Address, U256}, + context_interface::{ + host::{CompletedWrite, FrameStartKind}, + journaled_state::entry::{JournalEntry, SelfdestructionRevertStatus}, + }, + primitives::{Address, StorageKey, KECCAK_EMPTY, U256}, state::{Account, AccountInfo, EvmState, TransactionId}, Journal, }; @@ -62,7 +87,8 @@ pub(crate) struct StartRecords { /// 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. + /// 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, @@ -86,11 +112,50 @@ impl StartRecords { } } +/// 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(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, +} + +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 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, @@ -104,11 +169,31 @@ fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { 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) 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<'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, transaction_id: journal.transaction_id, transfer_logs } + Self { + state: &journal.state, + entries: &journal.journal, + transaction_id: journal.transaction_id, + transfer_logs, + } } /// The account at `address` as the transaction loaded it and holds it now: `None` for one @@ -117,6 +202,12 @@ impl<'a> Accounts<'a> { 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. @@ -137,6 +228,100 @@ impl<'a> Accounts<'a> { } } + /// 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 { @@ -189,6 +374,53 @@ impl<'a> Accounts<'a> { } } + /// 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 @@ -232,20 +464,34 @@ impl<'a> Accounts<'a> { )) } - /// What the completed write `write` counts, and the history bytes it appends and takes back: + /// 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; + /// 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. - pub(crate) fn write_counted(&self, write: &CompletedWrite<'_>) -> (Counted, HistoryBytes) { + /// 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, .. } => { - if slot.is_original_eq_present() { + let records = if slot.is_original_eq_present() { if slot.is_original_eq_new() { Counted::NONE } else { @@ -255,7 +501,11 @@ impl<'a> Accounts<'a> { Counted::records(0, 1, false) } else { 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)) } CompletedWrite::Log { topics, data_len, .. } => { Counted::bytes(log_history_bytes(u64::from(topics), data_len)) @@ -264,11 +514,20 @@ impl<'a> Accounts<'a> { let records = self.destruction_records(address, target, balance); let moved = result.had_value && target != address; let logged = self.transfer_logs && moved; - Counted::records(records.added, records.taken, logged) + 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 }; - (counted, HistoryBytes { appended: counted.added - log, taken: counted.taken }) + 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) } } @@ -282,18 +541,27 @@ impl<'a> Accounts<'a> { 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. + /// 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::{test_utils::MemoryDatabase, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::address; + 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}, + context_interface::{ + context::{SStoreResult, SelfDestructResult}, + journaled_state::account::JournaledAccountTr, + }, }; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); @@ -333,23 +601,55 @@ mod tests { } } + /// 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() { - let journal = journal(); - let accounts = Accounts::of(&journal, false); - let counted = |original, present, new| { - let slot = slot(original, present, new); - let write = CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: &slot }; - accounts.write_counted(&write).0 + 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)) }; - assert_eq!(counted(0, 0, 1), Counted::records(1, 0, false)); - assert_eq!(counted(5, 5, 0), Counted::records(1, 0, false)); - assert_eq!(counted(0, 1, 0), Counted::records(0, 1, false)); - assert_eq!(counted(0, 1, 2), Counted::NONE); - assert_eq!(counted(3, 3, 3), Counted::NONE); - assert_eq!(counted(3, 4, 4), Counted::NONE); + 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, all of them history; a @@ -359,12 +659,14 @@ mod tests { let journal = journal(); let accounts = Accounts::of(&journal, false); let counted = |topics, data_len| { - accounts.write_counted(&CompletedWrite::Log { address: OTHER, 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.added, TRANSFER_LOG_SIZE); + assert_eq!(counted(3, 32).0.bytes_added(), TRANSFER_LOG_SIZE); assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, TRANSFER_LOG_SIZE); } @@ -380,7 +682,8 @@ mod tests { let mut fresh = journal(); fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); - let (counted, history) = Accounts::of(&fresh, true).write_counted(&destruction(OTHER, 5)); + 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!( @@ -395,7 +698,7 @@ mod tests { 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) = + 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) }); @@ -417,6 +720,163 @@ mod tests { ); } + /// 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)) + }; + 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"); + } + + /// 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_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, + }; + let write = CompletedWrite::SelfDestruct { + address: fresh, + target: OTHER, + balance: U256::ZERO, + result: &result, + }; + 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)); + } + /// 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] @@ -475,4 +935,43 @@ mod tests { "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 652929f88..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 and its gas, the byte pool among it, as any depth-0 call, 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 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 8eaf6734f..990875528 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -11,7 +11,10 @@ use alloy_sol_types::SolCall; use revm::{ context::{Cfg, ContextError, ContextTr, JournalTr}, context_interface::{ - cfg::{gas::StartCharge, 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::StartRecords, - 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. @@ -66,7 +56,7 @@ pub(crate) struct Started { /// no record, or when the transaction pays no history. pub(super) signer_record_charge: u64, /// 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, } @@ -101,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, @@ -125,38 +116,12 @@ pub(crate) fn ready( 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 /// @@ -205,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 frame 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> { @@ -224,39 +191,30 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - let (on_frame, creator) = deployment.record_charges.unwrap_or((0, 0)); + // 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); - // The creation's start charge, which its failure gives back, and its creator's record, which - // the call keeps: counted on the call's pool before the creation's share of it is - // forwarded, as a `CREATE` opcode's start does. - create.set_charged_start(StartCharge::new(on_frame, 0)); - if deployment.records.creator { - ctx.additional_limit.count_creator_record(gas.tracker_mut(), creator); - } - #[cfg(debug_assertions)] - { - ctx.charged_records = Some(deployment.records); - } - let share = ctx.gas_params().bytes_forward_share(gas.bytes_remaining()); - gas.tracker_mut().forward_bytes(share); - create.set_bytes_share(share); - 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, |(_, creator)| creator), + signer_record_charge: signer_record, empty_deposit_refused: false, - })); + }); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) } @@ -273,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: StartRecords, - /// What the call paid for them: the created account's, and the signer's nonce. `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)>, } @@ -467,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 2d7607808..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,6 +162,7 @@ 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 @@ -164,16 +170,17 @@ pub(crate) fn settle( if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { 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,20 +231,25 @@ 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 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 — @@ -248,12 +260,8 @@ fn take_back_bump( gas: &mut Gas, started: &Started, ) -> Result<(), ContextError> { - let changed = ctx.accounts().is_changed(started.signer); ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); - if changed && !ctx.accounts().is_changed(started.signer) { - // A stop the record would leave the call, by putting it over a limit, goes with it: the - // call is held to its limits without the record once it is settled. - ctx.additional_limit.take_back_record(gas.tracker_mut()); + 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 228f194df..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 diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index fc94e65a9..9826675aa 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -151,7 +151,7 @@ mod tests { is_static: false, charged_new_account_state_gas: false, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, history_allowance: 0, } } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 16c9c3ba9..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. @@ -377,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); - transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), 250_000_000); - assert_eq!( - evm.ctx().additional_limit().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); - transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), SYSTEM_CALL_REGULAR_GAS_LIMIT); - assert_eq!(evm.ctx().additional_limit().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/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 452c09a25..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,14 +20,13 @@ 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, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; use revm::{ - bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, + bytecode::opcode::{CALLDATALOAD, GAS, MLOAD, SSTORE}, database::State, Database, }; @@ -444,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`. @@ -532,8 +554,7 @@ 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, 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 250M budget, and the word it was called -/// with. +/// 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 crate::op_reference::{self, OpContext}; @@ -570,7 +591,7 @@ fn test_a_pre_block_call_commits_the_state_op_revm_produces() { mega_evm::SYSTEM_ADDRESS, HISTORY_STORAGE_ADDRESS, PARENT_HASH.0.into(), - pre_block_call_gas_limit(250_000_000), + PRE_BLOCK_CALL_GAS_LIMIT, ) .expect("op-revm runs the call"); assert!(outcome.result.is_success()); diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index b798280c4..d09d03ecf 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -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 7d500b0bf..f34dd1331 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -268,7 +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/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 71c42ae95..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`. @@ -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 fc9d7d1dd..79cec5908 100644 --- a/crates/mega-evm/tests/fuzz/gen/program.rs +++ b/crates/mega-evm/tests/fuzz/gen/program.rs @@ -392,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), } 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/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index 2130da40d..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 @@ -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 d381bfeb2..8c5ff81ae 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -29,7 +29,9 @@ use crate::{ case::Case, 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::{history_rounds, runs_at_measurement_prices}, @@ -149,6 +151,61 @@ fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_ ); } +/// 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 @@ -210,8 +267,10 @@ fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it 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\n{rendered}" + "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!( diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index f300ac4b2..c8123427a 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -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); @@ -231,12 +266,18 @@ pub(crate) fn history(bytes: u64) -> u64 { } /// 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. +/// 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 { @@ -245,6 +286,7 @@ pub(crate) const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { records * mega_evm::WRITE_RECORD_SIZE + moves * mega_evm::TRANSFER_LOG_SIZE, write_records: records, + state_growth: 0, } } 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 ecb9a87e9..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, B256, U256}; -use alloy_sol_types::SolError; +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. @@ -138,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; @@ -157,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()))), @@ -168,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. @@ -261,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"); } @@ -291,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( @@ -300,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!( @@ -325,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() ); } @@ -336,11 +363,12 @@ 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 but its nonce record, - // counted on it as the creation starts, so the creation gets 98% of what the record leaves. - // Its start records the created account before the code. - let child_budget = share(CAP - WRITE_RECORD_SIZE); + 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); + 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)); @@ -351,7 +379,8 @@ 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().limit_usage(), @@ -369,8 +398,10 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { 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 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])); @@ -379,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!( @@ -415,20 +450,21 @@ fn create_returning_its_output(init: &Bytes, value: u64) -> Bytes { } /// A creation's start counts against the creation's own budget — the share of what its creator -/// has left once the creator's own nonce record is counted on the creator — the created account's -/// record, and with an endowment the transfer log. The creator here is the transaction's own -/// frame, with `R` bytes left under the transaction's limit, of which its nonce record takes 40. +/// 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 remainder's share falls short of the start stops the creation at its -/// start, which keeps its creator's nonce record: 80 without an endowment, a share of 39 against -/// 40 bytes. One byte more, a share of 40, starts it. With 100 left the share of the 60 left is -/// 58, so the creation may deposit the 18 bytes beyond its start, and the 19th stops it at its -/// deposit; with an endowment, 260 left leave room for 15. A stopped creation keeps nothing of -/// its own, and its creator resumes with the nonce record alone. -/// -/// Before the creator's record moved to the creating frame the creation's budget was the share of -/// the whole `R`, against a start of 80 bytes: 81 stopped it and 82 started it, 100 left the same -/// 18 bytes, and 260 with an endowment left 14. +/// 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| { @@ -438,14 +474,19 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { create_returning_its_output(&constructor_returning(deployed), endowment), ) .account_balance(A, U256::from(endowment)); - run_at(db, call(CALLER, A, U256::ZERO, GAS_LIMIT), mega_evm::TX_BODY_SIZE + left) + 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"); @@ -456,33 +497,60 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { ); assert_eq!(outcome.usage, nonce_record_alone, "{case}: A keeps its nonce record"); assert_eq!(outcome.state[&A].info.nonce, 1, "{case}"); - assert!( - outcome.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty()), - "{case}: nothing was created", - ); + assert!(nothing_created(outcome), "{case}: nothing was created"); }; - // The creation's budget: the share of what the creator has left after its nonce record. - let budget = |left: u64| share(left - WRITE_RECORD_SIZE); + // 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 = WRITE_RECORD_SIZE + child_room(at_start); + 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 started = run(starts, endowment, 0); + 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, - usage(WRITE_RECORD_SIZE + at_start, 2), - "{case}: both records and the log" + grown(usage(WRITE_RECORD_SIZE + at_start, 2), 1), + "{case}: both records and the log; the created account is new" ); - let left = 100 + log; + 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); @@ -490,8 +558,9 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { assert_eq!(fits.result.output().unwrap(), &Bytes::new(), "{case}: it deployed"); assert_eq!( fits.usage, - usage(WRITE_RECORD_SIZE + budget(left), 2), - "{case}: the creator's record, and exactly the creation's share" + 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, @@ -503,11 +572,11 @@ fn test_a_creation_is_held_to_its_share_from_its_start() { assert_stopped(&run(left, endowment, room + 1), budget(left), &case); if endowment == 0 { - assert_eq!((starts - 1, budget(starts - 1), starts), (80, 39, 81)); - assert_eq!((budget(left), room), (58, 18)); + 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), (244, 199, 245)); - assert_eq!((budget(left), room), (215, 15)); + assert_eq!((starts - 1, budget(starts - 1), starts, kept), (204, 199, 205, 240)); + assert_eq!((budget(left), room), (2_116, 1_916)); } } } @@ -547,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| { @@ -581,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, @@ -609,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", ); } } @@ -633,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, }) ); } @@ -666,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"); } @@ -692,12 +784,16 @@ 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 @@ -718,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 @@ -857,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. @@ -976,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 @@ -1001,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); @@ -1018,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 @@ -1045,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()) + @@ -1053,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)); @@ -1071,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}"); @@ -1083,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()); @@ -1101,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 ---------- */ @@ -1213,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 @@ -1236,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", @@ -1246,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", @@ -1255,6 +1363,7 @@ 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", @@ -1264,17 +1373,23 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ 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. @@ -1291,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"); @@ -1308,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}", ); } @@ -1485,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| { @@ -1511,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, + ); } } @@ -1560,7 +1694,7 @@ 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: `B`'s nonce @@ -1597,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}"); @@ -1614,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"); @@ -1630,18 +1768,75 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { } } -/// A creation's start is held to the transaction's limit even when it counts nothing: the record of -/// its creator's nonce lands on the creator unchecked, and the creation's start is where the -/// transaction first meets it. +/// 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`. `B`'s creation records nothing of its own — `X` is changed already, and -/// it carries no endowment — but the record of `B`'s nonce puts the transaction one byte over its -/// limit: the creation returns the stop before its first instruction, `B` returns it once the -/// creation returned into it, its nonce and its record going with its revert, and `A` resumes and -/// keeps what it kept. +/// 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_is_stopped_by_its_creators_record() { +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() @@ -1652,8 +1847,12 @@ fn test_a_creation_counting_nothing_is_stopped_by_its_creators_record() { .build(); let kept = mega_evm::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; let limit = kept + WRITE_RECORD_SIZE - 1; - let stop = - Bytes::from(MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.abi_encode()); + // `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()) @@ -1668,23 +1867,135 @@ fn test_a_creation_counting_nothing_is_stopped_by_its_creators_record() { assert_eq!(outcome.limit_exceeded, None, "inspect {inspect}: A caught it"); assert_eq!( outcome.usage, - LimitUsage { data_size: kept, write_records: 2 }, - "inspect {inspect}: A's transfer alone", + 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, - vec![(InstructionResult::Revert, stop.clone())], - "the creation returns the transaction's stop before its first instruction", - ); + 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, stop.clone())), - "B returns it once the creation returned into it: {:?}", + 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 73badf40c..5c1069362 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -23,7 +23,7 @@ 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, }; @@ -41,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. @@ -162,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", @@ -174,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", @@ -184,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", @@ -236,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", @@ -312,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)), @@ -399,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().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 5ac44f2ae..75da0292b 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -30,9 +30,9 @@ use revm::{ use crate::{ detention::{ - assert_caught_with_stipends, assert_stopped, 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, + 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}, }; @@ -248,7 +248,10 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { ); // 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()); @@ -275,7 +278,10 @@ 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"); } } @@ -301,9 +307,9 @@ fn calls_with_value_returning(first: u8, to: Address) -> Bytes { /// /// 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 limit 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. +/// 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; @@ -318,10 +324,12 @@ 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(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), @@ -344,12 +352,170 @@ fn test_a_start_crossing_data_size_and_compute_at_once_is_the_data_size_stop() { "{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 }; + 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 @@ -379,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}"); @@ -411,10 +577,10 @@ fn destruct_after_read() -> u64 { /// 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 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. +/// - 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); @@ -444,7 +610,10 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { 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"); } @@ -473,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"); } } diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 0b882aa6c..7cafb61d9 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -15,7 +15,10 @@ 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::{ @@ -758,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] @@ -1298,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)); @@ -1620,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, @@ -1758,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); @@ -1781,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", ); } } @@ -1860,11 +1949,11 @@ fn test_a_history_refill_after_the_read_does_not_lift_the_cap() { /// 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 a 64th of what it holds, a -/// 64th 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. +/// `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 @@ -1894,7 +1983,7 @@ fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { }; /// 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 - /// 64 times the price less one, which leaves it a 64th of what it holds a gas short. + /// 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, @@ -1923,11 +2012,11 @@ fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { 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 64 times the price less one, forwards - // all but a 64th of it less the price's 64th, and keeps the price less one. + // 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::() + 64 * (price(2) - 1); - let forward = 63 * (price(2) - 1); + 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)), @@ -1971,9 +2060,9 @@ fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { for Start { name, code: middle, charges, price, spilled, given } in rows { let spent: u64 = charges.iter().sum(); - let given = given.unwrap_or(64 * price - 1); + let given = given.unwrap_or(50 * price - 1); if given <= spent + spilled { - note_price_guard("a new account's state gas outweighs 64 times two records' history"); + note_price_guard("a new account's state gas outweighs 50 times two records' history"); continue; } let (run, called_other) = run(middle, given); diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 35cc2d91b..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 @@ -54,7 +55,8 @@ use revm::{ use crate::{ common::{ - account_state_gas, body_history, history, runs_at_measurement_prices, slot_state_gas, + account_state_gas, body_history, history, holding_to_keep, runs_at_measurement_prices, + slot_state_gas, }, op_reference::{self, Op, OpContext, Settled}, }; @@ -780,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 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 96% rename from crates/mega-evm/tests/satin/storage_call_stipend.rs rename to crates/mega-evm/tests/satin/history_allowance.rs index 76e18dcef..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, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + 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)); @@ -439,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", ); } @@ -454,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)); @@ -476,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)) @@ -531,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) @@ -606,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", ); } @@ -637,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() { @@ -738,7 +739,7 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { assert_eq!(outcome.usage.write_records, 0); assert_eq!( outcome.usage.data_size, - TX_BODY_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + TX_BODY_SIZE + GRANTS * HISTORY_ALLOWANCE_BYTES, "the body and every event's bytes are counted", ); assert_eq!( @@ -748,14 +749,14 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { ); assert_eq!( outcome.gas.history_bytes, - TX_BODY_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", ); } @@ -775,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), @@ -798,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", ); } @@ -828,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 3a9800d6a..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()), @@ -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, @@ -937,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 ce5085543..90da9fe90 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -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 428f672ff..37bc7f614 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -12,15 +12,15 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, - STATICCALL, STOP, + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, + REVERT, STATICCALL, STOP, }, context_interface::cfg::GasId, }; use crate::common::{ body_history, call, call_with_data, create, deploying, execute, history, history_is_free, - history_rounds, runs_at_measurement_prices, + history_rounds, reservoir_share, runs_at_measurement_prices, }; const CALLER: Address = address!("0000000000000000000000000000000000200000"); @@ -160,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]) @@ -191,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() { @@ -200,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"); @@ -219,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"); @@ -236,9 +236,9 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { /// 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 a 64th of what is left, keeping that -/// 64th to pay the start's records with. Given 64 times one record's price on top of its charges, -/// it starts the creation; one gas less, it does not. +/// 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 @@ -269,12 +269,12 @@ fn test_a_creation_onto_an_account_the_transaction_changed_charges_its_creator_o outcome }; - let short = run(charges + 64 * price - 1); + 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 + 64 * 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); @@ -341,10 +341,12 @@ fn test_every_call_kind_charges_its_records_after_its_forward() { 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 is spent, and a forward that leaves - // it one gas less than that, the most the 63/64 rule lets it forward. - let spill = price - reservoir.unwrap_or(0); - let forward = 63 * (spill - 1); + // 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); @@ -359,8 +361,14 @@ fn test_every_call_kind_charges_its_records_after_its_forward() { 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 reservoir paid first"); + 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 @@ -495,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 2680c1659..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 @@ -188,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"); @@ -199,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() { @@ -222,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"); @@ -341,5 +341,8 @@ fn test_an_out_of_gas_before_the_first_frame_keeps_the_body_the_reservoir_paid() 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 }); + 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 f093fee5f..ebb89e325 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -4,10 +4,10 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase, ReadOnlyObserver}, - MegaContext, MegaEvm, TX_BODY_SIZE, WRITE_RECORD_SIZE, + 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, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CallValue, @@ -18,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"); @@ -27,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. @@ -239,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 121 bytes, the creator keeps its nonce record, 40, and the creation 98% of the 81 -/// left, 79: the creation's start makes the created account's record, 40 bytes, and the write in -/// its init code a second, 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(121); + 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(121); + 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"); @@ -663,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}; @@ -676,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 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 d21832ff4..23a77a7aa 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -4,29 +4,32 @@ //! 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, nor -//! for what a later halt of the frame burns. -//! - 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::{BALANCE, CALL, JUMP, JUMPDEST, 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"); @@ -256,15 +259,17 @@ fn test_an_inspector_cannot_overdraw_a_frame() { } } -/// A charge an inspector's callback could not pay leaves nothing behind for what the frame burns -/// when it halts. `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 records what `B` had. What `B` burns is what it had at that -/// halt, not at the refused charge: counted as compute, the difference would leave `A` a longer -/// run to the limit, and a larger bill, than the transaction no inspector runs. +/// 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_leaves_nothing_for_a_later_halt() { +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) @@ -282,13 +287,34 @@ fn test_a_refused_charge_leaves_nothing_for_a_later_halt() { 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); - for from in [Callback::InitializeInterp, Callback::Step, Callback::StepEnd] { + // 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"); - assert_eq!(overdrawn.limit_exceeded, plain.limit_exceeded, "{from:?}: the same stop"); - assert_eq!(overdrawn.result, plain.result, "{from:?}"); - assert_eq!(overdrawn.gas, plain.gas, "{from:?}: the same run to the limit"); + 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 + ); } } @@ -300,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, } @@ -322,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( @@ -333,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] { @@ -354,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 894df5f92..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() { @@ -125,6 +137,7 @@ fn test_a_system_call_is_held_to_no_limit() { 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); @@ -135,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 789526736..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,7 +27,9 @@ 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"] @@ -34,6 +38,8 @@ 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; @@ -47,7 +53,6 @@ mod state; mod state_growth; mod static_callee; mod stops; -mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; mod system_call; 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 f59aa3072..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, 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 data-size budget; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those three 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,8 +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 | -| bytes_forward_percent | 100 | 100 | 98 | | 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 c82533a20..f5dd920d2 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -143,8 +143,9 @@ fn render() -> String { 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 data-size budget; the `Satin` column \ - differs from `Amsterdam` in exactly the entries where one of those three applies.\n\n", + 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 { @@ -309,10 +310,20 @@ 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 entries are the ones Satin adds — upstream prices no history - // byte at all — and so is the frame's share of the byte pool, which upstream forwards whole. + // 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, - ["call_history_allowance", "bytes_forward_percent", "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_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 19bfbcbec..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. @@ -432,7 +437,7 @@ fn charged_call_input(reservoir: u64) -> FrameInput { reservoir, charged_new_account_state_gas: true, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, history_allowance: 0, })) } @@ -470,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() { @@ -576,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()); @@ -614,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; @@ -627,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( @@ -635,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()), @@ -650,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 8a998115a..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::{ @@ -43,8 +44,8 @@ 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, + 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, }; @@ -79,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); @@ -95,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) { @@ -248,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}" @@ -270,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)), ); } @@ -370,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 3d0b22373..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. @@ -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 18498699a..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,8 +1507,8 @@ 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. @@ -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 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. +/// 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_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 d63cd193e..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,7 +218,7 @@ 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); + assert_stopped(&result.result, LimitKind::DataSize, 180); result }; let small = at(100_000_000); @@ -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().limit_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 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" ); } @@ -401,7 +415,11 @@ fn test_the_stop_does_not_outlive_its_transaction() { assert!(!stopped(&evm)); assert_eq!( evm.ctx().limit_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 + }, "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())); @@ -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 e1d609ea8..ac222def3 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -71,7 +71,7 @@ fn call_frame_init(depth: usize) -> FrameInit { reservoir: RESERVOIR, charged_new_account_state_gas: false, charged_start: Default::default(), - bytes_share: u64::MAX, + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, history_allowance: 0, })), } @@ -201,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( @@ -212,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), @@ -244,62 +250,6 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { 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; @@ -524,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; @@ -540,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()); @@ -572,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 d65fa3ed5..0ca8dc5f3 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -1,5 +1,6 @@ //! 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 — op-revm's handler with EIP-8037's split of a system @@ -18,17 +19,19 @@ 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::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, MIN_BUCKET_SIZE, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; @@ -102,20 +105,21 @@ fn both_evms(db: MemoryDatabase) -> (MegaEvm, Op), caller: Address, contract: Address, data: Bytes, - gas_limit: u64, ) -> (Settled, Settled) { - let result_and_state = mega - .transact_system_call_with_gas_limit(caller, contract, data.clone(), gas_limit) + let result_and_state = Evm::transact_system_call(&mut mega, caller, contract, data.clone()) .expect("the system call runs"); + 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, gas_limit) - .expect("the system call runs"); + 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) } @@ -158,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.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.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 @@ -200,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. @@ -212,20 +197,24 @@ 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(); + let reading = mega.state[&CONTRACT].storage[&reading_slot].present_value(); (reading.to::(), mega.reservoir_remaining) }; @@ -253,13 +242,7 @@ 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.reservoir_remaining, DEFAULT_RESERVOIR - writes * slot(), @@ -275,26 +258,14 @@ 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.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.reservoir_remaining, DEFAULT_RESERVOIR); assert_eq!( @@ -323,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"); @@ -350,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.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); } @@ -380,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::{ diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs index 8ab315fc0..6a50c6e83 100644 --- a/crates/mega-evm/tests/satin/tool_writes.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -22,7 +22,7 @@ use revm::{ Inspector, }; -use crate::common::{call, context, records_and_moves, value_call_room}; +use crate::common::{call, context, grown, records_and_moves, value_call_room}; const CALLER: Address = address!("0000000000000000000000000000000000e10000"); /// The transaction's own frame. @@ -95,7 +95,11 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { ], "the receipt carries the call's transfer log, then the precompile's log and transfer log", ); - assert_eq!(outcome.usage, records_and_moves(2, 1), "the call's start alone is counted"); + 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 @@ -148,27 +152,3 @@ fn test_a_value_call_answered_at_frame_start_counts_nothing() { assert_eq!(outcome.usage, records_and_moves(0, 0), "{case}"); } } - -/// The records a start's hook charged its caller for are that start's alone: a start an inspector -/// answers in `frame_start` leaves none of them to the next transaction on the same EVM, which a -/// debug build would otherwise hold its first frame's start to once the inspector is disabled. -#[test] -fn test_a_start_answered_at_frame_start_leaves_its_records_with_its_transaction() { - let code = BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).stop().build(); - let db = MemoryDatabase::default() - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(VALUE)) - .account_code(RECEIVER, Bytes::from_static(&[STOP])); - let mut evm = - MegaEvm::new(context(db)).with_inspector(AnswersAtFrameStart { target: RECEIVER }); - let answered = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); - let outcome = evm.execute_transaction(answered).expect("the transaction is valid"); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage, records_and_moves(0, 0), "the answered value call counts nothing"); - - alloy_evm::Evm::set_inspector_enabled(&mut evm, false); - let plain = call(CALLER, RECEIVER, U256::ZERO, value_call_room()); - let outcome = evm.execute_transaction(plain).expect("the transaction is valid"); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage, records_and_moves(0, 0), "a call without value makes no record"); -} diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 87533d237..bd954cf08 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -2,7 +2,7 @@ //! //! 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 @@ -16,7 +16,10 @@ //! 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 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 — @@ -108,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. @@ -127,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 { @@ -136,6 +139,18 @@ 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 and the account it /// clears. @@ -146,35 +161,30 @@ impl Site { } } - /// The bytes the move counts: its records and its transfer log. - const fn bytes(self) -> u64 { - self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - } - - /// The bytes of the move the creating frame keeps below the moving frame's lane: a creation's - /// creator nonce record, counted on the creator before the creation's budget is taken. - const fn below_the_frame(self) -> u64 { - match self { - Self::Create | Self::Create2 => WRITE_RECORD_SIZE, - _ => 0, + /// 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 on the moving frame's own lane: its records there and its - /// transfer log. - const fn frame_bytes(self) -> u64 { - self.bytes() - self.below_the_frame() + /// 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. @@ -310,24 +320,6 @@ fn cap_for(depth: u32, bytes: u64) -> u64 { cap } -/// The budget of `site`'s moving frame under a frame cap of `cap`, when no frame above it has -/// kept anything but what the move itself puts below the frame: a creation's creator nonce record, -/// which the creator keeps before the creation's budget is taken from what it has left. -fn frame_budget(site: Site, cap: u64) -> u64 { - match site.depth() { - 0 => cap, - depth => share(budget(depth - 1, cap).saturating_sub(site.below_the_frame())), - } -} - -/// The smallest frame cap under which `site`'s moving frame has exactly `bytes` of budget. -fn cap_for_site(site: Site, bytes: u64) -> u64 { - let cap = (bytes..).find(|cap| frame_budget(site, *cap) >= bytes).unwrap(); - assert_eq!(frame_budget(site, cap), bytes, "a cap that gives exactly the bytes"); - assert_eq!(frame_budget(site, 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 { @@ -393,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; @@ -410,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, @@ -426,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", ); } @@ -452,20 +447,20 @@ fn test_each_site_counts_its_transfer_log() { } } -/// A frame budget holds the move at exactly the bytes it counts on the moving frame's lane, and -/// one byte short of them stops the frame that moves the value, which keeps nothing of the move, -/// 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 creator nonce record is below the creation's lane, on the creator, which -/// keeps it before the creation's budget is taken. +/// 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(site, site.frame_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}"); @@ -483,8 +478,8 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { let (over, body) = run(cap - 1); let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: site.frame_bytes() - 1, - used: site.frame_bytes(), + limit: site.bytes() - 1, + used: site.bytes(), frame_local: true, }); assert_eq!( @@ -499,7 +494,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { ); let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), - limit: site.frame_bytes() - 1, + limit: site.bytes() - 1, }; match variant { Variant::Plain => assert_stopped_at_the_move(&case, site, &over, body, stop), @@ -509,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!(), @@ -521,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. @@ -543,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, @@ -559,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); @@ -570,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!(), @@ -634,7 +634,10 @@ fn test_an_answered_value_call_whose_start_crosses_is_taken_back_before_its_call (held, held), "{site:?}: the move is taken back before it reads" ); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + // 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"); @@ -659,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}"); } @@ -721,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] = [ + // (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), - ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 0, 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 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); @@ -748,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}", ); @@ -805,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); @@ -816,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())), @@ -868,7 +885,7 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { assert!(refused.result.is_success(), "{:?}", refused.result); 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!( @@ -877,19 +894,19 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { "and paid the body's history alone" ); - // 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. + // 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 = (64 * records).saturating_sub(1).min(150_000); + 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", ); return; } - assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); + 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); @@ -953,7 +970,7 @@ 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); } @@ -1002,7 +1019,7 @@ fn test_a_creation_onto_an_occupied_address_fails_on_the_collision() { 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", ); @@ -1014,10 +1031,12 @@ fn test_a_creation_onto_an_occupied_address_fails_on_the_collision() { let limit = body + WRITE_RECORD_SIZE - 1; let stopped = under(limit); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), 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 }); + 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 @@ -1040,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"); @@ -1061,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"); @@ -1127,7 +1151,10 @@ fn test_a_value_call_its_recipient_cannot_hold_keeps_nothing() { 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 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!( outcome.gas.history, history_gas(body).unwrap(), @@ -1173,20 +1200,22 @@ fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { 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 }); + 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 stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), 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 }); + 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 answered by revm without bumping it: -/// no account, no record, no log, and the history the creator paid at its opcode for the two -/// records comes back. A limit one byte short of the start's bytes changes nothing. +/// 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(); @@ -1212,13 +1241,12 @@ fn test_a_nested_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { 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 }); - assert_eq!(outcome.state[&ACTOR].info.nonce, u64::MAX, "{limits:?}: not bumped"); assert_eq!( - outcome.gas.history, - history_gas(body).unwrap(), - "the records' charge came back" + 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"); } } @@ -1249,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() @@ -1270,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"); } @@ -1317,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", ); @@ -1339,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 e1fb2514a..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"); } } @@ -1802,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 672315bd0..1489ee4c9 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -42,7 +42,7 @@ use revm::{ }; use crate::common::{ - account_state_gas, call, call_with_data, context, create, deposit, history, run, + account_state_gas, call, call_with_data, context, create, deposit, grown, history, run, value_call_room, }; @@ -52,17 +52,21 @@ const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); /// 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 { @@ -106,8 +110,9 @@ fn test_two_value_calls_record_the_sender_once() { 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" ); } @@ -128,8 +133,9 @@ fn test_value_calls_to_one_recipient_record_it_once() { assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(2), 3 * TRANSFER_LOG_SIZE), - "CALLEE once, CONTRACT once, and a transfer log for each transfer" + 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" ); } @@ -189,8 +195,8 @@ fn test_one_transfer_records_its_sender_and_its_recipient() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( outcome.usage, - guarded(with_extra(records(2), TRANSFER_LOG_SIZE)), - "CALLEE, CONTRACT, a log" + 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)); @@ -353,7 +359,11 @@ fn test_nested_creations_record_each_account_once() { call(CALLER, CALLEE, U256::ZERO, value_call_room()), ); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(usage, records(3), "CALLEE, the account it created, and the one that created"); + 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))); @@ -412,18 +422,18 @@ fn test_a_destruction_to_a_fresh_and_to_a_changed_beneficiary() { ); for (case, callee, contract, balance, expected) in [ ( - "to a fresh beneficiary", + "to a fresh beneficiary, which the destruction creates", destruct_to(BytecodeBuilder::default(), CONTRACT).build(), Bytes::new(), 5, - guarded(with_extra(records(2), TRANSFER_LOG_SIZE)), + guarded(grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), ), ( - "to a beneficiary a transfer changed", + "to a beneficiary a transfer changed, which the transfer creates", sends_then_destructs.build(), Bytes::new(), 5, - guarded(with_extra(records(2), 2 * TRANSFER_LOG_SIZE)), + guarded(grown(with_extra(records(2), 2 * TRANSFER_LOG_SIZE), 1)), ), ( "of an account whose balance the transaction gave it, back to the giver", @@ -503,23 +513,32 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { 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) - let rows: [(&str, Prelude, Created, u64, u64); 6] = [ - ("fund X only: CALLEE and X", fund, None, 2, 1), - ("create X only: CALLEE's nonce and X", nothing, Some((SUCCEEDS, 0)), 2, 0), - ("fund X, then create X: CALLEE and X", fund, Some((SUCCEEDS, 0)), 2, 1), - ("fund X, then create X with an endowment: CALLEE and X", fund, Some((SUCCEEDS, 1)), 2, 2), + // 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), + ("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) in rows { + 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); @@ -541,7 +560,7 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { ); assert_eq!( outcome.usage, - with_extra(records(records_kept), logs * TRANSFER_LOG_SIZE), + grown(with_extra(records(records_kept), logs * TRANSFER_LOG_SIZE), growth), "{case}" ); if !crate::common::history_rounds() { @@ -567,8 +586,9 @@ fn test_create_then_call_record_the_frame_account_once() { 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" ); } @@ -584,8 +604,9 @@ fn test_two_creates_record_the_creator_once() { 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" ); } @@ -625,8 +646,9 @@ fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { 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" ); } @@ -659,11 +681,14 @@ fn test_a_delegates_record_of_its_callers_account_follows_the_delegate() { 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 { - with_extra(records(2), TRANSFER_LOG_SIZE) + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1) } else { - with_extra(records(3), 2 * TRANSFER_LOG_SIZE) + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2) }; - assert_eq!(usage, expected, "CALLEE once, then CONTRACT2, and CONTRACT unless it failed"); + assert_eq!( + usage, expected, + "CALLEE once, then CONTRACT2, and CONTRACT unless it failed; each recipient is new" + ); } } @@ -729,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 @@ -773,8 +802,8 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { 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" ); } @@ -784,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)), ]; @@ -811,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() @@ -844,7 +875,8 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() }; let cases = [ - (U256::from(5), CONTRACT, with_extra(records(2), 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(records(1), TRANSFER_LOG_SIZE)), (U256::ZERO, CONTRACT, body_only()), @@ -868,7 +900,7 @@ fn test_top_level_create_records_the_created_account() { 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(), @@ -1072,7 +1104,7 @@ 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), value_call_room(), false); - assert_eq!(after_sstore(&steps), records(1)); + 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 counts nothing: the @@ -1101,7 +1133,11 @@ 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), value_call_room(), true); - assert_eq!(after_sstore(&steps), records(1), "the SSTORE's record, and not the tool's log"); + 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 ---------- */ @@ -1137,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()); @@ -1158,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 @@ -1215,8 +1253,8 @@ 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, - 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" ); } @@ -1235,7 +1273,8 @@ 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(); @@ -1265,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]) @@ -1276,7 +1316,7 @@ 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, value_call_room())) @@ -1284,7 +1324,12 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { 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().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 @@ -1310,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"); @@ -1320,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. @@ -1554,8 +1607,9 @@ fn test_value_receiving_child_records_itself_once() { assert_eq!(result.state[&CONTRACT].info.balance, U256::ZERO, "as it was loaded"); assert_eq!( usage, - with_extra(records(2), 2 * TRANSFER_LOG_SIZE), - "CALLEE, CONTRACT2, and two transfer logs: CONTRACT passed on what it received" + 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" ); } @@ -1583,8 +1637,8 @@ fn test_zero_value_child_starts_unrecorded() { 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" ); } @@ -1617,8 +1671,8 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); assert_eq!( usage, - with_extra(records(1), 2 * TRANSFER_LOG_SIZE), - "CONTRACT2 and two transfer logs: CALLEE passed on the value it received" + 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" ); } @@ -1642,8 +1696,8 @@ 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" ); } @@ -1663,7 +1717,11 @@ fn test_top_level_self_call_counts_the_sender_as_recorded() { 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. @@ -1688,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) @@ -1707,8 +1765,8 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { assert!(result.result.is_success()); assert_eq!( evm.ctx().limit_usage(), - with_extra(records(2), TRANSFER_LOG_SIZE), - "CALLEE and CONTRACT2, and the transfer log" + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "CALLEE and CONTRACT2, and the transfer log; CONTRACT2 is new" ); } @@ -2031,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; } @@ -2065,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 ---------- */ 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 b2efce301..9144638a0 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -884,19 +884,20 @@ fn test_a_deployment_carrying_value_logs_the_move() { } } -/// The transfer log is counted with the creation's start: a creation whose budget holds its two -/// records and not the log is stopped at its start, alone, before it runs, and its revert takes +/// 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( @@ -925,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 e92158a39..066a53282 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -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( diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 453672dd5..88db12ced 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -48,16 +48,17 @@ fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> Frame is_static: false, charged_new_account_state_gas: false, charged_start: Default::default(), - bytes_share: u64::MAX, + 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))); @@ -88,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 621b0c54b..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}, @@ -183,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 { @@ -200,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!( @@ -386,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"); @@ -419,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 8924715d0..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, @@ -123,10 +124,9 @@ 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, which the signer's nonce record, counted on the - // call before the creation's budget is taken, takes 40 of; the creation gets 98% of the - // 960 left. Before the record moved to the call the creation got 98% of the cap, 980. - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 940 }); + // 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); assert_eq!(outcome.usage.write_records, 1, "the signer's nonce record"); @@ -135,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))); @@ -147,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!( @@ -161,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))); @@ -189,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. @@ -202,16 +255,59 @@ 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, which the signer's nonce record, counted on the - // call before the creation's budget is taken, uses up: the creation gets 98% of nothing. - // Before the record moved to the call the creation got 98% of the cap, 38. - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 0 }); + // 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}"); assert_eq!(outcome.usage.write_records, 0, "at {gas_limit}"); } } +/// 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() { @@ -355,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 => { @@ -484,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 4b6621e03..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,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0x6be2c4a9e04b8cee42b1568a07dfc761f3625d225e1479f331f6898b873f7f43", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0xdb4cd2ecbbdc0409018a90520dfbe2fd4dfcd3228fe6918019701639fda73cb9", - "rule: arguments that do not decode @ 50000000 | keccak256=0x8a813b8ae24856b4670ed7c432e3f56d86a8fb94616b65b79f7aa5505c37ef8a", - "rule: malformed transaction @ 50000000 | keccak256=0x14d8b7934f5ffc986bf3ca9c62b683f0aa8cc6a81962fc4ecaca891ea8c09a43", - "rule: a trailing byte @ 50000000 | keccak256=0x5e2b8c4e1f373bdc071255c53792e3eeea4e33aea1483d461780e58a7a2bbc7c", - "rule: not a creation @ 50000000 | keccak256=0xd7f99061cfe84b1fc116b335579639fe83f72e30f559319b77040dda8294c4e3", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0x54e4035bd71deb715fdfcc17be3d9d64e85270ea83f26ed7f5b83b4ac37f2bee", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x4bd17b02bb35de5672fdd9b4380664f5bbb81a223eb4e7e7df754b988ec35e26", - "rule: override below the signed gas limit @ 50000000 | keccak256=0xa0d0ffa69a340796adf3fb60e4f23a78a358f0deb799ac4fb92b87790be106a6", - "rule: invalid signature @ 50000000 | keccak256=0x561b100463b72a94f271bb0827444f11ccd93c1040fd2f0735a0e678b03a40cf", - "rule: signer nonce 2 @ 50000000 | keccak256=0x2e3d79aa7d471bdb32dd53ae4a7ceb0e772cf42da9dae2d546eb3f5ae3f824de", - "rule: signer with code @ 50000000 | keccak256=0xf829b9a8e15c4516b260bcca3b6a5b4c5fc575c4d53fe8b72fbcde086fec6cd9", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x2b6a69e0ecd0cdacbaedbde179e9d2924c30793240c49d19de0e110d1eb22811", - "rule: occupied address @ 50000000 | keccak256=0xbe9f719ec43f447863b3228891ddf7cb67cc24943f826a733619ada658036ee8", - "rule: value the signer cannot fund @ 50000000 | keccak256=0xebfd7e580f06f4ce7173806ab4b07fe8d2f14779296c587134e45932d3cbedc9", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x48c202dde80bc36473bdad805104396592772162d4c1c0cac69957a6e7f87b91", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xbb1464b44b11119c689e90f7202032706d3a5bf99cc989449f1f77c4a6f3ad13", - "deploys from nonce 1 @ 50000000 | keccak256=0x58586ebdf3651fcdb6851c51672f8b9894f98f7241e0ed8e782ce587325b0585", - "the address already has a balance @ 50000000 | keccak256=0xc6f304d2539cf7f36aa9641180c7ac1eb2ef384208699307d4aa2e89de21ab3a", - "moves value @ 50000000 | keccak256=0x7791ff6b94b87d5190ceb3755aad4444dad6fd8990cc462e853883420cb98251", - "moves value from nonce 1 @ 50000000 | keccak256=0xc61f6eb4c373e8a0e26129ea81d3d650c19051b662283fc11d8a54563b226605", - "the CREATE2 factory @ 50000000 | keccak256=0x7257f5422ca230d3552cec8593662688d1e2bb8a66eb03826534cefb9825c68d", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x67e5c21d36073d3b2207faf6a8bb0e7077a8a8e7abcafc232d5f1e50ac27048a", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x734ed0efea72d4ad1653e96f333c25822faa0f6b31ab2b4df1227167ba0a147b", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xed92061138d839808c496c1b3a1880fd420c72fd56abee07bf654fcf54c170e9", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x792fcb2363c740a91e68bdc061b7c8bbaf98cbe1aff749e8dbdfbe9736d71207", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x0f44f2d81f3b8c26ddca17526eab2cd3eb52137bc9ecfed8f24bcae5a1a98ce5", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x9c6b93134642dbc82a216e8d1a0c4a86fd735529b6c2e87fa6e55f61282c7c55", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf254ed0372774046b90e9785fc3b9b7cc2e53c9724f963b381bb82bcd7570ae8", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x584ce5096b24c9af8af54fc81c58c8eb251b032c0a651ecf86c3c9fc4e82f8f7", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x4cf8709413710aaa0b36400ccb07610a80282f9f4328d592621162188ecc37b1", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xa891e7c22dd52bc557a741ba5cb73cc453f88fb645c6764076d655edd9f1d794", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xb56bb82c7e82d2bec5d78c97140fd962419bd4dd84661cd6441844f67a55d3b2", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xdc0eeec20ae5509fbc1f8fdcbfa3e551ed77cdbd2daf7ddf828005ab3026d246", - "a constructor out of gas @ 50000000 | keccak256=0x5d9e9859c6783124d05749d7d8d18080d2f3b85f9c6d59c653f6d03ee1432e00", - "the signer sends it @ 50000000 | keccak256=0xb86e75c9de01d038cc31626c50bbfb899cd9bc1aff693e832adf6d895fe0c0b8", - "the signer sends it, and it reverts @ 50000000 | keccak256=0xdbfbc4870331b30af5e411392cc7a3d3ff9fd70e32632d703b1095713e2bdfba", - "a delegated signer @ 50000000 | keccak256=0x615fe64c9175edc760269e3b34bb0acd09924c3a93eaf361ab60e0b81e5c1a18", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x57f1733c301bdcddb35328a6b05d88b4f9f7f148a1d3d69c31531804fd5cb6ff", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xa4badbe971db28ab8130cafb1b6b1ccaf35df75e748e531424b79071f747d4bc", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x421d276d9b66b743508f39a2f16df0c67d316c0424234548cbf6ab890f0e269a", - "limit: compute, nonce 0 @ 50000000 | keccak256=0x23b69940d238186cc2e474800bdd4505c3530a1b046950a35519e5f802db89f6", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x8f2cb657a8bc784c170b06958359d8d2cb6feb0e11fbe801c2e3f831f861e07e", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x8afa218026e3cd07dbe01cc2d5271b3e98d1a7d62f5e09caf56616f63c4f032b", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x8d7670e2a640e39ce62efe8a7a41d1a72fb781bb28f962c5c4a2b849a2e8047c", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xcf2f3d5e3b39aeca817a3052f5c7463fee70e19db014a1db450e3e1f4685e891", - "limit: compute, nonce 1 @ 50000000 | keccak256=0xb244a6e11c3b6f793159f9122aa1e0968de07920514f1d2cf3fa02d8d9693fa8", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xa6c90f9773d5434dfbf73f4fb6cd782f96509138441219f0f45304e76fe0a4a8", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x2d4d3cc36f54cfa8e1f3c8c20b274bfa95c6b6f7e9d0dbe8c4a9898523276ad2", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x6d8111208239652510ab44b66c7d5b63d50d00797a459bec6a32f68fb044f3df", + "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=0xd7487619833b3a89ec79d8c60f3e28058bc75f3aaba41636e80427944717be1d", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xd9d5aa4fe8ee4b858316adb50837a13dd3ec46c0a1b297c54551fffad5aef8e9", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x1b5bf70dd810bdbfa173abfc9bb651675def4d7009432485953c1348540cdb52", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x887eaa144b558fec53eacc9a7b67ebb840bf5c004f3b059868d67e2d5acb3c4e", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xb95346d264a4b219c08125f67413bb662ae31f91c3d898b21e86ea5629e51f8c", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x29395f62de1af080571f9173e19a164073e1b3915372ca32a5b0905db17d1776", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x7973e1fd3dc2e403960a81da78403d1c407569742c9bd4a3075ac6a878b91c35", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x013d06a21e951b01c385b47689137dac5c4f9d79a3c581c197be0daa14988065", - "not dispatched: version() @ 50000000 | keccak256=0x71b5f865bd3661322761b71fc4309da6208266782e81dbaf4fd603052eef0d13", - "not dispatched: no selector @ 50000000 | keccak256=0xbdd2f3a556c32236687fbd2c77b0dcd6b043149ad44562ab57c414de832a446b", - "not dispatched: from a contract @ 50000000 | keccak256=0x60def043245e382daab29836061360a339f0ed239fb0968391b466df61e229ce", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x86cff0e90a7dde446fc895e574b925799e65cc12b85771d6ff6bb16c16746063", - "no contract code @ 50000000 | keccak256=0x95de965c9dbee87d5a5abad6d3664d1c78528dce8eee432e7b9756682b21eb7c", - "a system call @ 50000000 | keccak256=0x39fed9f75314afb72adb029216af30534218ecf119b1738e50e821f73c96e654", - "rule: value @ 400000000 | keccak256=0x6621fff65c743a2795883489d013835a24b226a2b04df466978c950578193cff", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x403ab771ff977d1722d04d2256374a6bb81da23243a35f44d6214ade1c739959", - "rule: arguments that do not decode @ 400000000 | keccak256=0x953f0b00aaf0cb0c3828f8e1d898f34c4420908e4217b3bcfa97bcd27f63d1d8", - "rule: malformed transaction @ 400000000 | keccak256=0xfe1a1d713f9ba4fd3ee9a05c42f7bb8566b3e63ae85ab3db0c0a0ed17b652e57", - "rule: a trailing byte @ 400000000 | keccak256=0xc0f5106b1c89842f0173f57016bb3c7a1ed0c738fe1c2ebd9e4d48f66f392040", - "rule: not a creation @ 400000000 | keccak256=0x54f9544b6408475fb4307cde34fd6a54f02e45379d4a344ccac017e3be4b4066", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x112674d77e25ae333275a87088503d7334955992b3ce4ad1e6527eabf436ce86", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x1b9f2d4b41f900f726fa88f5db019e02ee4364c4bdaf54c98a38ff1305c54855", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x224d3c5e43f9d5323fe6b9f9bbd781fd2fa46f3f6763c26a68f29c7efe766eae", - "rule: invalid signature @ 400000000 | keccak256=0xa7c33a1a4839d113bf94afa1d8d5caae218b1d6b5a4c4d3ecbf19d63cc664dd1", - "rule: signer nonce 2 @ 400000000 | keccak256=0x36a94b5c8d88f0fa7854c48731a14077110271be7988492e5e6715f939b40bb4", - "rule: signer with code @ 400000000 | keccak256=0x12ceffc3e9bb891411bd6defbdaee189a9224e76671abb6c712f26851e4225c8", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xee84ab770836481c0d2b9f0f3fda578f366e10eafacfb6539872c76e22b0c6bd", - "rule: occupied address @ 400000000 | keccak256=0x15097e3e99676ea1dbc2b9ddf62930b551bec694a48311de72e73f0c0c09eefd", - "rule: value the signer cannot fund @ 400000000 | keccak256=0xd421efd34bb65e29f6fb1235cb8a12f2b998db4df186b05ce35537df7ee03992", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x848b0d734b52f41c15a8ea7e07818deb93a83c8fda8f2f5e4d00c55f55442ed9", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x62cb4df0295fe698a4bedf30f9891e09baf6f39d937873b00076906ca2a73a33", - "deploys from nonce 1 @ 400000000 | keccak256=0xcebe8a59449392e3d21bea17eb6768676c277af25bcbc6e68460c3e1676a7d44", - "the address already has a balance @ 400000000 | keccak256=0x36ccff4608574dba9a464ed028b47fb58d39533e34199b8f80f158cee221f283", - "moves value @ 400000000 | keccak256=0xfcaf2dd354f9db199d3d19e8ae0197824c9ad3671439df9d5d91fa8703ac4b9e", - "moves value from nonce 1 @ 400000000 | keccak256=0x86b54cf0da28ddbc6c13f0b13f4b3546400d8a21ec0773e00205f38762ec6275", - "the CREATE2 factory @ 400000000 | keccak256=0xd2572ebcf5c6cd0478ce3a8fb99daba77c43ea02e8be1a16d285847be3b1e12b", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x7d79966d2586bb18d0f3cd975617220b026ed14a7fc11bd985a3095edab36ab1", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xa7a2bed3e11fd77bac02885b4974d05d4e1a0333f115b68de02629dabb86bc0d", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0xaeb851f138d0aec9ff33d2c4349bfa936175e9bb2187892923ec8620c2273f0c", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xab5569c4a6209d9e854036f767b38fcdac1a65bd1616c4a9e0937b33aa8f9994", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe288cb34e9909960113b6e3cdb1e02be2d0a62efc15bf60e87c584476d2d3923", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0xe4ea5b03b83a33e8cdeca1788c7a46cce01c2d7ec2183d051acfba1cb9fe703b", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x217851801f9fd7fcf13aeb97d16923646e8561f3f4c998ff5d58b4926b5b13f5", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x7a8ba7478366ef8e3817763f9ed36ee748e65fe733d7443009a45de6484041b4", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0xf2ce34640bff1a53ddfb714e1f9bd6b25c35fac5f512fb58facdc0a1692182d0", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xd7b919e0f1753b880a1fff9cfaf36b21ab2e3884debc041616395f095cbd1202", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x4078316eada64a6161caec29df05c407e4c5f1ef1a20faff8f0d382816ebfdcf", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x6b8a101e66ef4010835fc3da00c74e610c23db0021eb6eba90b93eaf273f2f25", - "a constructor out of gas @ 400000000 | keccak256=0xac5a841f99f78b0e21076a347e60c48ae83555ec3bdefa5b8df4b862d99e618b", - "the signer sends it @ 400000000 | keccak256=0x55ee191f25b9ff082b5734bf12ca6a8e0d2d1766d39881a75c94bdc550a23e77", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xf8fa9c7e63710003664c34c12ffef4140efa5366930e795d7484837d22d7edf2", - "a delegated signer @ 400000000 | keccak256=0x1e6d8f5bde5cac9791e0bdd02c1d4880c1d22d08e496990a205964855a0e9a90", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xb1ac9749392dc3156f389a1b603ae5e69c9d08937bb4308cb7488ed61701c055", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x924a2702ff5ad4301372d7cff03137f759467b9ff7153eb6e143f1cebcc95397", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xe4dbf743f422c6726384de3115d2dc7f6079ea79723b3290d91aae49381ff779", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x185d095dc4ea9d189687a13fa993c28a8ad81b734c3fcd5da8e573aa5daf30cf", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x189bf4dad92f38af3fc108ab7e2946bf941520252ea42e03089efd29b213d93c", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xaa9e603ace266be85412fc48f16cf054cb4c8ae59a0261bacf2699c10f8c4e0d", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xffbeade2e2586b013d7cd68ba729d8e7cc6bc61439565ab2ef27fd4039b7bd42", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x84dbf201e6ceab370961d5fe7a37cea63d51618fc38e1614060f56bbbc5f8561", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x5014b568b4ae5d95ade79311955e48ebe07068cb47fa5461515c2aab7213fcdb", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x8ccb6d71d3af3a757525e928562dc212025eadd1f29d3eef90d5e75d09af28d6", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xace6753de34dd4fbfcbbdcc989ba0b9f5b04259776b3c833beba77f1d2c44f7c", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xf36763d00fe5507de7ba782c73f37cb52d18790eb95b5b3f9820181d02d735a9", + "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=0xef704d7bc2fce3e18a1da2af57ec8a2a53b98c4a180c3ec9cb776d24540c4852", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x042438c94d0621ae8a2f19c02ac3f04e76eb4e4a06a78979ace089a255440176", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xdd3b0907d4c6c127470d7ccb6124f0204603155431d5ba8daea66a1d2f0bcac9", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x143d38c359b8a8bbbbb25c51c937f0a1489fd237f6c171b4e3cbd223c5aa0061", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xed8375b46dc371b2031b4628fb78d08239fa9ee263815ea3d4f194f97feeea31", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x68ad51797ae01a1d145d2a59af9a0d39c2f1b874b0fc87b871dcacfb35980e0d", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x21490e3a5958ebc22af5cbbcb52b644ed09b709764bfb2598d5e541d07051b97", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x08c04c0bbed8559bf465611bb8d95c4c2a1b41003c103e9b79436feb53b321e2", - "not dispatched: version() @ 400000000 | keccak256=0xb0697f813fcf0b76481275f2fd8a71f3c313708da0b3968985003c5b622d7e42", - "not dispatched: no selector @ 400000000 | keccak256=0x75fe0bf0713bc6c078a16bac52359e7d3a89938d8337309c8ed301ea0f82eee0", - "not dispatched: from a contract @ 400000000 | keccak256=0xc1d016f94b74d3107a876c74f03b6d6e7b1503ead5d4b4bb82b3309c99680c96", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0xa27b66fb90ece2b8b19071bd98e27f6ab83f3a239058f22bd9b0df4b300dd8d4", - "no contract code @ 400000000 | keccak256=0x207f8e449c8da45440b71acbddc1796dd88e5adf27b2777372a45607c225c5dd", - "a system call @ 400000000 | keccak256=0xbc7901dc1b60b4c891850d89708756c04cc648058e8bce964e59c72ba9192aab", - "out of gas: the overhead @ 161535 | keccak256=0x9e5fa941ba924cb9ec361e5cff34ccb0655c61440dfba72525cf32bce4a0e324", - "out of gas: the signer's account @ 162536 | keccak256=0x1b10a06299a9c84eeff3f3a80bd672c3c89c8a04040c73b8e0b4abe9ad529be4", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x91244c305f19041671325d1f781e6f7119f34ef45c1f5b42312f6137d473f791", - "out of gas: the creation's charges @ 163024 | keccak256=0x6ad1b06738836db19511c6232f82e08f5148b1bbc5240ff4f59d2cb11f1d29c5", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0xa81c6721ab647bfc0dbed1d24a304344906c7ece94c08552a935bfd00bf772e6", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0x45a89392882dcc35e679fcd79e54fd30ff593f981d0e7172b906e4f2ecfbd061", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x1493c0d5815ef90d4b4ab4fb32569f119b7370e6765292497afc21f10b602572", - "rule: init code over the limit @ 150000000 | keccak256=0xdb26152222c6f33e3e4b11646593374057eb3619c2ee6ecf30af45f9602dfc75", - "rule: init code over the limit @ 2000000000 | keccak256=0xf7055f08d140f0e730be867a1240128308297c023ca11b8e05fd20b6f18d7bab" + "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": 2523500, + "bytes": 2577938, "cases": 139, "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/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 6803e89a4..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) @@ -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/README.md b/crates/mega-state-test/README.md index 93cc7e53e..9dffdb534 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -72,7 +72,7 @@ It is taken from the outcome as the engine produced it, before the runner takes ## 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-compute-gas GAS` replaces gas detention's two caps. +`--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. diff --git a/crates/mega-state-test/src/digest.rs b/crates/mega-state-test/src/digest.rs index 3faf44271..252c54f25 100644 --- a/crates/mega-state-test/src/digest.rs +++ b/crates/mega-state-test/src/digest.rs @@ -104,7 +104,12 @@ fn gas_usage(gas: &MegaGasUsage) -> Value { } fn usage(usage: &LimitUsage) -> Value { - fields([("data_size", usage.data_size.into()), ("write_records", usage.write_records.into())]) + 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 { @@ -256,7 +261,7 @@ mod tests { state, ), gas: MegaGasUsage::new(&gas(), 10_000, 125, 5_000), - usage: LimitUsage { data_size: 500, write_records: 3 }, + 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)) }], } @@ -319,8 +324,11 @@ mod tests { 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. diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index d280c0df7..f94235984 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -606,6 +606,7 @@ fn test_tightened_limits_reach_the_limit_stop_paths() { let (spec, tight) = (records(&spec)[0].unwrap(), records(&tight)[0].unwrap()); assert!(spec["limit_exceeded"].is_null()); assert_eq!(tight["limit_exceeded"]["kind"], "DataSize"); - assert_eq!(tight["limit_exceeded"]["limit"], 400); + // 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 dafbb2c97..b461230f3 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -13,7 +13,7 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--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` 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`. +- `--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. diff --git a/crates/state-test/src/main.rs b/crates/state-test/src/main.rs index 2361f838d..a95facd70 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -66,6 +66,15 @@ struct Cmd { /// 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, @@ -172,7 +181,9 @@ fn main() -> ExitCode { 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_compute_gas.is_none() && + cmd.limit_kv_updates.is_none() && + cmd.limit_state_growth.is_none() { return Ok(None); } @@ -193,6 +204,12 @@ fn tightened_limits(cmd: &Cmd) -> Result, String> { .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)) } diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index c0ae26e32..9d6fc4eab 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -196,6 +196,8 @@ fn test_the_limit_options_need_satin_mode() { ["--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); 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 b77de32fa..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): 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 ab3d9746b..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 at commit [`42e4c354`](https://github.com/megaeth-labs/revm/commit/42e4c3543af170ca911cbb52e68de1ecd8cd443e) ([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 [`e33fb15b`](https://github.com/megaeth-labs/op-revm/commit/e33fb15b416008ac9d45c52a2b1edd0a286ff521) ([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 `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 55a805c71..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,17 +377,32 @@ 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 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 — MUST be given back by it then, before what it makes is charged. +- 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 (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. 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 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. + 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, 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. + +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. @@ -387,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 @@ -401,11 +499,16 @@ 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 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)). @@ -417,29 +520,304 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw 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 is counted on the creator once the nonce was bumped, before the creation's budget is taken from what the creator has left, so it is held to the creator's budget and not the creation's, and it survives the creation's failure. - 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)). + 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, a creation of what its creator has left once the creator's nonce record is counted. + 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. + 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, lands on the creator, which MUST be held to its limits with it. + 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. @@ -456,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. @@ -465,18 +851,22 @@ 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. @@ -485,9 +875,11 @@ 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. - A stopped creation keeps its creator's nonce bump, 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. + 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. @@ -496,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, which the transaction's compute does not exceed (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 @@ -518,6 +914,7 @@ 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 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.** @@ -535,8 +932,9 @@ 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.** @@ -547,7 +945,9 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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. @@ -675,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 when the nonce set back leaves the signer's account as the transaction loaded it; 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)). + 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. @@ -770,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; @@ -813,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. @@ -830,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. @@ -881,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. @@ -930,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. @@ -993,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`. @@ -1047,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`. @@ -1055,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'. @@ -1086,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. @@ -1099,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 0d9a92e87a2a800927afc009f9d6fa46e80acc4b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 09:03:25 +0800 Subject: [PATCH 458/458] docs(skills): word the Satin review guide for #386 before and after #407 merges --- .claude/skills/satin-review/SKILL.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5f6088b08..5f51a5eae 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: 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) @@ -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 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. + 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. @@ -42,10 +42,11 @@ The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. ## What is still moving -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. +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. -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. +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.