From 544378018ccb150a468d4ed211a6bb79452d4cf5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:39:24 +0800 Subject: [PATCH 001/110] feat(interpreter): hooks for completed writes and frame starts Two defaulted `Host` methods let a consumer meter inside revm's own instructions, at the two points it otherwise reconstructs from outside: - `write_completed(write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, called by SSTORE, LOG0-LOG4 and SELFDESTRUCT once the write is in the journal and every charge the instruction makes has been made, so only on the instruction's success path; - `frame_starting(start: &FrameStart, gas: &mut GasTracker) -> bool`, called by CALL, CALLCODE, DELEGATECALL, STATICCALL, CREATE and CREATE2 once the forward is taken (`record_withheld_first_cost`) and before the frame's input is built, so the input copies the reservoir as the hook left it. The hook may debit and credit the running frame's tracker; the instruction uses it as the hook left it and charges nothing after the hook. One private helper applies the write verdict: `Continue` ends the instruction as before, `OutOfGas` fails it as a failed charge does, `Revert(output)` ends the frame as a `Revert` with the output on the gas the hook left (a SELFDESTRUCT so reverted does not self-destruct). A start hook's `false` fails the instruction out of gas and starts no frame. The types live in a new file, `host/instruction_hooks.rs`: `CompletedWrite` and `FrameStart` are `#[non_exhaustive]`, the latter built with `FrameStart::new`. The reported forward is the exact amount deducted from the caller: `load_acc_and_calc_gas` now wraps a crate-private `load_acc_and_calc_forward` that also returns it, last, so the call site does not repeat the value stipend's rule and no public signature changes. `load_acc_and_calc_gas` keeps its signature and results; it is `#[inline]` now, around the out-of-line helper, and nothing in the workspace calls it. The defaults continue and return `true`, touching nothing. Under callgrind (the fork's release profile) the write sites and the creations cost nothing per instruction; a call costs one instruction, the store of the returned forward. Reconstructing the forward at the call site instead costs the same, through the call instruction's stack layout. --- crates/context/interface/src/host.rs | 49 +++++++- .../interface/src/host/instruction_hooks.rs | 113 ++++++++++++++++++ crates/interpreter/src/instructions.rs | 1 + .../interpreter/src/instructions/contract.rs | 27 ++++- .../src/instructions/contract/call_helpers.rs | 29 ++++- crates/interpreter/src/instructions/host.rs | 27 ++++- .../src/instructions/instruction_hooks.rs | 59 +++++++++ 7 files changed, 296 insertions(+), 9 deletions(-) create mode 100644 crates/context/interface/src/host/instruction_hooks.rs create mode 100644 crates/interpreter/src/instructions/instruction_hooks.rs diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 297662fe63..0586955d94 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -1,7 +1,11 @@ //! Host interface for external blockchain state access. +mod instruction_hooks; + +pub use instruction_hooks::{CompletedWrite, FrameStart, FrameStartKind, WriteVerdict}; + use crate::{ - cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, + cfg::{gas::GasTracker, GasId, GasParams, StateGasCharge, StateGasSite}, context::{SStoreResult, SelfDestructResult, StateLoad}, journaled_state::{AccountInfoLoad, AccountLoad}, }; @@ -94,6 +98,49 @@ pub trait Host { .map(|unit_price| charge.total(unit_price)) } + /* Instruction hooks */ + + /// Called by `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` once `write` is in the journal and + /// every charge the instruction makes has been made, so only when the instruction completes. + /// `gas` is the running frame's. + /// + /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, + /// charging nothing after the hook; a charge the hook makes that fails records as any failed + /// charge does ([`GasTracker::failed_charge_remaining`]), whatever the verdict. + /// [`WriteVerdict::Continue`] ends the instruction as it would have ended. + /// [`WriteVerdict::OutOfGas`] fails it as a failed charge does: the frame halts out of gas, + /// and the halt records the regular gas the hook left unless a failed charge already did. + /// [`WriteVerdict::Revert`] ends the frame as a `Revert` with the verdict's output, on its gas + /// as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct. + /// + /// The default continues and touches nothing. + #[inline] + fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { + let _ = (write, gas); + WriteVerdict::Continue + } + + /// Called by `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` once + /// every charge the instruction makes has been made and the forward + /// ([`FrameStart::forward`]) has been taken from `gas`, the running frame's, and before the + /// frame's input is built. + /// + /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, + /// charging nothing after the hook: the frame's input copies its reservoir from `gas`. A + /// charge the hook makes that fails records as any failed charge does + /// ([`GasTracker::failed_charge_remaining`]), whatever the answer. `true` goes on to start the + /// frame, which the handler may still refuse or answer without running it. `false` fails the + /// instruction out of gas and starts no frame: the forward stays taken unless the hook gave it + /// back, and the halt records the regular gas the hook left unless a failed charge already + /// did. + /// + /// The default returns `true` and touches nothing. + #[inline] + fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + let _ = (start, gas); + true + } + /* Database */ /// Block hash, calls `ContextTr::journal_mut().db().block_hash(number)` diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs new file mode 100644 index 0000000000..fedee80558 --- /dev/null +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -0,0 +1,113 @@ +//! Hooks an instruction calls on the [`Host`](super::Host) at a point inside it: once a state write +//! is complete ([`Host::write_completed`](super::Host::write_completed)), and once a frame's forward +//! is taken, before the frame's input is built ([`Host::frame_starting`](super::Host::frame_starting)). +//! +//! Both hooks get the running frame's [`GasTracker`](crate::cfg::gas::GasTracker), and may debit +//! and credit it; the instruction goes on with the gas as the hook left it. Their defaults touch +//! nothing and let the instruction go on. + +use crate::context::{SStoreResult, SelfDestructResult}; +use primitives::{Address, Bytes, StorageKey, U256}; + +/// A state write an instruction completed: the write is in the journal, and every charge the +/// instruction makes has been made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum CompletedWrite<'a> { + /// `SSTORE` wrote slot `key` of `address`. + Sstore { + /// The account whose storage was written. + address: Address, + /// The slot written. + key: StorageKey, + /// The slot's original, present and new values, as the journal reported them. + result: &'a SStoreResult, + }, + /// `LOG0`–`LOG4` appended a log for `address`. + Log { + /// The account that logged. + address: Address, + /// The number of topics, `0` to `4`. + topics: u8, + /// The length of the log's data, in bytes. + data_len: u64, + }, + /// `SELFDESTRUCT` destructed `address` in favour of `target`. + SelfDestruct { + /// The account destructed. + address: Address, + /// The beneficiary. + target: Address, + /// What the journal reported. + result: &'a SelfDestructResult, + }, +} + +/// What an instruction does once [`Host::write_completed`](super::Host::write_completed) has seen +/// its write. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteVerdict { + /// The instruction ends as it would without the hook. + Continue, + /// The instruction fails out of gas, as a failed charge does. + OutOfGas, + /// The frame ends as a `Revert` with this output, on its gas as the hook left it. + Revert(Bytes), +} + +/// The kind of frame an instruction is about to start. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FrameStartKind { + /// `CALL`. + Call, + /// `CALLCODE`. + CallCode, + /// `DELEGATECALL`. + DelegateCall, + /// `STATICCALL`. + StaticCall, + /// `CREATE`. + Create, + /// `CREATE2`. + Create2, +} + +/// A frame an instruction is about to start: every charge the instruction makes has been made, the +/// gas it forwards has been taken from the caller, and the frame's input is not built yet. +/// +/// Built with [`FrameStart::new`], so a later field is not a breaking change. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct FrameStart { + /// The kind of frame. + pub kind: FrameStartKind, + /// The frame's caller: the account the frame sees as `CALLER`. + pub caller: Address, + /// The account the frame runs as; `None` for a creation, whose address is decided later. + pub target: Option
, + /// The value the start transfers; zero for `DELEGATECALL` and `STATICCALL`. + pub value: U256, + /// The regular gas the instruction took from the caller for the frame: the frame's gas limit + /// without a value call's stipend, which the caller does not pay. + pub forward: u64, +} + +impl FrameStart { + /// A frame start. + #[inline] + pub const fn new( + kind: FrameStartKind, + caller: Address, + target: Option
, + value: U256, + forward: u64, + ) -> Self { + Self { + kind, + caller, + target, + value, + forward, + } + } +} diff --git a/crates/interpreter/src/instructions.rs b/crates/interpreter/src/instructions.rs index 667f494022..313fb4d9ba 100644 --- a/crates/interpreter/src/instructions.rs +++ b/crates/interpreter/src/instructions.rs @@ -16,6 +16,7 @@ pub mod control; pub mod host; /// Signed 256-bit integer operations. pub mod i256; +mod instruction_hooks; /// Memory operations (MLOAD, MSTORE, MSIZE, etc.). pub mod memory; /// Stack operations (PUSH, POP, DUP, SWAP, etc.). diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 90c6791052..db7a6246c1 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -5,8 +5,10 @@ pub use call_helpers::{ load_account_delegated_handle_error, resize_memory, }; +use call_helpers::load_acc_and_calc_forward; + use crate::{ - instructions::utility::IntoAddress, + instructions::{instruction_hooks::frame_starting, utility::IntoAddress}, interpreter_action::FrameInput, interpreter_types::{ InputsTr, InterpreterTypes as ITy, LoopControl, MemoryTr, ReturnData, RuntimeFlag, StackTr, @@ -16,6 +18,7 @@ use crate::{ }; use context_interface::{ cfg::{GasId, StateGasCharge, StateGasSite}, + host::{FrameStart, FrameStartKind}, CreateScheme, }; use primitives::{ @@ -170,6 +173,14 @@ pub fn create( return Err(InstructionResult::OutOfGas); } + let kind = if IS_CREATE2 { + FrameStartKind::Create2 + } else { + FrameStartKind::Create + }; + let start = FrameStart::new(kind, create_inputs.caller(), None, value, gas_limit); + frame_starting(&mut context.interpreter.gas, context.host, &start)?; + create_inputs.set_gas_limit(gas_limit); create_inputs.set_reservoir(context.interpreter.gas.reservoir()); context @@ -215,8 +226,8 @@ pub fn call(mut context: Ictx<'_, H, get_memory_input_and_out_ranges(context.interpreter, context.host.gas_params())?; let is_call = KIND == CALL; - let (gas_limit, bytecode, bytecode_hash, charged_new_account_state_gas) = - load_acc_and_calc_gas(&mut context, to, has_transfer, is_call, local_gas_limit)?; + let (gas_limit, bytecode, bytecode_hash, charged_new_account_state_gas, forward) = + load_acc_and_calc_forward(&mut context, to, has_transfer, is_call, local_gas_limit)?; let target_address = if matches!(KIND, CALLCODE | DELEGATECALL) { context.interpreter.input.target_address() @@ -242,6 +253,16 @@ pub fn call(mut context: Ictx<'_, H, }; let is_static = context.interpreter.runtime_flag.is_static() || KIND == STATICCALL; + let kind = match KIND { + CALL => FrameStartKind::Call, + CALLCODE => FrameStartKind::CallCode, + DELEGATECALL => FrameStartKind::DelegateCall, + _ => FrameStartKind::StaticCall, + }; + let transferred = value.transfer().unwrap_or_default(); + let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); + frame_starting(&mut context.interpreter.gas, context.host, &start)?; + // Call host to interact with target contract context .interpreter diff --git a/crates/interpreter/src/instructions/contract/call_helpers.rs b/crates/interpreter/src/instructions/contract/call_helpers.rs index 0e38e2759b..0a1f1a3109 100644 --- a/crates/interpreter/src/instructions/contract/call_helpers.rs +++ b/crates/interpreter/src/instructions/contract/call_helpers.rs @@ -62,7 +62,7 @@ pub fn resize_memory( /// (transfers value into a previously-empty account). Callers should propagate /// it onto `CallInputs` so the parent can refund the charge if the resulting /// frame reverts/halts. -#[inline(never)] +#[inline] pub fn load_acc_and_calc_gas( context: &mut Ictx<'_, H, impl ITy>, to: Address, @@ -70,6 +70,30 @@ pub fn load_acc_and_calc_gas( create_empty_account: bool, stack_gas_limit: u64, ) -> Result<(u64, Bytecode, B256, bool), InstructionResult> { + load_acc_and_calc_forward( + context, + to, + transfers_value, + create_empty_account, + stack_gas_limit, + ) + .map(|(gas_limit, bytecode, code_hash, charged, _)| (gas_limit, bytecode, code_hash, charged)) +} + +/// [`load_acc_and_calc_gas`], also returning the forward: the gas taken from the caller for the +/// frame, which is the frame's gas limit without a value call's stipend. +/// +/// Returns `(gas_limit, bytecode, code_hash, charged_new_account_state_gas, forward)`. The forward +/// comes last, after the fields [`load_acc_and_calc_gas`] returns: placed second, it changed how +/// the others are stored and cost two more instructions per call. +#[inline(never)] +pub(super) fn load_acc_and_calc_forward( + context: &mut Ictx<'_, H, impl ITy>, + to: Address, + transfers_value: bool, + create_empty_account: bool, + stack_gas_limit: u64, +) -> Result<(u64, Bytecode, B256, bool, u64), InstructionResult> { // Transfer value cost if transfers_value { gas!( @@ -109,6 +133,8 @@ pub fn load_acc_and_calc_gas( return Err(InstructionResult::OutOfGas); } + let forward = gas_limit; + // Add call stipend if there is value to be transferred. if transfers_value { gas_limit = gas_limit.saturating_add(host.gas_params().call_stipend()); @@ -119,6 +145,7 @@ pub fn load_acc_and_calc_gas( bytecode, code_hash, charged_new_account_state_gas, + forward, )) } diff --git a/crates/interpreter/src/instructions/host.rs b/crates/interpreter/src/instructions/host.rs index e0b52ec219..4ec45b944b 100644 --- a/crates/interpreter/src/instructions/host.rs +++ b/crates/interpreter/src/instructions/host.rs @@ -1,11 +1,14 @@ use crate::{ - instructions::utility::{IntoAddress, IntoU256}, + instructions::{ + instruction_hooks::write_completed, + utility::{IntoAddress, IntoU256}, + }, interpreter_types::{InputsTr, InterpreterTypes as ITy, MemoryTr, RuntimeFlag, StackTr}, Gas, Host, InstructionExecResult as Result, InstructionResult, }; use context_interface::{ cfg::{GasId, StateGasCharge, StateGasSite}, - host::LoadError, + host::{CompletedWrite, LoadError}, journaled_state::AccountInfoLoad, }; use core::cmp::min; @@ -275,7 +278,12 @@ pub fn sstore(context: Ictx<'_, H, IT>) -> Result { .gas_params() .sstore_refund(is_istanbul, &state_load.data), ); - Ok(()) + let write = CompletedWrite::Sstore { + address: target, + key: index, + result: &state_load.data, + }; + write_completed(context.interpreter, context.host, write) } /// EIP-1153: Transient storage opcodes @@ -336,7 +344,12 @@ pub fn log(context: Ictx<'_, H, impl ITy>) -> }; context.host.log(log); - Ok(()) + let write = CompletedWrite::Log { + address: context.interpreter.input.target_address(), + topics: N as u8, + data_len: len as u64, + }; + write_completed(context.interpreter, context.host, write) } /// Implements the SELFDESTRUCT instruction. @@ -392,5 +405,11 @@ pub fn selfdestruct(context: Ictx<'_, H, IT>) -> Resu .record_refund(context.host.gas_params().selfdestruct_refund()); } + let write = CompletedWrite::SelfDestruct { + address: context.interpreter.input.target_address(), + target, + result: &res.data, + }; + write_completed(context.interpreter, context.host, write)?; Err(InstructionResult::SelfDestruct) } diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs new file mode 100644 index 0000000000..cc2b969ca9 --- /dev/null +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -0,0 +1,59 @@ +//! The instructions' side of the [`Host`] instruction hooks: what an instruction does with the +//! answer of [`Host::write_completed`] and [`Host::frame_starting`]. + +use crate::{ + interpreter_types::{InterpreterTypes as ITy, LoopControl}, + Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, InterpreterAction, +}; +use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; +use primitives::{hints_util::cold_path, Bytes}; + +/// Hands `write`, which the running instruction completed after its last charge, to +/// [`Host::write_completed`] with the frame's gas, and applies the verdict: the instruction goes +/// on, fails out of gas, or ends the frame as a `Revert` with the verdict's output on the gas as +/// the hook left it. +#[inline] +pub(crate) fn write_completed( + interpreter: &mut Interpreter, + host: &mut H, + write: CompletedWrite<'_>, +) -> Result { + match host.write_completed(write, interpreter.gas.tracker_mut()) { + WriteVerdict::Continue => Ok(()), + WriteVerdict::OutOfGas => { + cold_path(); + Err(InstructionResult::OutOfGas) + } + WriteVerdict::Revert(output) => revert(interpreter, output), + } +} + +/// Ends the frame as a `Revert` with `output`, as `REVERT` does. +#[cold] +#[inline(never)] +fn revert(interpreter: &mut Interpreter, output: Bytes) -> Result { + interpreter + .bytecode + .set_action(InterpreterAction::new_return( + InstructionResult::Revert, + output, + interpreter.gas, + )); + Err(InstructionResult::Revert) +} + +/// Hands `start`, whose forward the running instruction has taken from `gas`, to +/// [`Host::frame_starting`]; `false` fails the instruction out of gas. +#[inline] +pub(crate) fn frame_starting( + gas: &mut Gas, + host: &mut H, + start: &FrameStart, +) -> Result { + if host.frame_starting(start, gas.tracker_mut()) { + Ok(()) + } else { + cold_path(); + Err(InstructionResult::OutOfGas) + } +} From 08d0cdbdac462121068b5dfbf52e505bb71f66f1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:39:52 +0800 Subject: [PATCH 002/110] test: the instruction hooks at their call sites, on the plain and the inspected path In the interpreter, on a host that records each hook call with the gas it was handed and answers as told: - each write instruction (a cold slot set and one cleared, a log, a cold SELFDESTRUCT into a new account) reaches the hook after its last charge, refunds included, on Berlin, Osaka and Amsterdam: the frame ends on the gas the hook was handed, and one gas short of the charges before the hook fails without reaching it; every earlier failure (the stipend sentry, the static, dynamic, memory and log charges, a refused cold target, a failed state-gas price) never reaches it; - every verdict: `Continue` and `Revert` on the gas the hook left, a reverted SELFDESTRUCT returning `Revert`, `OutOfGas` halting with the record of what the hook left, or of the hook's own failed charge; - every call kind and both creations: the start's facts, the forward already taken, nothing charged after the hook, the value stipend outside the forward, a named gas against the 63/64 cap, the input's reservoir as the hook left it for a covered and a spilled hook charge, `false` halting out of gas with no frame, and every failure before the forward (memory, value, cold target, account and state-gas charges, price lookup, a forward before EIP-150, init-code and creation charges) never reaching it. Through `transact` and `inspect_tx` on a context that overrides the hooks, each run on both paths with the same outcome and the same hook calls: observing hooks change nothing against the default context on either path, on Prague and Amsterdam, which report the gas the fork reported before the hooks; each instruction, every call kind included, one gas short never reaches its hook, and with exactly the gas reaches it with nothing left and completes; each verdict ends the transaction the same way; a refused start runs no frame; each call kind's forward is the named gas or the 63/64 cap, taken before the hook, with the stipend outside it; a covered and a spilled charge by a write hook and by a start hook stand, and a started frame, or a precompile's answered one, inherits the reservoir the hook left. --- crates/inspector/tests/instruction_hooks.rs | 992 +++++++++++++++ crates/interpreter/tests/instruction_hooks.rs | 1109 +++++++++++++++++ 2 files changed, 2101 insertions(+) create mode 100644 crates/inspector/tests/instruction_hooks.rs create mode 100644 crates/interpreter/tests/instruction_hooks.rs diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs new file mode 100644 index 0000000000..3907270fe7 --- /dev/null +++ b/crates/inspector/tests/instruction_hooks.rs @@ -0,0 +1,992 @@ +//! The instruction hooks on the plain and the inspected path. +//! +//! `transact` runs a frame's instructions in the interpreter's loop and `inspect_tx` in the +//! inspector's; both run the same instructions, which call [`Host::write_completed`] and +//! [`Host::frame_starting`]. Each test runs a transaction both ways on [`HookContext`], which +//! delegates everything to the mainnet [`Context`] but the two hooks, and checks that the hooks are +//! reached at the same points with the same gas and that their answers end the transaction the same +//! way. + +use context::{ + context_interface::{ + cfg::{GasId, GasParams, StateGasSite}, + host::{CompletedWrite, FrameStart, FrameStartKind, LoadError, WriteVerdict}, + journaled_state::AccountInfoLoad, + result::{ExecutionResult, HaltReason, OutOfGasError, ResultAndState, ResultGas}, + }, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Host, Journal, + LocalContext, TxEnv, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + instructions::EthInstructions, EthFrame, EthPrecompiles, ExecuteEvm, MainBuilder, MainContext, + MainnetContext, +}; +use interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, GasTracker, + SStoreResult, SelfDestructResult, StateLoad, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, +}; +use revm_inspector::{InspectEvm, Inspector, NoOpInspector}; +use state::{ + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, LOG0, LOG1, MSTORE, POP, PUSH0, PUSH1, + PUSH4, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + }, + AccountInfo, Bytecode, +}; + +type Db = CacheDB; +type DbError = ::Error; + +/// The account the transaction calls. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// The account [`PARENT`] starts frames on. +const CHILD: Address = address!("0x00000000000000000000000000000000000c41d0"); +/// An account that does not exist, which `SELFDESTRUCT` pays. +const BENEFICIARY: Address = address!("0x00000000000000000000000000000000000be4e0"); +/// An account that does not exist, which a call sends value to. +const EMPTY: Address = address!("0x00000000000000000000000000000000000e3970"); +/// The identity precompile, a start the handler answers without a frame. +const IDENTITY: Address = address!("0x0000000000000000000000000000000000000004"); +/// The transaction's gas limit. +const GAS_LIMIT: u64 = 5_000_000; +/// What a reverting hook returns. +const STOP_OUTPUT: &[u8] = b"stop"; + +/// A write the hook saw, owned. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Write { + Sstore(Address, StorageKey, SStoreResult), + Log(Address, u8, u64), + SelfDestruct(Address, Address, SelfDestructResult), +} + +impl Write { + fn of(write: CompletedWrite<'_>) -> Self { + match write { + CompletedWrite::Sstore { + address, + key, + result, + } => Self::Sstore(address, key, result.clone()), + CompletedWrite::Log { + address, + topics, + data_len, + } => Self::Log(address, topics, data_len), + CompletedWrite::SelfDestruct { + address, + target, + result, + } => Self::SelfDestruct(address, target, result.clone()), + other => panic!("a write this test does not know: {other:?}"), + } + } + + const fn address(&self) -> Address { + match self { + Self::Sstore(address, ..) + | Self::Log(address, ..) + | Self::SelfDestruct(address, ..) => *address, + } + } +} + +/// What the hooks answer, and what they saw. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Hooks { + verdict: WriteVerdict, + admit: bool, + /// History gas the first write hook charges on the gas it is handed. + first_write_charge: u64, + /// History gas the first start hook charges on the gas it is handed. + first_start_charge: u64, + /// Every write, with the gas as the hook found it. + writes: Vec<(Write, GasTracker)>, + /// Every start, with the gas as the hook found it. + starts: Vec<(FrameStart, GasTracker)>, +} + +impl Hooks { + const fn observing() -> Self { + Self { + verdict: WriteVerdict::Continue, + admit: true, + first_write_charge: 0, + first_start_charge: 0, + writes: Vec::new(), + starts: Vec::new(), + } + } +} + +/// The mainnet [`Context`] with [`Hooks`]. +struct HookContext { + inner: MainnetContext, + hooks: Hooks, +} + +impl ContextTr for HookContext { + type Block = BlockEnv; + type Tx = TxEnv; + type Cfg = CfgEnv; + type Db = Db; + type Journal = Journal; + type Chain = (); + type Local = LocalContext; + + fn all( + &self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &Self::Db, + &Self::Journal, + &Self::Chain, + &Self::Local, + ) { + self.inner.all() + } + + fn all_mut( + &mut self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &mut Self::Journal, + &mut Self::Chain, + &mut Self::Local, + ) { + self.inner.all_mut() + } + + fn error(&mut self) -> &mut Result<(), ContextError> { + self.inner.error() + } +} + +impl ContextSetters for HookContext { + fn set_tx(&mut self, tx: Self::Tx) { + self.inner.set_tx(tx); + } + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } +} + +impl Host for HookContext { + fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { + self.hooks.writes.push((Write::of(write), *gas)); + if self.hooks.writes.len() == 1 && self.hooks.first_write_charge > 0 { + assert!(gas.record_history_cost(self.hooks.first_write_charge)); + } + self.hooks.verdict.clone() + } + + fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + self.hooks.starts.push((*start, *gas)); + if self.hooks.starts.len() == 1 && self.hooks.first_start_charge > 0 { + assert!(gas.record_history_cost(self.hooks.first_start_charge)); + } + self.hooks.admit + } + + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { + self.inner.state_gas_price(id, site) + } + + fn basefee(&self) -> U256 { + self.inner.basefee() + } + + fn blob_gasprice(&self) -> U256 { + self.inner.blob_gasprice() + } + + fn gas_limit(&self) -> U256 { + self.inner.gas_limit() + } + + fn difficulty(&self) -> U256 { + self.inner.difficulty() + } + + fn prevrandao(&self) -> Option { + self.inner.prevrandao() + } + + fn block_number(&self) -> U256 { + self.inner.block_number() + } + + fn timestamp(&self) -> U256 { + self.inner.timestamp() + } + + fn beneficiary(&self) -> Address { + self.inner.beneficiary() + } + + fn slot_num(&self) -> U256 { + self.inner.slot_num() + } + + fn chain_id(&self) -> U256 { + self.inner.chain_id() + } + + fn effective_gas_price(&self) -> U256 { + self.inner.effective_gas_price() + } + + fn caller(&self) -> Address { + self.inner.caller() + } + + fn blob_hash(&self, number: usize) -> Option { + self.inner.blob_hash(number) + } + + fn max_initcode_size(&self) -> usize { + self.inner.max_initcode_size() + } + + fn gas_params(&self) -> &GasParams { + self.inner.gas_params() + } + + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.inner.is_amsterdam_eip8037_enabled() + } + + fn block_hash(&mut self, number: u64) -> Option { + self.inner.block_hash(number) + } + + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner.selfdestruct(address, target, skip_cold_load) + } + + fn log(&mut self, log: Log) { + self.inner.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.inner.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.inner.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .load_account_info_skip_cold_load(address, load_code, skip_cold_load) + } +} + +/// The gas limit and reservoir of every frame the inspector saw start, the transaction's first. +#[derive(Default)] +struct Frames(Vec<(u64, u64)>); + +impl Inspector for Frames { + fn call(&mut self, _context: &mut HookContext, inputs: &mut CallInputs) -> Option { + self.0.push((inputs.gas_limit, inputs.reservoir)); + None + } + + fn create( + &mut self, + _context: &mut HookContext, + inputs: &mut CreateInputs, + ) -> Option { + self.0.push((inputs.gas_limit(), inputs.reservoir())); + None + } +} + +type HookEvm = Evm< + HookContext, + Frames, + EthInstructions, + EthPrecompiles, + EthFrame, +>; + +/// A transaction to [`PARENT`] and the accounts it runs on. +struct Run { + spec: SpecId, + /// The transaction's reservoir: its cap is set this far below [`GAS_LIMIT`] on Amsterdam. + reservoir: u64, + /// `(address, code, balance)`. + accounts: Vec<(Address, Vec, u64)>, + hooks: Hooks, +} + +impl Run { + fn new(spec: SpecId, parent: Vec) -> Self { + Self { + spec, + reservoir: 0, + accounts: vec![(PARENT, parent, 10)], + hooks: Hooks::observing(), + } + } + + fn with(mut self, address: Address, code: Vec, balance: u64) -> Self { + self.accounts.push((address, code, balance)); + self + } + + const fn reservoir(mut self, reservoir: u64) -> Self { + self.reservoir = reservoir; + self + } + + fn hooks(mut self, hooks: Hooks) -> Self { + self.hooks = hooks; + self + } + + fn context(&self) -> MainnetContext { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + for (address, code, balance) in &self.accounts { + let info = AccountInfo::from_balance(U256::from(*balance)) + .with_nonce(1) + .with_code(Bytecode::new_raw(Bytes::copy_from_slice(code))); + db.insert_account_info(*address, info); + } + let (spec, reservoir) = (self.spec, self.reservoir); + Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(spec); + if spec.is_enabled_in(SpecId::AMSTERDAM) { + cfg.tx_gas_limit_cap = Some(GAS_LIMIT - reservoir); + } + }) + } + + fn evm(&self) -> HookEvm { + let ctx = HookContext { + inner: self.context(), + hooks: self.hooks.clone(), + }; + Evm::new_with_inspector( + ctx, + Frames::default(), + EthInstructions::new_mainnet_with_spec(self.spec), + EthPrecompiles::new(self.spec), + ) + } + + fn tx() -> TxEnv { + TxEnv::builder() + .caller(BENCH_CALLER) + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build() + .unwrap() + } + + /// The transaction on the mainnet context, with the default hooks, with `transact` and with + /// `inspect_tx`, which must end the same way. + fn on_defaults(&self) -> ResultAndState { + let transacted = self + .context() + .build_mainnet() + .transact(Self::tx()) + .expect("the transaction runs"); + let inspected = self + .context() + .build_mainnet_with_inspector(NoOpInspector) + .inspect_tx(Self::tx()) + .expect("the transaction runs"); + assert_eq!(inspected, transacted, "both paths end the same way"); + transacted + } + + /// The transaction with `transact` and with `inspect_tx`, which must end the same way and + /// reach the hooks at the same points with the same gas. Returns the outcome, what the hooks + /// saw, and the frames the inspector saw start. + fn on_both_paths(&self) -> (ResultAndState, Hooks, Vec<(u64, u64)>) { + let mut plain = self.evm(); + let transacted = plain.transact(Self::tx()).expect("the transaction runs"); + let mut inspected = self.evm(); + let inspected_outcome = inspected + .inspect_tx(Self::tx()) + .expect("the transaction runs"); + + assert_eq!(inspected_outcome, transacted, "both paths end the same way"); + assert_eq!( + inspected.ctx.hooks, plain.ctx.hooks, + "both paths reach the hooks at the same points with the same gas" + ); + (transacted, plain.ctx.hooks, inspected.inspector.0) + } +} + +/// `PUSHn` of `bytes`. +fn push(bytes: &[u8]) -> Vec { + let mut code = vec![PUSH0 + bytes.len() as u8]; + code.extend_from_slice(bytes); + code +} + +/// The shortest push of `address`. +fn push_address(address: Address) -> Vec { + let bytes = address.as_slice(); + let first = bytes.iter().position(|byte| *byte != 0).unwrap_or(19); + push(&bytes[first..]) +} + +/// `SSTORE(0, 1)`. +fn sstore() -> Vec { + vec![PUSH1, 1, PUSH0, SSTORE] +} + +/// `LOG1` of 32 bytes of memory at offset 0. +fn log1() -> Vec { + vec![PUSH1, 0xaa, PUSH1, 32, PUSH0, LOG1] +} + +/// `SELFDESTRUCT` in favour of `target`. +fn selfdestruct(target: Address) -> Vec { + let mut code = push_address(target); + code.push(SELFDESTRUCT); + code +} + +/// `op` (a call) to `to` with `gas` and `value` (for `CALL` and `CALLCODE`), no input and no +/// output, dropping the success flag. +fn call(op: u8, to: Address, gas: u32, value: u8) -> Vec { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0]; + if matches!(op, CALL | CALLCODE) { + code.extend_from_slice(&[PUSH1, value]); + } + code.extend(push_address(to)); + code.push(PUSH4); + code.extend_from_slice(&gas.to_be_bytes()); + code.extend_from_slice(&[op, POP]); + code +} + +/// `op` (`CREATE` or `CREATE2`) of `initcode`, at most 32 bytes, endowed with nothing, dropping +/// the address. +fn create(op: u8, initcode: &[u8]) -> Vec { + let len = initcode.len() as u8; + let mut code = push(initcode); + code.extend_from_slice(&[PUSH0, MSTORE]); + if op == CREATE2 { + code.extend_from_slice(&[PUSH1, 0x5a]); + } + code.extend_from_slice(&[PUSH1, len, PUSH1, 32 - len, PUSH0, op, POP]); + code +} + +/// Code that starts a frame of its own: a `STATICCALL` of [`IDENTITY`], which a static frame may +/// make too. +fn nested_start() -> Vec { + let mut code = call(STATICCALL, IDENTITY, 0, 0); + code.push(STOP); + code +} + +fn ends(mut code: Vec) -> Vec { + code.push(STOP); + code +} + +/// A frame of each kind [`PARENT`] starts: on [`CHILD`], whose code starts a frame of its own, or +/// with that code as init code. +fn start_cases() -> Vec<(FrameStartKind, Vec)> { + vec![ + (FrameStartKind::Call, ends(call(CALL, CHILD, 100_000, 1))), + ( + FrameStartKind::CallCode, + ends(call(CALLCODE, CHILD, 100_000, 1)), + ), + ( + FrameStartKind::DelegateCall, + ends(call(DELEGATECALL, CHILD, 100_000, 0)), + ), + ( + FrameStartKind::StaticCall, + ends(call(STATICCALL, CHILD, 100_000, 0)), + ), + ( + FrameStartKind::Create, + ends(create(CREATE, &nested_start())), + ), + ( + FrameStartKind::Create2, + ends(create(CREATE2, &nested_start())), + ), + ] +} + +/// [`PARENT`] writes, logs, starts a frame of each kind and self-destructs; [`CHILD`] logs. +fn every_site() -> Run { + let mut parent = sstore(); + parent.extend(log1()); + parent.extend(call(CALL, CHILD, 50_000, 1)); + parent.extend(call(CALLCODE, CHILD, 50_000, 1)); + parent.extend(call(DELEGATECALL, CHILD, 50_000, 0)); + parent.extend(call(STATICCALL, CHILD, 50_000, 0)); + parent.extend(create(CREATE, &[])); + parent.extend(create(CREATE2, &[])); + parent.extend(selfdestruct(BENEFICIARY)); + Run::new(SpecId::PRAGUE, parent).with(CHILD, vec![PUSH0, PUSH0, LOG0, STOP], 0) +} + +/// [`every_site`]'s gas and number of logs as the fork reported them before the hooks, on a spec +/// before EIP-8037 and on one with it. +const EVERY_SITE: [(SpecId, ResultGas, usize); 2] = [ + ( + SpecId::PRAGUE, + ResultGas::new_with_state_gas(208_269, 0, 21_000, 0), + 4, + ), + // Two more logs: EIP-7708's transfer logs for the value `CALL` and the `SELFDESTRUCT`. + ( + SpecId::AMSTERDAM, + ResultGas::new_with_state_gas(790_389, 0, 15_000, 648_720), + 6, + ), +]; + +/// The default hooks change nothing: on a spec before EIP-8037 and on one with it, a transaction +/// that reaches every site reports what it reported before the hooks, and hooks that only observe +/// change nothing on either path. The observing hooks see every site. +#[test] +fn test_hooks_that_only_observe_change_nothing() { + for (spec, gas, logs) in EVERY_SITE { + let run = Run { + spec, + ..every_site() + }; + let defaults = run.on_defaults(); + let (outcome, hooks, _) = run.on_both_paths(); + + assert_eq!(outcome, defaults, "{spec:?}"); + assert!( + outcome.result.is_success(), + "{spec:?}: {:?}", + outcome.result + ); + assert_eq!(*outcome.result.gas(), gas, "{spec:?}"); + assert_eq!(outcome.result.logs().len(), logs, "{spec:?}"); + + let writes: Vec = hooks.writes.into_iter().map(|(write, _)| write).collect(); + let set = SStoreResult { + original_value: StorageValue::ZERO, + present_value: StorageValue::ZERO, + new_value: StorageValue::from(1), + }; + let destructed = SelfDestructResult { + had_value: true, + target_exists: false, + previously_destroyed: false, + }; + assert_eq!( + writes, + vec![ + Write::Sstore(PARENT, StorageKey::ZERO, set), + Write::Log(PARENT, 1, 32), + Write::Log(CHILD, 0, 0), + Write::Log(PARENT, 0, 0), + Write::Log(PARENT, 0, 0), + Write::SelfDestruct(PARENT, BENEFICIARY, destructed), + ], + "{spec:?}: the static call's log fails before the hook" + ); + let kinds: Vec = hooks.starts.iter().map(|(start, _)| start.kind).collect(); + assert_eq!( + kinds, + [ + FrameStartKind::Call, + FrameStartKind::CallCode, + FrameStartKind::DelegateCall, + FrameStartKind::StaticCall, + FrameStartKind::Create, + FrameStartKind::Create2, + ], + "{spec:?}" + ); + } +} + +/// `code` with its last instruction, which drops a result, replaced by `STOP`. +fn stops_after(mut code: Vec) -> Vec { + assert_eq!(code.pop(), Some(POP)); + ends(code) +} + +/// The instruction under test, on [`CHILD`], which [`PARENT`] calls with `gas`: the first is its +/// name, the second its code, which ends with the instruction. `CHILD` has a balance of 1, to send +/// or pay out; the calls go to an account that does not exist, so it is cold. +fn charge_cases() -> Vec<(&'static str, Vec)> { + vec![ + ("SSTORE", ends(sstore())), + ("LOG1", ends(log1())), + ("SELFDESTRUCT", selfdestruct(BENEFICIARY)), + ("CALL", stops_after(call(CALL, EMPTY, 0, 1))), + ("CALLCODE", stops_after(call(CALLCODE, EMPTY, 0, 1))), + ("DELEGATECALL", stops_after(call(DELEGATECALL, EMPTY, 0, 0))), + ("STATICCALL", stops_after(call(STATICCALL, EMPTY, 0, 0))), + ("CREATE", stops_after(create(CREATE, &[]))), + ("CREATE2", stops_after(create(CREATE2, &[]))), + ] +} + +/// On each path, an instruction one gas short of what it charges before its hook fails without +/// reaching it, and with exactly that gas reaches it with nothing left and nothing is charged +/// after it: the frame, which ends with the instruction, succeeds. On Amsterdam with no reservoir, +/// so the last charge is the state-gas charge where there is one. +#[test] +fn test_a_charge_that_fails_before_the_hook_never_reaches_it() { + // The parent stores whether the child succeeded in its slot 0. + let mut parent = stops_after(call(CALL, CHILD, 0, 0)); + parent.pop(); + parent.extend_from_slice(&[PUSH0, SSTORE, STOP]); + // The named gas: the four bytes before `CALL PUSH0 SSTORE STOP`. + let gas_at = parent.len() - 8; + let child_run = |code: &[u8], gas: u32| { + let mut parent = parent.clone(); + parent[gas_at..gas_at + 4].copy_from_slice(&gas.to_be_bytes()); + let (outcome, hooks, _) = Run::new(SpecId::AMSTERDAM, parent) + .with(CHILD, code.to_vec(), 1) + .on_both_paths(); + let succeeded = outcome.state[&PARENT].storage[&StorageKey::ZERO].present_value; + (hooks, succeeded == U256::from(1)) + }; + // The child's own hook call: its write, or the start it makes after the parent's. + let childs = |hooks: &Hooks| -> Option<(u64, u64)> { + if let Some((_, gas)) = hooks + .writes + .iter() + .find(|(write, _)| write.address() == CHILD) + { + return Some((gas.remaining(), 0)); + } + hooks + .starts + .get(1) + .map(|(start, gas)| (gas.remaining(), start.forward)) + }; + for (name, code) in charge_cases() { + let ample: u32 = 1_000_000; + let (hooks, succeeded) = child_run(&code, ample); + let (left, forward) = childs(&hooks).expect("the hook is reached"); + let needed = u64::from(ample) - left - forward; + assert!(succeeded, "{name}"); + + let (hooks, succeeded) = child_run(&code, needed as u32); + assert_eq!( + childs(&hooks), + Some((0, 0)), + "{name}: reached with nothing left" + ); + assert!(succeeded, "{name}: nothing is charged after the hook"); + + let (hooks, succeeded) = child_run(&code, needed as u32 - 1); + assert_eq!(childs(&hooks), None, "{name}: one gas short is not reached"); + assert!(!succeeded, "{name}"); + } +} + +/// [`PARENT`] runs `code` and stops, with what it changes: slot 0, a log, or [`BENEFICIARY`]'s +/// balance. +fn verdict_cases() -> Vec<(&'static str, Vec)> { + vec![ + ("SSTORE", ends(sstore())), + ("LOG1", ends(log1())), + ("SELFDESTRUCT", selfdestruct(BENEFICIARY)), + ] +} + +/// What the transaction left of the write: slot 0's value, the logs, and what [`BENEFICIARY`] got. +fn written(outcome: &ResultAndState) -> (U256, usize, U256) { + let slot = outcome + .state + .get(&PARENT) + .and_then(|account| account.storage.get(&StorageKey::ZERO)) + .map_or(U256::ZERO, |slot| slot.present_value); + let paid = outcome + .state + .get(&BENEFICIARY) + .map_or(U256::ZERO, |account| account.info.balance); + (slot, outcome.result.logs().len(), paid) +} + +/// Each verdict ends the transaction the same way on both paths: `Continue` keeps the write, +/// `OutOfGas` halts and `Revert` reverts with the verdict's output, on the gas the hook left, and +/// both undo it; a `SELFDESTRUCT` so stopped pays nothing. +#[test] +fn test_each_verdict_ends_the_write_the_same_way_on_both_paths() { + let kept = [ + (U256::from(1), 0, U256::ZERO), + (U256::ZERO, 1, U256::ZERO), + (U256::ZERO, 0, U256::from(10)), + ]; + for ((name, code), kept) in verdict_cases().into_iter().zip(kept) { + let run = |verdict| { + Run::new(SpecId::OSAKA, code.clone()) + .hooks(Hooks { + verdict, + ..Hooks::observing() + }) + .on_both_paths() + }; + + let (outcome, _, _) = run(WriteVerdict::Continue); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(written(&outcome), kept, "{name}: the write is kept"); + + let (outcome, _, _) = run(WriteVerdict::OutOfGas); + let ExecutionResult::Halt { reason, gas, .. } = &outcome.result else { + panic!("{name}: {:?}", outcome.result); + }; + assert_eq!(*reason, HaltReason::OutOfGas(OutOfGasError::Basic)); + assert_eq!(gas.total_gas_spent(), GAS_LIMIT, "{name}"); + assert_eq!(written(&outcome), (U256::ZERO, 0, U256::ZERO), "{name}"); + + let (outcome, hooks, _) = run(WriteVerdict::Revert(Bytes::from_static(STOP_OUTPUT))); + let ExecutionResult::Revert { output, gas, .. } = &outcome.result else { + panic!("{name}: {:?}", outcome.result); + }; + assert_eq!(*output, Bytes::from_static(STOP_OUTPUT), "{name}"); + assert_eq!( + gas.total_gas_spent(), + GAS_LIMIT - hooks.writes[0].1.remaining(), + "{name}: the frame ends on the gas the hook left" + ); + assert_eq!(written(&outcome), (U256::ZERO, 0, U256::ZERO), "{name}"); + } +} + +/// `false` fails the starting instruction out of gas and starts no frame, on both paths: the +/// frame's code never runs, so its own start never reaches the hook, and the inspector sees no +/// frame start. +#[test] +fn test_a_refused_start_starts_no_frame_on_both_paths() { + for (kind, parent) in start_cases() { + let run = Run::new(SpecId::OSAKA, parent).with(CHILD, nested_start(), 10); + + let (admitted, hooks, frames) = run.on_both_paths(); + assert!(admitted.result.is_success(), "{kind:?}"); + assert_eq!(hooks.starts.len(), 2, "{kind:?}: the frame ran"); + assert_eq!(frames.len(), 3, "{kind:?}"); + + let (refused, hooks, frames) = run + .hooks(Hooks { + admit: false, + ..Hooks::observing() + }) + .on_both_paths(); + let ExecutionResult::Halt { reason, .. } = &refused.result else { + panic!("{kind:?}: {:?}", refused.result); + }; + assert_eq!( + *reason, + HaltReason::OutOfGas(OutOfGasError::Basic), + "{kind:?}" + ); + assert_eq!(hooks.starts.len(), 1, "{kind:?}: the frame never ran"); + assert_eq!(hooks.starts[0].0.kind, kind); + assert_eq!(frames.len(), 1, "{kind:?}: no frame started but the first"); + } +} + +/// A started frame inherits the reservoir as the hook left it, on both paths: the parent's hook +/// charges history gas the reservoir covers, and the frame finds the rest, whether it runs its own +/// code or is answered without a frame, as a precompile is. +#[test] +fn test_a_started_frame_inherits_the_reservoir_the_hook_left() { + const CHARGE: u64 = 4_000; + let hooks = Hooks { + first_start_charge: CHARGE, + ..Hooks::observing() + }; + for (kind, parent) in start_cases() { + let (_, hooks, frames) = Run::new(SpecId::AMSTERDAM, parent) + .with(CHILD, nested_start(), 10) + .reservoir(1_000_000) + .hooks(hooks.clone()) + .on_both_paths(); + let handed = hooks.starts[0].1.reservoir(); + let inherited = hooks.starts[1].1.reservoir(); + + assert!(handed > CHARGE, "{kind:?}: the reservoir covers the charge"); + assert_eq!(inherited, handed - CHARGE, "{kind:?}"); + assert_eq!(frames[1].1, handed - CHARGE, "{kind:?}: the frame's input"); + } + + // The parent calls the identity precompile, then logs: the reservoir the answered call returns + // is the one its input carried. + let mut parent = call(STATICCALL, IDENTITY, 100_000, 0); + parent.extend_from_slice(&[PUSH0, PUSH0, LOG0, STOP]); + let (_, hooks, frames) = Run::new(SpecId::AMSTERDAM, parent) + .reservoir(1_000_000) + .hooks(hooks) + .on_both_paths(); + let handed = hooks.starts[0].1.reservoir(); + + assert_eq!(hooks.writes[0].1.reservoir(), handed - CHARGE); + assert_eq!(frames[1].1, handed - CHARGE); +} + +/// On both paths, a call's forward is the gas it names, or 63/64 of what the caller has left when it +/// names more, and a creation's is always the cap; the hook sees it already taken; and the frame's +/// gas limit is the forward with a value call's stipend on top. +#[test] +fn test_the_forward_on_both_paths() { + let stipend = GasParams::new_spec(SpecId::OSAKA).call_stipend(); + let run = |parent: Vec| { + let (_, hooks, frames) = Run::new(SpecId::OSAKA, parent) + .with(CHILD, vec![STOP], 0) + .on_both_paths(); + (hooks.starts[0], frames[1].0) + }; + for (op, value) in [(CALL, 1), (CALLCODE, 1), (DELEGATECALL, 0), (STATICCALL, 0)] { + let ((named, named_gas), named_limit) = run(ends(call(op, CHILD, 30_000, value))); + let ((capped, capped_gas), capped_limit) = run(ends(call(op, CHILD, u32::MAX, value))); + // Both runs had the same gas before the forward. + let left = capped_gas.remaining() + capped.forward; + let stipend = if value > 0 { stipend } else { 0 }; + + assert_eq!(named.forward, 30_000, "{op:#x}"); + assert_eq!(capped.forward, left - left / 64, "{op:#x}: the 63/64 cap"); + assert_eq!( + named_gas.remaining() + named.forward, + left, + "{op:#x}: the hook sees the forward taken" + ); + assert_eq!(named_limit, named.forward + stipend, "{op:#x}"); + assert_eq!(capped_limit, capped.forward + stipend, "{op:#x}"); + } + for op in [CREATE, CREATE2] { + let ((start, gas), limit) = run(ends(create(op, &[]))); + let left = gas.remaining() + start.forward; + + assert_eq!( + start.forward, + left - left / 64, + "{op:#x}: taken, and the 63/64 cap" + ); + assert_eq!(limit, start.forward, "{op:#x}"); + } +} + +/// On both paths, what a hook charges stands and the instruction goes on with the gas as the hook +/// left it: a charge the reservoir covers comes out of the reservoir, and one that spills empties +/// it and takes the rest from regular gas. A start's forward is what was taken before the charge. +#[test] +fn test_a_hook_charge_stands_on_both_paths() { + const RESERVOIR: u64 = 100_000; + + // The first `LOG1`'s hook charges; the second sees what it left. + let mut parent = log1(); + parent.extend(log1()); + let run = |charge| { + Run::new(SpecId::AMSTERDAM, ends(parent.clone())) + .reservoir(RESERVOIR) + .hooks(Hooks { + first_write_charge: charge, + ..Hooks::observing() + }) + .on_both_paths() + .1 + }; + let quiet = run(0).writes[1].1; + let handed = quiet.reservoir(); + for (charge, reservoir, spilled) in [(4_000, handed - 4_000, 0), (handed + 500, 0, 500)] { + let second = run(charge).writes[1].1; + + assert_eq!(second.reservoir(), reservoir, "charge {charge}"); + assert_eq!( + second.remaining(), + quiet.remaining() - spilled, + "charge {charge}" + ); + assert_eq!(second.history_gas_spent(), charge as i64, "charge {charge}"); + } + + // The `CALL`'s hook charges; the frame inherits the reservoir it left, with the gas limit it + // would have had, and the parent logs once the frame returns. + let mut parent = call(CALL, CHILD, 100_000, 1); + parent.extend_from_slice(&[PUSH0, PUSH0, LOG0, STOP]); + let run = |charge| { + Run::new(SpecId::AMSTERDAM, parent.clone()) + .with(CHILD, nested_start(), 0) + .reservoir(RESERVOIR) + .hooks(Hooks { + first_start_charge: charge, + ..Hooks::observing() + }) + .on_both_paths() + }; + let (_, quiet, quiet_frames) = run(0); + let handed = quiet.starts[0].1.reservoir(); + for (charge, reservoir, spilled) in [(4_000, handed - 4_000, 0), (handed + 500, 0, 500)] { + let (_, hooks, frames) = run(charge); + + assert_eq!( + hooks.starts[1].1.reservoir(), + reservoir, + "charge {charge}: inherited" + ); + assert_eq!( + frames[1], + (quiet_frames[1].0, reservoir), + "charge {charge}: the input" + ); + let (after, quiet_after) = (hooks.writes[0].1, quiet.writes[0].1); + assert_eq!(after.reservoir(), reservoir, "charge {charge}: returned"); + assert_eq!( + after.remaining(), + quiet_after.remaining() - spilled, + "charge {charge}" + ); + } +} diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs new file mode 100644 index 0000000000..94a6cc6427 --- /dev/null +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -0,0 +1,1109 @@ +//! The instruction hooks, at the instructions that call them. +//! +//! `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` hand the write they completed to +//! [`Host::write_completed`] after their last charge, and apply its verdict. The call and creation +//! instructions hand the frame they are about to start to [`Host::frame_starting`] once the forward +//! is taken and before the frame's input is built. Each test runs one frame on [`HookHost`], which +//! records every hook call with the gas the hook was handed, charges history gas on that gas if +//! told to, and answers as the test tells it. + +use bytecode::{opcode::*, Bytecode}; +use context_interface::{ + cfg::{GasId, GasParams, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::{CompletedWrite, FrameStart, FrameStartKind, LoadError, WriteVerdict}, + journaled_state::AccountInfoLoad, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, B256, U256, +}; +use revm_interpreter::{ + host::DummyHost, + instruction_table, + instructions::gas_table_spec, + interpreter::{EthInterpreter, ExtBytecode}, + FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, + InterpreterAction, SharedMemory, +}; +use state::AccountInfo; +use std::borrow::Cow; + +/// The account the frame runs as. +const CONTRACT: Address = address!("0x000000000000000000000000000000000000c0de"); +/// The frame's caller. +const CALLER: Address = address!("0x00000000000000000000000000000000000ca11e"); +/// The account a call or `SELFDESTRUCT` names. +const TARGET: Address = address!("0x0000000000000000000000000000000000007a59"); +/// The value the frame was called with, which `DELEGATECALL` passes on without transferring it. +const APPARENT_VALUE: u64 = 7; +/// Gas enough for every frame here. +const AMPLE: u64 = 1_000_000; +/// What a reverting hook returns. +const STOP_OUTPUT: &[u8] = b"stop"; + +/// A write the hook saw, owned. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Write { + Sstore(Address, StorageKey, SStoreResult), + Log(Address, u8, u64), + SelfDestruct(Address, Address, SelfDestructResult), +} + +impl Write { + fn of(write: CompletedWrite<'_>) -> Self { + match write { + CompletedWrite::Sstore { + address, + key, + result, + } => Self::Sstore(address, key, result.clone()), + CompletedWrite::Log { + address, + topics, + data_len, + } => Self::Log(address, topics, data_len), + CompletedWrite::SelfDestruct { + address, + target, + result, + } => Self::SelfDestruct(address, target, result.clone()), + other => panic!("a write this test does not know: {other:?}"), + } + } +} + +/// A [`DummyHost`] whose state answers as configured, and whose hooks record each call with the +/// gas they were handed, charge [`HookHost::charge`] of history gas on it, and answer +/// [`HookHost::verdict`] or [`HookHost::admit`]. +struct HookHost { + dummy: DummyHost, + /// Every account and slot is cold, and a cold load the instruction asks to skip is refused. + cold: bool, + /// Every account is empty. + empty: bool, + /// The original and present value of every slot. + slot: StorageValue, + /// What `SELFDESTRUCT` finds. + destruct: SelfDestructResult, + /// Every state-gas price lookup fails. + price_fails: bool, + /// History gas each hook charges on the gas it is handed before it answers. + charge: u64, + verdict: WriteVerdict, + admit: bool, + /// Every write the hook saw, with the gas as the hook found it. + writes: Vec<(Write, GasTracker)>, + /// Every start the hook saw, with the gas as the hook found it. + starts: Vec<(FrameStart, GasTracker)>, +} + +impl HookHost { + fn new(spec: SpecId) -> Self { + Self { + dummy: DummyHost::new(spec), + cold: false, + empty: false, + slot: StorageValue::ZERO, + destruct: SelfDestructResult::default(), + price_fails: false, + charge: 0, + verdict: WriteVerdict::Continue, + admit: true, + writes: Vec::new(), + starts: Vec::new(), + } + } + + const fn cold(mut self) -> Self { + self.cold = true; + self + } + + const fn empty(mut self) -> Self { + self.empty = true; + self + } + + fn holding(mut self, slot: u64) -> Self { + self.slot = StorageValue::from(slot); + self + } + + /// `SELFDESTRUCT` of an account with a balance in favour of an account that does not exist. + const fn destructs_into_a_new_account(mut self) -> Self { + self.destruct = SelfDestructResult { + had_value: true, + target_exists: false, + previously_destroyed: false, + }; + self + } + + const fn price_fails(mut self) -> Self { + self.price_fails = true; + self + } + + const fn charging(mut self, charge: u64) -> Self { + self.charge = charge; + self + } + + fn answering(mut self, verdict: WriteVerdict) -> Self { + self.verdict = verdict; + self + } + + const fn refusing(mut self) -> Self { + self.admit = false; + self + } + + const fn refuses_cold(&self, skip_cold_load: bool) -> Result<(), LoadError> { + if self.cold && skip_cold_load { + Err(LoadError::ColdLoadSkipped) + } else { + Ok(()) + } + } + + /// The one write the hook saw. + fn write(&self) -> &(Write, GasTracker) { + assert_eq!(self.writes.len(), 1, "one write: {:?}", self.writes); + &self.writes[0] + } + + /// The one start the hook saw. + fn start(&self) -> &(FrameStart, GasTracker) { + assert_eq!(self.starts.len(), 1, "one start: {:?}", self.starts); + &self.starts[0] + } + + const fn reached(&self) -> bool { + !self.writes.is_empty() || !self.starts.is_empty() + } +} + +impl Host for HookHost { + fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { + self.writes.push((Write::of(write), *gas)); + if self.charge > 0 { + let _ = gas.record_history_cost(self.charge); + } + self.verdict.clone() + } + + fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + self.starts.push((*start, *gas)); + if self.charge > 0 { + let _ = gas.record_history_cost(self.charge); + } + self.admit + } + + fn state_gas_price(&mut self, id: GasId, _site: StateGasSite) -> Option { + (!self.price_fails).then(|| self.gas_params().get(id)) + } + + fn basefee(&self) -> U256 { + self.dummy.basefee() + } + fn blob_gasprice(&self) -> U256 { + self.dummy.blob_gasprice() + } + fn gas_limit(&self) -> U256 { + self.dummy.gas_limit() + } + fn difficulty(&self) -> U256 { + self.dummy.difficulty() + } + fn prevrandao(&self) -> Option { + self.dummy.prevrandao() + } + fn block_number(&self) -> U256 { + self.dummy.block_number() + } + fn timestamp(&self) -> U256 { + self.dummy.timestamp() + } + fn beneficiary(&self) -> Address { + self.dummy.beneficiary() + } + fn slot_num(&self) -> U256 { + self.dummy.slot_num() + } + fn chain_id(&self) -> U256 { + self.dummy.chain_id() + } + fn effective_gas_price(&self) -> U256 { + self.dummy.effective_gas_price() + } + fn caller(&self) -> Address { + self.dummy.caller() + } + fn blob_hash(&self, number: usize) -> Option { + self.dummy.blob_hash(number) + } + fn max_initcode_size(&self) -> usize { + usize::MAX + } + fn gas_params(&self) -> &GasParams { + self.dummy.gas_params() + } + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.dummy.is_amsterdam_eip8037_enabled() + } + fn block_hash(&mut self, number: u64) -> Option { + self.dummy.block_hash(number) + } + + fn selfdestruct( + &mut self, + _address: Address, + _target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.refuses_cold(skip_cold_load)?; + Ok(StateLoad::new(self.destruct.clone(), self.cold)) + } + + fn log(&mut self, log: Log) { + self.dummy.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + _address: Address, + _key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.refuses_cold(skip_cold_load)?; + let result = SStoreResult { + original_value: self.slot, + present_value: self.slot, + new_value: value, + }; + Ok(StateLoad::new(result, self.cold)) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.dummy + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.dummy.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.dummy.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + _address: Address, + _load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.refuses_cold(skip_cold_load)?; + Ok(AccountInfoLoad { + account: Cow::Owned(AccountInfo::from_balance(U256::from(AMPLE))), + is_cold: self.cold, + is_empty: self.empty, + }) + } +} + +/// Runs `code` as [`CONTRACT`], called by [`CALLER`] with [`APPARENT_VALUE`], with `gas_limit` +/// regular gas and `reservoir`, and returns what the frame asked for and its gas. +fn run( + spec: SpecId, + code: &[u8], + gas_limit: u64, + reservoir: u64, + host: &mut HookHost, +) -> (InterpreterAction, Gas) { + let mut interpreter = Interpreter::::new( + SharedMemory::new(), + ExtBytecode::new(Bytecode::new_raw(Bytes::copy_from_slice(code))), + InputsImpl { + target_address: CONTRACT, + caller_address: CALLER, + call_value: U256::from(APPARENT_VALUE), + ..Default::default() + }, + false, + spec, + gas_limit, + ); + interpreter.gas = Gas::new_with_regular_gas_and_reservoir(gas_limit, reservoir); + let table = instruction_table::(); + let action = interpreter.run_plain(&table, &gas_table_spec(spec), host); + (action, interpreter.gas) +} + +/// The result a frame returned with, and its result's gas. +fn returned(action: InterpreterAction) -> (InstructionResult, Bytes, Gas) { + match action { + InterpreterAction::Return(result) => (result.result, result.output, result.gas), + other => panic!("expected the frame to return, got {other:?}"), + } +} + +/// The frame a frame asked to start. +fn started(action: InterpreterAction) -> FrameInput { + match action { + InterpreterAction::NewFrame(input) => input, + other => panic!("expected a new frame, got {other:?}"), + } +} + +/// The static gas of `op` on `spec`. +const fn static_gas(spec: SpecId, op: u8) -> u64 { + gas_table_spec(spec)[op as usize] as u64 +} + +/// `SSTORE(0, 1)`, then `STOP`. +const SSTORE_CODE: [u8; 6] = [PUSH1, 1, PUSH1, 0, SSTORE, STOP]; +/// `SSTORE(0, 0)`, then `STOP`. +const CLEAR_CODE: [u8; 6] = [PUSH1, 0, PUSH1, 0, SSTORE, STOP]; +/// What `SSTORE` finds when [`SSTORE_CODE`] sets a slot from zero. +fn set_from_zero() -> SStoreResult { + SStoreResult { + original_value: StorageValue::ZERO, + present_value: StorageValue::ZERO, + new_value: StorageValue::from(1), + } +} + +/// `LOG1` of `len` bytes of memory at offset 0, then `STOP`. +fn log1_code(len: u8) -> Vec { + vec![PUSH1, 0xaa, PUSH1, len, PUSH1, 0, LOG1, STOP] +} + +/// `SELFDESTRUCT` in favour of [`TARGET`]. +fn selfdestruct_code() -> Vec { + let mut code = vec![PUSH20]; + code.extend_from_slice(TARGET.as_slice()); + code.push(SELFDESTRUCT); + code +} + +/// `op` (a call) to [`TARGET`] with `gas`, `value` (for `CALL` and `CALLCODE`), `in_len` bytes of +/// input at offset 0 and no output, then `STOP`. +fn call_code(op: u8, gas: u32, value: u8, in_len: u8) -> Vec { + let mut code = vec![PUSH1, 0, PUSH1, 0, PUSH1, in_len, PUSH1, 0]; + if matches!(op, CALL | CALLCODE) { + code.extend_from_slice(&[PUSH1, value]); + } + code.push(PUSH20); + code.extend_from_slice(TARGET.as_slice()); + code.push(PUSH4); + code.extend_from_slice(&gas.to_be_bytes()); + code.extend_from_slice(&[op, STOP]); + code +} + +/// The gas [`call_code`]'s pushes cost. +const fn call_pushes(op: u8) -> u64 { + if matches!(op, CALL | CALLCODE) { + 7 * 3 + } else { + 6 * 3 + } +} + +/// `op` (`CREATE` or `CREATE2`) of `len` bytes of memory at offset 0, endowed with `value`, then +/// `STOP`. +fn create_code(op: u8, len: u8, value: u8) -> Vec { + let mut code = Vec::new(); + if op == CREATE2 { + code.extend_from_slice(&[PUSH1, 0x5a]); + } + code.extend_from_slice(&[PUSH1, len, PUSH1, 0, PUSH1, value, op, STOP]); + code +} + +/// The gas [`create_code`]'s pushes cost. +const fn create_pushes(op: u8) -> u64 { + if op == CREATE2 { + 4 * 3 + } else { + 3 * 3 + } +} + +/// A write instruction under test: its name, code, the host it runs on, the write the hook sees, +/// and the result of a frame one gas short of the instruction's last charge. +type WriteCase = ( + &'static str, + Vec, + fn(SpecId) -> HookHost, + Write, + InstructionResult, +); + +/// The write instructions, each on a host that makes it charge everything it can: a cold slot set +/// from zero, a cold slot cleared, which earns a refund, a log of 32 bytes, and a cold +/// `SELFDESTRUCT` into a new account, which earns a refund before EIP-3529. +fn write_cases() -> Vec { + let destruct = SelfDestructResult { + had_value: true, + target_exists: false, + previously_destroyed: false, + }; + vec![ + ( + "SSTORE", + SSTORE_CODE.to_vec(), + |spec| HookHost::new(spec).cold(), + Write::Sstore(CONTRACT, StorageKey::ZERO, set_from_zero()), + InstructionResult::OutOfGas, + ), + ( + "SSTORE clearing a slot", + CLEAR_CODE.to_vec(), + |spec| HookHost::new(spec).cold().holding(1), + Write::Sstore( + CONTRACT, + StorageKey::ZERO, + SStoreResult { + original_value: StorageValue::from(1), + present_value: StorageValue::from(1), + new_value: StorageValue::ZERO, + }, + ), + InstructionResult::OutOfGas, + ), + ( + "LOG1", + log1_code(32), + HookHost::new, + Write::Log(CONTRACT, 1, 32), + InstructionResult::MemoryOOG, + ), + ( + "SELFDESTRUCT", + selfdestruct_code(), + |spec| HookHost::new(spec).cold().destructs_into_a_new_account(), + Write::SelfDestruct(CONTRACT, TARGET, destruct), + InstructionResult::OutOfGas, + ), + ] +} + +/// Each write instruction hands its write to the hook after its last charge: the frame ends on the +/// gas the hook was handed, so nothing is charged after it, and a frame one gas short of what the +/// instruction charges before the hook fails without reaching it. On a spec with and without +/// EIP-8037, so the last charge is the state-gas charge where there is one, and on one before +/// EIP-3529, where `SELFDESTRUCT` earns a refund. +#[test] +fn test_a_write_reaches_the_hook_after_every_charge() { + for spec in [SpecId::BERLIN, SpecId::OSAKA, SpecId::AMSTERDAM] { + for (name, code, host, write, short) in write_cases() { + let mut ample = host(spec); + let (action, gas) = run(spec, &code, AMPLE, 0, &mut ample); + let (result, _, result_gas) = returned(action); + let (seen, at_hook) = ample.write().clone(); + assert_eq!(seen, write, "{name} on {spec:?}"); + assert!(result.is_ok(), "{name} on {spec:?}: {result:?}"); + assert_eq!( + *result_gas.tracker(), + at_hook, + "{name} on {spec:?}: nothing is charged after the hook" + ); + assert_eq!(*gas.tracker(), at_hook); + let refunds = name == "SSTORE clearing a slot" + || (name == "SELFDESTRUCT" && !spec.is_enabled_in(SpecId::LONDON)); + assert_eq!( + at_hook.refunded() > 0, + refunds, + "{name} on {spec:?}: the refund is made before the hook" + ); + + // What the instruction charges before the hook reaches it with nothing left; one gas + // less does not reach it. + let needed = AMPLE - at_hook.remaining(); + let mut exact = host(spec); + let (action, _) = run(spec, &code, needed, 0, &mut exact); + assert!(returned(action).0.is_ok(), "{name} on {spec:?}"); + assert_eq!(exact.write().1.remaining(), 0, "{name} on {spec:?}"); + + let mut one_short = host(spec); + let (action, _) = run(spec, &code, needed - 1, 0, &mut one_short); + assert_eq!(returned(action).0, short, "{name} on {spec:?}"); + assert!( + !one_short.reached(), + "{name} on {spec:?}: the hook is not reached" + ); + } + } +} + +/// A failure before the hook: its name, the spec, the code, the host, the gas limit and the result +/// the frame fails with. +type FailureCase = (Name, SpecId, Vec, HookHost, u64, InstructionResult); + +/// Every earlier failure of a write instruction, a charge or a check before its last charge, ends +/// the instruction before the hook. +#[test] +fn test_a_write_that_fails_before_its_last_charge_never_reaches_the_hook() { + let osaka = GasParams::new_spec(SpecId::OSAKA); + let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); + let petersburg = GasParams::new_spec(SpecId::PETERSBURG); + let set = set_from_zero(); + let cases: Vec> = vec![ + ( + "SSTORE with the stipend left", + SpecId::OSAKA, + SSTORE_CODE.to_vec(), + HookHost::new(SpecId::OSAKA), + 6 + osaka.call_stipend(), + InstructionResult::ReentrancySentryOOG, + ), + ( + "SSTORE's static charge, before EIP-2200's stipend check", + SpecId::PETERSBURG, + SSTORE_CODE.to_vec(), + HookHost::new(SpecId::PETERSBURG), + 6 + petersburg.sstore_static_gas() - 1, + InstructionResult::OutOfGas, + ), + ( + "SSTORE's dynamic charge, before its state-gas charge", + SpecId::AMSTERDAM, + SSTORE_CODE.to_vec(), + HookHost::new(SpecId::AMSTERDAM).cold(), + 6 + amsterdam.sstore_static_gas() + amsterdam.sstore_dynamic_gas(true, &set, true) - 1, + InstructionResult::OutOfGas, + ), + ( + "SSTORE's state-gas price", + SpecId::AMSTERDAM, + SSTORE_CODE.to_vec(), + HookHost::new(SpecId::AMSTERDAM).price_fails(), + AMPLE, + InstructionResult::FatalExternalError, + ), + ( + "LOG1's log charge, before its memory", + SpecId::OSAKA, + log1_code(32), + HookHost::new(SpecId::OSAKA), + 9 + static_gas(SpecId::OSAKA, LOG1) + osaka.log_cost(1, 32) - 1, + InstructionResult::OutOfGas, + ), + ( + "SELFDESTRUCT's cold target, refused", + SpecId::OSAKA, + selfdestruct_code(), + HookHost::new(SpecId::OSAKA).cold(), + 3 + static_gas(SpecId::OSAKA, SELFDESTRUCT) + osaka.selfdestruct_cold_cost() - 1, + InstructionResult::OutOfGas, + ), + ( + "SELFDESTRUCT's charge, before its state-gas charge", + SpecId::AMSTERDAM, + selfdestruct_code(), + HookHost::new(SpecId::AMSTERDAM) + .cold() + .destructs_into_a_new_account(), + 3 + static_gas(SpecId::AMSTERDAM, SELFDESTRUCT) + + amsterdam.selfdestruct_cost(true, true) + - 1, + InstructionResult::OutOfGas, + ), + ( + "SELFDESTRUCT's state-gas price", + SpecId::AMSTERDAM, + selfdestruct_code(), + HookHost::new(SpecId::AMSTERDAM) + .destructs_into_a_new_account() + .price_fails(), + AMPLE, + InstructionResult::FatalExternalError, + ), + ]; + for (name, spec, code, mut host, gas_limit, expected) in cases { + let (action, _) = run(spec, &code, gas_limit, 0, &mut host); + assert_eq!(returned(action).0, expected, "{name}"); + assert!(!host.reached(), "{name}: the hook is not reached"); + } +} + +/// `OutOfGas` fails the instruction as a failed charge does: the frame halts out of gas, and the +/// record of what it had left is what the hook left. +/// +/// The verdict tests run on Osaka, where the write instructions charge no state gas, so the hook +/// finds the frame's reservoir of 1,000 whole: a hook charge of 1,500 spills 500 into regular gas. +#[test] +fn test_out_of_gas_fails_the_write_on_the_gas_the_hook_left() { + for (name, code, host, _, _) in write_cases() { + let mut host = host(SpecId::OSAKA) + .charging(1_500) + .answering(WriteVerdict::OutOfGas); + let (action, _) = run(SpecId::OSAKA, &code, AMPLE, 1_000, &mut host); + let (result, _, gas) = returned(action); + let at_hook = host.write().1; + + assert_eq!(result, InstructionResult::OutOfGas, "{name}"); + assert_eq!(gas.remaining(), 0, "{name}: the halt spends all"); + assert_eq!( + gas.failed_charge_remaining(), + Some(at_hook.remaining() - 500), + "{name}: the record is what the hook left" + ); + } +} + +/// A hook's own failed charge is the record the halt keeps. +#[test] +fn test_out_of_gas_after_a_failed_hook_charge_keeps_its_record() { + let mut host = HookHost::new(SpecId::OSAKA) + .charging(AMPLE) + .answering(WriteVerdict::OutOfGas); + let (action, _) = run(SpecId::OSAKA, &log1_code(32), AMPLE, 0, &mut host); + let (result, _, gas) = returned(action); + + assert_eq!(result, InstructionResult::OutOfGas); + assert_eq!( + gas.failed_charge_remaining(), + Some(host.write().1.remaining()) + ); +} + +/// `Revert` ends the frame as a `Revert` with the verdict's output, on the gas the hook left: a +/// `SELFDESTRUCT` so reverted returns `Revert`, not `SelfDestruct`. +#[test] +fn test_revert_ends_the_frame_with_the_output_on_the_gas_the_hook_left() { + for (name, code, host, _, _) in write_cases() { + let mut host = host(SpecId::OSAKA) + .charging(400) + .answering(WriteVerdict::Revert(Bytes::from_static(STOP_OUTPUT))); + let (action, _) = run(SpecId::OSAKA, &code, AMPLE, 1_000, &mut host); + let (result, output, gas) = returned(action); + let mut expected = host.write().1; + assert!(expected.record_history_cost(400)); + + assert_eq!(result, InstructionResult::Revert, "{name}"); + assert_eq!(output, Bytes::from_static(STOP_OUTPUT), "{name}"); + assert_eq!(*gas.tracker(), expected, "{name}"); + assert_eq!(gas.reservoir(), 600, "{name}: the hook's charge stands"); + } +} + +/// `Continue` ends the instruction as it would have ended, on the gas the hook left: a +/// `SELFDESTRUCT` self-destructs. +#[test] +fn test_continue_ends_the_write_on_the_gas_the_hook_left() { + for ((name, code, host, _, _), ends) in write_cases().into_iter().zip([ + InstructionResult::Stop, + InstructionResult::Stop, + InstructionResult::Stop, + InstructionResult::SelfDestruct, + ]) { + let mut host = host(SpecId::OSAKA).charging(1_500); + let (action, _) = run(SpecId::OSAKA, &code, AMPLE, 1_000, &mut host); + let (result, _, gas) = returned(action); + let at_hook = host.write().1; + + assert_eq!(result, ends, "{name}"); + assert_eq!(gas.reservoir(), 0, "{name}"); + assert_eq!(gas.remaining(), at_hook.remaining() - 500, "{name}"); + assert_eq!(gas.history_gas_spent(), 1_500, "{name}"); + } +} + +/// The six frame-starting instructions, each with what the hook sees of it: kind, caller, target +/// and value. +fn start_cases() -> Vec<(&'static str, Vec, FrameStart)> { + let value = U256::from(3); + let start = |kind, caller, target, value| FrameStart::new(kind, caller, target, value, 0); + vec![ + ( + "CALL", + call_code(CALL, 50_000, 3, 0), + start(FrameStartKind::Call, CONTRACT, Some(TARGET), value), + ), + ( + "CALLCODE", + call_code(CALLCODE, 50_000, 3, 0), + start(FrameStartKind::CallCode, CONTRACT, Some(CONTRACT), value), + ), + ( + "DELEGATECALL", + call_code(DELEGATECALL, 50_000, 0, 0), + start( + FrameStartKind::DelegateCall, + CALLER, + Some(CONTRACT), + U256::ZERO, + ), + ), + ( + "STATICCALL", + call_code(STATICCALL, 50_000, 0, 0), + start( + FrameStartKind::StaticCall, + CONTRACT, + Some(TARGET), + U256::ZERO, + ), + ), + ( + "CREATE", + create_code(CREATE, 0, 3), + start(FrameStartKind::Create, CONTRACT, None, value), + ), + ( + "CREATE2", + create_code(CREATE2, 0, 3), + start(FrameStartKind::Create2, CONTRACT, None, value), + ), + ] +} + +/// The gas limit and reservoir of a frame's input. +fn input_gas(input: &FrameInput) -> (u64, u64) { + match input { + FrameInput::Call(inputs) => (inputs.gas_limit, inputs.reservoir), + FrameInput::Create(inputs) => (inputs.gas_limit(), inputs.reservoir()), + FrameInput::Empty => panic!("an empty frame input"), + } +} + +/// Each frame-starting instruction hands its start to the hook once the forward is taken, and +/// charges nothing after it: the instruction leaves the gas the hook was handed, and the frame's +/// input carries the forward, with a value call's stipend on top. +#[test] +fn test_a_start_reaches_the_hook_with_the_forward_taken() { + let spec = SpecId::OSAKA; + let params = GasParams::new_spec(spec); + for (name, code, expected) in start_cases() { + let mut host = HookHost::new(spec); + let (action, gas) = run(spec, &code, AMPLE, 0, &mut host); + let input = started(action); + let (start, at_hook) = *host.start(); + let (gas_limit, reservoir) = input_gas(&input); + let op = code[code.len() - 2]; + let charged = if matches!(op, CREATE | CREATE2) { + create_pushes(op) + params.create_cost() + } else { + let transfer = if start.value.is_zero() { + 0 + } else { + params.transfer_value_cost() + }; + call_pushes(op) + static_gas(spec, op) + transfer + }; + let before_forward = AMPLE - charged; + let forward = if matches!(op, CREATE | CREATE2) { + before_forward - before_forward / 64 + } else { + 50_000 + }; + + let expected = FrameStart::new( + expected.kind, + expected.caller, + expected.target, + expected.value, + forward, + ); + assert_eq!(start, expected, "{name}: the start's facts"); + assert_eq!( + at_hook.remaining(), + before_forward - forward, + "{name}: the hook sees the forward taken" + ); + assert_eq!( + *gas.tracker(), + at_hook, + "{name}: nothing is charged after the hook" + ); + let stipend = if matches!(op, CALL | CALLCODE) { + params.call_stipend() + } else { + 0 + }; + assert_eq!( + gas_limit, + forward + stipend, + "{name}: the frame's gas limit" + ); + assert_eq!(reservoir, 0, "{name}"); + } +} + +/// A call's forward is the gas it names when that is below 63/64 of what the caller has left, and +/// that cap otherwise, for every kind of call. +#[test] +fn test_the_forward_is_the_named_gas_or_the_63_64_cap() { + let spec = SpecId::OSAKA; + for op in [CALL, CALLCODE, DELEGATECALL, STATICCALL] { + let charged = call_pushes(op) + static_gas(spec, op); + let left = AMPLE - charged; + for (named, forward) in [(20_000, 20_000), (u32::MAX, left - left / 64)] { + let mut host = HookHost::new(spec); + let (action, _) = run(spec, &call_code(op, named, 0, 0), AMPLE, 0, &mut host); + + assert_eq!(host.start().0.forward, forward, "{op:#x}, named {named}"); + assert_eq!( + input_gas(&started(action)).0, + forward, + "{op:#x}, named {named}" + ); + } + } +} + +/// A value call's stipend is part of the frame's gas limit but not of the forward the hook sees: +/// the caller does not pay it. +#[test] +fn test_the_value_stipend_is_not_part_of_the_forward() { + let spec = SpecId::OSAKA; + let params = GasParams::new_spec(spec); + for op in [CALL, CALLCODE] { + let mut host = HookHost::new(spec); + let (action, gas) = run(spec, &call_code(op, 20_000, 1, 0), AMPLE, 0, &mut host); + let charged = call_pushes(op) + static_gas(spec, op) + params.transfer_value_cost(); + + assert_eq!(host.start().0.forward, 20_000); + assert_eq!( + input_gas(&started(action)).0, + 20_000 + params.call_stipend() + ); + assert_eq!(gas.remaining(), AMPLE - charged - 20_000); + } +} + +/// The frame's input copies the reservoir as the hook left it, for every kind of start. A charge the +/// reservoir covers leaves the forward and the caller's regular gas alone; one that spills draws the +/// caller's regular gas and empties the reservoir, and the forward is still what was taken before. +#[test] +fn test_the_input_copies_the_reservoir_the_hook_left() { + let spec = SpecId::AMSTERDAM; + for (name, code, _) in start_cases() { + let mut quiet = HookHost::new(spec); + let (quiet_action, quiet_gas) = run(spec, &code, AMPLE, 10_000, &mut quiet); + let quiet_limit = input_gas(&started(quiet_action)).0; + + for (charge, reservoir, spilled) in [(4_000, 6_000, 0), (10_500, 0, 500)] { + let mut host = HookHost::new(spec).charging(charge); + let (action, gas) = run(spec, &code, AMPLE, 10_000, &mut host); + let (gas_limit, input_reservoir) = input_gas(&started(action)); + + assert_eq!(host.start().1.reservoir(), 10_000, "{name}"); + assert_eq!(input_reservoir, reservoir, "{name}, charge {charge}"); + assert_eq!(gas.reservoir(), reservoir, "{name}, charge {charge}"); + assert_eq!( + gas_limit, quiet_limit, + "{name}, charge {charge}: the forward" + ); + assert_eq!( + gas.remaining(), + quiet_gas.remaining() - spilled, + "{name}, charge {charge}" + ); + } + } +} + +/// `false` fails the instruction out of gas and starts no frame. The forward stays taken, so the +/// halt records what the caller had left after it. +#[test] +fn test_a_refused_start_fails_out_of_gas_and_starts_no_frame() { + for (name, code, _) in start_cases() { + let mut host = HookHost::new(SpecId::OSAKA).refusing(); + let (action, _) = run(SpecId::OSAKA, &code, AMPLE, 0, &mut host); + let (result, _, gas) = returned(action); + + assert_eq!(result, InstructionResult::OutOfGas, "{name}"); + assert_eq!( + gas.failed_charge_remaining(), + Some(host.start().1.remaining()), + "{name}" + ); + } +} + +/// Every failure of a frame-starting instruction before its forward is taken ends the instruction +/// before the hook. +#[test] +fn test_a_start_that_fails_before_the_forward_never_reaches_the_hook() { + let osaka = GasParams::new_spec(SpecId::OSAKA); + let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); + let call = |params: &GasParams, spec| { + call_pushes(CALL) + static_gas(spec, CALL) + params.transfer_value_cost() + }; + let mut cases: Vec> = Vec::new(); + for op in [CALL, CALLCODE, DELEGATECALL, STATICCALL] { + cases.push(( + format!("{op:#x}'s input memory"), + SpecId::OSAKA, + call_code(op, 1_000, 0, 32), + HookHost::new(SpecId::OSAKA), + call_pushes(op) + static_gas(SpecId::OSAKA, op) + 2, + InstructionResult::MemoryOOG, + )); + cases.push(( + format!("{op:#x}'s cold target, refused"), + SpecId::OSAKA, + call_code(op, 1_000, 0, 0), + HookHost::new(SpecId::OSAKA).cold(), + call_pushes(op) + static_gas(SpecId::OSAKA, op) + osaka.cold_account_additional_cost() + - 1, + InstructionResult::OutOfGas, + )); + } + cases.extend([ + ( + "CALL's value charge".to_string(), + SpecId::OSAKA, + call_code(CALL, 1_000, 1, 0), + HookHost::new(SpecId::OSAKA), + call(&osaka, SpecId::OSAKA) - 1, + InstructionResult::OutOfGas, + ), + ( + "CALL's account charge".to_string(), + SpecId::OSAKA, + call_code(CALL, 1_000, 1, 0), + HookHost::new(SpecId::OSAKA).cold().empty(), + call(&osaka, SpecId::OSAKA) + + osaka.cold_account_additional_cost() + + osaka.new_account_cost(true, true) + - 1, + InstructionResult::OutOfGas, + ), + ( + "CALL's state-gas charge".to_string(), + SpecId::AMSTERDAM, + call_code(CALL, 1_000, 1, 0), + HookHost::new(SpecId::AMSTERDAM).empty(), + call(&amsterdam, SpecId::AMSTERDAM) + + amsterdam.new_account_cost(true, true) + + amsterdam.get(GasId::new_account_state_gas()) + - 1, + InstructionResult::OutOfGas, + ), + ( + "CALL's state-gas price".to_string(), + SpecId::AMSTERDAM, + call_code(CALL, 1_000, 1, 0), + HookHost::new(SpecId::AMSTERDAM).empty().price_fails(), + AMPLE, + InstructionResult::FatalExternalError, + ), + ( + "CALL's forward, before EIP-150's cap".to_string(), + SpecId::HOMESTEAD, + call_code(CALL, 1_000, 0, 0), + HookHost::new(SpecId::HOMESTEAD), + call_pushes(CALL) + static_gas(SpecId::HOMESTEAD, CALL) + 999, + InstructionResult::OutOfGas, + ), + ]); + for op in [CREATE, CREATE2] { + let pushes = create_pushes(op); + let cost = if op == CREATE2 { + osaka.create2_cost(32) + } else { + osaka.create_cost() + }; + let amsterdam_cost = if op == CREATE2 { + amsterdam.create2_cost(32) + } else { + amsterdam.create_cost() + }; + cases.extend([ + ( + format!("{op:#x}'s init-code charge"), + SpecId::OSAKA, + create_code(op, 32, 0), + HookHost::new(SpecId::OSAKA), + pushes + osaka.initcode_cost(32) - 1, + InstructionResult::OutOfGas, + ), + ( + format!("{op:#x}'s memory"), + SpecId::OSAKA, + create_code(op, 32, 0), + HookHost::new(SpecId::OSAKA), + pushes + osaka.initcode_cost(32) + 2, + InstructionResult::MemoryOOG, + ), + ( + format!("{op:#x}'s creation charge"), + SpecId::OSAKA, + create_code(op, 32, 0), + HookHost::new(SpecId::OSAKA), + pushes + osaka.initcode_cost(32) + 3 + cost - 1, + InstructionResult::OutOfGas, + ), + ( + format!("{op:#x}'s state-gas charge"), + SpecId::AMSTERDAM, + create_code(op, 32, 0), + HookHost::new(SpecId::AMSTERDAM).empty(), + pushes + + amsterdam.initcode_cost(32) + + 3 + + amsterdam_cost + + amsterdam.get(GasId::create_state_gas()) + - 1, + InstructionResult::OutOfGas, + ), + ( + format!("{op:#x}'s state-gas price"), + SpecId::AMSTERDAM, + create_code(op, 32, 0), + HookHost::new(SpecId::AMSTERDAM).empty().price_fails(), + AMPLE, + InstructionResult::FatalExternalError, + ), + ]); + } + for (name, spec, code, mut host, gas_limit, expected) in cases { + let (action, _) = run(spec, &code, gas_limit, 0, &mut host); + assert_eq!(returned(action).0, expected, "{name}"); + assert!(!host.reached(), "{name}: the hook is not reached"); + } +} + +/// With exactly the gas a start needs before its forward, it reaches the hook: the cases above fail +/// on the charge they name, not on one they share. +#[test] +fn test_a_start_with_the_gas_it_needs_reaches_the_hook() { + let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); + let call = call_pushes(CALL) + + static_gas(SpecId::AMSTERDAM, CALL) + + amsterdam.transfer_value_cost() + + amsterdam.new_account_cost(true, true) + + amsterdam.get(GasId::new_account_state_gas()); + let create = create_pushes(CREATE) + + amsterdam.initcode_cost(32) + + 3 + + amsterdam.create_cost() + + amsterdam.get(GasId::create_state_gas()); + for (name, code, gas_limit) in [ + ("CALL", call_code(CALL, 1_000, 1, 0), call), + ("CREATE", create_code(CREATE, 32, 0), create), + ] { + let mut host = HookHost::new(SpecId::AMSTERDAM).empty(); + let (action, _) = run(SpecId::AMSTERDAM, &code, gas_limit, 0, &mut host); + + let _ = started(action); + assert_eq!( + host.start().0.forward, + 0, + "{name}: nothing is left to forward" + ); + } +} From 7c6172e996318ae51a9bd42e10808e5c4ebf6323 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 20 Oct 2026 23:58:48 +0800 Subject: [PATCH 003/110] docs: the completed-write and frame-start hooks in MEGAETH-FORK.md Two entries in "Hooks", in the section's format: - Completed-write hook: `Host::write_completed`, called by SSTORE, LOG0-LOG4 and SELFDESTRUCT after every charge they make, refunds included, so only on their success path; the verdicts and what each does to the frame. - Frame-start hook: `Host::frame_starting`, called by the call and creation instructions after the forward and before the input is built; what the start's facts are, and what `true` and `false` do. Both say the hook may debit and credit the tracker it is handed and the instruction uses it as the hook left it, that a charge the hook fails records as any failed charge does, and what the defaults cost where measured: nothing for the write sites and the creations, one store per call. The failed-charge record's entry and its doc comments now list a hook's out-of-gas among the halts the interpreter records. --- MEGAETH-FORK.md | 29 ++++++++++++++++++- .../interface/src/cfg/gas/failed_charge.rs | 4 ++- crates/interpreter/src/gas/failed_charge.rs | 6 ++-- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 4fbd4af500..0d65bf30e9 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -138,7 +138,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - a regular charge (`record_regular_cost`, `record_cost_unsafe`), whether or not the withheld part would have paid it; - a state or history charge whose spill past the reservoir regular gas cannot pay (`record_state_cost`, `record_history_cost`), whether the reservoir paid nothing or part of it; the record is regular gas alone, and the reservoir is left as it was; - a forward to a child that regular gas cannot pay (`record_withheld_first_cost`), which only a call before EIP-150 can fail; - - an out-of-gas halt of the interpreter with no record there, before the halt zeroes the frame's gas: a cold access the instruction refused before its charge because the frame could not pay it (an account read, `SLOAD`, `SSTORE`, `SELFDESTRUCT`, a call's target and the account it delegates to), or an out-of-gas a consumer's instruction returned itself; a record already there is the failure that caused the halt, and is kept; + - an out-of-gas halt of the interpreter with no record there, before the halt zeroes the frame's gas: a cold access the instruction refused before its charge because the frame could not pay it (an account read, `SLOAD`, `SSTORE`, `SELFDESTRUCT`, a call's target and the account it delegates to), an out-of-gas a consumer's instruction returned itself, or one an instruction hook asked for (see Completed-write hook and Frame-start hook); a record already there is the failure that caused the halt, and is kept; - a precompile run that needs more gas than the frame has: the frame's whole gas limit, as nothing ran. The failed deduction took nothing, so the record is all the regular gas the frame had; the unchecked charge records it before the spendable part wraps, and a failure with nothing left records `Some(0)`. @@ -204,6 +204,33 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Removal.** When no consumer needs to reproduce revm 40.0.3's journal. - **Default.** Off, which is the picked behaviour; the journal reads one `bool` when it warms a cold slot and when it records a code change. +### Completed-write hook + +- **API.** `Host::write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, whose default continues. + `CompletedWrite` (`#[non_exhaustive]`: `Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. +- **Contract.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call it once the write is in the journal and every charge the instruction makes has been made, its refund included, so only on the instruction's success path, on the plain and the inspected path. + `gas` is the running frame's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook. A charge the hook makes that fails records as any failed charge does (see The failed-charge record), whatever the verdict. + `Continue` ends the instruction as it would have ended. `OutOfGas` fails it as a failed charge does: the frame halts out of gas, and the halt records the regular gas the hook left unless a failed charge already did. `Revert(output)` ends the frame as a `Revert` with `output`, on its gas as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct. + Only these instructions call it: a write the journal records any other way (a value transfer and its log, deployed code, an inspector's or a precompile's write) is not offered. +- **Consumer.** mega-evm meters each completed write against its per-transaction limits and charges its history. Without the hook it wraps the three instructions and stages what its `Host` saw. +- **Removal.** When upstream exposes an equivalent point, or when mega-evm stops metering writes. +- **Default.** Continues and touches nothing; the facts are references to values the instruction holds anyway. + Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook, and `SELFDESTRUCT`'s is laid out differently and runs one instruction fewer. + +### Frame-start hook + +- **API.** `Host::frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. + `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`) and `FrameStartKind`, in `revm_context_interface::host`. +- **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. + `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`; `target` is the account the frame runs as, `None` for a creation. + `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. + `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. + A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. +- **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. +- **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. +- **Default.** Returns `true` and touches nothing. + Where measured (callgrind, the fork's release profile), `CREATE` and `CREATE2` compile to the same code as without the hook, and a call runs one instruction more: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. + ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. diff --git a/crates/context/interface/src/cfg/gas/failed_charge.rs b/crates/context/interface/src/cfg/gas/failed_charge.rs index 25a2ae6c3f..9bd7b02c71 100644 --- a/crates/context/interface/src/cfg/gas/failed_charge.rs +++ b/crates/context/interface/src/cfg/gas/failed_charge.rs @@ -28,7 +28,9 @@ impl GasTracker { /// /// The interpreter records it too when it halts a frame out of gas with no record there: a /// cold access the instruction refused before its charge, because the frame could not pay it, - /// or an out-of-gas a consumer's instruction returned itself. The handler records it where a + /// an out-of-gas a consumer's instruction returned itself, or one an instruction hook asked + /// for ([`Host::write_completed`](crate::Host::write_completed), + /// [`Host::frame_starting`](crate::Host::frame_starting)). The handler records it where a /// precompile runs out of gas: the frame's whole gas limit, as nothing ran. A consumer that /// builds an out-of-gas result itself can record the same with /// [`set_failed_charge_remaining`](Self::set_failed_charge_remaining). diff --git a/crates/interpreter/src/gas/failed_charge.rs b/crates/interpreter/src/gas/failed_charge.rs index e85117aab9..26674fafcf 100644 --- a/crates/interpreter/src/gas/failed_charge.rs +++ b/crates/interpreter/src/gas/failed_charge.rs @@ -37,8 +37,10 @@ impl Gas { /// failure that caused this halt, and it is kept; the unchecked charge's record also holds /// the regular gas from before the spendable part wrapped. With none there, nothing failed: /// the halt is a cold access the instruction refused before its charge, because the frame - /// could not pay it, or an out-of-gas a consumer's instruction returned itself. Either way the - /// regular gas is as it was when the frame stopped. + /// could not pay it, an out-of-gas a consumer's instruction returned itself, or one an + /// instruction hook asked for ([`Host::write_completed`](crate::Host::write_completed), + /// [`Host::frame_starting`](crate::Host::frame_starting)). Either way the regular gas is as it + /// was when the frame stopped. #[inline] pub(crate) const fn record_out_of_gas_halt(&mut self) { if self.failed_charge_remaining().is_none() { From 84f4bf056b0aa2be69f3d69ef85099dbc2eb8aa7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 00:45:25 +0800 Subject: [PATCH 004/110] refactor: keep the instruction-hook kinds exhaustive `CompletedWrite` loses `#[non_exhaustive]`, and `FrameStartKind` stays without it. mega-evm matches both for consensus metering; a non-exhaustive enum forces it a wildcard arm, through which a kind added later would pass un-metered without a compile error. Exhaustive, a new kind is a compile error in every consumer that matches it, and adding one is a deliberate breaking change. Each enum's doc says so. `FrameStart` keeps `#[non_exhaustive]`: it is read through its fields and built with `FrameStart::new`, so a later field is not breaking. The tests' `Write::of` drops its wildcard arm, which no longer compiles cleanly, and now matches `CompletedWrite` exhaustively from outside the crate: putting the attribute back fails it with E0004. --- crates/context/interface/src/host/instruction_hooks.rs | 7 ++++++- crates/inspector/tests/instruction_hooks.rs | 1 - crates/interpreter/tests/instruction_hooks.rs | 1 - 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index fedee80558..b69adf7517 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -11,8 +11,10 @@ use primitives::{Address, Bytes, StorageKey, U256}; /// A state write an instruction completed: the write is in the journal, and every charge the /// instruction makes has been made. +/// +/// Exhaustive on purpose: a new variant is a breaking change, so that every consumer handles every +/// kind of write. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] pub enum CompletedWrite<'a> { /// `SSTORE` wrote slot `key` of `address`. Sstore { @@ -56,6 +58,9 @@ pub enum WriteVerdict { } /// The kind of frame an instruction is about to start. +/// +/// Exhaustive on purpose: a new variant is a breaking change, so that every consumer handles every +/// kind of start. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum FrameStartKind { /// `CALL`. diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index 3907270fe7..9ae6f2623e 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -82,7 +82,6 @@ impl Write { target, result, } => Self::SelfDestruct(address, target, result.clone()), - other => panic!("a write this test does not know: {other:?}"), } } diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index 94a6cc6427..c0aa1fea44 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -67,7 +67,6 @@ impl Write { target, result, } => Self::SelfDestruct(address, target, result.clone()), - other => panic!("a write this test does not know: {other:?}"), } } } From 6147a76d5f5963592359e06dc4aa6c179781e141 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 00:45:25 +0800 Subject: [PATCH 005/110] docs: the instruction-hook kinds are exhaustive in MEGAETH-FORK.md The completed-write and frame-start entries drop `#[non_exhaustive]` for `CompletedWrite`, list `FrameStartKind`'s kinds, and say both enums are exhaustive on purpose: mega-evm matches them to meter each write and charge each start, so a new kind is a compile error in every consumer rather than a kind that passes a wildcard arm unmetered, and adding one is an `api:exception` change. --- MEGAETH-FORK.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 0d65bf30e9..073c65f20b 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -207,7 +207,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th ### Completed-write hook - **API.** `Host::write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, whose default continues. - `CompletedWrite` (`#[non_exhaustive]`: `Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. + `CompletedWrite` (`Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. + `CompletedWrite` is exhaustive on purpose: mega-evm matches it to meter each write, so a new kind is a compile error in every consumer that matches it rather than a write that passes a wildcard arm un-metered, and adding one is an `api:exception` change. - **Contract.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call it once the write is in the journal and every charge the instruction makes has been made, its refund included, so only on the instruction's success path, on the plain and the inspected path. `gas` is the running frame's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook. A charge the hook makes that fails records as any failed charge does (see The failed-charge record), whatever the verdict. `Continue` ends the instruction as it would have ended. `OutOfGas` fails it as a failed charge does: the frame halts out of gas, and the halt records the regular gas the hook left unless a failed charge already did. `Revert(output)` ends the frame as a `Revert` with `output`, on its gas as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct. @@ -220,7 +221,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th ### Frame-start hook - **API.** `Host::frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. - `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`) and `FrameStartKind`, in `revm_context_interface::host`. + `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. + `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`; `target` is the account the frame runs as, `None` for a creation. `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. From f3a4e91c72191dcaea78d10dc1c4f5c5c0bc8707 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 09:32:01 +0800 Subject: [PATCH 006/110] docs: precompiles defined outside the fork price themselves from the run they wrap The "Precompile price" entry's Coverage bullet said the port to the op-revm fork was outstanding. That fork has done it: at v20.0.0-mega.3 its nine size-limited wrappers (bn254_pair::{GRANITE, JOVIAN, KARST} and bls12_381::{ISTHMUS, JOVIAN}_{G1_MSM, G2_MSM, PAIRING}) each carry a price function set with `with_required_gas`, guarded by its `tests/required_gas.rs`. The note becomes the rule it stood for, since this doc carries rules and not dated history: a precompile defined outside this repository that wraps a revm run must price itself from the run it wraps, as the op-revm fork's size-limited wrappers do, with a pointer to that fork's "Precompile prices" entry for their guard. --- MEGAETH-FORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 073c65f20b..296b33f339 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -170,7 +170,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Coverage.** Every precompile the crate defines carries its price function, so every precompile of every set `Precompiles::new` returns answers. A precompile built with `Precompile::new` carries none and answers `None`. A precompile that wraps a built-in must price itself from the price function of the run it wraps, and price its own refusals at `0`; `with_required_gas`'s documentation shows the pattern, and such a wrapper needs a differential test against its own run. - Outstanding: the port to the op-revm fork. At `v20.0.0-mega.2` its nine size-limited wrappers (the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and pairing, across its hardforks) are built with `Precompile::new` and answer `None`. + A precompile defined outside this repository that wraps a revm run must price itself from the run it wraps, as the op-revm fork's size-limited wrappers do; that fork's `MEGAETH-FORK.md` ("Precompile prices") carries their guard. - **Guard.** `ecrecover`, `sha256`, `ripemd160` and `blake2f` repeat literals their runs keep private; the differential test `required_gas_matches_every_builtin_run`, run under every backend, fails when a run's gas changes and its price does not. - **Consumer.** mega-evm holds a precompile call to an allowance below its forward and must tell a crossing from a plain out-of-gas without running it. A precompile's gas rule is private to its run. - **Removal.** When upstream exposes a precompile's price before the run, or when mega-evm stops holding precompile calls to an allowance. From 6df166509e623ba3d128c5ac8511b7b92534e0c8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:19:05 +0800 Subject: [PATCH 007/110] feat(gas): a byte pool, a history allowance and a start-charge carrier on GasTracker The byte pool is a budget of bytes a frame may append: bytes_remaining, unlimited by default, drawn by record_bytes, given back by refill_bytes, taken out for a child by forward_bytes and added back by absorb_returned_bytes. Its net, bytes_spent, is signed as history gas is, so rollback_state_gas gives a failing frame's draws back and a merge hands a successful frame's net on. A draw the pool cannot pay records a BytesCrossing on the failure side. The history allowance is history gas a frame may spend before it charges its budget; draw_history_allowance takes it first and returns the rest. The start charge is what the frame-start hook declares it charged the caller for the frame and the frame's failure gives back; the instruction takes it off the tracker and puts it on the frame's input. Nothing in the workspace draws any of the three, so a consumer that sets nothing sees upstream's behaviour. The tracker is 136 bytes. --- crates/context/interface/src/cfg/gas.rs | 68 ++- .../interface/src/cfg/gas/byte_pool.rs | 428 ++++++++++++++++++ .../src/cfg/gas/history_allowance.rs | 99 ++++ .../interface/src/cfg/gas/start_charge.rs | 105 +++++ .../context/interface/src/cfg/gas/withheld.rs | 14 +- 5 files changed, 707 insertions(+), 7 deletions(-) create mode 100644 crates/context/interface/src/cfg/gas/byte_pool.rs create mode 100644 crates/context/interface/src/cfg/gas/history_allowance.rs create mode 100644 crates/context/interface/src/cfg/gas/start_charge.rs diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 8582e8ae8a..1737bedf17 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -3,9 +3,14 @@ use crate::{cfg::gas_params, cfg::GasParams, Transaction}; use primitives::hardfork::SpecId; +mod byte_pool; mod failed_charge; +mod history_allowance; +mod start_charge; mod withheld; +pub use byte_pool::BytesCrossing; +pub use start_charge::StartCharge; pub use withheld::WithheldCrossing; /// Tracker for gas during execution. @@ -47,6 +52,12 @@ pub use withheld::WithheldCrossing; /// spendable part, so a consumer that caps a creating frame must not release before /// `return_create`, or those charges escape the cap. /// +/// Beside the gas, the tracker carries three figures of the fork that are inert until a consumer +/// uses them: the byte pool ([`bytes_remaining`](Self::bytes_remaining), unlimited by default, +/// forwarded to a child frame and settled with its gas), the history allowance +/// ([`history_allowance`](Self::history_allowance), zero by default) and the start charge the +/// frame-start hook declares ([`start_charge`](Self::start_charge), zero outside the hook). +/// /// The net counters (`state_gas_spent`, `history_gas_spent`) are `i64`, while charges and refills /// take `u64` amounts and convert them with saturation. The tracker assumes that the transaction /// gas limit, and so any single charge or refill and the state plus history net a rollback adds @@ -55,7 +66,7 @@ pub use withheld::WithheldCrossing; /// checks it. Above it, a rollback no longer restores the reservoir exactly and can burn or mint /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct GasTracker { /// Gas Limit, @@ -139,6 +150,50 @@ pub struct GasTracker { /// Encodings made before this field existed decode it as `None`. #[cfg_attr(feature = "serde", serde(default))] failed_charge_remaining: Option, + /// The byte pool ([`bytes_remaining`](Self::bytes_remaining)): what this frame may still + /// draw. Unlimited unless a consumer sets a pool; nothing in this workspace draws it. + /// + /// Encodings made before this field existed decode it as unlimited. + #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] + bytes_remaining: u64, + /// The frame's net draw of the pool ([`bytes_spent`](Self::bytes_spent)), signed as + /// `history_gas_spent` is, so a rollback can give it back and a merge can hand it on. + /// + /// Encodings made before this field existed decode it as zero. + #[cfg_attr(feature = "serde", serde(default))] + bytes_spent: i64, + /// The record of the last draw the pool could not pay + /// ([`bytes_crossing`](Self::bytes_crossing)). One word, since a failed draw is never zero. + /// + /// Encodings made before this field existed decode it as `None`. + #[cfg_attr(feature = "serde", serde(default))] + bytes_crossing: Option, + /// History gas this frame may spend before it charges its budget + /// ([`history_allowance`](Self::history_allowance)). Zero unless the schedule gives a value + /// call's child one. + /// + /// Encodings made before this field existed decode it as zero. + #[cfg_attr(feature = "serde", serde(default))] + history_allowance: u64, + /// The start charge the frame-start hook declared and the instruction has not yet taken + /// ([`start_charge`](Self::start_charge)). A carrier between the hook and the instruction, + /// zero at every other time, so it is not part of an encoded tracker. + #[cfg_attr(feature = "serde", serde(skip))] + start_charge: StartCharge, +} + +/// The pool a tracker starts with, and an encoding that predates the pool decodes to. +#[cfg(feature = "serde")] +const fn unlimited_bytes() -> u64 { + u64::MAX +} + +impl Default for GasTracker { + /// A tracker with no gas, as [`new`](Self::new) builds it, so the pool starts unlimited. + #[inline] + fn default() -> Self { + Self::new(0, 0, 0) + } } impl GasTracker { @@ -156,6 +211,11 @@ impl GasTracker { withheld: 0, withheld_crossing: None, failed_charge_remaining: None, + bytes_remaining: u64::MAX, + bytes_spent: 0, + bytes_crossing: None, + history_allowance: 0, + start_charge: StartCharge::new(0, 0), } } @@ -444,6 +504,11 @@ impl GasTracker { /// pays for bytes the failing frame no longer appends. The term is zero on any chain that /// never calls [`record_history_cost`](Self::record_history_cost). /// + /// The byte pool unwinds here too: the frame's net draw ([`bytes_spent`](Self::bytes_spent)) + /// goes back to the pool, which then reads as the pool the frame started with, for the same + /// reason, and the term is zero on any chain that never calls + /// [`record_bytes`](Self::record_bytes). + /// /// On revert the resulting `remaining` (including the refilled spill) is /// returned to the parent; on halt the caller additionally zeroes `remaining` /// so the spilled gas is consumed while the reservoir is left untouched. @@ -461,6 +526,7 @@ impl GasTracker { self.state_gas_spent = 0; self.state_gas_spilled = 0; self.history_gas_spent = 0; + self.rollback_bytes(); } /// Refills the reservoir with state gas that is returned by 0→x→0 storage diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs new file mode 100644 index 0000000000..e1bced4612 --- /dev/null +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -0,0 +1,428 @@ +//! The byte pool of a [`GasTracker`]: a budget of bytes a frame may append, forwarded to a child +//! frame and settled with the frame's gas. +//! +//! The pool is a figure beside the gas: `bytes_remaining` is what the frame may still draw, and +//! `bytes_spent` is the frame's net draw so far, signed as the state and history nets are. A draw +//! ([`record_bytes`](GasTracker::record_bytes)) the pool cannot pay fails, takes nothing and leaves +//! a [`BytesCrossing`]. A frame that reverts or halts gives its draws back +//! ([`rollback_state_gas`](GasTracker::rollback_state_gas)), and a frame that succeeds hands its +//! net to its caller, so a caller's rollback undoes its children's draws too. The pool starts +//! unlimited (`u64::MAX`), and nothing in this workspace draws it, so a consumer that sets no pool +//! sees nothing of it. + +use super::{saturating_signed, GasTracker}; +use core::num::NonZeroU64; + +/// A draw of the byte pool that the pool could not pay. +/// +/// Recorded by [`GasTracker::record_bytes`] when `cost > bytes_remaining`. The failed draw took +/// nothing, so the pool is as it was before it; the record says that a draw failed, and what it +/// asked for. A consumer reads it from a halted frame's result to tell a frame that ran out of +/// bytes from one that ran out of gas, and turns it into a stop of its own class. +/// +/// A draw of zero never fails, so the cost is never zero and `Option` takes no more +/// room than a `u64`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct BytesCrossing { + /// The bytes the failed draw asked for. + cost: NonZeroU64, +} + +impl BytesCrossing { + /// A record of a failed draw of `cost` bytes. + /// + /// The tracker makes its own records. This is for a consumer that marks a result it produced + /// outside the tracker as a failed draw, and puts the record on the tracker with + /// [`GasTracker::set_bytes_crossing`]. + #[inline] + pub const fn with_cost(cost: NonZeroU64) -> Self { + Self { cost } + } + + /// The bytes the failed draw asked for. Never zero. + #[inline] + pub const fn cost(&self) -> u64 { + self.cost.get() + } +} + +impl GasTracker { + /// The byte pool: what this frame may still draw. + /// + /// Starts at `u64::MAX`, an unlimited pool, in every tracker. A consumer that limits bytes + /// sets the transaction's pool ([`set_bytes_remaining`](Self::set_bytes_remaining)); every + /// child frame then receives a share of its caller's pool when it starts, and the caller keeps + /// the rest. + #[inline] + pub const fn bytes_remaining(&self) -> u64 { + self.bytes_remaining + } + + /// Sets the byte pool. The net draw ([`bytes_spent`](Self::bytes_spent)) is left as it is. + #[inline] + pub const fn set_bytes_remaining(&mut self, val: u64) { + self.bytes_remaining = val; + } + + /// The frame's net draw of the pool so far: draws less refills, plus the nets of the children + /// that succeeded. + /// + /// Negative while the frame has refilled more than it drew, as + /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. + #[inline] + pub const fn bytes_spent(&self) -> i64 { + self.bytes_spent + } + + /// Sets the net draw. + #[inline] + pub const fn set_bytes_spent(&mut self, val: i64) { + self.bytes_spent = val; + } + + /// Adds `delta` to the net draw, saturating. Used to merge a successful child's net into its + /// caller, so a later rollback of the caller undoes the child's draws too. + #[inline] + pub const fn add_bytes_spent(&mut self, delta: i64) { + self.bytes_spent = self.bytes_spent.saturating_add(delta); + } + + /// Draws `cost` bytes from the pool. + /// + /// Returns `false` if the pool cannot pay, leaving it untouched and recording a + /// [`BytesCrossing`] ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always + /// succeeds. The draw is counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives + /// it back. + #[inline] + #[must_use = "a draw the pool cannot pay is the consumer's stop"] + pub const fn record_bytes(&mut self, cost: u64) -> bool { + if let Some(left) = self.bytes_remaining.checked_sub(cost) { + self.bytes_remaining = left; + self.bytes_spent = self.bytes_spent.saturating_add(saturating_signed(cost)); + return true; + } + self.bytes_draw_failed(cost); + false + } + + /// Gives `amount` bytes back to the pool, for a draw the frame took back. + /// + /// The net draw falls by the same amount, below zero when the matching draw was a caller's, + /// which the merge on return reconciles, as [`refill_history`](Self::refill_history) does. + #[inline] + pub const fn refill_bytes(&mut self, amount: u64) { + self.bytes_remaining = self.bytes_remaining.saturating_add(amount); + self.bytes_spent = self.bytes_spent.saturating_sub(saturating_signed(amount)); + } + + /// Takes `share` out of the pool for a child frame, which starts with it as its pool. + /// + /// Not a draw: the net is unchanged, since the share comes back when the child returns + /// ([`absorb_returned_bytes`](Self::absorb_returned_bytes)). `share` is at most the pool, + /// which the schedule's forward share guarantees; more saturates at an empty pool. + #[inline] + pub const fn forward_bytes(&mut self, share: u64) { + self.bytes_remaining = self.bytes_remaining.saturating_sub(share); + } + + /// Adds back what a returning child left of its pool: its remaining pool when it succeeded, + /// the whole share it was given when it reverted or halted, since its rollback restored it. + #[inline] + pub const fn absorb_returned_bytes(&mut self, remaining: u64) { + self.bytes_remaining = self.bytes_remaining.saturating_add(remaining); + } + + /// The record of the last draw the pool could not pay, since the record was last cleared, or + /// one a consumer set with [`set_bytes_crossing`](Self::set_bytes_crossing); whichever was + /// written last. + /// + /// The failed draw took nothing, and no halt touches the pool, so the pool itself still reads + /// as it was at the failure until the frame's rollback. The record survives + /// [`spend_all`](Self::spend_all), starts empty in every child, and is not taken over by a + /// caller. + #[inline] + pub const fn bytes_crossing(&self) -> Option { + self.bytes_crossing + } + + /// Clears the record returned by [`bytes_crossing`](Self::bytes_crossing). + #[inline] + pub const fn clear_bytes_crossing(&mut self) { + self.bytes_crossing = None; + } + + /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing), replacing any record + /// already there; `None` clears it. The pool is left as it is. + /// + /// For a consumer that marks a result it produced itself, such as an answer it gave without + /// running a frame, as a failed draw, so a classifier reading the record treats it as one the + /// tracker recorded. + #[inline] + pub const fn set_bytes_crossing(&mut self, crossing: Option) { + self.bytes_crossing = crossing; + } + + /// Gives the frame's net draw back to the pool, which then reads as the pool the frame + /// started with, and zeroes the net. Part of [`rollback_state_gas`](Self::rollback_state_gas). + #[inline] + pub(super) const fn rollback_bytes(&mut self) { + self.bytes_remaining = self.bytes_remaining.saturating_add_signed(self.bytes_spent); + self.bytes_spent = 0; + } + + /// Records a draw of `cost` the pool could not pay. Only called on the failure side of + /// [`record_bytes`](Self::record_bytes), where `cost > bytes_remaining >= 0`, so the cost is + /// never zero and the success side does not pay for the record. + #[cold] + #[inline(never)] + const fn bytes_draw_failed(&mut self, cost: u64) { + if let Some(cost) = NonZeroU64::new(cost) { + self.bytes_crossing = Some(BytesCrossing::with_cost(cost)); + } + } +} + +#[cfg(test)] +mod tests { + use super::{BytesCrossing, GasTracker}; + use core::num::NonZeroU64; + + /// A tracker with a pool of 1,000 bytes. + fn pool_1000() -> GasTracker { + let mut tracker = GasTracker::new(1_000, 1_000, 300); + tracker.set_bytes_remaining(1_000); + tracker + } + + fn crossing(tracker: &GasTracker) -> Option { + tracker.bytes_crossing().map(|crossing| crossing.cost()) + } + + /// Every tracker starts with an unlimited pool, nothing drawn and no record; `Default` is + /// `new(0, 0, 0)`. + #[test] + fn test_a_new_tracker_has_an_unlimited_pool() { + let tracker = GasTracker::new(1_000, 1_000, 300); + assert_eq!(tracker.bytes_remaining(), u64::MAX); + assert_eq!(tracker.bytes_spent(), 0); + assert_eq!(tracker.bytes_crossing(), None); + assert_eq!(GasTracker::default(), GasTracker::new(0, 0, 0)); + assert_eq!(GasTracker::default().bytes_remaining(), u64::MAX); + } + + /// An absent record takes no extra room. + #[test] + fn test_an_absent_crossing_takes_no_extra_room() { + assert_eq!( + core::mem::size_of::>(), + core::mem::size_of::() + ); + } + + #[test] + fn test_record_bytes_draws_the_pool_and_counts_the_draw() { + let mut tracker = pool_1000(); + + assert!(tracker.record_bytes(300)); + assert!(tracker.record_bytes(200)); + + assert_eq!(tracker.bytes_remaining(), 500); + assert_eq!(tracker.bytes_spent(), 500); + assert_eq!(tracker.bytes_crossing(), None); + } + + /// A draw the pool cannot pay takes nothing and leaves a record of what it asked for. + #[test] + fn test_a_draw_beyond_the_pool_fails_and_records_the_crossing() { + let mut tracker = pool_1000(); + assert!(tracker.record_bytes(900)); + + assert!(!tracker.record_bytes(101)); + + assert_eq!( + tracker.bytes_remaining(), + 100, + "the failed draw took nothing" + ); + assert_eq!(tracker.bytes_spent(), 900); + assert_eq!(crossing(&tracker), Some(101)); + } + + /// A draw of exactly the pool succeeds, and a draw of zero succeeds on an empty pool. + #[test] + fn test_a_draw_of_the_whole_pool_succeeds_and_zero_always_does() { + let mut tracker = pool_1000(); + assert!(tracker.record_bytes(1_000)); + assert_eq!(tracker.bytes_remaining(), 0); + assert!(tracker.record_bytes(0)); + assert_eq!(tracker.bytes_crossing(), None); + assert!(!tracker.record_bytes(1)); + assert_eq!(crossing(&tracker), Some(1)); + } + + /// The record stays until it is cleared: a later draw that succeeds leaves it, a later failed + /// draw replaces it, and a consumer clears or sets it. + #[test] + fn test_the_record_stays_until_cleared_and_the_last_failure_wins() { + let mut tracker = pool_1000(); + assert!(!tracker.record_bytes(1_001)); + assert!(tracker.record_bytes(10)); + assert_eq!(crossing(&tracker), Some(1_001)); + + assert!(!tracker.record_bytes(2_000)); + assert_eq!(crossing(&tracker), Some(2_000)); + + tracker.clear_bytes_crossing(); + assert_eq!(tracker.bytes_crossing(), None); + + let set = BytesCrossing::with_cost(NonZeroU64::new(7).unwrap()); + tracker.set_bytes_crossing(Some(set)); + assert_eq!(tracker.bytes_crossing(), Some(set)); + assert_eq!( + tracker.bytes_remaining(), + 990, + "setting the record leaves the pool" + ); + } + + /// The halt that follows a failed draw zeroes the regular gas and nothing else: the record + /// and the pool are still readable after it. + #[test] + fn test_the_record_and_the_pool_survive_spend_all() { + let mut tracker = pool_1000(); + assert!(tracker.record_bytes(600)); + assert!(!tracker.record_bytes(500)); + + tracker.spend_all(); + + assert_eq!(tracker.remaining(), 0); + assert_eq!(tracker.bytes_remaining(), 400); + assert_eq!(crossing(&tracker), Some(500)); + } + + /// A refill gives bytes back and lowers the net, below zero when the draw was a caller's. + #[test] + fn test_refill_bytes_gives_bytes_back_and_can_take_the_net_below_zero() { + let mut tracker = pool_1000(); + assert!(tracker.record_bytes(300)); + + tracker.refill_bytes(500); + + assert_eq!(tracker.bytes_remaining(), 1_200); + assert_eq!(tracker.bytes_spent(), -200); + } + + /// Rolling a frame back gives its net draw back, so the pool reads as the pool the frame + /// started with, and nothing else of the rollback changes. + #[test] + fn test_rollback_restores_the_pool_the_frame_started_with() { + let mut tracker = pool_1000(); + assert!(tracker.record_state_cost(200)); + assert!(tracker.record_bytes(300)); + tracker.refill_bytes(100); + assert!(tracker.record_bytes(50)); + assert_eq!(tracker.bytes_remaining(), 750); + + tracker.rollback_state_gas(); + + assert_eq!(tracker.bytes_remaining(), 1_000); + assert_eq!(tracker.bytes_spent(), 0); + assert_eq!(tracker.reservoir(), 300, "the state rollback is as it was"); + assert_eq!(tracker.state_gas_spent(), 0); + } + + /// A rollback of a frame that refilled a caller's draw takes the refill back out. + #[test] + fn test_rollback_undoes_a_refill_of_a_callers_draw() { + let mut tracker = pool_1000(); + tracker.refill_bytes(100); + assert_eq!(tracker.bytes_remaining(), 1_100); + + tracker.rollback_state_gas(); + + assert_eq!(tracker.bytes_remaining(), 1_000); + assert_eq!(tracker.bytes_spent(), 0); + } + + /// The forward takes the share out of the pool without counting it as a draw; the child's + /// return adds back what it left. + #[test] + fn test_forward_takes_the_share_and_the_return_adds_back_what_the_child_left() { + let mut parent = pool_1000(); + parent.forward_bytes(980); + assert_eq!(parent.bytes_remaining(), 20); + assert_eq!(parent.bytes_spent(), 0, "a forward is not a draw"); + + parent.absorb_returned_bytes(700); + assert_eq!(parent.bytes_remaining(), 720); + } + + /// A forward above the pool and a return above `u64::MAX` saturate rather than wrap. + #[test] + fn test_forward_and_return_saturate() { + let mut tracker = pool_1000(); + tracker.forward_bytes(5_000); + assert_eq!(tracker.bytes_remaining(), 0); + + let mut unlimited = GasTracker::new(1, 1, 0); + unlimited.absorb_returned_bytes(1); + assert_eq!(unlimited.bytes_remaining(), u64::MAX); + } + + /// With the default pool, forwarding the whole pool and settling a child's return brings the + /// caller back to the pool less what the child drew and kept: a failed child's draws come + /// back whole. + #[test] + fn test_an_unlimited_pool_forwarded_whole_comes_back_less_the_childs_draws() { + for fails in [false, true] { + let mut parent = GasTracker::new(1_000, 1_000, 0); + let share = parent.bytes_remaining(); + parent.forward_bytes(share); + assert_eq!(parent.bytes_remaining(), 0); + + let mut child = GasTracker::new(500, 500, 0); + child.set_bytes_remaining(share); + assert!(child.record_bytes(100)); + if fails { + child.rollback_state_gas(); + } else { + parent.add_bytes_spent(child.bytes_spent()); + } + parent.absorb_returned_bytes(child.bytes_remaining()); + + let (pool, spent) = if fails { + (u64::MAX, 0) + } else { + (u64::MAX - 100, 100) + }; + assert_eq!(parent.bytes_remaining(), pool, "fails: {fails}"); + assert_eq!(parent.bytes_spent(), spent, "fails: {fails}"); + } + } + + /// Encodings made before the pool existed decode with an unlimited pool, nothing drawn and no + /// record; the pool's own encoding round-trips. + #[cfg(feature = "serde")] + #[test] + fn test_serde_round_trip_and_older_payloads() { + let mut tracker = pool_1000(); + assert!(tracker.record_bytes(300)); + assert!(!tracker.record_bytes(800)); + let encoded = serde_json::to_value(tracker).unwrap(); + assert_eq!( + serde_json::from_value::(encoded.clone()).unwrap(), + tracker + ); + + let mut older = encoded; + let fields = older.as_object_mut().unwrap(); + fields.remove("bytes_remaining"); + fields.remove("bytes_spent"); + fields.remove("bytes_crossing"); + let decoded = serde_json::from_value::(older).unwrap(); + assert_eq!(decoded.bytes_remaining(), u64::MAX); + assert_eq!(decoded.bytes_spent(), 0); + assert_eq!(decoded.bytes_crossing(), None); + } +} diff --git a/crates/context/interface/src/cfg/gas/history_allowance.rs b/crates/context/interface/src/cfg/gas/history_allowance.rs new file mode 100644 index 0000000000..e9ba102516 --- /dev/null +++ b/crates/context/interface/src/cfg/gas/history_allowance.rs @@ -0,0 +1,99 @@ +//! The history allowance of a [`GasTracker`]: history gas a frame may spend before it charges +//! its budget. +//! +//! The fork sets it on a value call's child, from the schedule's `call_history_allowance`, where +//! it adds the call stipend; it is zero on every schedule defined here and in every other frame. +//! Nothing in this workspace draws it: a consumer that charges history for a write draws the +//! allowance first ([`draw_history_allowance`](GasTracker::draw_history_allowance)) and charges +//! the rest. The allowance is the frame's alone: it is not returned, merged or rolled back. + +use super::GasTracker; + +impl GasTracker { + /// History gas this frame may spend before it charges its budget. + #[inline] + pub const fn history_allowance(&self) -> u64 { + self.history_allowance + } + + /// Sets the history allowance. + #[inline] + pub const fn set_history_allowance(&mut self, val: u64) { + self.history_allowance = val; + } + + /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` the + /// allowance did not cover, which the caller charges as history gas. + /// + /// With no allowance, which is the default, it returns `cost` whole and changes nothing. + #[inline] + #[must_use = "the part of the cost the allowance did not cover is still to be charged"] + pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { + let drawn = if cost < self.history_allowance { + cost + } else { + self.history_allowance + }; + self.history_allowance -= drawn; + cost - drawn + } +} + +#[cfg(test)] +mod tests { + use super::GasTracker; + + /// Every tracker starts with no allowance, and a draw on none is the whole cost. + #[test] + fn test_no_allowance_leaves_the_whole_cost_to_charge() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + assert_eq!(tracker.history_allowance(), 0); + assert_eq!(tracker.draw_history_allowance(100), 100); + assert_eq!(tracker, GasTracker::new(1_000, 1_000, 0)); + } + + /// A draw within the allowance leaves nothing to charge; one beyond it empties the allowance + /// and leaves the rest. + #[test] + fn test_draws_take_the_allowance_first() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_history_allowance(160); + + assert_eq!(tracker.draw_history_allowance(100), 0); + assert_eq!(tracker.history_allowance(), 60); + + assert_eq!(tracker.draw_history_allowance(100), 40); + assert_eq!(tracker.history_allowance(), 0); + + assert_eq!(tracker.draw_history_allowance(0), 0); + } + + /// The allowance touches no other figure of the tracker. + #[test] + fn test_the_allowance_is_its_own_figure() { + let mut tracker = GasTracker::new(1_000, 1_000, 300); + tracker.set_history_allowance(160); + assert_eq!(tracker.draw_history_allowance(50), 0); + assert_eq!(tracker.remaining(), 1_000); + assert_eq!(tracker.reservoir(), 300); + assert_eq!(tracker.history_gas_spent(), 0); + } + + /// Encodings made before the allowance existed decode with none. + #[cfg(feature = "serde")] + #[test] + fn test_serde_round_trip_and_older_payloads() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_history_allowance(160); + let encoded = serde_json::to_value(tracker).unwrap(); + assert_eq!( + serde_json::from_value::(encoded.clone()).unwrap(), + tracker + ); + + let mut older = encoded; + older.as_object_mut().unwrap().remove("history_allowance"); + let decoded = serde_json::from_value::(older).unwrap(); + assert_eq!(decoded.history_allowance(), 0); + } +} diff --git a/crates/context/interface/src/cfg/gas/start_charge.rs b/crates/context/interface/src/cfg/gas/start_charge.rs new file mode 100644 index 0000000000..cc223afe06 --- /dev/null +++ b/crates/context/interface/src/cfg/gas/start_charge.rs @@ -0,0 +1,105 @@ +//! The start charge a [`Host::frame_starting`](crate::Host::frame_starting) hook declares on the +//! caller's [`GasTracker`], and the instruction copies onto the frame's input. +//! +//! The hook charges the caller's gas for the frame it starts; the part of that charge the frame's +//! failure gives back is the start charge. The hook declares it on the tracker it is handed +//! ([`set_start_charge`](GasTracker::set_start_charge)), the instruction takes it off the tracker +//! right after the hook ([`take_start_charge`](GasTracker::take_start_charge)) and puts it on the +//! frame's input, and the handler refunds it to the caller when the frame fails. Outside that +//! window the carrier is zero. + +use super::GasTracker; + +/// What a frame start charged its caller and the frame's failure gives back: history gas and +/// bytes of the pool. +/// +/// Built with [`StartCharge::new`], so a later field is not a breaking change. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] +pub struct StartCharge { + /// History gas the start charged, refilled with + /// [`refill_history`](GasTracker::refill_history) when the frame fails. + pub history: u64, + /// Bytes the start drew from the pool, refilled with + /// [`refill_bytes`](GasTracker::refill_bytes) when the frame fails. + pub bytes: u64, +} + +impl StartCharge { + /// A start charge of `history` gas and `bytes` of the pool. + #[inline] + pub const fn new(history: u64, bytes: u64) -> Self { + Self { history, bytes } + } + + /// Nothing to refund. + #[inline] + pub const fn is_zero(&self) -> bool { + self.history == 0 && self.bytes == 0 + } +} + +impl GasTracker { + /// The start charge the frame-start hook declared and the instruction has not taken yet. + #[inline] + pub const fn start_charge(&self) -> StartCharge { + self.start_charge + } + + /// Declares the start charge of the frame about to start: what the hook charged this tracker + /// that the frame's failure gives back. Replaces what was declared before. + #[inline] + pub const fn set_start_charge(&mut self, charge: StartCharge) { + self.start_charge = charge; + } + + /// Takes the declared start charge off the tracker, leaving none. + #[inline] + pub const fn take_start_charge(&mut self) -> StartCharge { + let charge = self.start_charge; + self.start_charge = StartCharge::new(0, 0); + charge + } +} + +#[cfg(test)] +mod tests { + use super::{GasTracker, StartCharge}; + + /// A tracker carries no start charge until a hook declares one; taking it leaves none. + #[test] + fn test_the_carrier_is_empty_until_set_and_after_take() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + assert!(tracker.start_charge().is_zero()); + assert_eq!(tracker.take_start_charge(), StartCharge::default()); + + tracker.set_start_charge(StartCharge::new(3_520, 160)); + assert_eq!(tracker.start_charge(), StartCharge::new(3_520, 160)); + + assert_eq!(tracker.take_start_charge(), StartCharge::new(3_520, 160)); + assert!(tracker.start_charge().is_zero()); + assert_eq!(tracker, GasTracker::new(1_000, 1_000, 0)); + } + + /// A second declaration replaces the first. + #[test] + fn test_a_second_declaration_replaces_the_first() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_start_charge(StartCharge::new(1, 1)); + tracker.set_start_charge(StartCharge::new(2, 0)); + assert_eq!(tracker.take_start_charge(), StartCharge::new(2, 0)); + } + + /// The carrier is transient and not part of an encoded tracker. + #[cfg(feature = "serde")] + #[test] + fn test_the_carrier_is_not_encoded() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_start_charge(StartCharge::new(5, 5)); + let encoded = serde_json::to_value(tracker).unwrap(); + assert!(encoded.get("start_charge").is_none()); + let decoded = serde_json::from_value::(encoded).unwrap(); + assert!(decoded.start_charge().is_zero()); + } +} diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 875eef9769..4fa93e0dce 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,12 +236,14 @@ mod tests { assert_eq!(size_of::>(), size_of::()); } - /// The tracker is 88 bytes: 72 with the withheld part and its record, and two words more for - /// the failed-charge record. Copies of the tracker, and of every `Gas` and frame result that - /// holds one, grow with it, so a new field is measured before this changes. - #[test] - fn test_the_tracker_is_88_bytes() { - assert_eq!(size_of::(), 88); + /// The tracker is 136 bytes: 72 with the withheld part and its record, two words more for the + /// failed-charge record, and six more for the byte pool (the pool, its net and its record), + /// the history allowance and the start-charge carrier. Copies of the tracker, and of every + /// `Gas` and frame result that holds one, grow with it, so a new field is measured before + /// this changes. + #[test] + fn test_the_tracker_is_136_bytes() { + assert_eq!(size_of::(), 136); } /// Withholding moves gas between the parts and leaves the total alone. From 7373a474e9453a4323b3a19ea36943c249c61f1a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:20:49 +0800 Subject: [PATCH 008/110] feat(gas): schedule entries for the byte-pool forward share and the call history allowance bytes_forward_percent (id 254) is the share of a caller's byte pool a child frame receives, in per cent rounded down; a hundred on every spec, so the whole pool is forwarded. call_history_allowance (id 253) is the history gas a value call's child may spend before it charges its budget; zero on every spec. Both are fork ids allocated from the top of the table. --- .../context/interface/src/cfg/gas_params.rs | 138 +++++++++++++++++- 1 file changed, 132 insertions(+), 6 deletions(-) diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index 91785e0afb..6885bee849 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -232,6 +232,9 @@ impl GasParams { gas::NON_ZERO_BYTE_MULTIPLIER; table[GasId::tx_token_cost().as_usize()] = gas::STANDARD_TOKEN_COST; table[GasId::tx_base_stipend().as_usize()] = 21000; + // The fork's entries: a child frame receives the whole byte pool, and a value call's + // child no history allowance, on every spec. + table[GasId::bytes_forward_percent().as_usize()] = 100; if spec.is_enabled_in(SpecId::HOMESTEAD) { table[GasId::tx_create_cost().as_usize()] = gas::CREATE; @@ -814,6 +817,28 @@ impl GasParams { .saturating_mul(len as u64) } + /// The share of a caller's byte pool a child frame receives when it starts: + /// [`bytes_forward_percent`](GasId::bytes_forward_percent) per cent of `pool`, rounded down. + /// + /// A hundred or more, which every schedule here sets, forwards the whole pool. + #[inline] + pub fn bytes_forward_share(&self, pool: u64) -> u64 { + let percent = self.get(GasId::bytes_forward_percent()); + if percent >= 100 { + return pool; + } + // `floor(pool * percent / 100)` without widening: the quotient's part is exact, and the + // remainder's part is below a hundred times a hundred. + pool / 100 * percent + pool % 100 * percent / 100 + } + + /// History gas a value call's child may spend before it charges its budget + /// ([`call_history_allowance`](GasId::call_history_allowance)). Zero on every schedule here. + #[inline] + pub fn call_history_allowance(&self) -> u64 { + self.get(GasId::call_history_allowance()) + } + /// Used in [GasParams::initial_tx_gas] to calculate the eip7702 per-auth cost. /// /// Pre-Amsterdam this is the pessimistic bundled `PER_EMPTY_ACCOUNT_COST` @@ -1276,6 +1301,8 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", + x if x == Self::bytes_forward_percent().as_u8() => "bytes_forward_percent", + x if x == Self::call_history_allowance().as_u8() => "call_history_allowance", _ => "unknown", } } @@ -1351,6 +1378,8 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), + "bytes_forward_percent" => Some(Self::bytes_forward_percent()), + "call_history_allowance" => Some(Self::call_history_allowance()), _ => None, } } @@ -1641,6 +1670,28 @@ impl GasId { pub const fn code_deposit_history_gas() -> GasId { Self::new(255) } + + /// The share of a caller's byte pool a child frame receives when it starts, in per cent of + /// the pool, rounded down ([`GasParams::bytes_forward_share`]). A hundred, the whole pool, + /// on every schedule defined here; a chain that keeps part of the pool for the caller lowers + /// it. + /// + /// A fork id, allocated from the top of the table below + /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). + pub const fn bytes_forward_percent() -> GasId { + Self::new(254) + } + + /// History gas a value call's child may spend before it charges its budget + /// ([`GasTracker::history_allowance`](crate::cfg::gas::GasTracker::history_allowance)). The + /// call instruction sets it on the child where it adds the call stipend. Zero on every + /// schedule defined here. + /// + /// A fork id, allocated from the top of the table below + /// [`bytes_forward_percent`](Self::bytes_forward_percent). + pub const fn call_history_allowance() -> GasId { + Self::new(253) + } } #[cfg(test)] @@ -1713,19 +1764,94 @@ mod tests { "Not all unique names are resolvable via from_str" ); - // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's - // `code_deposit_history_gas` at 255, allocated from the top of the table so upstream's - // next sequential id does not collide with it. Every one of them has a name. - let expected_ids: HashSet = (1..=49).chain([255]).collect(); + // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated + // from the top of the table so upstream's next sequential id does not collide with them: + // `code_deposit_history_gas` at 255, `bytes_forward_percent` at 254 and + // `call_history_allowance` at 253. Every one of them has a name. + let expected_ids: HashSet = (1..=49).chain([253, 254, 255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), - 50, - "Expected 50 unique GasIds, found {}", + 52, + "Expected 52 unique GasIds, found {}", unique_names.len() ); } + /// Every schedule forwards the whole pool: the share is the pool itself, `u64::MAX` + /// included. A schedule that sets a percentage forwards that much, rounded down, and one at + /// or above a hundred forwards the whole pool. + #[test] + fn test_bytes_forward_share_defaults_to_the_whole_pool() { + for spec in [ + SpecId::FRONTIER, + SpecId::LONDON, + SpecId::OSAKA, + SpecId::AMSTERDAM, + SpecId::default(), + ] { + let params = GasParams::new_spec(spec); + assert_eq!(params.get(GasId::bytes_forward_percent()), 100, "{spec:?}"); + for pool in [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX] { + assert_eq!(params.bytes_forward_share(pool), pool, "{spec:?} {pool}"); + } + } + + let mut params = GasParams::new_spec(SpecId::OSAKA); + params.override_gas([(GasId::bytes_forward_percent(), 98)]); + assert_eq!(params.bytes_forward_share(0), 0); + assert_eq!(params.bytes_forward_share(1), 0); + assert_eq!(params.bytes_forward_share(100), 98); + assert_eq!(params.bytes_forward_share(149), 146, "rounded down"); + assert_eq!(params.bytes_forward_share(1_000), 980); + assert_eq!( + params.bytes_forward_share(u64::MAX), + (u64::MAX as u128 * 98 / 100) as u64, + "no overflow" + ); + + params.override_gas([(GasId::bytes_forward_percent(), 0)]); + assert_eq!(params.bytes_forward_share(1_000), 0); + params.override_gas([(GasId::bytes_forward_percent(), 250)]); + assert_eq!( + params.bytes_forward_share(1_000), + 1_000, + "capped at the whole pool" + ); + + assert_eq!( + GasId::from_name("bytes_forward_percent"), + Some(GasId::bytes_forward_percent()) + ); + assert_eq!( + GasId::bytes_forward_percent().name(), + "bytes_forward_percent" + ); + } + + /// No schedule gives a value call's child a history allowance. + #[test] + fn test_call_history_allowance_defaults_to_zero() { + for spec in [SpecId::FRONTIER, SpecId::OSAKA, SpecId::AMSTERDAM] { + assert_eq!( + GasParams::new_spec(spec).call_history_allowance(), + 0, + "{spec:?}" + ); + } + let mut params = GasParams::new_spec(SpecId::OSAKA); + params.override_gas([(GasId::call_history_allowance(), 160)]); + assert_eq!(params.call_history_allowance(), 160); + assert_eq!( + GasId::from_name("call_history_allowance"), + Some(GasId::call_history_allowance()) + ); + assert_eq!( + GasId::call_history_allowance().name(), + "call_history_allowance" + ); + } + #[test] fn test_max_refund_quotient_defaults_and_override() { let frontier = GasParams::new_spec(SpecId::FRONTIER); From 2ccf7132bc0c5127c5a05ccfe76f2a97fd2d5d40 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:27:28 +0800 Subject: [PATCH 009/110] feat(interpreter): forward the byte pool, the start charge and the history allowance to the frame input After the frame-start hook has answered, the call and creation instructions take the start charge the hook declared off the caller's gas, take the child's share of the caller's byte pool out of the pool by the schedule's bytes_forward_percent, and put both on the frame's input; a value call's input also carries the schedule's call_history_allowance, decided where the stipend is. CallInputs, CreateInputs, CallOutcome and CreateOutcome gain the fields (charged_start, bytes_share, history_allowance); the pool methods are forwarded on Gas. The defaults forward the whole pool, declare nothing and give no allowance. --- crates/handler/src/execution.rs | 5 +- crates/handler/src/frame.rs | 5 + crates/interpreter/src/gas.rs | 1 + crates/interpreter/src/gas/byte_pool.rs | 132 +++++ .../interpreter/src/instructions/contract.rs | 26 +- .../src/instructions/contract/call_helpers.rs | 25 +- .../src/instructions/instruction_hooks.rs | 24 +- .../src/interpreter_action/call_inputs.rs | 29 +- .../src/interpreter_action/call_outcome.rs | 10 +- .../src/interpreter_action/create_inputs.rs | 62 ++- .../src/interpreter_action/create_outcome.rs | 10 +- crates/interpreter/src/lib.rs | 2 +- crates/interpreter/tests/byte_pool.rs | 485 ++++++++++++++++++ crates/interpreter/tests/byte_pool_serde.rs | 132 +++++ crates/interpreter/tests/instruction_hooks.rs | 11 +- 15 files changed, 931 insertions(+), 28 deletions(-) create mode 100644 crates/interpreter/src/gas/byte_pool.rs create mode 100644 crates/interpreter/tests/byte_pool.rs create mode 100644 crates/interpreter/tests/byte_pool_serde.rs diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index 56b8a38bce..e61c432c22 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -6,7 +6,7 @@ use context_interface::{ }; use interpreter::{ CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - GasTracker, + GasTracker, StartCharge, }; use primitives::{Address, TxKind}; use state::Bytecode; @@ -132,6 +132,9 @@ pub fn create_init_frame( return_memory_offset: 0..0, reservoir: gas.reservoir(), charged_new_account_state_gas, + charged_start: StartCharge::default(), + bytes_share: u64::MAX, + history_allowance: 0, })))) } TxKind::Create => { diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index dc645c1540..4d0d56eff5 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -159,6 +159,7 @@ impl EthFrame { let reservoir_remaining_gas = inputs.reservoir; let charged_new_account_state_gas = inputs.charged_new_account_state_gas; let charged_state_gas_address = inputs.target_address; + let charged_start = inputs.charged_start; let gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas); @@ -174,6 +175,7 @@ impl EthFrame { precompile_call_logs: Vec::new(), charged_new_account_state_gas, charged_state_gas_address, + charged_start, }))) }; @@ -228,6 +230,7 @@ impl EthFrame { precompile_call_logs: logs, charged_new_account_state_gas, charged_state_gas_address, + charged_start, }))); } @@ -282,6 +285,7 @@ impl EthFrame { // Recorded by whoever made the charge — the CREATE opcode or the EIP-2780 runtime phase // — because the created address is not derivable here on the early-fail paths. let charged_state_gas_address = inputs.charged_state_gas_address(); + let charged_start = inputs.charged_start(); let return_error = |e| { Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome { result: InterpreterResult { @@ -295,6 +299,7 @@ impl EthFrame { address: None, charged_create_state_gas, charged_state_gas_address, + charged_start, }))) }; diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index 796eeaed50..6aa20b09c3 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -2,6 +2,7 @@ pub use context_interface::cfg::gas::*; +mod byte_pool; mod failed_charge; mod withheld; diff --git a/crates/interpreter/src/gas/byte_pool.rs b/crates/interpreter/src/gas/byte_pool.rs new file mode 100644 index 0000000000..96c2e2cd4f --- /dev/null +++ b/crates/interpreter/src/gas/byte_pool.rs @@ -0,0 +1,132 @@ +//! The byte pool, the history allowance and the start charge, on [`Gas`]. +//! +//! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which +//! documents it. + +use super::{BytesCrossing, Gas, StartCharge}; + +impl Gas { + /// The byte pool: what this frame may still draw. Unlimited unless a consumer set a pool. + /// + /// See [`GasTracker::bytes_remaining`](super::GasTracker::bytes_remaining). + #[inline] + pub const fn bytes_remaining(&self) -> u64 { + self.tracker.bytes_remaining() + } + + /// Sets the byte pool. + /// + /// See [`GasTracker::set_bytes_remaining`](super::GasTracker::set_bytes_remaining). + #[inline] + pub const fn set_bytes_remaining(&mut self, val: u64) { + self.tracker.set_bytes_remaining(val); + } + + /// The frame's net draw of the pool so far, signed. + /// + /// See [`GasTracker::bytes_spent`](super::GasTracker::bytes_spent). + #[inline] + pub const fn bytes_spent(&self) -> i64 { + self.tracker.bytes_spent() + } + + /// Sets the net draw. + /// + /// See [`GasTracker::set_bytes_spent`](super::GasTracker::set_bytes_spent). + #[inline] + pub const fn set_bytes_spent(&mut self, val: i64) { + self.tracker.set_bytes_spent(val); + } + + /// Draws `cost` bytes from the pool; `false` if the pool cannot pay, which records a + /// [`BytesCrossing`]. + /// + /// See [`GasTracker::record_bytes`](super::GasTracker::record_bytes). + #[inline] + #[must_use = "a draw the pool cannot pay is the consumer's stop"] + pub const fn record_bytes(&mut self, cost: u64) -> bool { + self.tracker.record_bytes(cost) + } + + /// Gives `amount` bytes back to the pool. + /// + /// See [`GasTracker::refill_bytes`](super::GasTracker::refill_bytes). + #[inline] + pub const fn refill_bytes(&mut self, amount: u64) { + self.tracker.refill_bytes(amount); + } + + /// The record of the last draw the pool could not pay, since it was last cleared. + /// + /// See [`GasTracker::bytes_crossing`](super::GasTracker::bytes_crossing). + #[inline] + pub const fn bytes_crossing(&self) -> Option { + self.tracker.bytes_crossing() + } + + /// Clears the record returned by [`bytes_crossing`](Self::bytes_crossing). + /// + /// See [`GasTracker::clear_bytes_crossing`](super::GasTracker::clear_bytes_crossing). + #[inline] + pub const fn clear_bytes_crossing(&mut self) { + self.tracker.clear_bytes_crossing(); + } + + /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing). + /// + /// See [`GasTracker::set_bytes_crossing`](super::GasTracker::set_bytes_crossing). + #[inline] + pub const fn set_bytes_crossing(&mut self, crossing: Option) { + self.tracker.set_bytes_crossing(crossing); + } + + /// History gas this frame may spend before it charges its budget. + /// + /// See [`GasTracker::history_allowance`](super::GasTracker::history_allowance). + #[inline] + pub const fn history_allowance(&self) -> u64 { + self.tracker.history_allowance() + } + + /// Sets the history allowance. + /// + /// See [`GasTracker::set_history_allowance`](super::GasTracker::set_history_allowance). + #[inline] + pub const fn set_history_allowance(&mut self, val: u64) { + self.tracker.set_history_allowance(val); + } + + /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` it did not + /// cover. + /// + /// See [`GasTracker::draw_history_allowance`](super::GasTracker::draw_history_allowance). + #[inline] + #[must_use = "the part of the cost the allowance did not cover is still to be charged"] + pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { + self.tracker.draw_history_allowance(cost) + } + + /// The start charge the frame-start hook declared and the instruction has not taken yet. + /// + /// See [`GasTracker::start_charge`](super::GasTracker::start_charge). + #[inline] + pub const fn start_charge(&self) -> StartCharge { + self.tracker.start_charge() + } + + /// Declares the start charge of the frame about to start. + /// + /// See [`GasTracker::set_start_charge`](super::GasTracker::set_start_charge). + #[inline] + pub const fn set_start_charge(&mut self, charge: StartCharge) { + self.tracker.set_start_charge(charge); + } + + /// Takes the declared start charge off the tracker, leaving none. + /// + /// See [`GasTracker::take_start_charge`](super::GasTracker::take_start_charge). + #[inline] + pub const fn take_start_charge(&mut self) -> StartCharge { + self.tracker.take_start_charge() + } +} diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index db7a6246c1..298cccea62 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -8,7 +8,10 @@ pub use call_helpers::{ use call_helpers::load_acc_and_calc_forward; use crate::{ - instructions::{instruction_hooks::frame_starting, utility::IntoAddress}, + instructions::{ + instruction_hooks::{forward_bytes, frame_starting}, + utility::IntoAddress, + }, interpreter_action::FrameInput, interpreter_types::{ InputsTr, InterpreterTypes as ITy, LoopControl, MemoryTr, ReturnData, RuntimeFlag, StackTr, @@ -179,10 +182,13 @@ pub fn create( FrameStartKind::Create }; let start = FrameStart::new(kind, create_inputs.caller(), None, value, gas_limit); - frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let charged_start = frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); create_inputs.set_gas_limit(gas_limit); create_inputs.set_reservoir(context.interpreter.gas.reservoir()); + create_inputs.set_charged_start(charged_start); + create_inputs.set_bytes_share(bytes_share); context .interpreter .bytecode @@ -226,8 +232,14 @@ pub fn call(mut context: Ictx<'_, H, get_memory_input_and_out_ranges(context.interpreter, context.host.gas_params())?; let is_call = KIND == CALL; - let (gas_limit, bytecode, bytecode_hash, charged_new_account_state_gas, forward) = - load_acc_and_calc_forward(&mut context, to, has_transfer, is_call, local_gas_limit)?; + let ( + gas_limit, + bytecode, + bytecode_hash, + charged_new_account_state_gas, + forward, + history_allowance, + ) = load_acc_and_calc_forward(&mut context, to, has_transfer, is_call, local_gas_limit)?; let target_address = if matches!(KIND, CALLCODE | DELEGATECALL) { context.interpreter.input.target_address() @@ -261,7 +273,8 @@ pub fn call(mut context: Ictx<'_, H, }; let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); - frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let charged_start = frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); // Call host to interact with target contract context @@ -281,6 +294,9 @@ pub fn call(mut context: Ictx<'_, H, return_memory_offset, reservoir: context.interpreter.gas.reservoir(), charged_new_account_state_gas, + charged_start, + bytes_share, + history_allowance, }, )))); Err(InstructionResult::Suspend) diff --git a/crates/interpreter/src/instructions/contract/call_helpers.rs b/crates/interpreter/src/instructions/contract/call_helpers.rs index 0a1f1a3109..9b4ebf2e13 100644 --- a/crates/interpreter/src/instructions/contract/call_helpers.rs +++ b/crates/interpreter/src/instructions/contract/call_helpers.rs @@ -77,15 +77,20 @@ pub fn load_acc_and_calc_gas( create_empty_account, stack_gas_limit, ) - .map(|(gas_limit, bytecode, code_hash, charged, _)| (gas_limit, bytecode, code_hash, charged)) + .map(|(gas_limit, bytecode, code_hash, charged, _, _)| { + (gas_limit, bytecode, code_hash, charged) + }) } -/// [`load_acc_and_calc_gas`], also returning the forward: the gas taken from the caller for the -/// frame, which is the frame's gas limit without a value call's stipend. +/// [`load_acc_and_calc_gas`], also returning the forward, the gas taken from the caller for the +/// frame, which is the frame's gas limit without a value call's stipend, and the frame's history +/// allowance, the schedule's `call_history_allowance` for a call that transfers value and zero +/// otherwise, decided where the stipend is. /// -/// Returns `(gas_limit, bytecode, code_hash, charged_new_account_state_gas, forward)`. The forward -/// comes last, after the fields [`load_acc_and_calc_gas`] returns: placed second, it changed how -/// the others are stored and cost two more instructions per call. +/// Returns `(gas_limit, bytecode, code_hash, charged_new_account_state_gas, forward, +/// history_allowance)`. The forward and the allowance come last, after the fields +/// [`load_acc_and_calc_gas`] returns: placed second, the forward changed how the others are +/// stored and cost two more instructions per call. #[inline(never)] pub(super) fn load_acc_and_calc_forward( context: &mut Ictx<'_, H, impl ITy>, @@ -93,7 +98,7 @@ pub(super) fn load_acc_and_calc_forward( transfers_value: bool, create_empty_account: bool, stack_gas_limit: u64, -) -> Result<(u64, Bytecode, B256, bool, u64), InstructionResult> { +) -> Result<(u64, Bytecode, B256, bool, u64, u64), InstructionResult> { // Transfer value cost if transfers_value { gas!( @@ -135,9 +140,12 @@ pub(super) fn load_acc_and_calc_forward( let forward = gas_limit; - // Add call stipend if there is value to be transferred. + // Add call stipend if there is value to be transferred, and with it the history allowance + // the schedule gives a value call's child (zero on every schedule defined here). + let mut history_allowance = 0; if transfers_value { gas_limit = gas_limit.saturating_add(host.gas_params().call_stipend()); + history_allowance = host.gas_params().call_history_allowance(); } Ok(( @@ -146,6 +154,7 @@ pub(super) fn load_acc_and_calc_forward( code_hash, charged_new_account_state_gas, forward, + history_allowance, )) } diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index cc2b969ca9..287fda4771 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -4,6 +4,7 @@ use crate::{ interpreter_types::{InterpreterTypes as ITy, LoopControl}, Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, InterpreterAction, + StartCharge, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; use primitives::{hints_util::cold_path, Bytes}; @@ -43,17 +44,32 @@ fn revert(interpreter: &mut Interpreter, output: Bytes) -> Result { } /// Hands `start`, whose forward the running instruction has taken from `gas`, to -/// [`Host::frame_starting`]; `false` fails the instruction out of gas. +/// [`Host::frame_starting`], and takes the start charge the hook declared off `gas`, whatever +/// the answer, so the carrier is empty once the hook has answered. `true` returns the charge for +/// the frame's input; `false` fails the instruction out of gas, and the charge goes with the +/// start it was declared for. #[inline] pub(crate) fn frame_starting( gas: &mut Gas, host: &mut H, start: &FrameStart, -) -> Result { - if host.frame_starting(start, gas.tracker_mut()) { - Ok(()) +) -> core::result::Result { + let admitted = host.frame_starting(start, gas.tracker_mut()); + let charged = gas.take_start_charge(); + if admitted { + Ok(charged) } else { cold_path(); Err(InstructionResult::OutOfGas) } } + +/// Takes the child's share of the caller's byte pool out of `gas`, by the schedule's +/// `bytes_forward_percent`, and returns it: the pool the child starts with. Called once the +/// frame-start hook has answered, so the share is of the pool as the hook left it. +#[inline] +pub(crate) fn forward_bytes(gas: &mut Gas, host: &H) -> u64 { + let share = host.gas_params().bytes_forward_share(gas.bytes_remaining()); + gas.tracker_mut().forward_bytes(share); + share +} diff --git a/crates/interpreter/src/interpreter_action/call_inputs.rs b/crates/interpreter/src/interpreter_action/call_inputs.rs index bfa6d2d2da..d46a9b536a 100644 --- a/crates/interpreter/src/interpreter_action/call_inputs.rs +++ b/crates/interpreter/src/interpreter_action/call_inputs.rs @@ -1,5 +1,5 @@ use crate::interpreter_types::MemoryTr; -use context_interface::{ContextTr, LocalContextTr}; +use context_interface::{cfg::gas::StartCharge, ContextTr, LocalContextTr}; use core::ops::Range; use primitives::{Address, Bytes, B256, U256}; use state::Bytecode; @@ -174,6 +174,33 @@ pub struct CallInputs { /// On revert/halt of the resulting frame the parent must refund this charge /// to the reservoir, matching the CREATE pattern. pub charged_new_account_state_gas: bool, + /// What the frame-start hook charged the caller for this call and the call's failure gives + /// back: history gas and bytes of the pool, refunded to the caller by `return_result` when + /// the call does not succeed, as `charged_new_account_state_gas` is. + /// + /// Encodings made before this field existed decode it as no charge. + #[cfg_attr(feature = "serde", serde(default))] + pub charged_start: StartCharge, + /// The share of the caller's byte pool the call receives: its pool when it starts. Taken out + /// of the caller's pool by the call instruction, by the schedule's `bytes_forward_percent`, + /// and given back with what the call left of it when it returns. + /// + /// Encodings made before this field existed decode it as unlimited. + #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] + pub bytes_share: u64, + /// History gas the call may spend before it charges its budget: the schedule's + /// `call_history_allowance` for a call that transfers value, set where the call instruction + /// adds the call stipend, and zero otherwise. + /// + /// Encodings made before this field existed decode it as zero. + #[cfg_attr(feature = "serde", serde(default))] + pub history_allowance: u64, +} + +/// The share an encoding that predates the byte pool decodes to. +#[cfg(feature = "serde")] +const fn unlimited_bytes() -> u64 { + u64::MAX } impl CallInputs { diff --git a/crates/interpreter/src/interpreter_action/call_outcome.rs b/crates/interpreter/src/interpreter_action/call_outcome.rs index 3d55a79b30..2edaf67a63 100644 --- a/crates/interpreter/src/interpreter_action/call_outcome.rs +++ b/crates/interpreter/src/interpreter_action/call_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult}; +use crate::{Gas, InstructionResult, InterpreterResult, StartCharge}; use core::ops::Range; use primitives::{Address, Bytes, Log}; use std::vec::Vec; @@ -39,6 +39,13 @@ pub struct CallOutcome { /// Encodings made before this field existed decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, + /// Copied from `CallInputs::charged_start`: what the frame-start hook charged the caller for + /// this call and the call's failure gives back, so the parent can refund it when the call + /// does not succeed. + /// + /// Encodings made before this field existed decode it as no charge. + #[cfg_attr(feature = "serde", serde(default))] + pub charged_start: StartCharge, } impl CallOutcome { @@ -58,6 +65,7 @@ impl CallOutcome { precompile_call_logs: Vec::new(), charged_new_account_state_gas: false, charged_state_gas_address: Address::ZERO, + charged_start: StartCharge::new(0, 0), } } diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index 6f1ef6217e..507309ee8a 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -1,9 +1,9 @@ -use context_interface::CreateScheme; +use context_interface::{cfg::gas::StartCharge, CreateScheme}; use core::cell::OnceCell; use primitives::{keccak256, Address, Bytes, B256, U256}; /// Inputs for a create call -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CreateInputs { /// Caller address of the EVM @@ -29,6 +29,20 @@ pub struct CreateInputs { /// Encodings made before this field existed decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] charged_state_gas_address: Address, + /// What the frame-start hook charged the caller for this creation and the creation's failure + /// gives back: history gas and bytes of the pool, refunded to the caller by `return_result` + /// when the creation fails, as `charged_create_state_gas` is. + /// + /// Encodings made before this field existed decode it as no charge. + #[cfg_attr(feature = "serde", serde(default))] + charged_start: StartCharge, + /// The share of the caller's byte pool the creation receives: its pool when it starts. Taken + /// out of the caller's pool by the creation instruction, by the schedule's + /// `bytes_forward_percent`, and given back with what the creation left of it when it returns. + /// + /// Encodings made before this field existed decode it as unlimited. + #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] + bytes_share: u64, /// Cached created address. This is computed lazily and cached to avoid /// redundant keccak computations when inspectors call `created_address`. #[cfg_attr(feature = "serde", serde(skip))] @@ -40,6 +54,27 @@ pub struct CreateInputs { cached_init_code_hash: OnceCell, } +/// The share an encoding that predates the byte pool decodes to. +#[cfg(feature = "serde")] +const fn unlimited_bytes() -> u64 { + u64::MAX +} + +impl Default for CreateInputs { + /// Empty inputs, as [`new`](Self::new) builds them, so the share starts unlimited. + #[inline] + fn default() -> Self { + Self::new( + Address::ZERO, + CreateScheme::Create, + U256::ZERO, + Bytes::new(), + 0, + 0, + ) + } +} + impl CreateInputs { /// Creates a new `CreateInputs` instance. pub const fn new( @@ -59,6 +94,8 @@ impl CreateInputs { reservoir, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, + charged_start: StartCharge::new(0, 0), + bytes_share: u64::MAX, cached_address: OnceCell::new(), cached_init_code_hash: OnceCell::new(), } @@ -173,4 +210,25 @@ impl CreateInputs { pub const fn set_reservoir(&mut self, reservoir: u64) { self.reservoir = reservoir; } + + /// What the frame-start hook charged the caller for this creation and the creation's failure + /// gives back. + pub const fn charged_start(&self) -> StartCharge { + self.charged_start + } + + /// Records what the frame-start hook charged the caller for this creation. + pub const fn set_charged_start(&mut self, charge: StartCharge) { + self.charged_start = charge; + } + + /// The share of the caller's byte pool the creation receives: its pool when it starts. + pub const fn bytes_share(&self) -> u64 { + self.bytes_share + } + + /// Sets the share of the caller's byte pool the creation receives. + pub const fn set_bytes_share(&mut self, share: u64) { + self.bytes_share = share; + } } diff --git a/crates/interpreter/src/interpreter_action/create_outcome.rs b/crates/interpreter/src/interpreter_action/create_outcome.rs index 50b0db729f..ffc9180f49 100644 --- a/crates/interpreter/src/interpreter_action/create_outcome.rs +++ b/crates/interpreter/src/interpreter_action/create_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult}; +use crate::{Gas, InstructionResult, InterpreterResult, StartCharge}; use primitives::{Address, Bytes}; /// Represents the outcome of a create operation in an interpreter. @@ -26,6 +26,13 @@ pub struct CreateOutcome { /// Encodings made before this field existed decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, + /// Copied from `CreateInputs::charged_start`: what the frame-start hook charged the caller + /// for this creation and the creation's failure gives back, so the parent can refund it when + /// the creation fails. + /// + /// Encodings made before this field existed decode it as no charge. + #[cfg_attr(feature = "serde", serde(default))] + pub charged_start: StartCharge, } impl CreateOutcome { @@ -45,6 +52,7 @@ impl CreateOutcome { address, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, + charged_start: StartCharge::new(0, 0), } } diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index b0063510fa..8b14cbbef4 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,7 +36,7 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{Gas, GasTracker}; +pub use gas::{BytesCrossing, Gas, GasTracker, StartCharge}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/byte_pool.rs b/crates/interpreter/tests/byte_pool.rs new file mode 100644 index 0000000000..620c6609c4 --- /dev/null +++ b/crates/interpreter/tests/byte_pool.rs @@ -0,0 +1,485 @@ +//! The byte pool, the start charge and the history allowance at the call and creation +//! instructions. +//! +//! Once [`Host::frame_starting`] has answered, the instruction takes the start charge the hook +//! declared off the caller's gas and puts it on the frame's input, takes the child's share of the +//! caller's byte pool out of the pool and puts it on the input too, and, for a value call, gives +//! the input the schedule's history allowance. Each test runs one frame on [`PoolHost`], whose +//! start hook draws bytes from the gas it is handed, declares a start charge, and admits or +//! refuses the start as the test tells it. + +use bytecode::{opcode::*, Bytecode}; +use context_interface::{ + cfg::{GasId, GasParams, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::{CompletedWrite, FrameStart, FrameStartKind, LoadError, WriteVerdict}, + journaled_state::AccountInfoLoad, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, B256, U256, +}; +use revm_interpreter::{ + host::DummyHost, + instruction_table, + instructions::gas_table_spec, + interpreter::{EthInterpreter, ExtBytecode}, + FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, + InterpreterAction, SharedMemory, StartCharge, +}; +use state::AccountInfo; +use std::borrow::Cow; + +/// The account the frame runs as. +const CONTRACT: Address = address!("0x000000000000000000000000000000000000c0de"); +/// The frame's caller. +const CALLER: Address = address!("0x00000000000000000000000000000000000ca11e"); +/// The account a call names. +const TARGET: Address = address!("0x0000000000000000000000000000000000007a59"); +/// Gas enough for every frame here. +const AMPLE: u64 = 1_000_000; +/// The pool the frame starts with, unless a test leaves it unlimited. +const POOL: u64 = 1_000; +/// A start charge a hook declares. +const DECLARED: StartCharge = StartCharge::new(3_520, 160); +/// What a chain's schedule sets: the child's share and a value call's allowance. +const PERCENT: u64 = 98; +const ALLOWANCE: u64 = 160; + +/// A [`DummyHost`] whose start hook draws [`PoolHost::draw`] bytes from the gas it is handed, +/// declares [`PoolHost::declare`], records what it saw, and answers [`PoolHost::admit`]. +struct PoolHost { + dummy: DummyHost, + spec: SpecId, + params: GasParams, + draw: u64, + declare: StartCharge, + admit: bool, + /// Every start the hook saw, with the gas as the hook found it, and whether its draw paid. + starts: Vec<(FrameStart, GasTracker, bool)>, +} + +impl PoolHost { + fn new(spec: SpecId) -> Self { + Self { + dummy: DummyHost::new(spec), + spec, + params: GasParams::new_spec(spec), + draw: 0, + declare: StartCharge::default(), + admit: true, + starts: Vec::new(), + } + } + + /// The schedule of a chain that keeps part of the pool for the caller and gives a value + /// call's child an allowance. + fn on_a_chains_schedule(mut self) -> Self { + self.params.override_gas([ + (GasId::bytes_forward_percent(), PERCENT), + (GasId::call_history_allowance(), ALLOWANCE), + ]); + self + } + + const fn drawing(mut self, draw: u64) -> Self { + self.draw = draw; + self + } + + const fn declaring(mut self, charge: StartCharge) -> Self { + self.declare = charge; + self + } + + const fn refusing(mut self) -> Self { + self.admit = false; + self + } + + /// The one start the hook saw. + fn start(&self) -> &(FrameStart, GasTracker, bool) { + assert_eq!(self.starts.len(), 1, "one start: {:?}", self.starts); + &self.starts[0] + } +} + +impl Host for PoolHost { + fn write_completed(&mut self, _: CompletedWrite<'_>, _: &mut GasTracker) -> WriteVerdict { + WriteVerdict::Continue + } + + fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + let found = *gas; + let paid = gas.record_bytes(self.draw); + gas.set_start_charge(self.declare); + self.starts.push((*start, found, paid)); + self.admit && paid + } + + fn state_gas_price(&mut self, id: GasId, _site: StateGasSite) -> Option { + Some(self.gas_params().get(id)) + } + + fn basefee(&self) -> U256 { + self.dummy.basefee() + } + fn blob_gasprice(&self) -> U256 { + self.dummy.blob_gasprice() + } + fn gas_limit(&self) -> U256 { + self.dummy.gas_limit() + } + fn difficulty(&self) -> U256 { + self.dummy.difficulty() + } + fn prevrandao(&self) -> Option { + self.dummy.prevrandao() + } + fn block_number(&self) -> U256 { + self.dummy.block_number() + } + fn timestamp(&self) -> U256 { + self.dummy.timestamp() + } + fn beneficiary(&self) -> Address { + self.dummy.beneficiary() + } + fn slot_num(&self) -> U256 { + self.dummy.slot_num() + } + fn chain_id(&self) -> U256 { + self.dummy.chain_id() + } + fn effective_gas_price(&self) -> U256 { + self.dummy.effective_gas_price() + } + fn caller(&self) -> Address { + self.dummy.caller() + } + fn blob_hash(&self, number: usize) -> Option { + self.dummy.blob_hash(number) + } + fn max_initcode_size(&self) -> usize { + usize::MAX + } + fn gas_params(&self) -> &GasParams { + &self.params + } + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.dummy.is_amsterdam_eip8037_enabled() + } + fn block_hash(&mut self, number: u64) -> Option { + self.dummy.block_hash(number) + } + + fn selfdestruct( + &mut self, + _address: Address, + _target: Address, + _skip_cold_load: bool, + ) -> Result, LoadError> { + Ok(StateLoad::new(SelfDestructResult::default(), false)) + } + + fn log(&mut self, log: Log) { + self.dummy.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.dummy + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.dummy + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.dummy.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.dummy.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + _address: Address, + _load_code: bool, + _skip_cold_load: bool, + ) -> Result, LoadError> { + Ok(AccountInfoLoad { + account: Cow::Owned(AccountInfo::from_balance(U256::from(AMPLE))), + is_cold: false, + is_empty: false, + }) + } +} + +/// Runs `code` as [`CONTRACT`], called by [`CALLER`], with [`AMPLE`] gas and a byte pool of +/// `pool`, if given, and returns what the frame asked for and its gas. +fn run(code: &[u8], pool: Option, host: &mut PoolHost) -> (InterpreterAction, Gas) { + let spec = host.spec; + let mut interpreter = Interpreter::::new( + SharedMemory::new(), + ExtBytecode::new(Bytecode::new_raw(Bytes::copy_from_slice(code))), + InputsImpl { + target_address: CONTRACT, + caller_address: CALLER, + ..Default::default() + }, + false, + spec, + AMPLE, + ); + if let Some(pool) = pool { + interpreter.gas.set_bytes_remaining(pool); + } + let table = instruction_table::(); + let action = interpreter.run_plain(&table, &gas_table_spec(spec), host); + (action, interpreter.gas) +} + +/// The frame a frame asked to start. +fn started(action: InterpreterAction) -> FrameInput { + match action { + InterpreterAction::NewFrame(input) => input, + other => panic!("expected a new frame, got {other:?}"), + } +} + +/// The result a frame returned with. +fn returned(action: InterpreterAction) -> InstructionResult { + match action { + InterpreterAction::Return(result) => result.result, + other => panic!("expected the frame to return, got {other:?}"), + } +} + +/// The pool figures of a started frame's input: its share, its start charge and its history +/// allowance (a creation has none). +fn figures(input: &FrameInput) -> (u64, StartCharge, u64) { + match input { + FrameInput::Call(inputs) => ( + inputs.bytes_share, + inputs.charged_start, + inputs.history_allowance, + ), + FrameInput::Create(inputs) => (inputs.bytes_share(), inputs.charged_start(), 0), + FrameInput::Empty => unreachable!(), + } +} + +/// `op` (a call) to [`TARGET`] with `value` (for `CALL` and `CALLCODE`), no input and no output, +/// then `STOP`. +fn call_code(op: u8, value: u8) -> Vec { + let mut code = vec![PUSH1, 0, PUSH1, 0, PUSH1, 0, PUSH1, 0]; + if matches!(op, CALL | CALLCODE) { + code.extend_from_slice(&[PUSH1, value]); + } + code.push(PUSH20); + code.extend_from_slice(TARGET.as_slice()); + code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, op, STOP]); + code +} + +/// `op` (`CREATE` or `CREATE2`) of one byte of memory, endowed with nothing, then `STOP`. +fn create_code(op: u8) -> Vec { + let mut code = Vec::new(); + if op == CREATE2 { + code.extend_from_slice(&[PUSH1, 0x5a]); + } + code.extend_from_slice(&[PUSH1, 1, PUSH1, 0, PUSH1, 0, op, STOP]); + code +} + +/// A start of each kind. +fn start_cases() -> Vec<(FrameStartKind, Vec)> { + vec![ + (FrameStartKind::Call, call_code(CALL, 1)), + (FrameStartKind::CallCode, call_code(CALLCODE, 1)), + (FrameStartKind::DelegateCall, call_code(DELEGATECALL, 0)), + (FrameStartKind::StaticCall, call_code(STATICCALL, 0)), + (FrameStartKind::Create, create_code(CREATE)), + (FrameStartKind::Create2, create_code(CREATE2)), + ] +} + +/// With the schedule as it is, every start forwards the whole pool: the child's share is the +/// caller's pool, the caller keeps nothing, and the forward is not a draw. The default hook +/// declares no start charge, and no frame gets an allowance. +#[test] +fn test_every_start_forwards_the_whole_pool_by_default() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA); + let (action, gas) = run(&code, Some(POOL), &mut host); + let input = started(action); + + assert_eq!(host.start().0.kind, kind); + assert_eq!( + figures(&input), + (POOL, StartCharge::default(), 0), + "{kind:?}" + ); + assert_eq!( + gas.bytes_remaining(), + 0, + "{kind:?}: the caller keeps nothing" + ); + assert_eq!(gas.bytes_spent(), 0, "{kind:?}: a forward is not a draw"); + assert!(gas.start_charge().is_zero(), "{kind:?}"); + assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); + } +} + +/// A frame that was given no pool has an unlimited one, and forwards it unlimited. +#[test] +fn test_an_unlimited_pool_is_forwarded_unlimited() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA); + let (action, gas) = run(&code, None, &mut host); + let (share, _, _) = figures(&started(action)); + + assert_eq!(share, u64::MAX, "{kind:?}"); + assert_eq!(gas.bytes_remaining(), 0, "{kind:?}"); + } +} + +/// The share is taken from the pool as the hook left it, by the schedule's percentage, rounded +/// down; the caller keeps the rest, and the hook's draw stays drawn. +#[test] +fn test_the_share_follows_the_schedule_after_the_hooks_draw() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA) + .on_a_chains_schedule() + .drawing(200); + let (action, gas) = run(&code, Some(POOL), &mut host); + let (share, _, _) = figures(&started(action)); + + let (_, found, paid) = host.start(); + assert_eq!( + found.bytes_remaining(), + POOL, + "{kind:?}: the hook found the pool" + ); + assert!(paid); + // 800 left after the draw; 98% of it, rounded down. + assert_eq!(share, 784, "{kind:?}"); + assert_eq!( + gas.bytes_remaining(), + 16, + "{kind:?}: the caller keeps the rest" + ); + assert_eq!(gas.bytes_spent(), 200, "{kind:?}: the hook's draw stays"); + } +} + +/// The start charge the hook declares rides on the frame's input, and the carrier on the +/// caller's gas is empty again once the instruction has taken it. +#[test] +fn test_the_declared_start_charge_rides_on_the_input_and_leaves_the_tracker() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA).declaring(DECLARED); + let (action, gas) = run(&code, Some(POOL), &mut host); + let (_, charged, _) = figures(&started(action)); + + assert_eq!(charged, DECLARED, "{kind:?}"); + assert!( + gas.start_charge().is_zero(), + "{kind:?}: the carrier is taken" + ); + } +} + +/// A start the hook refuses fails out of gas and starts no frame: the hook's draw stays, as the +/// forward of regular gas does, no share is taken, and the declared charge is discarded with the +/// start rather than left on the caller's gas. +#[test] +fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA) + .drawing(200) + .declaring(DECLARED) + .refusing(); + let (action, gas) = run(&code, Some(POOL), &mut host); + + assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); + assert_eq!( + gas.bytes_remaining(), + POOL - 200, + "{kind:?}: no share taken" + ); + assert_eq!(gas.bytes_spent(), 200, "{kind:?}"); + assert!( + gas.start_charge().is_zero(), + "{kind:?}: the carrier is taken" + ); + assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); + } +} + +/// A draw the pool cannot pay takes nothing and records the crossing; the hook turns it into a +/// refusal, and the record, with the pool as it was, is readable after the halt zeroed the gas. +#[test] +fn test_a_draw_the_pool_cannot_pay_records_a_crossing_that_survives_the_halt() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA).drawing(POOL + 1); + let (action, gas) = run(&code, Some(POOL), &mut host); + + assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); + assert!(!host.start().2, "{kind:?}: the draw failed"); + assert_eq!( + gas.remaining(), + 0, + "{kind:?}: the halt zeroed the regular gas" + ); + assert_eq!( + gas.bytes_remaining(), + POOL, + "{kind:?}: the failed draw took nothing" + ); + assert_eq!(gas.bytes_spent(), 0, "{kind:?}"); + assert_eq!( + gas.bytes_crossing().map(|crossing| crossing.cost()), + Some(POOL + 1), + "{kind:?}" + ); + } +} + +/// A value call's child gets the schedule's history allowance where it gets the call stipend; +/// no other start does, and the default schedule gives none. +#[test] +fn test_the_history_allowance_is_set_on_a_value_call_only() { + let cases = [ + ("CALL with value", call_code(CALL, 1), ALLOWANCE), + ("CALLCODE with value", call_code(CALLCODE, 1), ALLOWANCE), + ("CALL without value", call_code(CALL, 0), 0), + ("CALLCODE without value", call_code(CALLCODE, 0), 0), + ("DELEGATECALL", call_code(DELEGATECALL, 0), 0), + ("STATICCALL", call_code(STATICCALL, 0), 0), + ]; + for (name, code, allowance) in &cases { + let mut host = PoolHost::new(SpecId::OSAKA).on_a_chains_schedule(); + let (action, _) = run(code, Some(POOL), &mut host); + let (_, _, found) = figures(&started(action)); + assert_eq!(found, *allowance, "{name}"); + + let mut host = PoolHost::new(SpecId::OSAKA); + let (action, _) = run(code, Some(POOL), &mut host); + let (_, _, found) = figures(&started(action)); + assert_eq!(found, 0, "{name}: none on the default schedule"); + } +} diff --git a/crates/interpreter/tests/byte_pool_serde.rs b/crates/interpreter/tests/byte_pool_serde.rs new file mode 100644 index 0000000000..4d2bdb6620 --- /dev/null +++ b/crates/interpreter/tests/byte_pool_serde.rs @@ -0,0 +1,132 @@ +//! Serde encoding of the byte-pool fields on the frame inputs and outcomes: the child's share, +//! the start charge and a call's history allowance. +//! +//! New encodings carry the fields. Encodings made before they existed lack them and still decode: +//! to an unlimited share, no start charge and no allowance, which is what a frame of a consumer +//! that uses none of them carries. +#![cfg(feature = "serde")] + +use core::fmt::Debug; +use primitives::{address, Bytes, U256}; +use revm_interpreter::{ + CallInput, CallInputs, CallOutcome, CallScheme, CallValue, CreateInputs, CreateOutcome, + CreateScheme, Gas, InstructionResult, InterpreterResult, StartCharge, +}; +use serde::{de::DeserializeOwned, Serialize}; +use serde_json::Value; +use state::Bytecode; + +const CHARGE: StartCharge = StartCharge::new(3_520, 160); + +/// Checks that `value` round-trips, and decodes to `without` once `fields` are removed from its +/// encoding. +fn assert_decodes_with_and_without(value: &T, fields: &[&str], without: &T) +where + T: Serialize + DeserializeOwned + PartialEq + Debug, +{ + let encoded = serde_json::to_value(value).unwrap(); + assert_eq!( + &serde_json::from_value::(encoded.clone()).unwrap(), + value + ); + + let Value::Object(mut object) = encoded else { + panic!("expected a JSON object, got {encoded}"); + }; + for field in fields { + assert!(object.remove(*field).is_some(), "{field} is encoded"); + } + assert_eq!( + &serde_json::from_value::(Value::Object(object)).unwrap(), + without + ); +} + +const fn interpreter_result() -> InterpreterResult { + InterpreterResult::new( + InstructionResult::Revert, + Bytes::from_static(b"reverted"), + Gas::new(100_000), + ) +} + +#[test] +fn test_call_inputs_decode_with_and_without_the_pool_fields() { + let inputs = |share, charge, allowance| CallInputs { + input: CallInput::Bytes(Bytes::from_static(b"in")), + return_memory_offset: 0..8, + gas_limit: 100_000, + reservoir: 50_000, + bytecode_address: address!("0x00000000000000000000000000000000000c0de0"), + known_bytecode: (Default::default(), Bytecode::default()), + target_address: address!("0x00000000000000000000000000000000000c0de0"), + caller: address!("0x00000000000000000000000000000000000ca11e"), + value: CallValue::Transfer(U256::from(1)), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: true, + charged_start: charge, + bytes_share: share, + history_allowance: allowance, + }; + + assert_decodes_with_and_without( + &inputs(980, CHARGE, 160), + &["bytes_share", "charged_start", "history_allowance"], + &inputs(u64::MAX, StartCharge::default(), 0), + ); +} + +#[test] +fn test_create_inputs_decode_with_and_without_the_pool_fields() { + let inputs = |share, charge| { + let mut inputs = CreateInputs::new( + address!("0x00000000000000000000000000000000000c0de0"), + CreateScheme::Create, + U256::from(1), + Bytes::from_static(&[0x5f, 0x5f, 0xfd]), + 100_000, + 50_000, + ); + inputs.set_bytes_share(share); + inputs.set_charged_start(charge); + inputs + }; + + assert_decodes_with_and_without( + &inputs(980, CHARGE), + &["bytes_share", "charged_start"], + &inputs(u64::MAX, StartCharge::default()), + ); + assert_eq!(CreateInputs::default().bytes_share(), u64::MAX); +} + +#[test] +fn test_call_outcome_decodes_with_and_without_the_start_charge() { + let outcome = |charge| { + let mut outcome = CallOutcome::new(interpreter_result(), 0..8); + outcome.charged_start = charge; + outcome + }; + + assert_decodes_with_and_without( + &outcome(CHARGE), + &["charged_start"], + &outcome(StartCharge::default()), + ); +} + +#[test] +fn test_create_outcome_decodes_with_and_without_the_start_charge() { + let outcome = |charge| { + let mut outcome = CreateOutcome::new(interpreter_result(), None); + outcome.charged_start = charge; + outcome + }; + + assert_decodes_with_and_without( + &outcome(CHARGE), + &["charged_start"], + &outcome(StartCharge::default()), + ); +} diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index c0aa1fea44..868920006e 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -778,8 +778,9 @@ fn input_gas(input: &FrameInput) -> (u64, u64) { } /// Each frame-starting instruction hands its start to the hook once the forward is taken, and -/// charges nothing after it: the instruction leaves the gas the hook was handed, and the frame's -/// input carries the forward, with a value call's stipend on top. +/// charges nothing after it: the instruction leaves the gas the hook was handed, apart from the +/// byte pool, whose share goes to the frame after the hook, and the frame's input carries the +/// forward, with a value call's stipend on top. #[test] fn test_a_start_reaches_the_hook_with_the_forward_taken() { let spec = SpecId::OSAKA; @@ -821,10 +822,12 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { before_forward - forward, "{name}: the hook sees the forward taken" ); + let mut after_the_forward = at_hook; + after_the_forward.set_bytes_remaining(0); assert_eq!( *gas.tracker(), - at_hook, - "{name}: nothing is charged after the hook" + after_the_forward, + "{name}: nothing is charged after the hook; the whole pool is forwarded" ); let stipend = if matches!(op, CALL | CALLCODE) { params.call_stipend() From 3a3c545066eb92a8f677bf6c07a32f0cc7327f2c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:38:48 +0800 Subject: [PATCH 010/110] feat(handler): seed, settle and refund the byte pool and the start charge A frame's gas starts with the share its caller forwarded as its byte pool and with the allowance its input carries, on the frame the handler runs and on an answer it gives without one. handle_reservoir_remaining_gas settles the pool as it settles the reservoir, not as regular gas: a child's rollback gives its draws back, so the caller absorbs the child's remaining pool on success and the whole share on revert and on halt, and the child's net draw merges into the caller's on success only, so a caller's rollback undoes its children's draws too. The transaction's frame gets the whole pool and the start charge a consumer declared on the transaction's gas. The start charge on a frame's input rides to its outcome and is refunded whole by return_result, and by last_frame_result for the first frame, on the condition the upfront state charge is refunded on, with refill_history and refill_bytes. --- crates/handler/src/execution.rs | 22 +++- crates/handler/src/frame.rs | 206 +++++++++++++++++++++++++++---- crates/handler/src/frame_data.rs | 28 ++++- crates/handler/src/handler.rs | 11 ++ 4 files changed, 241 insertions(+), 26 deletions(-) diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index e61c432c22..90dfc49d77 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -6,7 +6,7 @@ use context_interface::{ }; use interpreter::{ CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - GasTracker, StartCharge, + GasTracker, }; use primitives::{Address, TxKind}; use state::Bytecode; @@ -132,8 +132,11 @@ pub fn create_init_frame( return_memory_offset: 0..0, reservoir: gas.reservoir(), charged_new_account_state_gas, - charged_start: StartCharge::default(), - bytes_share: u64::MAX, + // The transaction's frame gets the whole pool, and the start charge a consumer + // declared on the transaction's gas; it gets no allowance, which is a value + // call's below the transaction. + charged_start: gas.take_start_charge(), + bytes_share: forward_whole_pool(gas), history_allowance: 0, })))) } @@ -179,11 +182,24 @@ pub fn create_init_frame( ); inputs.set_charged_create_state_gas(charged_create_state_gas); inputs.set_charged_state_gas_address(charged_state_gas_address); + inputs.set_charged_start(gas.take_start_charge()); + inputs.set_bytes_share(forward_whole_pool(gas)); Ok(Some(FrameInput::Create(Box::new(inputs)))) } } } +/// Takes the whole byte pool out of the transaction-level `gas` for the transaction's frame and +/// returns it: the frame's pool. The schedule's share applies to the frames below it; the +/// transaction's frame is the pool's first holder. `last_frame_result` adds back what the frame +/// leaves, as a caller does. +#[inline] +const fn forward_whole_pool(gas: &mut GasTracker) -> u64 { + let pool = gas.bytes_remaining(); + gas.forward_bytes(pool); + pool +} + /// Unwinds the EIP-2780 runtime gas phase after first-frame creation ran out /// of gas ([`create_init_frame`] returned `None`): reverts the phase's /// journal checkpoint — dropping all runtime state changes, including applied diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 4d0d56eff5..f5a69b1c44 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -18,7 +18,7 @@ use interpreter::{ interpreter_types::ReturnData, CallInput, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, CreateScheme, FrameInput, Gas, GasTracker, InputsImpl, InstructionResult, Interpreter, InterpreterAction, - InterpreterResult, InterpreterTypes, SharedMemory, + InterpreterResult, InterpreterTypes, SharedMemory, StartCharge, }; use primitives::{ constants::CALL_STACK_LIMIT, @@ -160,8 +160,15 @@ impl EthFrame { let charged_new_account_state_gas = inputs.charged_new_account_state_gas; let charged_state_gas_address = inputs.target_address; let charged_start = inputs.charged_start; - let gas = + // The child's byte pool is the share its caller forwarded, and its history allowance + // what the call instruction gave it; both ride on the frame's gas, as the reservoir + // does, whether the handler runs the frame or answers the start without one. + let bytes_share = inputs.bytes_share; + let history_allowance = inputs.history_allowance; + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas); + gas.set_bytes_remaining(bytes_share); + gas.set_history_allowance(history_allowance); let return_result = |instruction_result: InstructionResult| { Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome { @@ -211,7 +218,12 @@ impl EthFrame { let is_static = inputs.is_static; let gas_limit = inputs.gas_limit; - if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { + if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { + // The provider built the answer's gas from the inputs' regular gas and reservoir; the + // pool and the allowance it does not know are set here, so the caller's settlement + // gets its share back from the answer as it would from a frame. + result.gas.set_bytes_remaining(bytes_share); + result.gas.set_history_allowance(history_allowance); let mut logs = Vec::new(); if result.result.is_ok() { // Preserve the reservoir on the result gas so it can be reimbursed. @@ -244,7 +256,8 @@ impl EthFrame { } // Create interpreter and executes call and push new CallStackFrame. - this.get(EthFrame::invalid).clear( + let frame = this.get(EthFrame::invalid); + frame.clear( FrameData::Call(CallFrame { return_memory_range: inputs.return_memory_offset.clone(), }), @@ -259,6 +272,11 @@ impl EthFrame { reservoir_remaining_gas, checkpoint, ); + frame.interpreter.gas.set_bytes_remaining(bytes_share); + frame + .interpreter + .gas + .set_history_allowance(history_allowance); Ok(ItemOrResult::Item(this.consume())) } @@ -286,14 +304,20 @@ impl EthFrame { // — because the created address is not derivable here on the early-fail paths. let charged_state_gas_address = inputs.charged_state_gas_address(); let charged_start = inputs.charged_start(); + // The creation's byte pool is the share its caller forwarded; it rides on the frame's + // gas, as the reservoir does, on an early failure too, so the caller's settlement gets + // it back. + let bytes_share = inputs.bytes_share(); let return_error = |e| { + let mut gas = Gas::new_with_regular_gas_and_reservoir( + inputs.gas_limit(), + reservoir_remaining_gas, + ); + gas.set_bytes_remaining(bytes_share); Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome { result: InterpreterResult { result: e, - gas: Gas::new_with_regular_gas_and_reservoir( - inputs.gas_limit(), - reservoir_remaining_gas, - ), + gas, output: Bytes::new(), }, address: None, @@ -361,7 +385,8 @@ impl EthFrame { }; let gas_limit = inputs.gas_limit(); - this.get(EthFrame::invalid).clear( + let frame = this.get(EthFrame::invalid); + frame.clear( FrameData::Create(CreateFrame { created_address }), FrameInput::Create(inputs), depth, @@ -374,6 +399,7 @@ impl EthFrame { reservoir_remaining_gas, checkpoint, ); + frame.interpreter.gas.set_bytes_remaining(bytes_share); Ok(ItemOrResult::Item(this.consume())) } @@ -445,16 +471,21 @@ impl EthFrame { // Propagate EIP-8037 new-account state-gas flag from the frame // input so the parent can refund the upfront charge if the call // ends in revert/halt. - let (charged_new_account_state_gas, charged_state_gas_address) = match &self.input { - FrameInput::Call(inputs) => { - (inputs.charged_new_account_state_gas, inputs.target_address) - } - _ => (false, Address::ZERO), - }; + // The start charge rides along for the same refund. + let (charged_new_account_state_gas, charged_state_gas_address, charged_start) = + match &self.input { + FrameInput::Call(inputs) => ( + inputs.charged_new_account_state_gas, + inputs.target_address, + inputs.charged_start, + ), + _ => (false, Address::ZERO, StartCharge::default()), + }; let mut outcome = CallOutcome::new(interpreter_result, frame.return_memory_range.clone()); outcome.charged_new_account_state_gas = charged_new_account_state_gas; outcome.charged_state_gas_address = charged_state_gas_address; + outcome.charged_start = charged_start; ItemOrResult::Result(FrameResult::Call(outcome)) } FrameData::Create(frame) => { @@ -471,15 +502,18 @@ impl EthFrame { // inputs carry the address the charge site recorded, which is the one the // refund must use. An uncharged creation leaves it zero, so the field is // meaningful only when `charged_create_state_gas` is set. - let (charged_create_state_gas, charged_state_gas_address) = match &self.input { - FrameInput::Create(inputs) => ( - inputs.charged_create_state_gas(), - inputs.charged_state_gas_address(), - ), - _ => (false, Address::ZERO), - }; + let (charged_create_state_gas, charged_state_gas_address, charged_start) = + match &self.input { + FrameInput::Create(inputs) => ( + inputs.charged_create_state_gas(), + inputs.charged_state_gas_address(), + inputs.charged_start(), + ), + _ => (false, Address::ZERO, StartCharge::default()), + }; create_outcome.charged_create_state_gas = charged_create_state_gas; create_outcome.charged_state_gas_address = charged_state_gas_address; + create_outcome.charged_start = charged_start; ItemOrResult::Result(FrameResult::Create(create_outcome)) } }; @@ -516,6 +550,10 @@ impl EthFrame { }, None => None, }; + // The start charge the frame-start hook declared on this (parent) frame's tracker is + // refunded on the same condition, whole, by the same two refills a consumer's own + // take-back uses; it needs no price lookup, since the hook declared the amounts. + let refund_start_charge = result.refundable_start_charge(); // Insert result to the top frame. match result { @@ -606,6 +644,10 @@ impl EthFrame { if let Some(charge) = refund_state_gas { self.interpreter.gas.refill_reservoir(charge); } + if let Some(charge) = refund_start_charge { + self.interpreter.gas.refill_history(charge.history); + self.interpreter.gas.refill_bytes(charge.bytes); + } Ok(()) } @@ -631,6 +673,14 @@ impl EthFrame { /// - net state gas, net history gas, the spilled portion, and the refund counter /// persist only on success; on revert/halt the child's state changes roll back /// and contribute nothing. +/// - the byte pool settles as the reservoir does, not as regular gas: the child's +/// rollback gives its draws back to its pool, so what it hands back is its +/// remaining pool on success and the whole share it was given on revert *and on +/// halt*, since a halted frame appends nothing; the parent, which kept what it +/// did not forward, always absorbs it. The child's net draw merges into the +/// parent's on success only, as the history net does, so a later rollback of +/// the parent undoes the child's draws too. With no pool set, every figure here +/// is the unlimited pool going out and coming back. #[inline] pub const fn handle_reservoir_remaining_gas( instruction_result: InstructionResult, @@ -674,8 +724,10 @@ pub const fn handle_reservoir_remaining_gas( .saturating_add(child_gas.history_gas_spent()), ); parent_gas.record_refund(child_gas.refunded()); + parent_gas.add_bytes_spent(child_gas.bytes_spent()); } parent_gas.absorb_returned_reservoir(child_gas.reservoir()); + parent_gas.absorb_returned_bytes(child_gas.bytes_remaining()); } /// Handles the result of a CREATE operation, including validation and state updates. @@ -877,4 +929,114 @@ mod tests { assert_eq!(parent.state_gas_spent(), 0); assert_eq!(parent.state_gas_spilled(), 0); } + + /// A child with a share of its caller's pool. + fn child_with_share(parent: &mut GasTracker, share: u64) -> GasTracker { + parent.forward_bytes(share); + let mut child = GasTracker::new(500, 500, 0); + child.set_bytes_remaining(share); + child + } + + /// A child that succeeds hands back what it left of its share and its net draw; one that + /// reverts or halts hands back the whole share, its draws undone, and no net. The caller + /// kept what it did not forward either way. + #[test] + fn test_the_pool_settles_like_the_reservoir_not_like_regular_gas() { + for result in [ + InstructionResult::Stop, + InstructionResult::Revert, + InstructionResult::OutOfGas, + ] { + let mut parent = GasTracker::new(1_000, 1_000, 0); + parent.set_bytes_remaining(1_000); + assert!(parent.record_bytes(100)); + let mut child = child_with_share(&mut parent, 800); + assert_eq!(parent.bytes_remaining(), 100, "{result:?}: kept back"); + assert!(child.record_bytes(300)); + + handle_reservoir_remaining_gas(result, &mut parent, &mut child); + + let (pool, spent) = if result.is_ok() { + (600, 400) + } else { + (900, 100) + }; + assert_eq!(parent.bytes_remaining(), pool, "{result:?}"); + assert_eq!(parent.bytes_spent(), spent, "{result:?}"); + assert_eq!( + child.bytes_remaining(), + if result.is_ok() { 500 } else { 800 }, + "{result:?}: a failed child's pool reads as its share" + ); + } + } + + /// A caller's rollback undoes the draws of a child that succeeded inside it: B's revert + /// gives A back the whole share it forwarded, C's draws included. + #[test] + fn test_a_callers_rollback_undoes_a_successful_childs_draws() { + let mut a = GasTracker::new(1_000, 1_000, 0); + a.set_bytes_remaining(1_000); + let mut b = child_with_share(&mut a, 1_000); + assert!(b.record_bytes(100)); + let mut c = child_with_share(&mut b, 900); + assert!(c.record_bytes(100)); + + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); + assert_eq!((b.bytes_remaining(), b.bytes_spent()), (800, 200)); + + handle_reservoir_remaining_gas(InstructionResult::Revert, &mut a, &mut b); + assert_eq!((a.bytes_remaining(), a.bytes_spent()), (1_000, 0)); + } + + /// A child that gives back a draw its caller made goes below zero, and merging it into the + /// caller on success nets the two out, as a history refill does; on failure the refill is + /// undone with the rest. + #[test] + fn test_a_childs_refill_of_a_callers_draw_nets_out_on_success_only() { + for result in [InstructionResult::Stop, InstructionResult::Revert] { + let mut parent = GasTracker::new(1_000, 1_000, 0); + parent.set_bytes_remaining(1_000); + assert!(parent.record_bytes(100)); + let mut child = child_with_share(&mut parent, 900); + child.refill_bytes(100); + assert_eq!( + (child.bytes_remaining(), child.bytes_spent()), + (1_000, -100) + ); + + handle_reservoir_remaining_gas(result, &mut parent, &mut child); + + let (pool, spent) = if result.is_ok() { + (1_000, 0) + } else { + (900, 100) + }; + assert_eq!(parent.bytes_remaining(), pool, "{result:?}"); + assert_eq!(parent.bytes_spent(), spent, "{result:?}"); + } + } + + /// With no pool set, the unlimited pool goes out whole and comes back, less only what was + /// drawn and kept, and the regular-gas settlement is what it was. + #[test] + fn test_an_unset_pool_settles_to_the_same_regular_gas() { + for result in [InstructionResult::Stop, InstructionResult::OutOfGas] { + let mut parent = GasTracker::new(1_000, 1_000, 0); + assert!(parent.record_regular_cost(500)); + let mut with_pool = parent; + let pool = with_pool.bytes_remaining(); + let mut child = child_with_share(&mut with_pool, pool); + assert!(child.record_regular_cost(200)); + let mut plain_child = child; + + handle_reservoir_remaining_gas(result, &mut with_pool, &mut child); + handle_reservoir_remaining_gas(result, &mut parent, &mut plain_child); + + assert_eq!(with_pool.remaining(), parent.remaining(), "{result:?}"); + assert_eq!(with_pool.bytes_remaining(), u64::MAX, "{result:?}"); + assert_eq!(with_pool.bytes_spent(), 0, "{result:?}"); + } + } } diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index cfda9f3844..aac2c175ab 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -3,7 +3,9 @@ use context_interface::{ result::Output, }; use core::ops::Range; -use interpreter::{CallOutcome, CreateOutcome, Gas, InstructionResult, InterpreterResult}; +use interpreter::{ + CallOutcome, CreateOutcome, Gas, InstructionResult, InterpreterResult, StartCharge, +}; use primitives::Address; /// Call Frame @@ -171,6 +173,30 @@ impl FrameResult { } } +impl FrameResult { + /// The start charge to refund, or `None` when there is nothing to refund: the frame + /// succeeded, or its start charged nothing. + /// + /// The frame-start hook declared the charge on the caller's gas before the frame ran, and it + /// rides on the outcome's `charged_start`. The decision is the one + /// [`Self::refundable_state_gas_charge`] makes: a call refunds when it did not succeed, a + /// creation also when no contract address was deployed. The charge is refunded whole, with + /// `refill_history` and `refill_bytes`. + #[inline] + pub fn refundable_start_charge(&self) -> Option { + let (failed, charge) = match self { + FrameResult::Call(outcome) => { + (!outcome.instruction_result().is_ok(), outcome.charged_start) + } + FrameResult::Create(outcome) => ( + outcome.address.is_none() || !outcome.instruction_result().is_ok(), + outcome.charged_start, + ), + }; + (failed && !charge.is_zero()).then_some(charge) + } +} + impl FrameData { /// Creates a new create frame data. pub const fn new_create(created_address: Address) -> Self { diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 19c26b4faf..215b42b540 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -548,6 +548,17 @@ pub trait Handler { } } + // Refund the start charge a consumer declared on the transaction's gas for its frame, + // whole, on the same condition and with the same halt rule, exactly like + // `EthFrame::return_result` refunds the start charges of inner frames. + if let Some(charge) = frame_result.refundable_start_charge() { + parent_gas.refill_history(charge.history); + parent_gas.refill_bytes(charge.bytes); + if instruction_result.is_halt() { + parent_gas.spend_all(); + } + } + // The frame result carries the transaction-level gas onward to the // post-execution phase. *frame_result.gas_mut().tracker_mut() = *parent_gas; From a05ef6e70bc8176d2e3fdaaa2009c8b61920e077 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:38:48 +0800 Subject: [PATCH 011/110] test: the byte pool, the start charge and the allowance at the handler, on the plain and the inspected path The handler tests set a pool on the transaction's gas and drive the frames with instructions of their own that stand in for a consumer's hooks: the forward and the settlement at depth, a failed draw's record, the start charge refunded on revert, halt, a refused start, an answered start and a failed creation, the first frame's pool and charge, the allowance set on a value call's child and drawn only by the consumer, and a consumer that sets nothing ending as the mainnet handler does. The inspector tests run the same scenarios with transact and inspect_tx and check that both paths end the same way. --- crates/handler/tests/byte_pool.rs | 675 ++++++++++++++++++++++++++++ crates/inspector/tests/byte_pool.rs | 446 ++++++++++++++++++ 2 files changed, 1121 insertions(+) create mode 100644 crates/handler/tests/byte_pool.rs create mode 100644 crates/inspector/tests/byte_pool.rs diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs new file mode 100644 index 0000000000..3086e8076a --- /dev/null +++ b/crates/handler/tests/byte_pool.rs @@ -0,0 +1,675 @@ +//! The byte pool, the start charge and the history allowance, as the mainnet handler forwards +//! and settles them. +//! +//! A consumer sets the transaction's pool on the gas `tx_gas` returns; every frame then starts +//! with the share its caller's instruction forwarded, and `handle_reservoir_remaining_gas` settles +//! what it left: its remaining pool when it succeeded, the whole share when it reverted or halted. +//! A start charge a hook declared rides on the frame's input and is refunded whole when the frame +//! fails. The handler here is the mainnet one, observed through overrides that leave its behaviour +//! alone, and the frames draw the pool through instructions of the test's own, which stand in for +//! a consumer's hooks: `DRAW` draws bytes, `DECLARE` charges and declares a start charge before +//! the next start, and `LOG` charges history after drawing the frame's allowance, as a consumer's +//! write hook would. + +use bytecode::opcode::{ + CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, STOP, +}; +use context::{ + result::{EVMError, ExecutionResult}, + Context, ContextSetters, Evm, TxEnv, +}; +use context_interface::{ + cfg::{gas::InitialAndFloorGas, GasId}, + Database, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, StartCharge, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_handler::{ + instructions::EthInstructions, EthFrame, EthPrecompiles, EvmTr, FrameResult, Handler, + ItemOrResult, MainContext, MainnetContext, MainnetEvm, MainnetHandler, +}; +use state::{AccountInfo, Bytecode}; + +type Db = CacheDB; +type DbError = ::Error; +type TestContext = MainnetContext; +type TestEvm = MainnetEvm; +type TestError = EVMError; +type Mainnet = MainnetHandler>; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 3_000_000; +/// The pool the transaction's frame starts with. +const POOL: u64 = 1_000; +/// What `DRAW` draws. +const DRAW_BYTES: u64 = 100; +/// What `DECLARE` charges and declares. +const DECLARED: StartCharge = StartCharge::new(3_520, 160); +/// What `LOG` charges as history. +const HISTORY_COST: u64 = 100; +/// A value call's history allowance on a chain that gives one. +const ALLOWANCE: u64 = 160; + +/// The account the transaction calls. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Draws and stops. +const OK: Address = address!("0x0000000000000000000000000000000000000c00"); +/// Draws and reverts. +const REVERTER: Address = address!("0x000000000000000000000000000000000000c0fd"); +/// Draws and halts. +const HALTER: Address = address!("0x000000000000000000000000000000000000c0fe"); +/// Draws, calls [`OK`] and reverts. +const NESTER: Address = address!("0x000000000000000000000000000000000000c0e5"); +/// Charges history after drawing its allowance, and stops. +const LOGGER: Address = address!("0x000000000000000000000000000000000000c109"); +/// An account that does not exist. +const EMPTY: Address = address!("0x00000000000000000000000000000000000e3970"); +/// The `ECRECOVER` precompile, which costs 3,000. +const ECRECOVER: Address = address!("0x0000000000000000000000000000000000000001"); + +/// The test's instructions, on opcodes the EVM does not assign. +const DRAW: u8 = 0x0c; +const DECLARE: u8 = 0x0d; +const LOG: u8 = 0x0e; + +/// Draws [`DRAW_BYTES`] from the frame's pool; a draw the pool cannot pay is the frame's stop. +const fn draw( + context: InstructionContext<'_, TestContext, EthInterpreter>, +) -> InstructionExecResult { + if context.interpreter.gas.record_bytes(DRAW_BYTES) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +/// What a consumer's start hook does for the start that follows: charges [`DECLARED`] on the +/// frame's gas and declares it. +const fn declare( + context: InstructionContext<'_, TestContext, EthInterpreter>, +) -> InstructionExecResult { + let gas = &mut context.interpreter.gas; + assert!(gas.record_history_cost(DECLARED.history)); + assert!(gas.record_bytes(DECLARED.bytes)); + gas.set_start_charge(DECLARED); + Ok(()) +} + +/// What a consumer's write hook does for a log: draws the frame's allowance for [`HISTORY_COST`] +/// and charges the rest as history. +const fn log( + context: InstructionContext<'_, TestContext, EthInterpreter>, +) -> InstructionExecResult { + let gas = &mut context.interpreter.gas; + let rest = gas.draw_history_allowance(HISTORY_COST); + if gas.record_history_cost(rest) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +/// A frame's pool figures as it returned, before its caller settled it: its result, its pool, +/// its net draw, the draw that failed, its history gas and its allowance. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Returned { + result: InstructionResult, + pool: u64, + spent: i64, + crossing: Option, + history: i64, + allowance: u64, +} + +impl Returned { + fn of(result: &FrameResult) -> Self { + let gas = result.gas(); + Self { + result: result.instruction_result(), + pool: gas.bytes_remaining(), + spent: gas.bytes_spent(), + crossing: gas.bytes_crossing().map(|crossing| crossing.cost()), + history: gas.history_gas_spent(), + allowance: gas.history_allowance(), + } + } + + const fn stopped(pool: u64, spent: i64) -> Self { + Self::ended(InstructionResult::Stop, pool, spent) + } + + const fn ended(result: InstructionResult, pool: u64, spent: i64) -> Self { + Self { + result, + pool, + spent, + crossing: None, + history: 0, + allowance: 0, + } + } +} + +/// The figures of a frame's input as it started: its share, its start charge and its allowance. +type Started = (u64, StartCharge, u64); + +fn started(input: &FrameInput) -> Started { + match input { + FrameInput::Call(inputs) => ( + inputs.bytes_share, + inputs.charged_start, + inputs.history_allowance, + ), + FrameInput::Create(inputs) => (inputs.bytes_share(), inputs.charged_start(), 0), + FrameInput::Empty => unreachable!(), + } +} + +/// The transaction's gas after the first frame settled into it: its pool, its net draw and its +/// history gas. +type Settled = (u64, i64, i64); + +/// The mainnet handler with the consumer's part: a pool and a start charge set on the +/// transaction's gas, and a record of every frame's start and return. +struct PoolHandler { + mainnet: Mainnet, + /// The pool the transaction's gas gets, if any. + pool: Option, + /// Whether the transaction's gas is charged [`DECLARED`] for its frame and declares it. + declare: bool, + starts: Vec, + returned: Vec, + settled: Option, +} + +impl PoolHandler { + fn new(pool: Option) -> Self { + Self { + mainnet: Mainnet::default(), + pool, + declare: false, + starts: Vec::new(), + returned: Vec::new(), + settled: None, + } + } +} + +impl Handler for PoolHandler { + type Evm = TestEvm; + type Error = TestError; + type HaltReason = context::result::HaltReason; + + /// The mainnet gas, with the consumer's pool and, if told to, the start charge of the + /// transaction's frame, charged here as a consumer charges the body's records. + fn tx_gas(&self, evm: &mut TestEvm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.mainnet.tx_gas(evm, init_and_floor_gas); + if let Some(pool) = self.pool { + gas.set_bytes_remaining(pool); + } + if self.declare { + assert!(gas.record_history_cost(DECLARED.history)); + assert!(gas.record_bytes(DECLARED.bytes)); + gas.set_start_charge(DECLARED); + } + gas + } + + /// The default loop, recording each frame's input as it starts and its result as it + /// returns, before its caller settles it. + fn run_exec_loop( + &mut self, + evm: &mut TestEvm, + first_frame_input: FrameInit, + ) -> Result { + self.starts.push(started(&first_frame_input.frame_input)); + if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { + self.returned.push(Returned::of(&result)); + return Ok(result); + } + loop { + let result = match evm.frame_run()? { + ItemOrResult::Item(init) => { + self.starts.push(started(&init.frame_input)); + match evm.frame_init(init)? { + ItemOrResult::Item(_) => continue, + ItemOrResult::Result(result) => result, + } + } + ItemOrResult::Result(result) => result, + }; + self.returned.push(Returned::of(&result)); + if let Some(result) = evm.frame_return_result(result)? { + return Ok(result); + } + } + } + + /// The default, recording the transaction's gas as the first frame left it. + fn post_execution( + &self, + evm: &mut TestEvm, + exec_result: &mut FrameResult, + init_and_floor_gas: InitialAndFloorGas, + eip7702_refund: i64, + ) -> Result { + let gas = exec_result.gas(); + // `post_execution` takes `&self`; the record goes through a cell. + SETTLED.with(|settled| { + settled.set(Some(( + gas.bytes_remaining(), + gas.bytes_spent(), + gas.history_gas_spent(), + ))) + }); + self.mainnet + .post_execution(evm, exec_result, init_and_floor_gas, eip7702_refund) + } +} + +thread_local! { + static SETTLED: core::cell::Cell> = const { core::cell::Cell::new(None) }; +} + +/// `CALL(100_000, to, value, 0, 0, 0, 0)`, dropping the success flag. +fn call(to: Address, value: u8) -> Vec { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]; + code.extend_from_slice(to.as_slice()); + code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP]); + code +} + +/// `CALL(10, to, 0, 0, 0, 0, 0)`: too little gas for any precompile, dropping the success flag. +fn starved_call(to: Address) -> Vec { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + code.extend_from_slice(to.as_slice()); + code.extend_from_slice(&[PUSH1, 10, CALL, POP]); + code +} + +/// `CREATE` of `initcode`, at most 32 bytes, endowed with nothing, dropping the address. +fn create(initcode: &[u8]) -> Vec { + let len = initcode.len() as u8; + let mut code = vec![PUSH0 + len]; + code.extend_from_slice(initcode); + code.extend_from_slice(&[ + PUSH0, + MSTORE, + PUSH1, + len, + PUSH1, + 32 - len, + PUSH0, + CREATE, + POP, + ]); + code +} + +fn ends(mut code: Vec) -> Vec { + code.push(STOP); + code +} + +/// A transaction to [`PARENT`], holding `parent`, on the accounts every test knows. +struct Run { + parent: Vec, + parent_balance: u64, + parent_nonce: u64, + /// `call_history_allowance` in the schedule. + allowance: u64, +} + +impl Run { + const fn new(parent: Vec) -> Self { + Self { + parent, + parent_balance: 10, + parent_nonce: 1, + allowance: 0, + } + } + + const fn penniless(mut self) -> Self { + self.parent_balance = 0; + self + } + + const fn nonce(mut self, nonce: u64) -> Self { + self.parent_nonce = nonce; + self + } + + const fn allowance(mut self, allowance: u64) -> Self { + self.allowance = allowance; + self + } + + fn db(&self) -> Db { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut nester = vec![DRAW]; + nester.extend(call(OK, 0)); + nester.extend_from_slice(&[PUSH0, PUSH0, REVERT]); + let accounts: [(Address, Vec, u64, u64); 6] = [ + ( + PARENT, + self.parent.clone(), + self.parent_balance, + self.parent_nonce, + ), + (OK, vec![DRAW, STOP], 0, 1), + (REVERTER, vec![DRAW, PUSH0, PUSH0, REVERT], 0, 1), + (HALTER, vec![DRAW, INVALID], 0, 1), + (NESTER, nester, 0, 1), + (LOGGER, vec![LOG, STOP], 0, 1), + ]; + for (address, code, balance, nonce) in accounts { + let info = AccountInfo::from_balance(U256::from(balance)) + .with_nonce(nonce) + .with_code(Bytecode::new_raw(Bytes::from(code))); + db.insert_account_info(address, info); + } + db + } + + fn evm(&self) -> TestEvm { + let allowance = self.allowance; + let ctx: TestContext = Context::mainnet() + .with_db(self.db()) + .modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SPEC); + cfg.gas_params + .override_gas([(GasId::call_history_allowance(), allowance)]); + }); + let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); + instructions.insert_instruction(DRAW, Instruction::new(draw), 0); + instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); + instructions.insert_instruction(LOG, Instruction::new(log), 0); + let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(SPEC)); + evm.ctx.set_tx( + TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(), + ); + evm + } + + /// Runs the transaction with `handler` and returns its result and the handler, with what it + /// recorded. + fn with(&self, mut handler: PoolHandler) -> (ExecutionResult, PoolHandler) { + SETTLED.with(|settled| settled.set(None)); + let result = handler.run(&mut self.evm()).expect("the transaction runs"); + handler.settled = SETTLED.with(|settled| settled.get()); + (result, handler) + } + + /// Runs the transaction with the mainnet handler as it is. + fn on_mainnet(&self) -> ExecutionResult { + Mainnet::default() + .run(&mut self.evm()) + .expect("the transaction runs") + } +} + +/// [`PARENT`] draws, then calls a child that stops, one that reverts, one that halts and one +/// that calls a child of its own and reverts. +fn at_depth() -> Run { + let mut parent = vec![DRAW]; + for child in [OK, REVERTER, HALTER, NESTER] { + parent.extend(call(child, 0)); + } + Run::new(ends(parent)) +} + +/// The transaction's frame gets the whole pool, and every start forwards the whole pool its +/// caller has left. A child that succeeds hands back what it left and its net draw merges into +/// the caller's; a child that reverts or halts hands back the whole share, its draws undone, and +/// so do the draws of a child of its own that succeeded. +#[test] +fn test_the_pool_is_forwarded_whole_and_settled_at_depth() { + let (result, handler) = at_depth().with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{result:?}"); + let share = |pool| (pool, StartCharge::default(), 0); + assert_eq!( + handler.starts, + [ + share(POOL), + // PARENT drew 100. + share(900), + // OK drew 100 and stopped. + share(800), + // REVERTER and HALTER gave the whole share back. + share(800), + share(800), + // OK, inside NESTER, which drew 100 first. + share(700), + ] + ); + assert_eq!( + handler.returned, + [ + Returned::stopped(800, 100), + Returned::ended(InstructionResult::Revert, 700, 100), + Returned::ended(InstructionResult::InvalidFEOpcode, 700, 100), + // OK inside NESTER. + Returned::stopped(600, 100), + // NESTER: its own draw and OK's, before its rollback. + Returned::ended(InstructionResult::Revert, 600, 200), + // PARENT: its own draw and the first OK's. + Returned::stopped(800, 200), + ] + ); + assert_eq!(handler.settled, Some((800, 200, 0))); +} + +/// A draw the pool cannot pay takes nothing and records the crossing; the consumer's instruction +/// halts the frame, and the record is readable on the frame's result before its caller settles +/// it, with the pool as the failed draw found it. The caller gets the whole share back. +#[test] +fn test_a_failed_draw_halts_the_frame_with_a_record_the_caller_can_read() { + let mut parent = vec![DRAW]; + parent.extend(call(OK, 0)); + let run = Run::new(ends(parent)); + + let (result, handler) = run.with(PoolHandler::new(Some(150))); + + assert!(result.is_success(), "{result:?}"); + assert_eq!(handler.starts[1], (50, StartCharge::default(), 0)); + assert_eq!( + handler.returned, + [ + Returned { + crossing: Some(DRAW_BYTES), + ..Returned::ended(InstructionResult::OutOfGas, 50, 0) + }, + Returned::stopped(50, 100), + ] + ); + assert_eq!(handler.settled, Some((50, 100, 0))); +} + +/// A start charge declared before a start rides on the frame's input, and is refunded to the +/// caller whole when the frame fails: a revert, a halt, a start the handler refused before any +/// frame ran (a transfer the caller cannot pay), one it answered without a frame (a precompile +/// out of gas), a creation that reverted and one whose caller's nonce overflowed. A frame that +/// succeeds keeps the charge. +#[test] +fn test_the_start_charge_is_refunded_when_the_frame_fails() { + let reverting_initcode = [PUSH0, PUSH0, REVERT]; + let cases: Vec<(&str, Run, bool)> = vec![ + ("a child that stops", Run::new(call(OK, 0)), false), + ("a child that reverts", Run::new(call(REVERTER, 0)), true), + ("a child that halts", Run::new(call(HALTER, 0)), true), + ( + "a transfer the caller cannot pay", + Run::new(call(EMPTY, 1)).penniless(), + true, + ), + ( + "a precompile out of gas", + Run::new(starved_call(ECRECOVER)), + true, + ), + ( + "a creation that reverts", + Run::new(create(&reverting_initcode)), + true, + ), + ( + "a creation whose caller's nonce overflowed", + Run::new(create(&[STOP])).nonce(u64::MAX), + true, + ), + ]; + for (name, run, fails) in cases { + let mut parent = vec![DECLARE]; + parent.extend(run.parent.clone()); + let run = Run { + parent: ends(parent), + ..run + }; + + let (result, handler) = run.with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{name}: {result:?}"); + assert_eq!(handler.starts.len(), 2, "{name}"); + assert_eq!( + handler.starts[1], + (POOL - DECLARED.bytes, DECLARED, 0), + "{name}: the charge rides on the input" + ); + let settled = handler.settled.expect(name); + if fails { + assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); + } else { + let drawn = DECLARED.bytes + DRAW_BYTES; + assert_eq!( + settled, + (POOL - drawn, drawn as i64, DECLARED.history as i64), + "{name}: kept" + ); + } + } +} + +/// The transaction's frame gets the pool as the consumer left it after the body's charges, and +/// the start charge the consumer declared, which is refunded whole when the frame reverts or +/// halts and kept when it succeeds. +#[test] +fn test_the_first_frame_gets_the_pool_and_its_start_charge() { + for (name, parent, fails) in [ + ("stops", vec![DRAW, STOP], false), + ("reverts", vec![DRAW, PUSH0, PUSH0, REVERT], true), + ("halts", vec![DRAW, INVALID], true), + ] { + let mut handler = PoolHandler::new(Some(POOL)); + handler.declare = true; + + let (result, handler) = Run::new(parent).with(handler); + + assert_eq!(result.is_success(), name == "stops", "{name}: {result:?}"); + assert_eq!( + handler.starts, + [(POOL - DECLARED.bytes, DECLARED, 0)], + "{name}" + ); + let settled = handler.settled.expect(name); + if fails { + assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); + } else { + let drawn = DECLARED.bytes + DRAW_BYTES; + assert_eq!( + settled, + (POOL - drawn, drawn as i64, DECLARED.history as i64), + "{name}: kept" + ); + } + } +} + +/// A value call's child starts with the schedule's history allowance and no other frame does; +/// nothing but the consumer draws it, so a frame that charges no history returns it whole, and a +/// consumer's charge takes the allowance before the budget. +#[test] +fn test_the_history_allowance_reaches_a_value_calls_child_and_only_the_consumer_draws_it() { + let mut parent = call(LOGGER, 1); + parent.extend(call(LOGGER, 0)); + parent.extend(call(OK, 1)); + let run = Run::new(ends(parent)).allowance(ALLOWANCE); + + let (result, handler) = run.with(PoolHandler::new(None)); + + assert!(result.is_success(), "{result:?}"); + let shares: Vec = handler.starts.iter().map(|start| start.0).collect(); + assert_eq!(shares, [u64::MAX; 4], "no pool was set"); + let allowances: Vec = handler.starts.iter().map(|start| start.2).collect(); + assert_eq!(allowances, [0, ALLOWANCE, 0, ALLOWANCE]); + assert_eq!( + handler.returned, + [ + // The value call's logger: the allowance paid the whole charge. + Returned { + allowance: ALLOWANCE - HISTORY_COST, + ..Returned::stopped(u64::MAX, 0) + }, + // The plain call's logger: no allowance, the budget paid. + Returned { + history: HISTORY_COST as i64, + ..Returned::stopped(u64::MAX, 0) + }, + // A value call that charges no history keeps its allowance whole. + Returned { + allowance: ALLOWANCE, + ..Returned::stopped(u64::MAX - DRAW_BYTES, DRAW_BYTES as i64) + }, + // PARENT, with the plain call's history charge merged in and no allowance of its own. + Returned { + history: HISTORY_COST as i64, + ..Returned::stopped(u64::MAX - DRAW_BYTES, DRAW_BYTES as i64) + }, + ] + ); + assert_eq!( + handler.settled, + Some(( + u64::MAX - DRAW_BYTES, + DRAW_BYTES as i64, + HISTORY_COST as i64 + )) + ); + + // On the default schedule no frame gets an allowance. + let (_, handler) = Run::new(ends(call(LOGGER, 1))).with(PoolHandler::new(None)); + assert_eq!(handler.starts[1].2, 0); + assert_eq!(handler.returned[0].history, HISTORY_COST as i64); +} + +/// A consumer that sets nothing runs on an unlimited pool, which every start forwards whole, less +/// only what the test's own draws took, and every return settles back; the transaction ends as it +/// does on the mainnet handler. +#[test] +fn test_a_consumer_that_sets_nothing_sees_the_mainnet_result() { + let run = at_depth(); + let (result, handler) = run.with(PoolHandler::new(None)); + + assert_eq!(result, run.on_mainnet()); + let shares: Vec = handler.starts.iter().map(|start| start.0).collect(); + let less = |draws: u64| u64::MAX - draws * DRAW_BYTES; + assert_eq!( + shares, + [less(0), less(1), less(2), less(2), less(2), less(3)], + "the unlimited pool, less the draws so far" + ); + assert_eq!(handler.settled, Some((less(2), 2 * DRAW_BYTES as i64, 0))); +} diff --git a/crates/inspector/tests/byte_pool.rs b/crates/inspector/tests/byte_pool.rs new file mode 100644 index 0000000000..ea09440522 --- /dev/null +++ b/crates/inspector/tests/byte_pool.rs @@ -0,0 +1,446 @@ +//! The byte pool, the start charge and the history allowance on the plain and the inspected path. +//! +//! `transact` runs the frames in the handler's loop and `inspect_tx` in the inspector's; both +//! build frames with `make_call_frame` and `make_create_frame` and settle them with +//! `return_result`, so a child's share, its start charge and its allowance travel the same way +//! and settle to the same figures. Each test runs a transaction both ways on the mainnet context +//! with instructions of the test's own, which stand in for a consumer's hooks, and checks that the +//! two paths end the same way; an inspector records each frame's input as it starts and its +//! outcome as it ends, before its caller settles it, and the figures are checked on the inspected +//! path (the handler's tests check them on the plain one). + +use context::{result::ResultAndState, Context, Evm, TxEnv}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + instructions::EthInstructions, EthFrame, EthPrecompiles, ExecuteEvm, MainContext, + MainnetContext, +}; +use interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Instruction, + InstructionContext, InstructionExecResult, InstructionResult, StartCharge, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{InspectEvm, Inspector}; +use state::{ + bytecode::opcode::{ + CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, STOP, + }, + AccountInfo, Bytecode, +}; + +type Db = CacheDB; +type Ctx = MainnetContext; +type PoolEvm = Evm, EthPrecompiles, EthFrame>; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 3_000_000; +/// What `DRAW` draws. +const DRAW_BYTES: u64 = 100; +/// What `DECLARE` charges and declares. +const DECLARED: StartCharge = StartCharge::new(3_520, 160); +/// What `LOG` charges as history. +const HISTORY_COST: u64 = 100; +/// A value call's history allowance on a chain that gives one. +const ALLOWANCE: u64 = 160; +/// The pool nobody set. +const UNLIMITED: u64 = u64::MAX; + +/// The account the transaction calls. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Draws and stops. +const OK: Address = address!("0x0000000000000000000000000000000000000c00"); +/// Draws and reverts. +const REVERTER: Address = address!("0x000000000000000000000000000000000000c0fd"); +/// Draws and halts. +const HALTER: Address = address!("0x000000000000000000000000000000000000c0fe"); +/// Draws, calls [`OK`] and reverts. +const NESTER: Address = address!("0x000000000000000000000000000000000000c0e5"); +/// Draws more than any pool holds. +const DRAINER: Address = address!("0x000000000000000000000000000000000000d7a1"); +/// Charges history after drawing its allowance, and stops. +const LOGGER: Address = address!("0x000000000000000000000000000000000000c109"); + +/// The test's instructions, on opcodes the EVM does not assign. +const DRAW: u8 = 0x0c; +const DECLARE: u8 = 0x0d; +const LOG: u8 = 0x0e; +const DRAIN: u8 = 0x0f; + +const fn draw(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { + if context.interpreter.gas.record_bytes(DRAW_BYTES) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { + if context.interpreter.gas.record_bytes(u64::MAX) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +/// What a consumer's start hook does for the start that follows. +const fn declare(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { + let gas = &mut context.interpreter.gas; + assert!(gas.record_history_cost(DECLARED.history)); + assert!(gas.record_bytes(DECLARED.bytes)); + gas.set_start_charge(DECLARED); + Ok(()) +} + +/// What a consumer's write hook does for a log. +const fn log(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { + let gas = &mut context.interpreter.gas; + let rest = gas.draw_history_allowance(HISTORY_COST); + if gas.record_history_cost(rest) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +/// A frame's figures as it ended, before its caller settled it. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Ended { + result: InstructionResult, + pool: u64, + spent: i64, + crossing: Option, + history: i64, + allowance: u64, + charged_start: StartCharge, +} + +impl Ended { + const fn stopped(pool: u64, spent: i64) -> Self { + Self::with(InstructionResult::Stop, pool, spent) + } + + const fn with(result: InstructionResult, pool: u64, spent: i64) -> Self { + Self { + result, + pool, + spent, + crossing: None, + history: 0, + allowance: 0, + charged_start: StartCharge::new(0, 0), + } + } +} + +/// Every frame's input as it started (share, start charge, allowance) and its outcome as it +/// ended. +#[derive(Default)] +struct Figures { + starts: Vec<(u64, StartCharge, u64)>, + ends: Vec, +} + +impl Figures { + fn end(&mut self, result: InstructionResult, gas: &interpreter::Gas, charged: StartCharge) { + self.ends.push(Ended { + result, + pool: gas.bytes_remaining(), + spent: gas.bytes_spent(), + crossing: gas.bytes_crossing().map(|crossing| crossing.cost()), + history: gas.history_gas_spent(), + allowance: gas.history_allowance(), + charged_start: charged, + }); + } +} + +impl Inspector for Figures { + fn call(&mut self, _context: &mut Ctx, inputs: &mut CallInputs) -> Option { + self.starts.push(( + inputs.bytes_share, + inputs.charged_start, + inputs.history_allowance, + )); + None + } + + fn create(&mut self, _context: &mut Ctx, inputs: &mut CreateInputs) -> Option { + self.starts + .push((inputs.bytes_share(), inputs.charged_start(), 0)); + None + } + + fn call_end(&mut self, _context: &mut Ctx, _inputs: &CallInputs, outcome: &mut CallOutcome) { + self.end( + *outcome.instruction_result(), + &outcome.result.gas, + outcome.charged_start, + ); + } + + fn create_end( + &mut self, + _context: &mut Ctx, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.end( + *outcome.instruction_result(), + &outcome.result.gas, + outcome.charged_start, + ); + } +} + +/// `CALL(100_000, to, value, 0, 0, 0, 0)`, dropping the success flag. +fn call(to: Address, value: u8) -> Vec { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]; + code.extend_from_slice(to.as_slice()); + code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP]); + code +} + +/// `CREATE` of `initcode`, at most 32 bytes, endowed with nothing, dropping the address. +fn create(initcode: &[u8]) -> Vec { + let len = initcode.len() as u8; + let mut code = vec![PUSH0 + len]; + code.extend_from_slice(initcode); + code.extend_from_slice(&[ + PUSH0, + MSTORE, + PUSH1, + len, + PUSH1, + 32 - len, + PUSH0, + CREATE, + POP, + ]); + code +} + +fn ends(mut code: Vec) -> Vec { + code.push(STOP); + code +} + +/// A transaction to [`PARENT`], holding `parent`, on the accounts every test knows. +struct Run { + parent: Vec, + allowance: u64, +} + +impl Run { + const fn new(parent: Vec) -> Self { + Self { + parent, + allowance: 0, + } + } + + const fn allowance(mut self, allowance: u64) -> Self { + self.allowance = allowance; + self + } + + fn evm(&self) -> PoolEvm { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut nester = vec![DRAW]; + nester.extend(call(OK, 0)); + nester.extend_from_slice(&[PUSH0, PUSH0, REVERT]); + let accounts: [(Address, Vec); 7] = [ + (PARENT, self.parent.clone()), + (OK, vec![DRAW, STOP]), + (REVERTER, vec![DRAW, PUSH0, PUSH0, REVERT]), + (HALTER, vec![DRAW, INVALID]), + (NESTER, nester), + (DRAINER, vec![DRAIN, STOP]), + (LOGGER, vec![LOG, STOP]), + ]; + for (address, code) in accounts { + let info = AccountInfo::from_balance(U256::from(10)) + .with_nonce(1) + .with_code(Bytecode::new_raw(Bytes::from(code))); + db.insert_account_info(address, info); + } + let allowance = self.allowance; + let ctx: Ctx = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SPEC); + cfg.gas_params.override_gas([( + context::context_interface::cfg::GasId::call_history_allowance(), + allowance, + )]); + }); + let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); + instructions.insert_instruction(DRAW, Instruction::new(draw), 0); + instructions.insert_instruction(DRAIN, Instruction::new(drain), 0); + instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); + instructions.insert_instruction(LOG, Instruction::new(log), 0); + Evm::new_with_inspector( + ctx, + Figures::default(), + instructions, + EthPrecompiles::new(SPEC), + ) + } + + fn tx() -> TxEnv { + TxEnv::builder() + .caller(BENCH_CALLER) + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build() + .unwrap() + } + + /// The transaction with `transact` and with `inspect_tx`, which must end the same way. + /// Returns the outcome and the figures the inspector saw. + fn on_both_paths(&self) -> (ResultAndState, Figures) { + let mut plain = self.evm(); + let transacted = plain.transact(Self::tx()).expect("the transaction runs"); + let mut inspected = self.evm(); + let inspected_outcome = inspected + .inspect_tx(Self::tx()) + .expect("the transaction runs"); + assert_eq!(inspected_outcome, transacted, "both paths end the same way"); + (transacted, inspected.inspector) + } +} + +/// Both paths forward the whole pool, less the draws so far, and settle a child's return the +/// same way: what it left on success, the whole share on revert and on halt, a nested success's +/// draws undone with its caller's revert. +#[test] +fn test_both_paths_forward_and_settle_the_pool_at_depth() { + let mut parent = vec![DRAW]; + for child in [OK, REVERTER, HALTER, NESTER] { + parent.extend(call(child, 0)); + } + let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let less = |draws: u64| UNLIMITED - draws * DRAW_BYTES; + let share = |pool| (pool, StartCharge::default(), 0); + assert_eq!( + figures.starts, + [ + share(less(0)), + share(less(1)), + share(less(2)), + share(less(2)), + share(less(2)), + share(less(3)), + ] + ); + assert_eq!( + figures.ends, + [ + Ended::stopped(less(2), 100), + Ended::with(InstructionResult::Revert, less(3), 100), + Ended::with(InstructionResult::InvalidFEOpcode, less(3), 100), + Ended::stopped(less(4), 100), + Ended::with(InstructionResult::Revert, less(4), 200), + Ended::stopped(less(2), 200), + ] + ); +} + +/// A draw the pool cannot pay records a crossing the inspector reads off the frame's outcome, +/// with the pool as the draw found it, on both paths. +#[test] +fn test_both_paths_record_a_failed_draw() { + let mut parent = vec![DRAW]; + parent.extend(call(DRAINER, 0)); + let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + figures.ends, + [ + Ended { + crossing: Some(u64::MAX), + ..Ended::with(InstructionResult::OutOfGas, UNLIMITED - DRAW_BYTES, 0) + }, + Ended::stopped(UNLIMITED - DRAW_BYTES, DRAW_BYTES as i64), + ] + ); +} + +/// A declared start charge rides on the input and the outcome, and the caller gets it back whole +/// when the frame reverts, halts or is a creation that reverts, and keeps it when the frame +/// succeeds, on both paths. +#[test] +fn test_both_paths_refund_the_start_charge_when_the_frame_fails() { + let reverting_initcode = [PUSH0, PUSH0, REVERT]; + for (name, start, fails) in [ + ("a child that stops", call(OK, 0), false), + ("a child that reverts", call(REVERTER, 0), true), + ("a child that halts", call(HALTER, 0), true), + ("a creation that reverts", create(&reverting_initcode), true), + ] { + let mut parent = vec![DECLARE]; + parent.extend(start); + let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); + + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!( + figures.starts[1], + (UNLIMITED - DECLARED.bytes, DECLARED, 0), + "{name}: the charge rides on the input" + ); + assert_eq!( + figures.ends[0].charged_start, DECLARED, + "{name}: and on the outcome" + ); + let parent_end = figures.ends.last().unwrap(); + if fails { + assert_eq!( + (parent_end.pool, parent_end.spent, parent_end.history), + (UNLIMITED, 0, 0), + "{name}: refunded whole" + ); + } else { + let drawn = DECLARED.bytes + DRAW_BYTES; + assert_eq!( + (parent_end.pool, parent_end.spent, parent_end.history), + (UNLIMITED - drawn, drawn as i64, DECLARED.history as i64), + "{name}: kept" + ); + } + } +} + +/// A value call's child starts with the schedule's allowance on both paths, and a consumer's +/// charge takes it before the budget. +#[test] +fn test_both_paths_give_a_value_calls_child_the_allowance() { + let mut parent = call(LOGGER, 1); + parent.extend(call(LOGGER, 0)); + let (outcome, figures) = Run::new(ends(parent)).allowance(ALLOWANCE).on_both_paths(); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let allowances: Vec = figures.starts.iter().map(|start| start.2).collect(); + assert_eq!(allowances, [0, ALLOWANCE, 0]); + assert_eq!( + figures.ends, + [ + Ended { + allowance: ALLOWANCE - HISTORY_COST, + ..Ended::stopped(UNLIMITED, 0) + }, + Ended { + history: HISTORY_COST as i64, + ..Ended::stopped(UNLIMITED, 0) + }, + Ended { + history: HISTORY_COST as i64, + ..Ended::stopped(UNLIMITED, 0) + }, + ] + ); +} From 3351330334a9eb2fe5e819d9cf9d1201c74b7c7c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 15:40:01 +0800 Subject: [PATCH 012/110] docs: the byte pool, the start charge and the history allowance in MEGAETH-FORK.md Three hook entries in the section's format, the frame-start hook's contract extended by what the instruction takes off the caller's gas after the hook, and the failed-charge entry's tracker size brought up to date. --- MEGAETH-FORK.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 296b33f339..f0fb970211 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -151,7 +151,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns. - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. - It is two words: the tracker is 88 bytes, and a copy of the tracker, and of every `Gas` and frame result that holds one, is 16 bytes larger. + It is two words: the tracker was 88 bytes with it (136 with the byte pool, see The byte pool), and a copy of the tracker, and of every `Gas` and frame result that holds one, is 16 bytes larger. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. ### Precompile price @@ -226,6 +226,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`; `target` is the account the frame runs as, `None` for a creation. `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. + After the hook the instruction takes two more things off `gas` for the frame's input: the start charge the hook declared (see The start charge) and the child's share of the byte pool (see The byte pool); the share is of the pool as the hook left it. `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. @@ -233,6 +234,59 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), `CREATE` and `CREATE2` compile to the same code as without the hook, and a call runs one instruction more: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. +### The byte pool + +- **API.** On `GasTracker`, forwarded on `Gas`: `bytes_remaining`, `set_bytes_remaining`, `bytes_spent`, `set_bytes_spent`, `record_bytes`, `refill_bytes`, `bytes_crossing`, `clear_bytes_crossing`, `set_bytes_crossing`. + On `GasTracker` alone, the fork's own plumbing: `add_bytes_spent`, `forward_bytes`, `absorb_returned_bytes`. + The type `BytesCrossing` (`with_cost`, `cost`), re-exported from `revm_interpreter`. + `GasId::bytes_forward_percent` and `GasParams::bytes_forward_share(pool)`. + `bytes_share` on `CallInputs` (a field) and `CreateInputs` (`bytes_share`, `set_bytes_share`). +- **Contract.** The pool is a budget of bytes a frame may append, beside its gas: `bytes_remaining` is what the frame may still draw, `bytes_spent` its net draw, signed as `history_gas_spent` is. + `record_bytes(n)` draws; a draw the pool cannot pay takes nothing, returns `false` and records a `BytesCrossing` holding the draw refused, which survives `spend_all`, starts empty in every child, is not taken over by a caller, and stays until cleared or replaced; a consumer marks a result it produced itself with `set_bytes_crossing`. + No halt touches the pool, so a halted frame's result still reads the pool as the failed draw found it, until its caller settles it. + `refill_bytes(n)` gives bytes back and lowers the net, below zero when the draw was a caller's. + The transaction's frame gets the whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution. + At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `bytes_forward_share` of the caller's pool out of it and puts it on the frame's input as `bytes_share`: the child's pool when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). + `bytes_forward_share` is `bytes_forward_percent` per cent of the pool, rounded down; a hundred or more forwards the whole pool. + A forward is not a draw. + The settlement is in `handle_reservoir_remaining_gas` and follows the reservoir, not regular gas: a child that reverts or halts has its draws undone by `rollback_state_gas`, which now gives `bytes_spent` back to the pool, so what the caller absorbs is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame appends nothing; the caller kept what it did not forward. + The child's net merges into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. + `rollback_state_gas` rolls the pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pool back with it. + The first frame's return settles into the transaction's tracker the same way (`last_frame_result`), whose `bytes_spent` is then the transaction's net draw. + An outcome a consumer or an inspector builds itself carries whatever pool its gas was built with, an unlimited one by default, and the settlement absorbs it as it is; a consumer that answers a start itself sets the answer's pool to the share it was given. + The pool is not reported on `ResultGas`. +- **Consumer.** mega-evm keeps a per-frame budget of the bytes a transaction appends to the state and the history, which a failed frame gives back and a successful one hands to its caller. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry a figure that moves with a frame's gas. +- **Removal.** When upstream carries an equivalent per-frame budget on its gas, or when mega-evm stops limiting bytes per frame. +- **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. + The tracker is 136 bytes with the pool (three words), the allowance (one) and the start-charge carrier (two); encodings that predate the fields decode with an unlimited pool and zero for the rest. + +### The start charge + +- **API.** The type `StartCharge` (`new`, `history`, `bytes`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`. + On `GasTracker`, forwarded on `Gas`: `start_charge`, `set_start_charge`, `take_start_charge`. + `charged_start` on `CallInputs`, `CallOutcome` and `CreateOutcome` (fields) and on `CreateInputs` (`charged_start`, `set_charged_start`); `FrameResult::refundable_start_charge`. +- **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and bytes of the pool. + The `frame_starting` hook declares it on the tracker it is handed (`set_start_charge`), after charging it; the instruction takes it off the tracker right after the hook, whatever the answer, and puts it on the frame's input, so the carrier is zero outside that window and is not part of an encoded tracker; a start the hook refuses discards the charge with the start, and what the hook charged stands. + The transaction's frame takes the charge a consumer declared on the transaction's tracker. + The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. + A frame that succeeds keeps the charge. +- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. +- **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. +- **Default.** The hook declares nothing, so the carrier, the fields and the refund are zero. + This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. alloy-evm 0.36, revm-inspectors 0.40 and the op-revm fork construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. + +### The history allowance + +- **API.** On `GasTracker`, forwarded on `Gas`: `history_allowance`, `set_history_allowance`, `draw_history_allowance`. + `GasId::call_history_allowance` and `GasParams::call_history_allowance()`; `history_allowance` on `CallInputs`. +- **Contract.** The allowance is history gas a frame may spend before it charges its budget. + A call that transfers value gives its child the schedule's `call_history_allowance`, decided where the call instruction adds the call stipend, carried on the input and set on the child's tracker when it starts, on the frame and on an answer alike; no other start gives one, and the transaction's frame has none. + Only a consumer draws it: `draw_history_allowance(cost)` takes `min(cost, allowance)` and returns the part of `cost` the allowance did not cover, which the consumer charges as history. + The allowance is the frame's alone: it is not returned, merged or rolled back. +- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. Only the call instruction knows which starts get the stipend. +- **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. +- **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. + ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. From 2726bc408a018ca1007d8adfc0999f4f23c75d90 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 20:51:41 +0800 Subject: [PATCH 013/110] perf: the frame-start hook declares the start charge on the start, not the tracker `Host::frame_starting` takes `&mut FrameStart`, and the hook declares the refundable part of its charge in the new `FrameStart::charge`. The call and creation instructions copy it onto the frame's input when the hook admits the start; a refused start drops it with the start. The carrier on `GasTracker` (`start_charge`, `set_start_charge`, `take_start_charge`, forwarded on `Gas`) is gone, and with it 16 bytes of every tracker (136 -> 120), so every copy of `Gas`, `InterpreterResult` and a frame result moves 16 bytes less. The transaction's frame has no start hook: a consumer that charges the transaction's gas for it puts the charge on the first frame's input (`Handler::first_frame_input`), and `last_frame_result` refunds it as before. The handler and inspector tests declare through a start hook on a context of their own instead of the tracker; their figures are unchanged. --- crates/context/interface/src/cfg/gas.rs | 13 +- .../interface/src/cfg/gas/start_charge.rs | 82 +----- .../context/interface/src/cfg/gas/withheld.rs | 15 +- crates/context/interface/src/host.rs | 14 +- .../interface/src/host/instruction_hooks.rs | 13 +- crates/handler/src/execution.rs | 12 +- crates/handler/src/frame.rs | 6 +- crates/handler/src/frame_data.rs | 5 +- crates/handler/src/handler.rs | 6 +- crates/handler/tests/byte_pool.rs | 268 ++++++++++++++++-- crates/inspector/tests/byte_pool.rs | 251 ++++++++++++++-- crates/inspector/tests/instruction_hooks.rs | 2 +- crates/interpreter/src/gas/byte_pool.rs | 28 +- .../interpreter/src/instructions/contract.rs | 4 +- .../src/instructions/instruction_hooks.rs | 11 +- crates/interpreter/tests/byte_pool.rs | 47 ++- crates/interpreter/tests/instruction_hooks.rs | 2 +- 17 files changed, 555 insertions(+), 224 deletions(-) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 1737bedf17..c88e408ea5 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -52,11 +52,10 @@ pub use withheld::WithheldCrossing; /// spendable part, so a consumer that caps a creating frame must not release before /// `return_create`, or those charges escape the cap. /// -/// Beside the gas, the tracker carries three figures of the fork that are inert until a consumer +/// Beside the gas, the tracker carries two figures of the fork that are inert until a consumer /// uses them: the byte pool ([`bytes_remaining`](Self::bytes_remaining), unlimited by default, -/// forwarded to a child frame and settled with its gas), the history allowance -/// ([`history_allowance`](Self::history_allowance), zero by default) and the start charge the -/// frame-start hook declares ([`start_charge`](Self::start_charge), zero outside the hook). +/// forwarded to a child frame and settled with its gas) and the history allowance +/// ([`history_allowance`](Self::history_allowance), zero by default). /// /// The net counters (`state_gas_spent`, `history_gas_spent`) are `i64`, while charges and refills /// take `u64` amounts and convert them with saturation. The tracker assumes that the transaction @@ -175,11 +174,6 @@ pub struct GasTracker { /// Encodings made before this field existed decode it as zero. #[cfg_attr(feature = "serde", serde(default))] history_allowance: u64, - /// The start charge the frame-start hook declared and the instruction has not yet taken - /// ([`start_charge`](Self::start_charge)). A carrier between the hook and the instruction, - /// zero at every other time, so it is not part of an encoded tracker. - #[cfg_attr(feature = "serde", serde(skip))] - start_charge: StartCharge, } /// The pool a tracker starts with, and an encoding that predates the pool decodes to. @@ -215,7 +209,6 @@ impl GasTracker { bytes_spent: 0, bytes_crossing: None, history_allowance: 0, - start_charge: StartCharge::new(0, 0), } } diff --git a/crates/context/interface/src/cfg/gas/start_charge.rs b/crates/context/interface/src/cfg/gas/start_charge.rs index cc223afe06..16bac4676e 100644 --- a/crates/context/interface/src/cfg/gas/start_charge.rs +++ b/crates/context/interface/src/cfg/gas/start_charge.rs @@ -1,14 +1,12 @@ //! The start charge a [`Host::frame_starting`](crate::Host::frame_starting) hook declares on the -//! caller's [`GasTracker`], and the instruction copies onto the frame's input. +//! [`FrameStart`](crate::host::FrameStart) it is handed, and the instruction copies onto the +//! frame's input. //! //! The hook charges the caller's gas for the frame it starts; the part of that charge the frame's -//! failure gives back is the start charge. The hook declares it on the tracker it is handed -//! ([`set_start_charge`](GasTracker::set_start_charge)), the instruction takes it off the tracker -//! right after the hook ([`take_start_charge`](GasTracker::take_start_charge)) and puts it on the -//! frame's input, and the handler refunds it to the caller when the frame fails. Outside that -//! window the carrier is zero. - -use super::GasTracker; +//! failure gives back is the start charge. The hook declares it on the start +//! ([`FrameStart::charge`](crate::host::FrameStart::charge)), the instruction copies it onto the +//! frame's input when the hook admits the start, and the handler refunds it to the caller when the +//! frame fails. /// What a frame start charged its caller and the frame's failure gives back: history gas and /// bytes of the pool. @@ -19,10 +17,10 @@ use super::GasTracker; #[non_exhaustive] pub struct StartCharge { /// History gas the start charged, refilled with - /// [`refill_history`](GasTracker::refill_history) when the frame fails. + /// [`refill_history`](super::GasTracker::refill_history) when the frame fails. pub history: u64, /// Bytes the start drew from the pool, refilled with - /// [`refill_bytes`](GasTracker::refill_bytes) when the frame fails. + /// [`refill_bytes`](super::GasTracker::refill_bytes) when the frame fails. pub bytes: u64, } @@ -39,67 +37,3 @@ impl StartCharge { self.history == 0 && self.bytes == 0 } } - -impl GasTracker { - /// The start charge the frame-start hook declared and the instruction has not taken yet. - #[inline] - pub const fn start_charge(&self) -> StartCharge { - self.start_charge - } - - /// Declares the start charge of the frame about to start: what the hook charged this tracker - /// that the frame's failure gives back. Replaces what was declared before. - #[inline] - pub const fn set_start_charge(&mut self, charge: StartCharge) { - self.start_charge = charge; - } - - /// Takes the declared start charge off the tracker, leaving none. - #[inline] - pub const fn take_start_charge(&mut self) -> StartCharge { - let charge = self.start_charge; - self.start_charge = StartCharge::new(0, 0); - charge - } -} - -#[cfg(test)] -mod tests { - use super::{GasTracker, StartCharge}; - - /// A tracker carries no start charge until a hook declares one; taking it leaves none. - #[test] - fn test_the_carrier_is_empty_until_set_and_after_take() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - assert!(tracker.start_charge().is_zero()); - assert_eq!(tracker.take_start_charge(), StartCharge::default()); - - tracker.set_start_charge(StartCharge::new(3_520, 160)); - assert_eq!(tracker.start_charge(), StartCharge::new(3_520, 160)); - - assert_eq!(tracker.take_start_charge(), StartCharge::new(3_520, 160)); - assert!(tracker.start_charge().is_zero()); - assert_eq!(tracker, GasTracker::new(1_000, 1_000, 0)); - } - - /// A second declaration replaces the first. - #[test] - fn test_a_second_declaration_replaces_the_first() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_start_charge(StartCharge::new(1, 1)); - tracker.set_start_charge(StartCharge::new(2, 0)); - assert_eq!(tracker.take_start_charge(), StartCharge::new(2, 0)); - } - - /// The carrier is transient and not part of an encoded tracker. - #[cfg(feature = "serde")] - #[test] - fn test_the_carrier_is_not_encoded() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_start_charge(StartCharge::new(5, 5)); - let encoded = serde_json::to_value(tracker).unwrap(); - assert!(encoded.get("start_charge").is_none()); - let decoded = serde_json::from_value::(encoded).unwrap(); - assert!(decoded.start_charge().is_zero()); - } -} diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 4fa93e0dce..74a10188df 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,14 +236,13 @@ mod tests { assert_eq!(size_of::>(), size_of::()); } - /// The tracker is 136 bytes: 72 with the withheld part and its record, two words more for the - /// failed-charge record, and six more for the byte pool (the pool, its net and its record), - /// the history allowance and the start-charge carrier. Copies of the tracker, and of every - /// `Gas` and frame result that holds one, grow with it, so a new field is measured before - /// this changes. - #[test] - fn test_the_tracker_is_136_bytes() { - assert_eq!(size_of::(), 136); + /// The tracker is 120 bytes: 72 with the withheld part and its record, two words more for the + /// failed-charge record, and four more for the byte pool (the pool, its net and its record) + /// and the history allowance. Copies of the tracker, and of every `Gas` and frame result that + /// holds one, grow with it, so a new field is measured before this changes. + #[test] + fn test_the_tracker_is_120_bytes() { + assert_eq!(size_of::(), 120); } /// Withholding moves gas between the parts and leaves the total alone. diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 0586955d94..175d4e6b87 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -128,15 +128,17 @@ pub trait Host { /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, /// charging nothing after the hook: the frame's input copies its reservoir from `gas`. A /// charge the hook makes that fails records as any failed charge does - /// ([`GasTracker::failed_charge_remaining`]), whatever the answer. `true` goes on to start the - /// frame, which the handler may still refuse or answer without running it. `false` fails the - /// instruction out of gas and starts no frame: the forward stays taken unless the hook gave it - /// back, and the halt records the regular gas the hook left unless a failed charge already - /// did. + /// ([`GasTracker::failed_charge_remaining`]), whatever the answer. The part of its charge + /// that the frame's failure gives back, the hook declares on `start` + /// ([`FrameStart::charge`]). `true` goes on to start the frame, which the handler may still + /// refuse or answer without running it, and the frame's input carries the declared charge. + /// `false` fails the instruction out of gas and starts no frame: the forward stays taken + /// unless the hook gave it back, the declared charge goes with the start, and the halt + /// records the regular gas the hook left unless a failed charge already did. /// /// The default returns `true` and touches nothing. #[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 _ = (start, gas); true } diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index b69adf7517..7b325ce304 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -6,7 +6,10 @@ //! and credit it; the instruction goes on with the gas as the hook left it. Their defaults touch //! nothing and let the instruction go on. -use crate::context::{SStoreResult, SelfDestructResult}; +use crate::{ + cfg::gas::StartCharge, + context::{SStoreResult, SelfDestructResult}, +}; use primitives::{Address, Bytes, StorageKey, U256}; /// A state write an instruction completed: the write is in the journal, and every charge the @@ -80,6 +83,9 @@ pub enum FrameStartKind { /// A frame an instruction is about to start: every charge the instruction makes has been made, the /// gas it forwards has been taken from the caller, and the frame's input is not built yet. /// +/// The hook is handed it mutably to declare the start's [`charge`](Self::charge); the instruction +/// reads nothing else back. +/// /// Built with [`FrameStart::new`], so a later field is not a breaking change. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -95,6 +101,10 @@ pub struct FrameStart { /// The regular gas the instruction took from the caller for the frame: the frame's gas limit /// without a value call's stipend, which the caller does not pay. pub forward: u64, + /// The start charge: what the hook charged the caller for this start that the frame's failure + /// gives back. Empty when the hook is called; the hook declares it here after charging it, + /// and the instruction copies it onto the frame's input if the hook admits the start. + pub charge: StartCharge, } impl FrameStart { @@ -113,6 +123,7 @@ impl FrameStart { target, value, forward, + charge: StartCharge::new(0, 0), } } } diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index 90dfc49d77..bd0b10d1c6 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -6,7 +6,7 @@ use context_interface::{ }; use interpreter::{ CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - GasTracker, + GasTracker, StartCharge, }; use primitives::{Address, TxKind}; use state::Bytecode; @@ -132,10 +132,11 @@ pub fn create_init_frame( return_memory_offset: 0..0, reservoir: gas.reservoir(), charged_new_account_state_gas, - // The transaction's frame gets the whole pool, and the start charge a consumer - // declared on the transaction's gas; it gets no allowance, which is a value - // call's below the transaction. - charged_start: gas.take_start_charge(), + // The transaction's frame gets the whole pool. It has no start charge until a + // consumer that charged the transaction's gas for it puts one on this input + // (`Handler::first_frame_input`), and no allowance, which is a value call's below + // the transaction. + charged_start: StartCharge::new(0, 0), bytes_share: forward_whole_pool(gas), history_allowance: 0, })))) @@ -182,7 +183,6 @@ pub fn create_init_frame( ); inputs.set_charged_create_state_gas(charged_create_state_gas); inputs.set_charged_state_gas_address(charged_state_gas_address); - inputs.set_charged_start(gas.take_start_charge()); inputs.set_bytes_share(forward_whole_pool(gas)); Ok(Some(FrameInput::Create(Box::new(inputs)))) } diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index f5a69b1c44..a1d4872964 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -550,9 +550,9 @@ impl EthFrame { }, None => None, }; - // The start charge the frame-start hook declared on this (parent) frame's tracker is - // refunded on the same condition, whole, by the same two refills a consumer's own - // take-back uses; it needs no price lookup, since the hook declared the amounts. + // The start charge the frame-start hook charged this (parent) frame and declared on the + // start is refunded on the same condition, whole, by the same two refills a consumer's + // own take-back uses; it needs no price lookup, since the hook declared the amounts. let refund_start_charge = result.refundable_start_charge(); // Insert result to the top frame. diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index aac2c175ab..c7b44463e0 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -177,8 +177,9 @@ impl FrameResult { /// The start charge to refund, or `None` when there is nothing to refund: the frame /// succeeded, or its start charged nothing. /// - /// The frame-start hook declared the charge on the caller's gas before the frame ran, and it - /// rides on the outcome's `charged_start`. The decision is the one + /// The frame-start hook charged the caller's gas before the frame ran and declared the charge + /// on the start (a consumer declares the transaction frame's on its input), and it rides on + /// the outcome's `charged_start`. The decision is the one /// [`Self::refundable_state_gas_charge`] makes: a call refunds when it did not succeed, a /// creation also when no contract address was deployed. The charge is refunded whole, with /// `refill_history` and `refill_bytes`. diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 215b42b540..d0edfe49a4 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -548,9 +548,9 @@ pub trait Handler { } } - // Refund the start charge a consumer declared on the transaction's gas for its frame, - // whole, on the same condition and with the same halt rule, exactly like - // `EthFrame::return_result` refunds the start charges of inner frames. + // Refund the start charge a consumer put on the first frame's input for what it charged + // the transaction's gas, whole, on the same condition and with the same halt rule, + // exactly like `EthFrame::return_result` refunds the start charges of inner frames. if let Some(charge) = frame_result.refundable_start_charge() { parent_gas.refill_history(charge.history); parent_gas.refill_bytes(charge.bytes); diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index 3086e8076a..0b4de01db6 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -6,28 +6,35 @@ //! what it left: its remaining pool when it succeeded, the whole share when it reverted or halted. //! A start charge a hook declared rides on the frame's input and is refunded whole when the frame //! fails. The handler here is the mainnet one, observed through overrides that leave its behaviour -//! alone, and the frames draw the pool through instructions of the test's own, which stand in for -//! a consumer's hooks: `DRAW` draws bytes, `DECLARE` charges and declares a start charge before -//! the next start, and `LOG` charges history after drawing the frame's allowance, as a consumer's -//! write hook would. +//! alone, on the mainnet context with a start hook of the test's own ([`DeclaringContext`]), and +//! the frames draw the pool through instructions of the test's own, which stand in for a +//! consumer's hooks: `DRAW` draws bytes, `DECLARE` has the start hook charge and declare a start +//! charge at the next start, and `LOG` charges history after drawing the frame's allowance, as a +//! consumer's write hook would. use bytecode::opcode::{ CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, STOP, }; use context::{ result::{EVMError, ExecutionResult}, - Context, ContextSetters, Evm, TxEnv, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Journal, LocalContext, + TxEnv, }; use context_interface::{ - cfg::{gas::InitialAndFloorGas, GasId}, - Database, + cfg::{gas::InitialAndFloorGas, GasId, GasParams, StateGasSite}, + host::{FrameStart, LoadError}, + journaled_state::AccountInfoLoad, + Database, Host, }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, StartCharge, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, SStoreResult, + SelfDestructResult, StartCharge, StateLoad, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, }; -use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, EvmTr, FrameResult, Handler, ItemOrResult, MainContext, MainnetContext, MainnetEvm, MainnetHandler, @@ -36,7 +43,7 @@ use state::{AccountInfo, Bytecode}; type Db = CacheDB; type DbError = ::Error; -type TestContext = MainnetContext; +type TestContext = DeclaringContext; type TestEvm = MainnetEvm; type TestError = EVMError; type Mainnet = MainnetHandler>; @@ -47,7 +54,7 @@ const GAS_LIMIT: u64 = 3_000_000; const POOL: u64 = 1_000; /// What `DRAW` draws. const DRAW_BYTES: u64 = 100; -/// What `DECLARE` charges and declares. +/// What the start hook charges and declares after `DECLARE`. const DECLARED: StartCharge = StartCharge::new(3_520, 160); /// What `LOG` charges as history. const HISTORY_COST: u64 = 100; @@ -87,15 +94,11 @@ const fn draw( } } -/// What a consumer's start hook does for the start that follows: charges [`DECLARED`] on the -/// frame's gas and declares it. +/// Has the start hook charge and declare [`DECLARED`] at the start that follows. const fn declare( context: InstructionContext<'_, TestContext, EthInterpreter>, ) -> InstructionExecResult { - let gas = &mut context.interpreter.gas; - assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_bytes(DECLARED.bytes)); - gas.set_start_charge(DECLARED); + context.host.declare_next = true; Ok(()) } @@ -154,6 +157,200 @@ impl Returned { } } +/// The mainnet [`Context`] with a start hook that does what a consumer's does for a start +/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start. +struct DeclaringContext { + inner: MainnetContext, + /// Set by `DECLARE`, taken by the next start. + declare_next: bool, +} + +impl ContextTr for DeclaringContext { + type Block = BlockEnv; + type Tx = TxEnv; + type Cfg = CfgEnv; + type Db = Db; + type Journal = Journal; + type Chain = (); + type Local = LocalContext; + + fn all( + &self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &Self::Db, + &Self::Journal, + &Self::Chain, + &Self::Local, + ) { + self.inner.all() + } + + fn all_mut( + &mut self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &mut Self::Journal, + &mut Self::Chain, + &mut Self::Local, + ) { + self.inner.all_mut() + } + + fn error(&mut self) -> &mut Result<(), ContextError> { + self.inner.error() + } +} + +impl ContextSetters for DeclaringContext { + fn set_tx(&mut self, tx: Self::Tx) { + self.inner.set_tx(tx); + } + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } +} + +impl Host for DeclaringContext { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + if core::mem::take(&mut self.declare_next) { + assert!(gas.record_history_cost(DECLARED.history)); + assert!(gas.record_bytes(DECLARED.bytes)); + start.charge = DECLARED; + } + true + } + + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { + self.inner.state_gas_price(id, site) + } + + fn basefee(&self) -> U256 { + self.inner.basefee() + } + + fn blob_gasprice(&self) -> U256 { + self.inner.blob_gasprice() + } + + fn gas_limit(&self) -> U256 { + self.inner.gas_limit() + } + + fn difficulty(&self) -> U256 { + self.inner.difficulty() + } + + fn prevrandao(&self) -> Option { + self.inner.prevrandao() + } + + fn block_number(&self) -> U256 { + self.inner.block_number() + } + + fn timestamp(&self) -> U256 { + self.inner.timestamp() + } + + fn beneficiary(&self) -> Address { + self.inner.beneficiary() + } + + fn slot_num(&self) -> U256 { + self.inner.slot_num() + } + + fn chain_id(&self) -> U256 { + self.inner.chain_id() + } + + fn effective_gas_price(&self) -> U256 { + self.inner.effective_gas_price() + } + + fn caller(&self) -> Address { + self.inner.caller() + } + + fn blob_hash(&self, number: usize) -> Option { + self.inner.blob_hash(number) + } + + fn max_initcode_size(&self) -> usize { + self.inner.max_initcode_size() + } + + fn gas_params(&self) -> &GasParams { + self.inner.gas_params() + } + + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.inner.is_amsterdam_eip8037_enabled() + } + + fn block_hash(&mut self, number: u64) -> Option { + self.inner.block_hash(number) + } + + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner.selfdestruct(address, target, skip_cold_load) + } + + fn log(&mut self, log: Log) { + self.inner.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.inner.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.inner.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .load_account_info_skip_cold_load(address, load_code, skip_cold_load) + } +} + /// The figures of a frame's input as it started: its share, its start charge and its allowance. type Started = (u64, StartCharge, u64); @@ -173,13 +370,14 @@ fn started(input: &FrameInput) -> Started { /// history gas. type Settled = (u64, i64, i64); -/// The mainnet handler with the consumer's part: a pool and a start charge set on the -/// transaction's gas, and a record of every frame's start and return. +/// The mainnet handler with the consumer's part: a pool set on the transaction's gas and a start +/// charge for the transaction's frame, and a record of every frame's start and return. struct PoolHandler { mainnet: Mainnet, /// The pool the transaction's gas gets, if any. pool: Option, - /// Whether the transaction's gas is charged [`DECLARED`] for its frame and declares it. + /// Whether the transaction's gas is charged [`DECLARED`] for its frame, declared on the + /// frame's input. declare: bool, starts: Vec, returned: Vec, @@ -214,11 +412,27 @@ impl Handler for PoolHandler { if self.declare { assert!(gas.record_history_cost(DECLARED.history)); assert!(gas.record_bytes(DECLARED.bytes)); - gas.set_start_charge(DECLARED); } gas } + /// The mainnet input, with the start charge `tx_gas` charged declared on it, if told to. + fn first_frame_input( + &mut self, + evm: &mut TestEvm, + gas: &mut GasTracker, + ) -> Result, TestError> { + let mut init = self.mainnet.first_frame_input(evm, gas)?; + if let (true, Some(init)) = (self.declare, &mut init) { + match &mut init.frame_input { + FrameInput::Call(inputs) => inputs.charged_start = DECLARED, + FrameInput::Create(inputs) => inputs.set_charged_start(DECLARED), + FrameInput::Empty => unreachable!(), + } + } + Ok(init) + } + /// The default loop, recording each frame's input as it starts and its result as it /// returns, before its caller settles it. fn run_exec_loop( @@ -382,13 +596,17 @@ impl Run { fn evm(&self) -> TestEvm { let allowance = self.allowance; - let ctx: TestContext = Context::mainnet() + let inner = Context::mainnet() .with_db(self.db()) .modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); cfg.gas_params .override_gas([(GasId::call_history_allowance(), allowance)]); }); + let ctx = DeclaringContext { + inner, + declare_next: false, + }; let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(DRAW, Instruction::new(draw), 0); instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); @@ -499,7 +717,7 @@ fn test_a_failed_draw_halts_the_frame_with_a_record_the_caller_can_read() { assert_eq!(handler.settled, Some((50, 100, 0))); } -/// A start charge declared before a start rides on the frame's input, and is refunded to the +/// A start charge the start hook declared rides on the frame's input, and is refunded to the /// caller whole when the frame fails: a revert, a halt, a start the handler refused before any /// frame ran (a transfer the caller cannot pay), one it answered without a frame (a precompile /// out of gas), a creation that reverted and one whose caller's nonce overflowed. A frame that @@ -564,8 +782,8 @@ fn test_the_start_charge_is_refunded_when_the_frame_fails() { } /// The transaction's frame gets the pool as the consumer left it after the body's charges, and -/// the start charge the consumer declared, which is refunded whole when the frame reverts or -/// halts and kept when it succeeds. +/// the start charge the consumer declared on its input, which is refunded whole when the frame +/// reverts or halts and kept when it succeeds. #[test] fn test_the_first_frame_gets_the_pool_and_its_start_charge() { for (name, parent, fails) in [ diff --git a/crates/inspector/tests/byte_pool.rs b/crates/inspector/tests/byte_pool.rs index ea09440522..57236612bd 100644 --- a/crates/inspector/tests/byte_pool.rs +++ b/crates/inspector/tests/byte_pool.rs @@ -3,23 +3,36 @@ //! `transact` runs the frames in the handler's loop and `inspect_tx` in the inspector's; both //! build frames with `make_call_frame` and `make_create_frame` and settle them with //! `return_result`, so a child's share, its start charge and its allowance travel the same way -//! and settle to the same figures. Each test runs a transaction both ways on the mainnet context -//! with instructions of the test's own, which stand in for a consumer's hooks, and checks that the -//! two paths end the same way; an inspector records each frame's input as it starts and its -//! outcome as it ends, before its caller settles it, and the figures are checked on the inspected -//! path (the handler's tests check them on the plain one). - -use context::{result::ResultAndState, Context, Evm, TxEnv}; +//! and settle to the same figures. Each test runs a transaction both ways on the mainnet context, +//! with a start hook of the test's own ([`DeclaringContext`]) and instructions of the test's own, +//! which stand in for a consumer's hooks, and checks that the two paths end the same way; an +//! inspector records each frame's input as it starts and its outcome as it ends, before its caller +//! settles it, and the figures are checked on the inspected path (the handler's tests check them +//! on the plain one). + +use context::{ + context_interface::{ + cfg::{GasId, GasParams, StateGasSite}, + host::{FrameStart, LoadError}, + journaled_state::AccountInfoLoad, + }, + result::ResultAndState, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Host, Journal, + LocalContext, TxEnv, +}; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, ExecuteEvm, MainContext, MainnetContext, }; use interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Instruction, - InstructionContext, InstructionExecResult, InstructionResult, StartCharge, + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, GasTracker, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, SStoreResult, + SelfDestructResult, StartCharge, StateLoad, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, }; -use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{InspectEvm, Inspector}; use state::{ bytecode::opcode::{ @@ -29,14 +42,15 @@ use state::{ }; type Db = CacheDB; -type Ctx = MainnetContext; +type DbError = ::Error; +type Ctx = DeclaringContext; type PoolEvm = Evm, EthPrecompiles, EthFrame>; const SPEC: SpecId = SpecId::OSAKA; const GAS_LIMIT: u64 = 3_000_000; /// What `DRAW` draws. const DRAW_BYTES: u64 = 100; -/// What `DECLARE` charges and declares. +/// What the start hook charges and declares after `DECLARE`. const DECLARED: StartCharge = StartCharge::new(3_520, 160); /// What `LOG` charges as history. const HISTORY_COST: u64 = 100; @@ -82,12 +96,9 @@ const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> Instruct } } -/// What a consumer's start hook does for the start that follows. +/// Has the start hook charge and declare [`DECLARED`] at the start that follows. const fn declare(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - let gas = &mut context.interpreter.gas; - assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_bytes(DECLARED.bytes)); - gas.set_start_charge(DECLARED); + context.host.declare_next = true; Ok(()) } @@ -102,6 +113,200 @@ const fn log(context: InstructionContext<'_, Ctx, EthInterpreter>) -> Instructio } } +/// The mainnet [`Context`] with a start hook that does what a consumer's does for a start +/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start. +struct DeclaringContext { + inner: MainnetContext, + /// Set by `DECLARE`, taken by the next start. + declare_next: bool, +} + +impl ContextTr for DeclaringContext { + type Block = BlockEnv; + type Tx = TxEnv; + type Cfg = CfgEnv; + type Db = Db; + type Journal = Journal; + type Chain = (); + type Local = LocalContext; + + fn all( + &self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &Self::Db, + &Self::Journal, + &Self::Chain, + &Self::Local, + ) { + self.inner.all() + } + + fn all_mut( + &mut self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &mut Self::Journal, + &mut Self::Chain, + &mut Self::Local, + ) { + self.inner.all_mut() + } + + fn error(&mut self) -> &mut Result<(), ContextError> { + self.inner.error() + } +} + +impl ContextSetters for DeclaringContext { + fn set_tx(&mut self, tx: Self::Tx) { + self.inner.set_tx(tx); + } + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } +} + +impl Host for DeclaringContext { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + if core::mem::take(&mut self.declare_next) { + assert!(gas.record_history_cost(DECLARED.history)); + assert!(gas.record_bytes(DECLARED.bytes)); + start.charge = DECLARED; + } + true + } + + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { + self.inner.state_gas_price(id, site) + } + + fn basefee(&self) -> U256 { + self.inner.basefee() + } + + fn blob_gasprice(&self) -> U256 { + self.inner.blob_gasprice() + } + + fn gas_limit(&self) -> U256 { + self.inner.gas_limit() + } + + fn difficulty(&self) -> U256 { + self.inner.difficulty() + } + + fn prevrandao(&self) -> Option { + self.inner.prevrandao() + } + + fn block_number(&self) -> U256 { + self.inner.block_number() + } + + fn timestamp(&self) -> U256 { + self.inner.timestamp() + } + + fn beneficiary(&self) -> Address { + self.inner.beneficiary() + } + + fn slot_num(&self) -> U256 { + self.inner.slot_num() + } + + fn chain_id(&self) -> U256 { + self.inner.chain_id() + } + + fn effective_gas_price(&self) -> U256 { + self.inner.effective_gas_price() + } + + fn caller(&self) -> Address { + self.inner.caller() + } + + fn blob_hash(&self, number: usize) -> Option { + self.inner.blob_hash(number) + } + + fn max_initcode_size(&self) -> usize { + self.inner.max_initcode_size() + } + + fn gas_params(&self) -> &GasParams { + self.inner.gas_params() + } + + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.inner.is_amsterdam_eip8037_enabled() + } + + fn block_hash(&mut self, number: u64) -> Option { + self.inner.block_hash(number) + } + + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner.selfdestruct(address, target, skip_cold_load) + } + + fn log(&mut self, log: Log) { + self.inner.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.inner.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.inner.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError> { + self.inner + .load_account_info_skip_cold_load(address, load_code, skip_cold_load) + } +} + /// A frame's figures as it ended, before its caller settled it. #[derive(Clone, Debug, PartialEq, Eq)] struct Ended { @@ -268,13 +473,15 @@ impl Run { db.insert_account_info(address, info); } let allowance = self.allowance; - let ctx: Ctx = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + let inner = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); - cfg.gas_params.override_gas([( - context::context_interface::cfg::GasId::call_history_allowance(), - allowance, - )]); + cfg.gas_params + .override_gas([(GasId::call_history_allowance(), allowance)]); }); + let ctx = DeclaringContext { + inner, + declare_next: false, + }; let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(DRAW, Instruction::new(draw), 0); instructions.insert_instruction(DRAIN, Instruction::new(drain), 0); diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index 9ae6f2623e..aaeb246eae 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -188,7 +188,7 @@ impl Host for HookContext { self.hooks.verdict.clone() } - fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { self.hooks.starts.push((*start, *gas)); if self.hooks.starts.len() == 1 && self.hooks.first_start_charge > 0 { assert!(gas.record_history_cost(self.hooks.first_start_charge)); diff --git a/crates/interpreter/src/gas/byte_pool.rs b/crates/interpreter/src/gas/byte_pool.rs index 96c2e2cd4f..8be8347898 100644 --- a/crates/interpreter/src/gas/byte_pool.rs +++ b/crates/interpreter/src/gas/byte_pool.rs @@ -1,9 +1,9 @@ -//! The byte pool, the history allowance and the start charge, on [`Gas`]. +//! The byte pool and the history allowance, on [`Gas`]. //! //! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which //! documents it. -use super::{BytesCrossing, Gas, StartCharge}; +use super::{BytesCrossing, Gas}; impl Gas { /// The byte pool: what this frame may still draw. Unlimited unless a consumer set a pool. @@ -105,28 +105,4 @@ impl Gas { pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { self.tracker.draw_history_allowance(cost) } - - /// The start charge the frame-start hook declared and the instruction has not taken yet. - /// - /// See [`GasTracker::start_charge`](super::GasTracker::start_charge). - #[inline] - pub const fn start_charge(&self) -> StartCharge { - self.tracker.start_charge() - } - - /// Declares the start charge of the frame about to start. - /// - /// See [`GasTracker::set_start_charge`](super::GasTracker::set_start_charge). - #[inline] - pub const fn set_start_charge(&mut self, charge: StartCharge) { - self.tracker.set_start_charge(charge); - } - - /// Takes the declared start charge off the tracker, leaving none. - /// - /// See [`GasTracker::take_start_charge`](super::GasTracker::take_start_charge). - #[inline] - pub const fn take_start_charge(&mut self) -> StartCharge { - self.tracker.take_start_charge() - } } diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 298cccea62..e520e545b5 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -182,7 +182,7 @@ pub fn create( FrameStartKind::Create }; let start = FrameStart::new(kind, create_inputs.caller(), None, value, gas_limit); - let charged_start = frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); create_inputs.set_gas_limit(gas_limit); @@ -273,7 +273,7 @@ pub fn call(mut context: Ictx<'_, H, }; let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); - let charged_start = frame_starting(&mut context.interpreter.gas, context.host, &start)?; + let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); // Call host to interact with target contract diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 287fda4771..3e36891813 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -44,20 +44,17 @@ fn revert(interpreter: &mut Interpreter, output: Bytes) -> Result { } /// Hands `start`, whose forward the running instruction has taken from `gas`, to -/// [`Host::frame_starting`], and takes the start charge the hook declared off `gas`, whatever -/// the answer, so the carrier is empty once the hook has answered. `true` returns the charge for +/// [`Host::frame_starting`]. `true` returns the start charge the hook declared on `start`, for /// the frame's input; `false` fails the instruction out of gas, and the charge goes with the /// start it was declared for. #[inline] pub(crate) fn frame_starting( gas: &mut Gas, host: &mut H, - start: &FrameStart, + mut start: FrameStart, ) -> core::result::Result { - let admitted = host.frame_starting(start, gas.tracker_mut()); - let charged = gas.take_start_charge(); - if admitted { - Ok(charged) + if host.frame_starting(&mut start, gas.tracker_mut()) { + Ok(start.charge) } else { cold_path(); Err(InstructionResult::OutOfGas) diff --git a/crates/interpreter/tests/byte_pool.rs b/crates/interpreter/tests/byte_pool.rs index 620c6609c4..e3a4996407 100644 --- a/crates/interpreter/tests/byte_pool.rs +++ b/crates/interpreter/tests/byte_pool.rs @@ -1,12 +1,12 @@ //! The byte pool, the start charge and the history allowance at the call and creation //! instructions. //! -//! Once [`Host::frame_starting`] has answered, the instruction takes the start charge the hook -//! declared off the caller's gas and puts it on the frame's input, takes the child's share of the -//! caller's byte pool out of the pool and puts it on the input too, and, for a value call, gives -//! the input the schedule's history allowance. Each test runs one frame on [`PoolHost`], whose -//! start hook draws bytes from the gas it is handed, declares a start charge, and admits or -//! refuses the start as the test tells it. +//! Once [`Host::frame_starting`] has answered, the instruction copies the start charge the hook +//! declared on the start onto the frame's input, takes the child's share of the caller's byte pool +//! out of the pool and puts it on the input too, and, for a value call, gives the input the +//! schedule's history allowance. Each test runs one frame on [`PoolHost`], whose start hook draws +//! bytes from the gas it is handed, declares a start charge, and admits or refuses the start as +//! the test tells it. use bytecode::{opcode::*, Bytecode}; use context_interface::{ @@ -46,7 +46,8 @@ const PERCENT: u64 = 98; const ALLOWANCE: u64 = 160; /// A [`DummyHost`] whose start hook draws [`PoolHost::draw`] bytes from the gas it is handed, -/// declares [`PoolHost::declare`], records what it saw, and answers [`PoolHost::admit`]. +/// declares [`PoolHost::declare`] on the start, records what it saw, and answers +/// [`PoolHost::admit`]. struct PoolHost { dummy: DummyHost, spec: SpecId, @@ -54,7 +55,8 @@ struct PoolHost { draw: u64, declare: StartCharge, admit: bool, - /// Every start the hook saw, with the gas as the hook found it, and whether its draw paid. + /// Every start the hook saw and the gas, both as the hook found them, and whether its draw + /// paid. starts: Vec<(FrameStart, GasTracker, bool)>, } @@ -108,11 +110,11 @@ impl Host for PoolHost { WriteVerdict::Continue } - fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { - let found = *gas; + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + let found = (*start, *gas); let paid = gas.record_bytes(self.draw); - gas.set_start_charge(self.declare); - self.starts.push((*start, found, paid)); + start.charge = self.declare; + self.starts.push((found.0, found.1, paid)); self.admit && paid } @@ -339,7 +341,6 @@ fn test_every_start_forwards_the_whole_pool_by_default() { "{kind:?}: the caller keeps nothing" ); assert_eq!(gas.bytes_spent(), 0, "{kind:?}: a forward is not a draw"); - assert!(gas.start_charge().is_zero(), "{kind:?}"); assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); } } @@ -386,26 +387,22 @@ fn test_the_share_follows_the_schedule_after_the_hooks_draw() { } } -/// The start charge the hook declares rides on the frame's input, and the carrier on the -/// caller's gas is empty again once the instruction has taken it. +/// A start reaches the hook with nothing declared, and the start charge the hook declares on it +/// rides on the frame's input. #[test] -fn test_the_declared_start_charge_rides_on_the_input_and_leaves_the_tracker() { +fn test_the_declared_start_charge_rides_on_the_input() { for (kind, code) in start_cases() { let mut host = PoolHost::new(SpecId::OSAKA).declaring(DECLARED); - let (action, gas) = run(&code, Some(POOL), &mut host); + let (action, _) = run(&code, Some(POOL), &mut host); let (_, charged, _) = figures(&started(action)); + assert!(host.start().0.charge.is_zero(), "{kind:?}: none at first"); assert_eq!(charged, DECLARED, "{kind:?}"); - assert!( - gas.start_charge().is_zero(), - "{kind:?}: the carrier is taken" - ); } } /// A start the hook refuses fails out of gas and starts no frame: the hook's draw stays, as the -/// forward of regular gas does, no share is taken, and the declared charge is discarded with the -/// start rather than left on the caller's gas. +/// forward of regular gas does, no share is taken, and the declared charge goes with the start. #[test] fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { for (kind, code) in start_cases() { @@ -422,10 +419,6 @@ fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { "{kind:?}: no share taken" ); assert_eq!(gas.bytes_spent(), 200, "{kind:?}"); - assert!( - gas.start_charge().is_zero(), - "{kind:?}: the carrier is taken" - ); assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); } } diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index 868920006e..a2fee4502c 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -192,7 +192,7 @@ impl Host for HookHost { self.verdict.clone() } - fn frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { self.starts.push((*start, *gas)); if self.charge > 0 { let _ = gas.record_history_cost(self.charge); From f538e25b80c9c45d7cc2309da532c87bfe63de55 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 20:52:47 +0800 Subject: [PATCH 014/110] perf(gas): the byte pool's crossing is a bit beside the failed-charge record The failed-charge record was an `Option`, whose tag took a word of its own, and the byte pool's crossing a second word (`Option`). The record is now a number and a flag, and the crossing a `bool` in the same word as the flag: `GasTracker` goes from 120 to 112 bytes. `bytes_crossing` returns `bool` and `set_bytes_crossing` takes one; the record says that a draw failed, not what it asked for, which the hook that drew knows when the draw fails. `BytesCrossing` is gone. `failed_charge_remaining` and its setter keep their signatures and behaviour, and `PartialEq` and `Hash` see the same figures, since the number is zero whenever the flag is clear. `GasTracker` (de)serializes through a mirror (`gas/encoding.rs`) with the same fields, names, order and defaults as the derived encoding: the failed-charge record is still an optional number. Only the crossing's own encoding changes, from `{"cost": n}` or `null` to a `bool`; it has not been released. --- crates/context/interface/src/cfg/gas.rs | 50 +++--- .../interface/src/cfg/gas/byte_pool.rs | 156 +++++++----------- .../context/interface/src/cfg/gas/encoding.rs | 150 +++++++++++++++++ .../interface/src/cfg/gas/failed_charge.rs | 23 ++- .../context/interface/src/cfg/gas/withheld.rs | 15 +- crates/handler/tests/byte_pool.rs | 12 +- crates/inspector/tests/byte_pool.rs | 8 +- crates/interpreter/src/gas/byte_pool.rs | 12 +- crates/interpreter/src/lib.rs | 2 +- crates/interpreter/tests/byte_pool.rs | 10 +- 10 files changed, 284 insertions(+), 154 deletions(-) create mode 100644 crates/context/interface/src/cfg/gas/encoding.rs diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index c88e408ea5..ef38c4ca2b 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -4,12 +4,13 @@ use crate::{cfg::gas_params, cfg::GasParams, Transaction}; use primitives::hardfork::SpecId; mod byte_pool; +#[cfg(feature = "serde")] +mod encoding; mod failed_charge; mod history_allowance; mod start_charge; mod withheld; -pub use byte_pool::BytesCrossing; pub use start_charge::StartCharge; pub use withheld::WithheldCrossing; @@ -65,8 +66,16 @@ pub use withheld::WithheldCrossing; /// checks it. Above it, a rollback no longer restores the reservoir exactly and can burn or mint /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). +/// +/// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and +/// the byte pool's crossing, which share a word in memory, are encoded as an optional number and +/// a `bool` in their own places. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr( + feature = "serde", + derive(serde::Serialize, serde::Deserialize), + serde(from = "encoding::Encoded", into = "encoding::Encoded") +)] pub struct GasTracker { /// Gas Limit, gas_limit: u64, @@ -116,7 +125,6 @@ pub struct GasTracker { /// exactly as it did before this field existed. /// /// Encodings made before this field existed decode it as zero. - #[cfg_attr(feature = "serde", serde(default))] history_gas_spent: i64, /// Refunded gas. Used to refund the gas to the caller at the end of execution. refunded: i64, @@ -128,7 +136,6 @@ pub struct GasTracker { /// method behaves as it did before this field existed. /// /// Encodings made before this field existed decode it as zero. - #[cfg_attr(feature = "serde", serde(default))] withheld: u64, /// The record of the last failed regular charge the withheld part would have paid /// ([`withheld_crossing`](Self::withheld_crossing)): the regular gas left before that @@ -141,47 +148,41 @@ pub struct GasTracker { /// position, such as bincode, cannot tell the two records apart and reads the old one as the /// regular gas left, so a record persisted in such a format must not cross an upgrade of this /// crate. - #[cfg_attr(feature = "serde", serde(default))] withheld_crossing: Option, /// The regular gas left, spendable and withheld parts together, before the last charge that - /// failed ([`failed_charge_remaining`](Self::failed_charge_remaining)). + /// failed ([`failed_charge_remaining`](Self::failed_charge_remaining)), if + /// `failed_charge_recorded` is set, and zero otherwise. /// /// Encodings made before this field existed decode it as `None`. - #[cfg_attr(feature = "serde", serde(default))] - failed_charge_remaining: Option, + failed_charge_remaining: u64, + /// Whether `failed_charge_remaining` holds a record. A flag apart from the record rather than + /// an `Option`, whose tag would take a word of its own, so it shares a word with + /// `bytes_crossing`. + failed_charge_recorded: bool, /// The byte pool ([`bytes_remaining`](Self::bytes_remaining)): what this frame may still /// draw. Unlimited unless a consumer sets a pool; nothing in this workspace draws it. /// /// Encodings made before this field existed decode it as unlimited. - #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] bytes_remaining: u64, /// The frame's net draw of the pool ([`bytes_spent`](Self::bytes_spent)), signed as /// `history_gas_spent` is, so a rollback can give it back and a merge can hand it on. /// /// Encodings made before this field existed decode it as zero. - #[cfg_attr(feature = "serde", serde(default))] bytes_spent: i64, - /// The record of the last draw the pool could not pay - /// ([`bytes_crossing`](Self::bytes_crossing)). One word, since a failed draw is never zero. + /// Whether a draw failed that the pool could not pay + /// ([`bytes_crossing`](Self::bytes_crossing)). A bit, in the word `failed_charge_recorded` + /// takes. /// - /// Encodings made before this field existed decode it as `None`. - #[cfg_attr(feature = "serde", serde(default))] - bytes_crossing: Option, + /// Encodings made before this field existed decode it as `false`. + bytes_crossing: bool, /// History gas this frame may spend before it charges its budget /// ([`history_allowance`](Self::history_allowance)). Zero unless the schedule gives a value /// call's child one. /// /// Encodings made before this field existed decode it as zero. - #[cfg_attr(feature = "serde", serde(default))] history_allowance: u64, } -/// The pool a tracker starts with, and an encoding that predates the pool decodes to. -#[cfg(feature = "serde")] -const fn unlimited_bytes() -> u64 { - u64::MAX -} - impl Default for GasTracker { /// A tracker with no gas, as [`new`](Self::new) builds it, so the pool starts unlimited. #[inline] @@ -204,10 +205,11 @@ impl GasTracker { refunded: 0, withheld: 0, withheld_crossing: None, - failed_charge_remaining: None, + failed_charge_remaining: 0, + failed_charge_recorded: false, bytes_remaining: u64::MAX, bytes_spent: 0, - bytes_crossing: None, + bytes_crossing: false, history_allowance: 0, } } diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index e1bced4612..6be7e6cd49 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -3,49 +3,14 @@ //! //! The pool is a figure beside the gas: `bytes_remaining` is what the frame may still draw, and //! `bytes_spent` is the frame's net draw so far, signed as the state and history nets are. A draw -//! ([`record_bytes`](GasTracker::record_bytes)) the pool cannot pay fails, takes nothing and leaves -//! a [`BytesCrossing`]. A frame that reverts or halts gives its draws back -//! ([`rollback_state_gas`](GasTracker::rollback_state_gas)), and a frame that succeeds hands its -//! net to its caller, so a caller's rollback undoes its children's draws too. The pool starts -//! unlimited (`u64::MAX`), and nothing in this workspace draws it, so a consumer that sets no pool -//! sees nothing of it. +//! ([`record_bytes`](GasTracker::record_bytes)) the pool cannot pay fails, takes nothing and sets +//! the crossing ([`bytes_crossing`](GasTracker::bytes_crossing)). A frame that reverts or halts +//! gives its draws back ([`rollback_state_gas`](GasTracker::rollback_state_gas)), and a frame that +//! succeeds hands its net to its caller, so a caller's rollback undoes its children's draws too. +//! The pool starts unlimited (`u64::MAX`), and nothing in this workspace draws it, so a consumer +//! that sets no pool sees nothing of it. use super::{saturating_signed, GasTracker}; -use core::num::NonZeroU64; - -/// A draw of the byte pool that the pool could not pay. -/// -/// Recorded by [`GasTracker::record_bytes`] when `cost > bytes_remaining`. The failed draw took -/// nothing, so the pool is as it was before it; the record says that a draw failed, and what it -/// asked for. A consumer reads it from a halted frame's result to tell a frame that ran out of -/// bytes from one that ran out of gas, and turns it into a stop of its own class. -/// -/// A draw of zero never fails, so the cost is never zero and `Option` takes no more -/// room than a `u64`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BytesCrossing { - /// The bytes the failed draw asked for. - cost: NonZeroU64, -} - -impl BytesCrossing { - /// A record of a failed draw of `cost` bytes. - /// - /// The tracker makes its own records. This is for a consumer that marks a result it produced - /// outside the tracker as a failed draw, and puts the record on the tracker with - /// [`GasTracker::set_bytes_crossing`]. - #[inline] - pub const fn with_cost(cost: NonZeroU64) -> Self { - Self { cost } - } - - /// The bytes the failed draw asked for. Never zero. - #[inline] - pub const fn cost(&self) -> u64 { - self.cost.get() - } -} impl GasTracker { /// The byte pool: what this frame may still draw. @@ -90,9 +55,8 @@ impl GasTracker { /// Draws `cost` bytes from the pool. /// - /// Returns `false` if the pool cannot pay, leaving it untouched and recording a - /// [`BytesCrossing`] ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always - /// succeeds. The draw is counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives + /// Returns `false` if the pool cannot pay, leaving it untouched and setting the crossing + /// ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always succeeds. The draw is counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives /// it back. #[inline] #[must_use = "a draw the pool cannot pay is the consumer's stop"] @@ -102,7 +66,7 @@ impl GasTracker { self.bytes_spent = self.bytes_spent.saturating_add(saturating_signed(cost)); return true; } - self.bytes_draw_failed(cost); + self.bytes_crossing = true; false } @@ -133,33 +97,37 @@ impl GasTracker { self.bytes_remaining = self.bytes_remaining.saturating_add(remaining); } - /// The record of the last draw the pool could not pay, since the record was last cleared, or - /// one a consumer set with [`set_bytes_crossing`](Self::set_bytes_crossing); whichever was - /// written last. + /// The crossing: whether a draw failed that the pool could not pay, since the record was last + /// cleared, or a consumer set it with [`set_bytes_crossing`](Self::set_bytes_crossing). /// + /// A consumer reads it from a halted frame's result to tell a frame that ran out of bytes from + /// one that ran out of gas, and turns it into a stop of its own class. The record says that a + /// draw failed, not what it asked for: the hook that drew knows its cost when the draw fails. /// The failed draw took nothing, and no halt touches the pool, so the pool itself still reads /// as it was at the failure until the frame's rollback. The record survives /// [`spend_all`](Self::spend_all), starts empty in every child, and is not taken over by a - /// caller. + /// caller. It is a bit beside the failed-charge record + /// ([`failed_charge_remaining`](Self::failed_charge_remaining)), and each is set and cleared + /// apart from the other. #[inline] - pub const fn bytes_crossing(&self) -> Option { + pub const fn bytes_crossing(&self) -> bool { self.bytes_crossing } /// Clears the record returned by [`bytes_crossing`](Self::bytes_crossing). #[inline] pub const fn clear_bytes_crossing(&mut self) { - self.bytes_crossing = None; + self.bytes_crossing = false; } - /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing), replacing any record - /// already there; `None` clears it. The pool is left as it is. + /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing); `false` clears it. + /// The pool is left as it is. /// /// For a consumer that marks a result it produced itself, such as an answer it gave without /// running a frame, as a failed draw, so a classifier reading the record treats it as one the /// tracker recorded. #[inline] - pub const fn set_bytes_crossing(&mut self, crossing: Option) { + pub const fn set_bytes_crossing(&mut self, crossing: bool) { self.bytes_crossing = crossing; } @@ -170,23 +138,11 @@ impl GasTracker { self.bytes_remaining = self.bytes_remaining.saturating_add_signed(self.bytes_spent); self.bytes_spent = 0; } - - /// Records a draw of `cost` the pool could not pay. Only called on the failure side of - /// [`record_bytes`](Self::record_bytes), where `cost > bytes_remaining >= 0`, so the cost is - /// never zero and the success side does not pay for the record. - #[cold] - #[inline(never)] - const fn bytes_draw_failed(&mut self, cost: u64) { - if let Some(cost) = NonZeroU64::new(cost) { - self.bytes_crossing = Some(BytesCrossing::with_cost(cost)); - } - } } #[cfg(test)] mod tests { - use super::{BytesCrossing, GasTracker}; - use core::num::NonZeroU64; + use super::GasTracker; /// A tracker with a pool of 1,000 bytes. fn pool_1000() -> GasTracker { @@ -195,10 +151,6 @@ mod tests { tracker } - fn crossing(tracker: &GasTracker) -> Option { - tracker.bytes_crossing().map(|crossing| crossing.cost()) - } - /// Every tracker starts with an unlimited pool, nothing drawn and no record; `Default` is /// `new(0, 0, 0)`. #[test] @@ -206,18 +158,32 @@ mod tests { let tracker = GasTracker::new(1_000, 1_000, 300); assert_eq!(tracker.bytes_remaining(), u64::MAX); assert_eq!(tracker.bytes_spent(), 0); - assert_eq!(tracker.bytes_crossing(), None); + assert!(!tracker.bytes_crossing()); assert_eq!(GasTracker::default(), GasTracker::new(0, 0, 0)); assert_eq!(GasTracker::default().bytes_remaining(), u64::MAX); } - /// An absent record takes no extra room. + /// The crossing shares a word with the failed-charge record and is a record of its own: a + /// failed draw records no failed charge, a failed charge records no crossing, and setting or + /// clearing either leaves the other as it is. #[test] - fn test_an_absent_crossing_takes_no_extra_room() { - assert_eq!( - core::mem::size_of::>(), - core::mem::size_of::() - ); + fn test_the_crossing_and_the_failed_charge_record_are_independent() { + let mut tracker = pool_1000(); + assert!(!tracker.record_bytes(1_001)); + assert!(tracker.bytes_crossing()); + assert_eq!(tracker.failed_charge_remaining(), None); + + tracker.clear_bytes_crossing(); + assert!(!tracker.record_regular_cost(1_001)); + assert_eq!(tracker.failed_charge_remaining(), Some(1_000)); + assert!(!tracker.bytes_crossing()); + + tracker.set_bytes_crossing(true); + tracker.set_failed_charge_remaining(None); + assert!(tracker.bytes_crossing()); + tracker.set_failed_charge_remaining(Some(0)); + tracker.clear_bytes_crossing(); + assert_eq!(tracker.failed_charge_remaining(), Some(0)); } #[test] @@ -229,10 +195,10 @@ mod tests { assert_eq!(tracker.bytes_remaining(), 500); assert_eq!(tracker.bytes_spent(), 500); - assert_eq!(tracker.bytes_crossing(), None); + assert!(!tracker.bytes_crossing()); } - /// A draw the pool cannot pay takes nothing and leaves a record of what it asked for. + /// A draw the pool cannot pay takes nothing and leaves the record. #[test] fn test_a_draw_beyond_the_pool_fails_and_records_the_crossing() { let mut tracker = pool_1000(); @@ -246,7 +212,7 @@ mod tests { "the failed draw took nothing" ); assert_eq!(tracker.bytes_spent(), 900); - assert_eq!(crossing(&tracker), Some(101)); + assert!(tracker.bytes_crossing()); } /// A draw of exactly the pool succeeds, and a draw of zero succeeds on an empty pool. @@ -256,29 +222,27 @@ mod tests { assert!(tracker.record_bytes(1_000)); assert_eq!(tracker.bytes_remaining(), 0); assert!(tracker.record_bytes(0)); - assert_eq!(tracker.bytes_crossing(), None); + assert!(!tracker.bytes_crossing()); assert!(!tracker.record_bytes(1)); - assert_eq!(crossing(&tracker), Some(1)); + assert!(tracker.bytes_crossing()); } - /// The record stays until it is cleared: a later draw that succeeds leaves it, a later failed - /// draw replaces it, and a consumer clears or sets it. + /// The record stays until it is cleared: a later draw that succeeds leaves it, and a consumer + /// clears or sets it, which leaves the pool as it is. #[test] - fn test_the_record_stays_until_cleared_and_the_last_failure_wins() { + fn test_the_record_stays_until_cleared() { let mut tracker = pool_1000(); assert!(!tracker.record_bytes(1_001)); assert!(tracker.record_bytes(10)); - assert_eq!(crossing(&tracker), Some(1_001)); - - assert!(!tracker.record_bytes(2_000)); - assert_eq!(crossing(&tracker), Some(2_000)); + assert!(tracker.bytes_crossing()); tracker.clear_bytes_crossing(); - assert_eq!(tracker.bytes_crossing(), None); + assert!(!tracker.bytes_crossing()); - let set = BytesCrossing::with_cost(NonZeroU64::new(7).unwrap()); - tracker.set_bytes_crossing(Some(set)); - assert_eq!(tracker.bytes_crossing(), Some(set)); + tracker.set_bytes_crossing(true); + assert!(tracker.bytes_crossing()); + tracker.set_bytes_crossing(false); + assert!(!tracker.bytes_crossing()); assert_eq!( tracker.bytes_remaining(), 990, @@ -298,7 +262,7 @@ mod tests { assert_eq!(tracker.remaining(), 0); assert_eq!(tracker.bytes_remaining(), 400); - assert_eq!(crossing(&tracker), Some(500)); + assert!(tracker.bytes_crossing()); } /// A refill gives bytes back and lowers the net, below zero when the draw was a caller's. @@ -423,6 +387,6 @@ mod tests { let decoded = serde_json::from_value::(older).unwrap(); assert_eq!(decoded.bytes_remaining(), u64::MAX); assert_eq!(decoded.bytes_spent(), 0); - assert_eq!(decoded.bytes_crossing(), None); + assert!(!decoded.bytes_crossing()); } } diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs new file mode 100644 index 0000000000..a187e8c6ec --- /dev/null +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -0,0 +1,150 @@ +//! The encoding of a [`GasTracker`]. +//! +//! In memory the failed-charge record is a number and a flag, and the flag shares a word with the +//! byte pool's crossing. Encoded, the tracker keeps the fields, names and order the derived +//! encoding had: the failed-charge record is an optional number in its place, and the crossing a +//! `bool` in its own. + +use super::{GasTracker, WithheldCrossing}; + +/// A [`GasTracker`] as it is encoded: its fields in their order, with the defaults an encoding +/// made before a field existed decodes to. Each field of the tracker documents its own. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename = "GasTracker")] +pub(super) struct Encoded { + gas_limit: u64, + remaining: u64, + reservoir: u64, + state_gas_spent: i64, + state_gas_spilled: u64, + #[serde(default)] + history_gas_spent: i64, + refunded: i64, + #[serde(default)] + withheld: u64, + #[serde(default)] + withheld_crossing: Option, + #[serde(default)] + failed_charge_remaining: Option, + #[serde(default = "unlimited_bytes")] + bytes_remaining: u64, + #[serde(default)] + bytes_spent: i64, + #[serde(default)] + bytes_crossing: bool, + #[serde(default)] + history_allowance: u64, +} + +/// The pool a tracker starts with, and an encoding that predates the pool decodes to. +const fn unlimited_bytes() -> u64 { + u64::MAX +} + +impl From for Encoded { + fn from(tracker: GasTracker) -> Self { + Self { + gas_limit: tracker.gas_limit, + remaining: tracker.remaining, + reservoir: tracker.reservoir, + state_gas_spent: tracker.state_gas_spent, + state_gas_spilled: tracker.state_gas_spilled, + history_gas_spent: tracker.history_gas_spent, + refunded: tracker.refunded, + withheld: tracker.withheld, + withheld_crossing: tracker.withheld_crossing, + failed_charge_remaining: tracker.failed_charge_remaining(), + bytes_remaining: tracker.bytes_remaining, + bytes_spent: tracker.bytes_spent, + bytes_crossing: tracker.bytes_crossing, + history_allowance: tracker.history_allowance, + } + } +} + +impl From for GasTracker { + fn from(encoded: Encoded) -> Self { + let mut tracker = Self { + gas_limit: encoded.gas_limit, + remaining: encoded.remaining, + reservoir: encoded.reservoir, + state_gas_spent: encoded.state_gas_spent, + state_gas_spilled: encoded.state_gas_spilled, + history_gas_spent: encoded.history_gas_spent, + refunded: encoded.refunded, + withheld: encoded.withheld, + withheld_crossing: encoded.withheld_crossing, + failed_charge_remaining: 0, + failed_charge_recorded: false, + bytes_remaining: encoded.bytes_remaining, + bytes_spent: encoded.bytes_spent, + bytes_crossing: encoded.bytes_crossing, + history_allowance: encoded.history_allowance, + }; + tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); + tracker + } +} + +#[cfg(test)] +mod tests { + use super::super::GasTracker; + + /// A tracker with every field away from its default: part of its regular gas withheld, a + /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a refund, + /// a pool drawn and a draw refused, and an allowance. + fn every_field_set() -> GasTracker { + let mut tracker = GasTracker::new(1_000, 400, 300); + tracker.withhold(100); + assert!(!tracker.record_regular_cost(350)); + assert!(tracker.record_state_cost(500)); + tracker.set_bytes_remaining(900); + assert!(tracker.record_bytes(20)); + assert!(!tracker.record_bytes(10_000)); + tracker.set_history_allowance(160); + tracker.record_refund(-3); + tracker + } + + /// The encoding has the fields, the names and the order it had before the failed-charge + /// record and the crossing shared a word, so a format that encodes by position reads it as + /// before; the failed-charge record is an optional number, and the crossing a `bool`. + #[test] + fn test_the_encoding_keeps_its_fields_and_their_order() { + assert_eq!( + serde_json::to_string(&every_field_set()).unwrap(), + concat!( + r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#, + r#""state_gas_spilled":200,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, + r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#, + r#""bytes_remaining":880,"bytes_spent":20,"bytes_crossing":true,"#, + r#""history_allowance":160}"#, + ) + ); + assert_eq!( + serde_json::to_string(&GasTracker::new(1_000, 1_000, 0)).unwrap(), + concat!( + r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#, + r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#, + r#""withheld_crossing":null,"failed_charge_remaining":null,"#, + r#""bytes_remaining":18446744073709551615,"bytes_spent":0,"bytes_crossing":false,"#, + r#""history_allowance":0}"#, + ) + ); + } + + /// Every field round-trips, a failed charge of zero apart from none. + #[test] + fn test_the_encoding_round_trips() { + let mut zero_left = GasTracker::new(1_000, 0, 0); + assert!(!zero_left.record_regular_cost(1)); + for tracker in [every_field_set(), zero_left, GasTracker::default()] { + let encoded = serde_json::to_string(&tracker).unwrap(); + assert_eq!( + serde_json::from_str::(&encoded).unwrap(), + tracker, + "{encoded}" + ); + } + } +} diff --git a/crates/context/interface/src/cfg/gas/failed_charge.rs b/crates/context/interface/src/cfg/gas/failed_charge.rs index 9bd7b02c71..2c49159cf8 100644 --- a/crates/context/interface/src/cfg/gas/failed_charge.rs +++ b/crates/context/interface/src/cfg/gas/failed_charge.rs @@ -47,7 +47,11 @@ impl GasTracker { /// record is left on a creation that returns successfully. #[inline] pub const fn failed_charge_remaining(&self) -> Option { - self.failed_charge_remaining + if self.failed_charge_recorded { + Some(self.failed_charge_remaining) + } else { + None + } } /// Sets the record returned by [`failed_charge_remaining`](Self::failed_charge_remaining), @@ -59,7 +63,20 @@ impl GasTracker { /// failure, the record survives [`spend_all`](Self::spend_all). #[inline] pub const fn set_failed_charge_remaining(&mut self, remaining: Option) { + match remaining { + Some(remaining) => self.record_failed_charge(remaining), + None => { + self.failed_charge_remaining = 0; + self.failed_charge_recorded = false; + } + } + } + + /// Records `remaining` as the regular gas left before a failed charge. + #[inline] + const fn record_failed_charge(&mut self, remaining: u64) { self.failed_charge_remaining = remaining; + self.failed_charge_recorded = true; } /// Records a failed regular charge of `cost` against `spendable`: the regular gas left, @@ -74,7 +91,7 @@ impl GasTracker { #[inline(never)] pub(super) const fn regular_charge_failed(&mut self, cost: u64, spendable: u64) { let remaining = spendable.saturating_add(self.withheld); - self.failed_charge_remaining = Some(remaining); + self.record_failed_charge(remaining); // `cost > spendable`, so a withheld part that covers the difference is never zero, and // neither is the regular gas left. if cost - spendable <= self.withheld { @@ -94,7 +111,7 @@ impl GasTracker { #[cold] #[inline(never)] pub(super) const fn withheld_first_cost_failed(&mut self) { - self.failed_charge_remaining = Some(self.remaining.saturating_add(self.withheld)); + self.record_failed_charge(self.remaining.saturating_add(self.withheld)); } } diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 74a10188df..824d4e91ef 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,13 +236,14 @@ mod tests { assert_eq!(size_of::>(), size_of::()); } - /// The tracker is 120 bytes: 72 with the withheld part and its record, two words more for the - /// failed-charge record, and four more for the byte pool (the pool, its net and its record) - /// and the history allowance. Copies of the tracker, and of every `Gas` and frame result that - /// holds one, grow with it, so a new field is measured before this changes. - #[test] - fn test_the_tracker_is_120_bytes() { - assert_eq!(size_of::(), 120); + /// The tracker is 112 bytes: 72 with the withheld part and its record, two words more for the + /// failed-charge record, whose second word also holds the byte pool's crossing, and three more + /// for the byte pool and its net and the history allowance. Copies of the tracker, and of + /// every `Gas` and frame result that holds one, grow with it, so a new field is measured + /// before this changes. + #[test] + fn test_the_tracker_is_112_bytes() { + assert_eq!(size_of::(), 112); } /// Withholding moves gas between the parts and leaves the total alone. diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index 0b4de01db6..968c5a04ce 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -117,25 +117,25 @@ const fn log( } /// A frame's pool figures as it returned, before its caller settled it: its result, its pool, -/// its net draw, the draw that failed, its history gas and its allowance. +/// its net draw, whether a draw failed, its history gas and its allowance. #[derive(Clone, Debug, PartialEq, Eq)] struct Returned { result: InstructionResult, pool: u64, spent: i64, - crossing: Option, + crossing: bool, history: i64, allowance: u64, } impl Returned { - fn of(result: &FrameResult) -> Self { + const fn of(result: &FrameResult) -> Self { let gas = result.gas(); Self { result: result.instruction_result(), pool: gas.bytes_remaining(), spent: gas.bytes_spent(), - crossing: gas.bytes_crossing().map(|crossing| crossing.cost()), + crossing: gas.bytes_crossing(), history: gas.history_gas_spent(), allowance: gas.history_allowance(), } @@ -150,7 +150,7 @@ impl Returned { result, pool, spent, - crossing: None, + crossing: false, history: 0, allowance: 0, } @@ -708,7 +708,7 @@ fn test_a_failed_draw_halts_the_frame_with_a_record_the_caller_can_read() { handler.returned, [ Returned { - crossing: Some(DRAW_BYTES), + crossing: true, ..Returned::ended(InstructionResult::OutOfGas, 50, 0) }, Returned::stopped(50, 100), diff --git a/crates/inspector/tests/byte_pool.rs b/crates/inspector/tests/byte_pool.rs index 57236612bd..354f908575 100644 --- a/crates/inspector/tests/byte_pool.rs +++ b/crates/inspector/tests/byte_pool.rs @@ -313,7 +313,7 @@ struct Ended { result: InstructionResult, pool: u64, spent: i64, - crossing: Option, + crossing: bool, history: i64, allowance: u64, charged_start: StartCharge, @@ -329,7 +329,7 @@ impl Ended { result, pool, spent, - crossing: None, + crossing: false, history: 0, allowance: 0, charged_start: StartCharge::new(0, 0), @@ -351,7 +351,7 @@ impl Figures { result, pool: gas.bytes_remaining(), spent: gas.bytes_spent(), - crossing: gas.bytes_crossing().map(|crossing| crossing.cost()), + crossing: gas.bytes_crossing(), history: gas.history_gas_spent(), allowance: gas.history_allowance(), charged_start: charged, @@ -570,7 +570,7 @@ fn test_both_paths_record_a_failed_draw() { figures.ends, [ Ended { - crossing: Some(u64::MAX), + crossing: true, ..Ended::with(InstructionResult::OutOfGas, UNLIMITED - DRAW_BYTES, 0) }, Ended::stopped(UNLIMITED - DRAW_BYTES, DRAW_BYTES as i64), diff --git a/crates/interpreter/src/gas/byte_pool.rs b/crates/interpreter/src/gas/byte_pool.rs index 8be8347898..d7f7b97439 100644 --- a/crates/interpreter/src/gas/byte_pool.rs +++ b/crates/interpreter/src/gas/byte_pool.rs @@ -3,7 +3,7 @@ //! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which //! documents it. -use super::{BytesCrossing, Gas}; +use super::Gas; impl Gas { /// The byte pool: what this frame may still draw. Unlimited unless a consumer set a pool. @@ -38,8 +38,8 @@ impl Gas { self.tracker.set_bytes_spent(val); } - /// Draws `cost` bytes from the pool; `false` if the pool cannot pay, which records a - /// [`BytesCrossing`]. + /// Draws `cost` bytes from the pool; `false` if the pool cannot pay, which sets the crossing + /// ([`bytes_crossing`](Self::bytes_crossing)). /// /// See [`GasTracker::record_bytes`](super::GasTracker::record_bytes). #[inline] @@ -56,11 +56,11 @@ impl Gas { self.tracker.refill_bytes(amount); } - /// The record of the last draw the pool could not pay, since it was last cleared. + /// Whether a draw failed that the pool could not pay, since the record was last cleared. /// /// See [`GasTracker::bytes_crossing`](super::GasTracker::bytes_crossing). #[inline] - pub const fn bytes_crossing(&self) -> Option { + pub const fn bytes_crossing(&self) -> bool { self.tracker.bytes_crossing() } @@ -76,7 +76,7 @@ impl Gas { /// /// See [`GasTracker::set_bytes_crossing`](super::GasTracker::set_bytes_crossing). #[inline] - pub const fn set_bytes_crossing(&mut self, crossing: Option) { + pub const fn set_bytes_crossing(&mut self, crossing: bool) { self.tracker.set_bytes_crossing(crossing); } diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 8b14cbbef4..79828853b7 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,7 +36,7 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{BytesCrossing, Gas, GasTracker, StartCharge}; +pub use gas::{Gas, GasTracker, StartCharge}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/byte_pool.rs b/crates/interpreter/tests/byte_pool.rs index e3a4996407..f90a3a826a 100644 --- a/crates/interpreter/tests/byte_pool.rs +++ b/crates/interpreter/tests/byte_pool.rs @@ -341,7 +341,7 @@ fn test_every_start_forwards_the_whole_pool_by_default() { "{kind:?}: the caller keeps nothing" ); assert_eq!(gas.bytes_spent(), 0, "{kind:?}: a forward is not a draw"); - assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); + assert!(!gas.bytes_crossing(), "{kind:?}"); } } @@ -419,7 +419,7 @@ fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { "{kind:?}: no share taken" ); assert_eq!(gas.bytes_spent(), 200, "{kind:?}"); - assert_eq!(gas.bytes_crossing(), None, "{kind:?}"); + assert!(!gas.bytes_crossing(), "{kind:?}"); } } @@ -444,11 +444,7 @@ fn test_a_draw_the_pool_cannot_pay_records_a_crossing_that_survives_the_halt() { "{kind:?}: the failed draw took nothing" ); assert_eq!(gas.bytes_spent(), 0, "{kind:?}"); - assert_eq!( - gas.bytes_crossing().map(|crossing| crossing.cost()), - Some(POOL + 1), - "{kind:?}" - ); + assert!(gas.bytes_crossing(), "{kind:?}"); } } From 4953722961b6a203d2ff26fea4a73eccd0aa1242 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 21:00:22 +0800 Subject: [PATCH 015/110] docs: the start charge on the start, the crossing as a bit and their sizes in MEGAETH-FORK.md The frame-start hook takes `&mut FrameStart` and declares the start charge on it; the carrier on the tracker is gone. The byte pool's crossing is a bit beside the failed-charge record's flag, and `BytesCrossing` is gone. The tracker is 112 bytes and a frame result 248; the default cost is measured against the base. --- MEGAETH-FORK.md | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index f0fb970211..301ae77dbb 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -151,7 +151,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns. - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. - It is two words: the tracker was 88 bytes with it (136 with the byte pool, see The byte pool), and a copy of the tracker, and of every `Gas` and frame result that holds one, is 16 bytes larger. + It was two words as an `Option`: the tracker was 88 bytes with it, and a copy of the tracker, and of every `Gas` and frame result that holds one, 16 bytes larger. + It is now a number and a flag, and the flag shares its word with the byte pool's crossing (see The byte pool); the encoding is unchanged, an optional number in the same place. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. ### Precompile price @@ -220,13 +221,14 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th ### Frame-start hook -- **API.** `Host::frame_starting(&mut self, start: &FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. - `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. +- **API.** `Host::frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. + `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, and `charge`, which `new` leaves empty) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`; `target` is the account the frame runs as, `None` for a creation. `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. - After the hook the instruction takes two more things off `gas` for the frame's input: the start charge the hook declared (see The start charge) and the child's share of the byte pool (see The byte pool); the share is of the pool as the hook left it. + `start` is the hook's to declare the start charge on (`charge`, see The start charge); the instruction reads nothing else back from it. + After the hook the instruction copies that charge onto the frame's input and takes the child's share of the byte pool off `gas` for it (see The byte pool); the share is of the pool as the hook left it. `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. @@ -238,11 +240,11 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **API.** On `GasTracker`, forwarded on `Gas`: `bytes_remaining`, `set_bytes_remaining`, `bytes_spent`, `set_bytes_spent`, `record_bytes`, `refill_bytes`, `bytes_crossing`, `clear_bytes_crossing`, `set_bytes_crossing`. On `GasTracker` alone, the fork's own plumbing: `add_bytes_spent`, `forward_bytes`, `absorb_returned_bytes`. - The type `BytesCrossing` (`with_cost`, `cost`), re-exported from `revm_interpreter`. `GasId::bytes_forward_percent` and `GasParams::bytes_forward_share(pool)`. `bytes_share` on `CallInputs` (a field) and `CreateInputs` (`bytes_share`, `set_bytes_share`). - **Contract.** The pool is a budget of bytes a frame may append, beside its gas: `bytes_remaining` is what the frame may still draw, `bytes_spent` its net draw, signed as `history_gas_spent` is. - `record_bytes(n)` draws; a draw the pool cannot pay takes nothing, returns `false` and records a `BytesCrossing` holding the draw refused, which survives `spend_all`, starts empty in every child, is not taken over by a caller, and stays until cleared or replaced; a consumer marks a result it produced itself with `set_bytes_crossing`. + `record_bytes(n)` draws; a draw the pool cannot pay takes nothing, returns `false` and sets the crossing (`bytes_crossing()` is `true`), which survives `spend_all`, starts clear in every child, is not taken over by a caller, and stays until cleared; a consumer marks a result it produced itself with `set_bytes_crossing`. + The crossing is a bit: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. No halt touches the pool, so a halted frame's result still reads the pool as the failed draw found it, until its caller settles it. `refill_bytes(n)` gives bytes back and lowers the net, below zero when the draw was a caller's. The transaction's frame gets the whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution. @@ -258,21 +260,23 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm keeps a per-frame budget of the bytes a transaction appends to the state and the history, which a failed frame gives back and a successful one hands to its caller. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry a figure that moves with a frame's gas. - **Removal.** When upstream carries an equivalent per-frame budget on its gas, or when mega-evm stops limiting bytes per frame. - **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. - The tracker is 136 bytes with the pool (three words), the allowance (one) and the start-charge carrier (two); encodings that predate the fields decode with an unlimited pool and zero for the rest. + The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest. + `Gas` is 128 bytes (104), `InterpreterResult` 168 (144), `CallOutcome` and `FrameResult` 248 (208), `CreateOutcome` 232 (192), the outcomes with the start charge's two words. + Where measured (callgrind, the fork's release profile, against the base without the pool, the start charge and the allowance), the three figures together cost a transfer 122 instructions (+2.3%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 152 (+1.9%) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. ### The start charge - **API.** The type `StartCharge` (`new`, `history`, `bytes`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`. - On `GasTracker`, forwarded on `Gas`: `start_charge`, `set_start_charge`, `take_start_charge`. + `FrameStart::charge` (see Frame-start hook). `charged_start` on `CallInputs`, `CallOutcome` and `CreateOutcome` (fields) and on `CreateInputs` (`charged_start`, `set_charged_start`); `FrameResult::refundable_start_charge`. - **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and bytes of the pool. - The `frame_starting` hook declares it on the tracker it is handed (`set_start_charge`), after charging it; the instruction takes it off the tracker right after the hook, whatever the answer, and puts it on the frame's input, so the carrier is zero outside that window and is not part of an encoded tracker; a start the hook refuses discards the charge with the start, and what the hook charged stands. - The transaction's frame takes the charge a consumer declared on the transaction's tracker. + The `frame_starting` hook charges the caller's tracker and declares the refundable part on the start it is handed (`start.charge`); the instruction copies it onto the frame's input when the hook admits the start; a start the hook refuses discards the charge with the start, and what the hook charged stands. + The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. A frame that succeeds keeps the charge. - **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. -- **Default.** The hook declares nothing, so the carrier, the fields and the refund are zero. +- **Default.** The hook declares nothing, so the fields and the refund are zero. This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. alloy-evm 0.36, revm-inspectors 0.40 and the op-revm fork construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. ### The history allowance From 08330cfbc244c3d74c6d48214aee1e4b1d79df58 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 21:53:02 +0800 Subject: [PATCH 016/110] feat(context): the code-deposit admission hook is lent the creating frame's tracker `ContextTr::admit_code_deposit` takes the creating frame's tracker as `gas: &mut GasTracker` beside the deposit, as `write_completed` and `frame_starting` take the running frame's. The hook may charge it: a consumer that holds deployed code to a byte budget draws the code's bytes from the frame's pool there, between `return_create`'s last charge and the checkpoint commit. An admitted deposit returns with the gas as the hook left it; a refusal puts it back to `gas_before`, which undoes the hook's charges and a crossing its failed draw recorded. `CodeDeposit` is unchanged and stays `Copy`: `gas_after` reads a copy of the frame's gas as `return_create` left it, so the deposit's charges read the same whatever the hook does. The default hook admits and touches nothing. This changes a released hook's signature, so an override of the hook does not compile until it takes the parameter (`api:exception`). mega-evm's `MegaContext` is the one override found. Tests: the hook draws on the frame's gas through `return_create` (admitted, admitted with a failed draw, refused, refused with a failed draw, and the default hook), and end to end, where an admitted deposit's draw reaches the transaction's net and a refused one gives the whole share back. --- crates/context/interface/src/context.rs | 30 +++-- .../interface/src/context/code_deposit.rs | 6 +- crates/handler/src/frame/code_deposit.rs | 29 +++-- crates/handler/tests/byte_pool.rs | 83 +++++++++++- .../handler/tests/code_deposit_admission.rs | 118 +++++++++++++++++- .../inspector/tests/code_deposit_admission.rs | 8 +- 6 files changed, 241 insertions(+), 33 deletions(-) diff --git a/crates/context/interface/src/context.rs b/crates/context/interface/src/context.rs index 86ad87cdec..946595bcb1 100644 --- a/crates/context/interface/src/context.rs +++ b/crates/context/interface/src/context.rs @@ -2,7 +2,8 @@ //! Context trait and related types. pub use crate::journaled_state::StateLoad; use crate::{ - result::FromStringError, Block, Cfg, Database, Host, JournalTr, LocalContextTr, Transaction, + cfg::gas::GasTracker, result::FromStringError, Block, Cfg, Database, Host, JournalTr, + LocalContextTr, Transaction, }; use auto_impl::auto_impl; use primitives::{Bytes, StorageValue}; @@ -180,14 +181,21 @@ pub trait ContextTr: Host { /// [`gas_before`](CodeDeposit::gas_before) does not: an admitted deposit returns with the /// record, and a refused one, put back to `gas_before`, discards it. /// + /// `gas` is the creating frame's tracker, as [`gas_after`](CodeDeposit::gas_after) reads it + /// when the hook is called. The hook may debit and credit it, for instance draw the deployed + /// code's bytes from the frame's byte pool + /// ([`GasTracker::record_bytes`](crate::cfg::gas::GasTracker::record_bytes)); a charge it + /// makes that fails records as any failed charge does. + /// /// - `Ok(())` admits it: the checkpoint is committed and the code is written, as without this - /// hook. + /// hook, and the frame returns with `gas` as the hook left it. /// - `Err(output)` refuses it: the checkpoint is reverted, so no state change of the creation /// is kept and no code is written; the frame's gas is put back to - /// [`gas_before`](CodeDeposit::gas_before), so none of the deposit's charges is paid; and the - /// creation ends as a `Revert` with `output` as its revert data. From there it settles as a - /// creation whose init code reverted: its caller gets its unspent gas back, a zero address - /// and `output` as return data. + /// [`gas_before`](CodeDeposit::gas_before), so none of the deposit's charges is paid and + /// whatever the hook did to `gas` is undone, a crossing its failed draw recorded included; + /// and the creation ends as a `Revert` with `output` as its revert data. From there it + /// settles as a creation whose init code reverted: its caller gets its unspent gas back, a + /// zero address and `output` as return data. /// /// The deposit's charges are made before it is offered, and with them the lookup of its state /// gas price through [`Host::state_gas_price`]. So that lookup is made whether or not the @@ -197,10 +205,14 @@ pub trait ContextTr: Host { /// [`Host::state_gas_price`] lookup does, and refuses; the transaction then returns the /// error. /// - /// The default admits every deposit. + /// The default admits every deposit and leaves `gas` alone. #[inline] - fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { - let _ = deposit; + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + gas: &mut GasTracker, + ) -> Result<(), Bytes> { + let _ = (deposit, gas); Ok(()) } } diff --git a/crates/context/interface/src/context/code_deposit.rs b/crates/context/interface/src/context/code_deposit.rs index 54af68ec39..df5aaf462e 100644 --- a/crates/context/interface/src/context/code_deposit.rs +++ b/crates/context/interface/src/context/code_deposit.rs @@ -16,7 +16,9 @@ use primitives::{Address, Bytes}; /// /// The charges are read off the two trackers: [`gas_before`](Self::gas_before), the creating /// frame's gas before the first deposit charge, and [`gas_after`](Self::gas_after), the same gas -/// with every deposit charge recorded. Nothing else touches the frame's gas between the two. +/// with every deposit charge recorded. Nothing else touches the frame's gas between the two. Both +/// are as `return_create` left them: the hook is lent the frame's gas itself beside the deposit, +/// and what it does to that gas shows on neither. /// /// The fields are public to read. The type is `#[non_exhaustive]`, so it is built with /// [`new`](Self::new) outside this crate, and a field added later is not a breaking change. @@ -32,7 +34,7 @@ pub struct CodeDeposit<'a> { /// gas back to this. pub gas_before: &'a GasTracker, /// The creating frame's gas with every deposit charge recorded: what the frame returns with - /// when the deposit is admitted. + /// when the deposit is admitted, unless the hook charges the gas it is lent. /// /// Before Homestead, when the frame could not pay the code-deposit cost, nothing was charged /// and [`code`](Self::code) is empty. If that failed charge was a crossing of the frame's diff --git a/crates/handler/src/frame/code_deposit.rs b/crates/handler/src/frame/code_deposit.rs index 47a0728695..1f1e03ebf8 100644 --- a/crates/handler/src/frame/code_deposit.rs +++ b/crates/handler/src/frame/code_deposit.rs @@ -10,13 +10,14 @@ use primitives::Address; /// ([`ContextTr::admit_code_deposit`]), and returns whether it did. /// /// `interpreter_result` holds the code and the creating frame's gas with every deposit charge -/// recorded; `gas_before_deposit` is that gas before the first of them. A refused deposit reverts -/// `checkpoint`, puts the frame's gas back to `gas_before_deposit` and turns the result into a -/// `Revert` carrying the output the context named; `return_create` then returns without -/// committing. +/// recorded; `gas_before_deposit` is that gas before the first of them. The hook reads a copy of +/// the frame's gas as the deposit's `gas_after` and is lent the gas itself, which it may charge. A +/// refused deposit reverts `checkpoint`, puts the frame's gas back to `gas_before_deposit`, which +/// undoes whatever the hook did to it, and turns the result into a `Revert` carrying the output +/// the context named; `return_create` then returns without committing. /// -/// Inlined into `return_create`, so under the default hook, which admits, it compiles away with -/// the copy of the frame's gas it reads. +/// Inlined into `return_create`, so under the default hook, which admits and touches nothing, it +/// compiles away with the copies of the frame's gas it reads. #[inline(always)] pub(super) fn admit_code_deposit( context: &mut CTX, @@ -25,12 +26,16 @@ pub(super) fn admit_code_deposit( gas_before_deposit: &Gas, address: Address, ) -> bool { - let admitted = context.admit_code_deposit(&CodeDeposit::new( - address, - &interpreter_result.output, - gas_before_deposit.tracker(), - interpreter_result.gas.tracker(), - )); + let gas_after_deposit = interpreter_result.gas; + let admitted = context.admit_code_deposit( + &CodeDeposit::new( + address, + &interpreter_result.output, + gas_before_deposit.tracker(), + gas_after_deposit.tracker(), + ), + interpreter_result.gas.tracker_mut(), + ); let Err(output) = admitted else { return true; }; diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index 968c5a04ce..f413cfaf0c 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -10,10 +10,11 @@ //! the frames draw the pool through instructions of the test's own, which stand in for a //! consumer's hooks: `DRAW` draws bytes, `DECLARE` has the start hook charge and declare a start //! charge at the next start, and `LOG` charges history after drawing the frame's allowance, as a -//! consumer's write hook would. +//! consumer's write hook would. The context's code-deposit admission hook draws deployed code's +//! bytes when a test asks it to. use bytecode::opcode::{ - CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, STOP, + CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, RETURN, REVERT, STOP, }; use context::{ result::{EVMError, ExecutionResult}, @@ -22,6 +23,7 @@ use context::{ }; use context_interface::{ cfg::{gas::InitialAndFloorGas, GasId, GasParams, StateGasSite}, + context::CodeDeposit, host::{FrameStart, LoadError}, journaled_state::AccountInfoLoad, Database, Host, @@ -157,12 +159,25 @@ impl Returned { } } +/// What the code-deposit admission hook does with a deposit. +#[derive(Clone, Copy, Debug)] +enum Deposit { + /// Admits it and touches nothing, as the default hook does. + Untouched, + /// Draws the code's bytes from the creating frame's pool and admits it. + Drawn, + /// Draws the code's bytes from the creating frame's pool and refuses it. + DrawnAndRefused, +} + /// The mainnet [`Context`] with a start hook that does what a consumer's does for a start -/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start. +/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start; and an +/// admission hook that does with a code deposit what [`Deposit`] says. struct DeclaringContext { inner: MainnetContext, /// Set by `DECLARE`, taken by the next start. declare_next: bool, + deposit: Deposit, } impl ContextTr for DeclaringContext { @@ -204,6 +219,24 @@ impl ContextTr for DeclaringContext { fn error(&mut self) -> &mut Result<(), ContextError> { self.inner.error() } + + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + gas: &mut GasTracker, + ) -> Result<(), Bytes> { + let refuses = match self.deposit { + Deposit::Untouched => return Ok(()), + Deposit::Drawn => false, + Deposit::DrawnAndRefused => true, + }; + assert!(gas.record_bytes(deposit.code.len() as u64)); + if refuses { + Err(Bytes::new()) + } else { + Ok(()) + } + } } impl ContextSetters for DeclaringContext { @@ -536,6 +569,7 @@ struct Run { parent_nonce: u64, /// `call_history_allowance` in the schedule. allowance: u64, + deposit: Deposit, } impl Run { @@ -545,9 +579,15 @@ impl Run { parent_balance: 10, parent_nonce: 1, allowance: 0, + deposit: Deposit::Untouched, } } + const fn deposit(mut self, deposit: Deposit) -> Self { + self.deposit = deposit; + self + } + const fn penniless(mut self) -> Self { self.parent_balance = 0; self @@ -606,6 +646,7 @@ impl Run { let ctx = DeclaringContext { inner, declare_next: false, + deposit: self.deposit, }; let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(DRAW, Instruction::new(draw), 0); @@ -891,3 +932,39 @@ fn test_a_consumer_that_sets_nothing_sees_the_mainnet_result() { ); assert_eq!(handler.settled, Some((less(2), 2 * DRAW_BYTES as i64, 0))); } + +/// The admission hook draws deployed code's bytes from the creating frame's pool. An admitted +/// deposit's draw is the creation's own: its caller takes its net over and the transaction's net +/// counts it, as for any draw of a frame that succeeded. A refused deposit ends the creation as a +/// revert with the draw undone, and its caller gets the whole share back. +#[test] +fn test_a_deposit_drawn_at_admission_is_held_against_the_transaction() { + // Deploys 32 zero bytes. + let initcode = [PUSH1, 32, PUSH0, RETURN]; + for (name, deposit, returned, settled) in [ + ( + "admitted", + Deposit::Drawn, + Returned::ended(InstructionResult::Return, POOL - 32, 32), + (POOL - 32, 32, 0), + ), + ( + "refused", + Deposit::DrawnAndRefused, + Returned::ended(InstructionResult::Revert, POOL, 0), + (POOL, 0, 0), + ), + ] { + let run = Run::new(ends(create(&initcode))).deposit(deposit); + + let (result, handler) = run.with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{name}: {result:?}"); + assert_eq!( + handler.starts[1].0, POOL, + "{name}: the whole pool forwarded" + ); + assert_eq!(handler.returned[0], returned, "{name}"); + assert_eq!(handler.settled, Some(settled), "{name}"); + } +} diff --git a/crates/handler/tests/code_deposit_admission.rs b/crates/handler/tests/code_deposit_admission.rs index 3ee58db10e..79e24f628a 100644 --- a/crates/handler/tests/code_deposit_admission.rs +++ b/crates/handler/tests/code_deposit_admission.rs @@ -5,7 +5,8 @@ //! admission hook, which records every deposit it is offered and admits, refuses with a named //! output, or fails fatally. Each case is compared with a twin: an admitting context against //! [`Context`] itself, and a refused deposit against the same creation whose init code reverts. -//! One test calls `return_create` directly, on a frame whose regular gas is partly withheld. +//! Two tests call `return_create` directly: on a frame whose regular gas is partly withheld, and +//! on a frame with a byte pool the hook draws the deposit from. use bytecode::opcode::{ CREATE, MSTORE, MSTORE8, PUSH0, PUSH1, PUSH3, PUSH4, RETURN, RETURNDATASIZE, REVERT, SSTORE, @@ -60,7 +61,7 @@ const REVERT_32: [u8; 4] = [PUSH1, 32, PUSH0, REVERT]; const RETURN_EF: [u8; 8] = [PUSH1, 0xEF, PUSH0, MSTORE8, PUSH1, 1, PUSH0, RETURN]; /// What the context does with a deposit it is offered. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] enum Policy { Admit, Refuse, @@ -81,6 +82,9 @@ struct Offered { struct AdmissionContext { inner: MainnetContext, policy: Policy, + /// Bytes the hook draws from the creating frame's pool before it decides, as a consumer that + /// holds deployed code to a byte budget does; zero draws nothing. + draw: u64, offered: Vec, /// The creating frame's gas before and after the deposit's charges, of every deposit offered. offered_gas: Vec<(GasTracker, GasTracker)>, @@ -128,7 +132,13 @@ impl ContextTr for AdmissionContext { self.inner.error() } - fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + gas: &mut GasTracker, + ) -> Result<(), Bytes> { + // A draw the pool cannot pay records the crossing on `gas`, as any failed draw does. + let _ = gas.record_bytes(self.draw); self.offered.push(Offered { address: deposit.address, code: deposit.code.clone(), @@ -327,6 +337,7 @@ fn admission_context(db: Db, schedule: Schedule, policy: Policy) -> AdmissionCon AdmissionContext { inner: context(db, schedule), policy, + draw: 0, offered: Vec::new(), offered_gas: Vec::new(), deposit_prices: Vec::new(), @@ -647,11 +658,18 @@ fn return_create_on( history_per_byte: 0, }; let mut ctx = admission_context(db(None), schedule, policy); + let result = return_create_with(&mut ctx, gas, code); + (result, ctx) +} + +/// Calls `return_create` on `ctx` for a creation at [`CONTRACT`] that returned `code` with `gas`, +/// and returns the creation's result. +fn return_create_with(ctx: &mut CTX, gas: Gas, code: Bytes) -> InterpreterResult { ctx.journal_mut().load_account(CONTRACT).unwrap(); let checkpoint = ctx.journal_mut().checkpoint(); let mut result = InterpreterResult::new(InstructionResult::Return, code, gas); - return_create(&mut ctx, checkpoint, &mut result, CONTRACT); - (result, ctx) + return_create(ctx, checkpoint, &mut result, CONTRACT); + result } /// Before Homestead a frame that cannot pay the code deposit does not fail: `return_create` @@ -719,6 +737,96 @@ fn test_a_pre_homestead_deposit_the_frame_cannot_pay_is_offered_with_its_crossin assert_eq!(result.result, InstructionResult::OutOfGas); } +/// The hook is lent the creating frame's gas, so it can draw the deployed code's bytes from the +/// frame's pool. A draw on an admitted deposit stays on the frame, a failed one with its crossing; +/// a refusal puts the gas back to `gas_before`, which undoes the draw and discards the crossing. +/// The default hook leaves the gas as the deposit's charges left it. +#[test] +fn test_the_hook_draws_the_deposit_from_the_frames_pool() { + const POOL: u64 = 1_000; + let mut gas = Gas::new(100_000); + gas.set_bytes_remaining(POOL); + let code = Bytes::from_static(&[0; 32]); + // OSAKA: the deposit is one regular charge, 200 per byte. + let charged = { + let mut charged = gas; + assert!(charged.record_regular_cost(32 * 200)); + charged + }; + let pool = |gas: &Gas| { + ( + gas.bytes_remaining(), + gas.bytes_spent(), + gas.bytes_crossing(), + ) + }; + + let default = return_create_with(&mut context(db(None), SCHEDULES[0]), gas, code.clone()); + assert_eq!(default.result, InstructionResult::Return, "the default"); + assert_eq!( + default.gas, charged, + "the default hook leaves the gas alone" + ); + + for (name, policy, draw, result, figures) in [ + ( + "admitted", + Policy::Admit, + 32, + InstructionResult::Return, + (POOL - 32, 32, false), + ), + ( + "admitted, the draw failed", + Policy::Admit, + POOL + 1, + InstructionResult::Return, + (POOL, 0, true), + ), + ( + "refused", + Policy::Refuse, + 32, + InstructionResult::Revert, + (POOL, 0, false), + ), + ( + "refused, the draw failed", + Policy::Refuse, + POOL + 1, + InstructionResult::Revert, + (POOL, 0, false), + ), + ] { + let mut ctx = admission_context(db(None), SCHEDULES[0], policy); + ctx.draw = draw; + + let returned = return_create_with(&mut ctx, gas, code.clone()); + + assert_eq!(ctx.offered.len(), 1, "{name}"); + assert_eq!(returned.result, result, "{name}"); + assert_eq!(pool(&returned.gas), figures, "{name}"); + let [(before, after)] = ctx.offered_gas[..] else { + panic!("{name}: offered {} times", ctx.offered_gas.len()); + }; + assert_eq!(&before, gas.tracker(), "{name}: gas_before"); + assert_eq!( + &after, + charged.tracker(), + "{name}: gas_after, before the hook drew" + ); + if policy == Policy::Refuse { + assert_eq!(returned.gas, gas, "{name}: put back to gas_before"); + } else { + assert_eq!( + returned.gas.remaining(), + charged.remaining(), + "{name}: the deposit is paid" + ); + } + } +} + /// A hook that fails fatally records the cause and refuses; the transaction returns the cause, /// for a top-level creation and a nested one alike. #[test] diff --git a/crates/inspector/tests/code_deposit_admission.rs b/crates/inspector/tests/code_deposit_admission.rs index b82004f3ff..8d9cf508cb 100644 --- a/crates/inspector/tests/code_deposit_admission.rs +++ b/crates/inspector/tests/code_deposit_admission.rs @@ -7,7 +7,7 @@ use context::{ context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, + cfg::{gas::GasTracker, GasId, GasParams, StateGasSite}, context::CodeDeposit, host::LoadError, journaled_state::AccountInfoLoad, @@ -88,7 +88,11 @@ impl ContextTr for RefusingContext { self.inner.error() } - fn admit_code_deposit(&mut self, _deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + fn admit_code_deposit( + &mut self, + _deposit: &CodeDeposit<'_>, + _gas: &mut GasTracker, + ) -> Result<(), Bytes> { self.offered += 1; Err(Bytes::from_static(REFUSAL)) } From 384bb614c605a9efaf4bdbd4b3393beefa603b2d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 21:54:07 +0800 Subject: [PATCH 017/110] fix(handler): a precompile answer's pool is the share less what its provider drew `make_call_frame` set a precompile answer's pool to the caller's share and kept the net the provider left, so a provider that drew on its answer returned a pool and a net that did not add up to the share: on success the caller absorbed the whole share and merged the draw on top, and on failure the rollback gave back more than the share. The answer now adopts the share as the pool it started with: `GasTracker::adopt_bytes_share(share)`, plumbing beside `forward_bytes` and `absorb_returned_bytes`, sets the pool to the share less the net drawn so far, so the pool and the net add up to the share as a frame's do and a rollback restores the share. `EthPrecompiles` draws nothing, so its answers start with the whole share as before; the derivation costs 10 instructions per precompile answer (callgrind, the fork's release profile; +0.003% of a transaction that calls a precompile). Tests: a provider that draws 40 bytes on its answer, through the handler, where the caller takes the draw over when the call succeeds and gets the whole share back when it fails; and the tracker adopting a share after draws, after a refill below zero and after none. --- .../interface/src/cfg/gas/byte_pool.rs | 38 +++++++ crates/handler/src/frame.rs | 9 +- crates/handler/tests/byte_pool.rs | 104 ++++++++++++++++-- 3 files changed, 139 insertions(+), 12 deletions(-) diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index 6be7e6cd49..52cef5bb2c 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -97,6 +97,17 @@ impl GasTracker { self.bytes_remaining = self.bytes_remaining.saturating_add(remaining); } + /// Takes `share` as the pool this tracker started with: the pool becomes `share` less the net + /// drawn so far, so that the pool and the net add up to `share`, as a frame's do. + /// + /// For a tracker built outside a frame, such as a precompile's answer, which may have drawn + /// before it learns the share its caller forwarded. A rollback then restores `share`. A net + /// above `share` leaves an empty pool. + #[inline] + pub const fn adopt_bytes_share(&mut self, share: u64) { + self.bytes_remaining = share.saturating_add_signed(self.bytes_spent.saturating_neg()); + } + /// The crossing: whether a draw failed that the pool could not pay, since the record was last /// cleared, or a consumer set it with [`set_bytes_crossing`](Self::set_bytes_crossing). /// @@ -322,6 +333,33 @@ mod tests { assert_eq!(parent.bytes_remaining(), 720); } + /// A tracker that adopts a share keeps its net and takes the share less the net as its pool, + /// so a rollback restores the share: after draws, after a refill below zero, and after none. + #[test] + fn test_an_adopted_share_less_the_net_is_the_pool() { + for (name, draws, refills, pool) in [ + ("drew", 40, 0, 860), + ("refilled", 0, 25, 925), + ("nothing", 0, 0, 900), + ] { + let mut answer = GasTracker::new(500, 500, 0); + assert!(answer.record_bytes(draws)); + answer.refill_bytes(refills); + let spent = answer.bytes_spent(); + + answer.adopt_bytes_share(900); + + assert_eq!(answer.bytes_remaining(), pool, "{name}"); + assert_eq!(answer.bytes_spent(), spent, "{name}: the net is kept"); + answer.rollback_state_gas(); + assert_eq!( + answer.bytes_remaining(), + 900, + "{name}: a rollback restores the share" + ); + } + } + /// A forward above the pool and a return above `u64::MAX` saturate rather than wrap. #[test] fn test_forward_and_return_saturate() { diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index a1d4872964..36d3a62ac2 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -219,10 +219,11 @@ impl EthFrame { let gas_limit = inputs.gas_limit; if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { - // The provider built the answer's gas from the inputs' regular gas and reservoir; the - // pool and the allowance it does not know are set here, so the caller's settlement - // gets its share back from the answer as it would from a frame. - result.gas.set_bytes_remaining(bytes_share); + // The provider built the answer's gas from the inputs' regular gas and reservoir. The + // answer takes the caller's share as the pool it started with, less what the provider + // drew on it, and the allowance the input carries, so the caller's settlement gets the + // share back from the answer as it would from a frame. + result.gas.tracker_mut().adopt_bytes_share(bytes_share); result.gas.set_history_allowance(history_allowance); let mut logs = Vec::new(); if result.result.is_ok() { diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index f413cfaf0c..93481bcb36 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -11,7 +11,7 @@ //! consumer's hooks: `DRAW` draws bytes, `DECLARE` has the start hook charge and declare a start //! charge at the next start, and `LOG` charges history after drawing the frame's allowance, as a //! consumer's write hook would. The context's code-deposit admission hook draws deployed code's -//! bytes when a test asks it to. +//! bytes, and the precompile provider draws on the answers it builds, when a test asks them to. use bytecode::opcode::{ CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, RETURN, REVERT, STOP, @@ -30,23 +30,30 @@ use context_interface::{ }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, SStoreResult, - SelfDestructResult, StartCharge, StateLoad, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, FrameInput, GasTracker, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, InterpreterResult, + SStoreResult, SelfDestructResult, StartCharge, StateLoad, }; use primitives::{ - address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, + address, hardfork::SpecId, Address, AddressSet, Bytes, Log, StorageKey, StorageValue, TxKind, + B256, U256, }; use revm_handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, EvmTr, FrameResult, Handler, - ItemOrResult, MainContext, MainnetContext, MainnetEvm, MainnetHandler, + ItemOrResult, MainContext, MainnetContext, MainnetHandler, PrecompileProvider, }; use state::{AccountInfo, Bytecode}; type Db = CacheDB; type DbError = ::Error; type TestContext = DeclaringContext; -type TestEvm = MainnetEvm; +type TestEvm = Evm< + TestContext, + (), + EthInstructions, + DrawingPrecompiles, + EthFrame, +>; type TestError = EVMError; type Mainnet = MainnetHandler>; @@ -384,6 +391,39 @@ impl Host for DeclaringContext { } } +/// [`EthPrecompiles`], whose answers the provider draws on when told to: it starts an answer's +/// pool at the share the input carries and draws `draw` bytes from it, as a provider that appends +/// bytes for a call would. With nothing to draw it is [`EthPrecompiles`]. +struct DrawingPrecompiles { + inner: EthPrecompiles, + draw: u64, +} + +impl PrecompileProvider for DrawingPrecompiles { + type Output = InterpreterResult; + + fn set_spec(&mut self, spec: SpecId) -> bool { + PrecompileProvider::::set_spec(&mut self.inner, spec) + } + + fn run( + &mut self, + context: &mut TestContext, + inputs: &CallInputs, + ) -> Result, String> { + let mut answer = self.inner.run(context, inputs)?; + if let Some(answer) = answer.as_mut().filter(|_| self.draw > 0) { + answer.gas.set_bytes_remaining(inputs.bytes_share); + assert!(answer.gas.record_bytes(self.draw)); + } + Ok(answer) + } + + fn warm_addresses(&self) -> &AddressSet { + self.inner.warm_addresses() + } +} + /// The figures of a frame's input as it started: its share, its start charge and its allowance. type Started = (u64, StartCharge, u64); @@ -570,6 +610,8 @@ struct Run { /// `call_history_allowance` in the schedule. allowance: u64, deposit: Deposit, + /// What the precompile provider draws on each answer. + precompile_draw: u64, } impl Run { @@ -580,9 +622,15 @@ impl Run { parent_nonce: 1, allowance: 0, deposit: Deposit::Untouched, + precompile_draw: 0, } } + const fn precompile_draw(mut self, draw: u64) -> Self { + self.precompile_draw = draw; + self + } + const fn deposit(mut self, deposit: Deposit) -> Self { self.deposit = deposit; self @@ -652,7 +700,11 @@ impl Run { instructions.insert_instruction(DRAW, Instruction::new(draw), 0); instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); instructions.insert_instruction(LOG, Instruction::new(log), 0); - let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(SPEC)); + let precompiles = DrawingPrecompiles { + inner: EthPrecompiles::new(SPEC), + draw: self.precompile_draw, + }; + let mut evm: TestEvm = Evm::new(ctx, instructions, precompiles); evm.ctx.set_tx( TxEnv::builder_for_bench() .kind(TxKind::Call(PARENT)) @@ -968,3 +1020,39 @@ fn test_a_deposit_drawn_at_admission_is_held_against_the_transaction() { assert_eq!(handler.settled, Some(settled), "{name}"); } } + +/// A precompile's answer starts with its caller's share as its pool, less what the provider drew +/// on it, so its pool and its net add up to the share, as a frame's do: the caller takes the +/// provider's draw over when the call succeeds, and gets the whole share back when it fails. +#[test] +fn test_a_precompile_answer_keeps_what_its_provider_drew() { + const PROVIDER_DRAW: u64 = 40; + let mut succeeding = vec![DRAW]; + succeeding.extend(call(ECRECOVER, 0)); + let mut failing = vec![DRAW]; + failing.extend(starved_call(ECRECOVER)); + // PARENT drew 100 and forwards the 900 left; the provider draws 40 of them. + for (name, parent, returned, settled) in [ + ( + "succeeds", + succeeding, + Returned::ended(InstructionResult::Return, 860, 40), + (860, 140, 0), + ), + ( + "fails", + failing, + Returned::ended(InstructionResult::PrecompileOOG, 860, 40), + (900, 100, 0), + ), + ] { + let run = Run::new(ends(parent)).precompile_draw(PROVIDER_DRAW); + + let (result, handler) = run.with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{name}: {result:?}"); + assert_eq!(handler.starts[1].0, 900, "{name}"); + assert_eq!(handler.returned[0], returned, "{name}"); + assert_eq!(handler.settled, Some(settled), "{name}"); + } +} From 5ec9eaf07cb1757fa3fa5d75e210cbc7b4e25b95 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 21:57:17 +0800 Subject: [PATCH 018/110] test: the byte pool at a creating transaction, a depth refusal, a partial share and inspector outcomes Pins behaviour the suites did not reach: - the transaction's frame of a creating transaction gets the whole pool and the start charge declared on its input, refunded when the creation reverts or halts and kept when it deploys (the first-frame test now runs a call's frame and a creation's); - a start the handler refuses for the call depth, a call's and a creation's, gives its caller the whole share and the start charge back; - with `bytes_forward_percent` at 98, every start through the handler forwards 98% of the caller's pool rounded down, and the transaction ends with the figures the whole-pool forward gives; - on the inspected path, an outcome the inspector builds to answer a start settles as built (`CallOutcome::new` carries no start charge and an unlimited pool; one carrying the input's share and charge settles as the frame would), and a success the inspector rewrites into a revert at `call_end` refunds the start charge and rolls the frame's draws back. Checked against mutants: dropping the creating transaction's pool forward and giving the depth refusal a plain `CallOutcome::new` each fail a test. --- crates/handler/tests/byte_pool.rs | 142 +++++++++++++++++++++++-- crates/inspector/tests/byte_pool.rs | 156 ++++++++++++++++++++++++++-- 2 files changed, 279 insertions(+), 19 deletions(-) diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index 93481bcb36..71f3fb8587 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -35,8 +35,8 @@ use interpreter::{ SStoreResult, SelfDestructResult, StartCharge, StateLoad, }; use primitives::{ - address, hardfork::SpecId, Address, AddressSet, Bytes, Log, StorageKey, StorageValue, TxKind, - B256, U256, + address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, AddressSet, Bytes, Log, + StorageKey, StorageValue, TxKind, B256, U256, }; use revm_handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, EvmTr, FrameResult, Handler, @@ -452,6 +452,9 @@ struct PoolHandler { /// Whether the transaction's gas is charged [`DECLARED`] for its frame, declared on the /// frame's input. declare: bool, + /// Whether every frame below the transaction's starts one past the call-stack limit, where a + /// 1,025th nested start would. + too_deep: bool, starts: Vec, returned: Vec, settled: Option, @@ -463,6 +466,7 @@ impl PoolHandler { mainnet: Mainnet::default(), pool, declare: false, + too_deep: false, starts: Vec::new(), returned: Vec::new(), settled: None, @@ -507,7 +511,8 @@ impl Handler for PoolHandler { } /// The default loop, recording each frame's input as it starts and its result as it - /// returns, before its caller settles it. + /// returns, before its caller settles it, and starting the frames below the transaction's + /// past the call-stack limit if told to. fn run_exec_loop( &mut self, evm: &mut TestEvm, @@ -520,8 +525,11 @@ impl Handler for PoolHandler { } loop { let result = match evm.frame_run()? { - ItemOrResult::Item(init) => { + ItemOrResult::Item(mut init) => { self.starts.push(started(&init.frame_input)); + if self.too_deep { + init.depth = CALL_STACK_LIMIT as usize + 1; + } match evm.frame_init(init)? { ItemOrResult::Item(_) => continue, ItemOrResult::Result(result) => result, @@ -602,7 +610,8 @@ fn ends(mut code: Vec) -> Vec { code } -/// A transaction to [`PARENT`], holding `parent`, on the accounts every test knows. +/// A transaction on the accounts every test knows: a call to [`PARENT`], which holds `parent`, or +/// a creation with `parent` as its init code ([`Run::creation`]). struct Run { parent: Vec, parent_balance: u64, @@ -612,6 +621,10 @@ struct Run { deposit: Deposit, /// What the precompile provider draws on each answer. precompile_draw: u64, + /// `bytes_forward_percent` in the schedule, if not the default. + forward_percent: Option, + /// Whether the transaction creates a contract from `parent` instead of calling [`PARENT`]. + creates: bool, } impl Run { @@ -623,9 +636,23 @@ impl Run { allowance: 0, deposit: Deposit::Untouched, precompile_draw: 0, + forward_percent: None, + creates: false, } } + /// A transaction that creates a contract from `initcode`. + const fn creation(initcode: Vec) -> Self { + let mut run = Self::new(initcode); + run.creates = true; + run + } + + const fn forward_percent(mut self, percent: u64) -> Self { + self.forward_percent = Some(percent); + self + } + const fn precompile_draw(mut self, draw: u64) -> Self { self.precompile_draw = draw; self @@ -684,12 +711,17 @@ impl Run { fn evm(&self) -> TestEvm { let allowance = self.allowance; + let forward_percent = self.forward_percent; let inner = Context::mainnet() .with_db(self.db()) .modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); cfg.gas_params .override_gas([(GasId::call_history_allowance(), allowance)]); + if let Some(percent) = forward_percent { + cfg.gas_params + .override_gas([(GasId::bytes_forward_percent(), percent)]); + } }); let ctx = DeclaringContext { inner, @@ -705,9 +737,15 @@ impl Run { draw: self.precompile_draw, }; let mut evm: TestEvm = Evm::new(ctx, instructions, precompiles); + let (kind, data) = if self.creates { + (TxKind::Create, Bytes::from(self.parent.clone())) + } else { + (TxKind::Call(PARENT), Bytes::new()) + }; evm.ctx.set_tx( TxEnv::builder_for_bench() - .kind(TxKind::Call(PARENT)) + .kind(kind) + .data(data) .gas_price(0) .gas_limit(GAS_LIMIT) .build_fill(), @@ -876,20 +914,30 @@ fn test_the_start_charge_is_refunded_when_the_frame_fails() { /// The transaction's frame gets the pool as the consumer left it after the body's charges, and /// the start charge the consumer declared on its input, which is refunded whole when the frame -/// reverts or halts and kept when it succeeds. +/// reverts or halts and kept when it succeeds: a call's frame and a creation's alike. #[test] fn test_the_first_frame_gets_the_pool_and_its_start_charge() { - for (name, parent, fails) in [ + let cases = [ ("stops", vec![DRAW, STOP], false), ("reverts", vec![DRAW, PUSH0, PUSH0, REVERT], true), ("halts", vec![DRAW, INVALID], true), - ] { + ]; + let calls = cases + .clone() + .map(|(name, code, fails)| (name, Run::new(code), fails)); + let creations = cases.map(|(name, code, fails)| (name, Run::creation(code), fails)); + for (name, run, fails) in calls.into_iter().chain(creations) { + let name = format!( + "{} {name}", + if run.creates { "a creation" } else { "a call" } + ); + let name = name.as_str(); let mut handler = PoolHandler::new(Some(POOL)); handler.declare = true; - let (result, handler) = Run::new(parent).with(handler); + let (result, handler) = run.with(handler); - assert_eq!(result.is_success(), name == "stops", "{name}: {result:?}"); + assert_eq!(result.is_success(), !fails, "{name}: {result:?}"); assert_eq!( handler.starts, [(POOL - DECLARED.bytes, DECLARED, 0)], @@ -1056,3 +1104,75 @@ fn test_a_precompile_answer_keeps_what_its_provider_drew() { assert_eq!(handler.settled, Some(settled), "{name}"); } } + +/// A start the handler refuses for the call depth gives its caller the whole share and the start +/// charge back, as any start that fails does, for a call and a creation alike. The handler's loop +/// starts the frame one past the call-stack limit, where a 1,025th nested start would be. +#[test] +fn test_a_start_refused_for_the_depth_gives_the_share_and_the_start_charge_back() { + for (name, start) in [("a call", call(OK, 0)), ("a creation", create(&[STOP]))] { + let mut parent = vec![DRAW, DECLARE]; + parent.extend(start); + let mut handler = PoolHandler::new(Some(POOL)); + handler.too_deep = true; + + let (result, handler) = Run::new(ends(parent)).with(handler); + + assert!(result.is_success(), "{name}: {result:?}"); + let share = POOL - DRAW_BYTES - DECLARED.bytes; + assert_eq!(handler.starts[1], (share, DECLARED, 0), "{name}"); + assert_eq!( + handler.returned[0], + Returned::ended(InstructionResult::CallTooDeep, share, 0), + "{name}" + ); + assert_eq!( + handler.settled, + Some((POOL - DRAW_BYTES, DRAW_BYTES as i64, 0)), + "{name}: the start charge refunded, PARENT's own draw kept" + ); + } +} + +/// With `bytes_forward_percent` at 98, every start forwards 98% of its caller's pool, rounded +/// down, and the caller keeps the rest; what a child hands back adds to what its caller kept, so +/// the transaction ends with the figures the whole-pool forward gives. +#[test] +fn test_a_share_below_the_whole_pool_is_forwarded_and_settled_at_depth() { + let (result, handler) = at_depth() + .forward_percent(98) + .with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{result:?}"); + let share = |pool| (pool, StartCharge::default(), 0); + assert_eq!( + handler.starts, + [ + // The transaction's frame takes the whole pool. + share(POOL), + // PARENT drew 100: 98% of 900, PARENT keeps 18. + share(882), + // OK left 782, PARENT holds 800 again: 98% of 800, PARENT keeps 16. + share(784), + share(784), + share(784), + // NESTER drew 100 of its 784: 98% of 684 is 670.32, NESTER keeps 14. + share(670), + ] + ); + assert_eq!( + handler.returned, + [ + Returned::stopped(782, 100), + Returned::ended(InstructionResult::Revert, 684, 100), + Returned::ended(InstructionResult::InvalidFEOpcode, 684, 100), + // OK inside NESTER. + Returned::stopped(570, 100), + // NESTER: the 14 it kept and the 570 OK left, before its rollback. + Returned::ended(InstructionResult::Revert, 584, 200), + // PARENT: 16 kept and the whole 784 NESTER gave back. + Returned::stopped(800, 200), + ] + ); + assert_eq!(handler.settled, Some((800, 200, 0))); +} diff --git a/crates/inspector/tests/byte_pool.rs b/crates/inspector/tests/byte_pool.rs index 354f908575..9add294130 100644 --- a/crates/inspector/tests/byte_pool.rs +++ b/crates/inspector/tests/byte_pool.rs @@ -8,7 +8,8 @@ //! which stand in for a consumer's hooks, and checks that the two paths end the same way; an //! inspector records each frame's input as it starts and its outcome as it ends, before its caller //! settles it, and the figures are checked on the inspected path (the handler's tests check them -//! on the plain one). +//! on the plain one). Two tests run on the inspected path alone: an outcome the inspector builds +//! or rewrites itself has no counterpart on the plain path. use context::{ context_interface::{ @@ -26,9 +27,9 @@ use handler::{ MainnetContext, }; use interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, SStoreResult, - SelfDestructResult, StartCharge, StateLoad, + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, + GasTracker, Instruction, InstructionContext, InstructionExecResult, InstructionResult, + InterpreterResult, SStoreResult, SelfDestructResult, StartCharge, StateLoad, }; use primitives::{ address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, @@ -58,6 +59,8 @@ const HISTORY_COST: u64 = 100; const ALLOWANCE: u64 = 160; /// The pool nobody set. const UNLIMITED: u64 = u64::MAX; +/// The pool `LIMIT` sets. +const LIMITED: u64 = 1_000; /// The account the transaction calls. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); @@ -79,6 +82,7 @@ const DRAW: u8 = 0x0c; const DECLARE: u8 = 0x0d; const LOG: u8 = 0x0e; const DRAIN: u8 = 0x0f; +const LIMIT: u8 = 0x10; const fn draw(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { if context.interpreter.gas.record_bytes(DRAW_BYTES) { @@ -96,6 +100,12 @@ const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> Instruct } } +/// Sets the frame's pool to [`LIMITED`], as a consumer sets the transaction's. +const fn limit(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { + context.interpreter.gas.set_bytes_remaining(LIMITED); + Ok(()) +} + /// Has the start hook charge and declare [`DECLARED`] at the start that follows. const fn declare(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { context.host.declare_next = true; @@ -337,16 +347,31 @@ impl Ended { } } +/// What the inspector does with a call to [`OK`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Answer { + /// Lets the frame run. + #[default] + Runs, + /// Answers the start with a revert built by `CallOutcome::new`, as a tool builds one. + AsBuilt, + /// Answers the start with a revert that carries the input's share and start charge. + WithShareAndCharge, + /// Lets the frame run, and rewrites its success into a revert at `call_end`. + RewrittenIntoRevert, +} + /// Every frame's input as it started (share, start charge, allowance) and its outcome as it -/// ended. +/// ended; and what the inspector does with a call to [`OK`]. #[derive(Default)] struct Figures { starts: Vec<(u64, StartCharge, u64)>, ends: Vec, + answer: Answer, } impl Figures { - fn end(&mut self, result: InstructionResult, gas: &interpreter::Gas, charged: StartCharge) { + fn end(&mut self, result: InstructionResult, gas: &Gas, charged: StartCharge) { self.ends.push(Ended { result, pool: gas.bytes_remaining(), @@ -366,7 +391,21 @@ impl Inspector for Figures { inputs.charged_start, inputs.history_allowance, )); - None + let answers = matches!(self.answer, Answer::AsBuilt | Answer::WithShareAndCharge); + if !answers || inputs.target_address != OK { + return None; + } + let revert = InterpreterResult::new( + InstructionResult::Revert, + Bytes::new(), + Gas::new(inputs.gas_limit), + ); + let mut outcome = CallOutcome::new(revert, inputs.return_memory_offset.clone()); + if self.answer == Answer::WithShareAndCharge { + outcome.result.gas.set_bytes_remaining(inputs.bytes_share); + outcome.charged_start = inputs.charged_start; + } + Some(outcome) } fn create(&mut self, _context: &mut Ctx, inputs: &mut CreateInputs) -> Option { @@ -375,7 +414,10 @@ impl Inspector for Figures { None } - fn call_end(&mut self, _context: &mut Ctx, _inputs: &CallInputs, outcome: &mut CallOutcome) { + fn call_end(&mut self, _context: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + if self.answer == Answer::RewrittenIntoRevert && inputs.target_address == OK { + outcome.result.result = InstructionResult::Revert; + } self.end( *outcome.instruction_result(), &outcome.result.gas, @@ -485,6 +527,7 @@ impl Run { let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(DRAW, Instruction::new(draw), 0); instructions.insert_instruction(DRAIN, Instruction::new(drain), 0); + instructions.insert_instruction(LIMIT, Instruction::new(limit), 0); instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); instructions.insert_instruction(LOG, Instruction::new(log), 0); Evm::new_with_inspector( @@ -517,6 +560,15 @@ impl Run { assert_eq!(inspected_outcome, transacted, "both paths end the same way"); (transacted, inspected.inspector) } + + /// The transaction with `inspect_tx` alone, the inspector doing `answer` with a call to + /// [`OK`]. Returns the outcome and the figures the inspector saw. + fn inspected(&self, answer: Answer) -> (ResultAndState, Figures) { + let mut evm = self.evm(); + evm.inspector.answer = answer; + let outcome = evm.inspect_tx(Self::tx()).expect("the transaction runs"); + (outcome, evm.inspector) + } } /// Both paths forward the whole pool, less the draws so far, and settle a child's return the @@ -651,3 +703,91 @@ fn test_both_paths_give_a_value_calls_child_the_allowance() { ] ); } + +/// [`PARENT`] limits its pool to [`LIMITED`] and calls [`OK`] with a start charge declared, on +/// the inspected path alone, the inspector doing `answer`. Returns the share the call was given, +/// [`OK`]'s outcome as the inspector left it, and [`PARENT`]'s pool, net and history after the +/// settlement. +fn limited_call_to_ok(answer: Answer) -> (u64, Ended, (u64, i64, i64)) { + let parent = ends([vec![LIMIT, DECLARE], call(OK, 0)].concat()); + let (outcome, figures) = Run::new(parent).inspected(answer); + + assert!( + outcome.result.is_success(), + "{answer:?}: {:?}", + outcome.result + ); + let [ok, parent_end] = &figures.ends[..] else { + panic!("{answer:?}: {} ends", figures.ends.len()); + }; + assert_eq!(figures.starts[1].1, DECLARED, "{answer:?}"); + ( + figures.starts[1].0, + ok.clone(), + (parent_end.pool, parent_end.spent, parent_end.history), + ) +} + +/// An outcome the inspector builds to answer a start settles as built, as revm settles its own +/// upfront state charge on such an outcome. `CallOutcome::new` carries no start charge and an +/// unlimited pool, so a caller whose start the inspector answers with a revert keeps the start +/// charge, and its limited pool, plus the unlimited one absorbed, saturates to `u64::MAX`. An +/// answer that carries the input's share and charge settles as the frame's own revert would: the +/// caller gets the share and the charge back. +#[test] +fn test_an_outcome_the_inspector_builds_settles_as_built() { + let share = LIMITED - DECLARED.bytes; + for (answer, answered, kept) in [ + ( + Answer::AsBuilt, + Ended::with(InstructionResult::Revert, UNLIMITED, 0), + (UNLIMITED, DECLARED.bytes as i64, DECLARED.history as i64), + ), + ( + Answer::WithShareAndCharge, + Ended { + charged_start: DECLARED, + ..Ended::with(InstructionResult::Revert, share, 0) + }, + (LIMITED, 0, 0), + ), + ] { + assert_eq!( + limited_call_to_ok(answer), + (share, answered, kept), + "{answer:?}: the share, the answer as built, the caller after the settlement" + ); + } +} + +/// A frame's outcome carries its input's start charge, so a success the inspector rewrites into a +/// revert at `call_end` refunds the charge and rolls the frame's draws back, as the frame's own +/// revert would; the frame left alone keeps both. +#[test] +fn test_a_success_the_inspector_rewrites_into_a_revert_refunds_the_start_charge() { + let share = LIMITED - DECLARED.bytes; + let drawn = DECLARED.bytes + DRAW_BYTES; + for (answer, result, kept) in [ + ( + Answer::Runs, + InstructionResult::Stop, + (LIMITED - drawn, drawn as i64, DECLARED.history as i64), + ), + ( + Answer::RewrittenIntoRevert, + InstructionResult::Revert, + (LIMITED, 0, 0), + ), + ] { + let ended = Ended { + charged_start: DECLARED, + ..Ended::with(result, share - DRAW_BYTES, DRAW_BYTES as i64) + }; + assert_eq!( + limited_call_to_ok(answer), + (share, ended, kept), + "{answer:?}: the share, the frame's outcome as the inspector left it, the caller after \ + the settlement" + ); + } +} From 731c02d0c0a40e9848f014d6e0161c937e928a22 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 21:59:12 +0800 Subject: [PATCH 019/110] docs: the admission hook's tracker, answers' pools and charges, and the literal consumers in MEGAETH-FORK.md - Code-deposit admission: the hook takes the creating frame's tracker as `gas`; an admitted deposit returns with it as the hook left it, a refusal puts it back to `gas_before`; lending it costs nothing where measured; the signature change is an `api:exception`, with the one override found (mega-evm's `MegaContext`). - The byte pool: a consumer draws deployed code's bytes at admission; `adopt_bytes_share` in the plumbing list; the one sentence on outcomes built outside a frame becomes three cases: a precompile's answer (the share less the provider's draw), an inspector's answer (as built), a consumer's own answer (sets the share). The cost figures are re-measured at this head: a transfer 120 instructions, a precompile call 135. - The start charge: a precompile's answer and a start the handler refuses carry the input's charge; an inspector's answer keeps the caller's charge unless it copies it, as revm keeps its upfront state charge on an outcome a tool builds; an outcome rewritten at `call_end` / `create_end` keeps the frame's charge; a consumer's own answer follows the same rule. - The `api:exception` consumer list names Foundry's and mega-reth's oracle executor's literal constructions: their outcome literals already fail against the fork's base on the earlier EIP-8037 field `charged_state_gas_address`; Foundry's one `CallInputs` literal is new breakage, in a file its outcome literals already break. Also wraps a `record_bytes` doc line that ran past 100 columns. --- MEGAETH-FORK.md | 28 ++++++++++++++----- .../interface/src/cfg/gas/byte_pool.rs | 4 +-- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 301ae77dbb..b56f470333 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -179,22 +179,27 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th ### Code-deposit admission -- **API.** `ContextTr::admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes>`, whose default admits. +- **API.** `ContextTr::admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>, gas: &mut GasTracker) -> Result<(), Bytes>`, whose default admits and leaves `gas` alone. `CodeDeposit` carries `address`, `code`, `gas_before` and `gas_after`; `regular_gas`, `state_gas` and `history_gas` read the deposit's charges off the two trackers. It is `#[non_exhaustive]` and built with `CodeDeposit::new`, so a later field is not a breaking change. - **Contract.** `return_create` calls it once for every creation it deploys, on the plain and the inspected path: after the code passed every check and every deposit charge is recorded, before the journal checkpoint is committed. A creation `return_create` fails itself, out of gas on a deposit charge included, is never offered. Before Homestead a deposit the frame cannot pay does not fail: `return_create` deploys empty code instead, and offers that deposit with empty code and no charge. If the failed charge was a crossing of the frame's withheld gas, `gas_after` carries its crossing record and `gas_before` does not, so an admitted deposit keeps the record and a refusal discards it. - `Err(output)` refuses: the checkpoint is reverted, the frame's gas is put back to `gas_before`, and the creation ends as a `Revert` with `output`, settling as a creation whose init code reverted. + `gas` is the creating frame's tracker, which `gas_after` reads a copy of: the hook may debit and credit it, for instance draw the deployed code's bytes from the frame's pool (see The byte pool), and a charge it makes that fails records as any failed charge does. + `Ok(())` admits, and the frame returns with `gas` as the hook left it. + `Err(output)` refuses: the checkpoint is reverted, the frame's gas is put back to `gas_before`, which undoes whatever the hook did to `gas`, a crossing its failed draw recorded included, and the creation ends as a `Revert` with `output`, settling as a creation whose init code reverted. A hook that fails fatally records the cause in the context error and refuses; the transaction returns the error. The deposit's charges, and with them its state-gas price lookup through `Host::state_gas_price`, are made before it is offered, so that lookup is made whether or not the deposit is admitted; a refusal does not undo what the lookup recorded. - **Reach.** The hook is on the context `return_create` is called with, so a consumer that wraps `EthFrame`, runs `process_next_action` from its own `frame_run`, or customises `Handler` reaches it by implementing `ContextTr` for its context. A context that wraps another and implements `ContextTr` by hand must forward the method, or it gets the admitting default. -- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits. That point is inside `return_create`, between its last charge and the checkpoint commit. +- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits, and holds the deployed code to the creating frame's byte budget there. That point is inside `return_create`, between its last charge and the checkpoint commit, and no other hook is lent the frame's gas between the two. - **Removal.** When upstream has an equivalent admission point, or when mega-evm stops refusing deposits. - **Default.** `return_create` compiles to the same code, on its own and inlined into the handler on the plain and the inspected path. Inlined into a consumer's own function, the admitting default may shift its block layout; where measured, that cost one unconditional branch on one out-of-gas path and changed no success path. + Where measured (callgrind, the fork's release profile), lending `gas` costs nothing: a top-level creation runs the same instruction count as without it, and a nested `CREATE` 0.06 fewer. + The `gas` parameter changed this released hook's signature, an exception to rule 1 (`api:exception`): an override does not compile until it takes the parameter. + mega-evm's `MegaContext::admit_code_deposit` is the one override found; alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth do not override it, and nothing built against upstream revm can, since the hook is the fork's. ### revm 40.0.3's journal semantics @@ -239,7 +244,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th ### The byte pool - **API.** On `GasTracker`, forwarded on `Gas`: `bytes_remaining`, `set_bytes_remaining`, `bytes_spent`, `set_bytes_spent`, `record_bytes`, `refill_bytes`, `bytes_crossing`, `clear_bytes_crossing`, `set_bytes_crossing`. - On `GasTracker` alone, the fork's own plumbing: `add_bytes_spent`, `forward_bytes`, `absorb_returned_bytes`. + On `GasTracker` alone, the fork's own plumbing: `add_bytes_spent`, `forward_bytes`, `absorb_returned_bytes`, `adopt_bytes_share`. `GasId::bytes_forward_percent` and `GasParams::bytes_forward_share(pool)`. `bytes_share` on `CallInputs` (a field) and `CreateInputs` (`bytes_share`, `set_bytes_share`). - **Contract.** The pool is a budget of bytes a frame may append, beside its gas: `bytes_remaining` is what the frame may still draw, `bytes_spent` its net draw, signed as `history_gas_spent` is. @@ -247,6 +252,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th The crossing is a bit: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. No halt touches the pool, so a halted frame's result still reads the pool as the failed draw found it, until its caller settles it. `refill_bytes(n)` gives bytes back and lowers the net, below zero when the draw was a caller's. + A consumer draws deployed code's bytes where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). The transaction's frame gets the whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution. At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `bytes_forward_share` of the caller's pool out of it and puts it on the frame's input as `bytes_share`: the child's pool when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). `bytes_forward_share` is `bytes_forward_percent` per cent of the pool, rounded down; a hundred or more forwards the whole pool. @@ -255,14 +261,16 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th The child's net merges into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. `rollback_state_gas` rolls the pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pool back with it. The first frame's return settles into the transaction's tracker the same way (`last_frame_result`), whose `bytes_spent` is then the transaction's net draw. - An outcome a consumer or an inspector builds itself carries whatever pool its gas was built with, an unlimited one by default, and the settlement absorbs it as it is; a consumer that answers a start itself sets the answer's pool to the share it was given. + A precompile's answer adopts the share as the pool it started with (`adopt_bytes_share`): its pool is the share less what its provider drew on it, so its pool and net add up to the share as a frame's do; a provider that draws on its answer starts the answer's pool at the input's `bytes_share` first, so a draw the share cannot pay fails. + An outcome an inspector builds to answer a start carries whatever pool its gas was built with, an unlimited one with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs it as it is. + A consumer that answers a start itself, without a frame or a provider, sets the answer's pool to the share it was given. The pool is not reported on `ResultGas`. - **Consumer.** mega-evm keeps a per-frame budget of the bytes a transaction appends to the state and the history, which a failed frame gives back and a successful one hands to its caller. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry a figure that moves with a frame's gas. - **Removal.** When upstream carries an equivalent per-frame budget on its gas, or when mega-evm stops limiting bytes per frame. - **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest. `Gas` is 128 bytes (104), `InterpreterResult` 168 (144), `CallOutcome` and `FrameResult` 248 (208), `CreateOutcome` 232 (192), the outcomes with the start charge's two words. - Where measured (callgrind, the fork's release profile, against the base without the pool, the start charge and the allowance), the three figures together cost a transfer 122 instructions (+2.3%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 152 (+1.9%) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. + Where measured (callgrind, the fork's release profile, against the base without the pool, the start charge and the allowance), the three figures together cost a transfer 120 instructions (+2.2%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 151 (+1.9%), a transaction that calls a precompile 135 (+0.04%; 10 of them the answer's adopted share) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. ### The start charge @@ -274,10 +282,16 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. A frame that succeeds keeps the charge. + A precompile's answer and a start the handler refuses before any frame (call depth, balance) carry the input's charge, so they refund as a frame does. + An outcome an inspector builds to answer a start carries no charge unless the inspector copies the input's (`CallOutcome::new` and `CreateOutcome::new` carry none), so the caller keeps the charge, as revm keeps its own upfront state charge on an outcome a tool builds; an outcome the inspector rewrites at `call_end` or `create_end` keeps the frame's charge, so a success rewritten into a failure is refunded. + An answer a consumer builds itself, such as an interceptor's, is refunded by the same rule: it carries the charge the consumer puts on it, and none when built with `new`. - **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. - **Default.** The hook declares nothing, so the fields and the refund are zero. - This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. alloy-evm 0.36, revm-inspectors 0.40 and the op-revm fork construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. + This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. + alloy-evm 0.36, revm-inspectors 0.40 and the op-revm fork construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. + Foundry constructs `CallOutcome` and `CreateOutcome` by literal in its cheatcodes and its inspector stack, and mega-reth's oracle executor constructs a `CallOutcome` by literal; both already fail against the fork's base, whose outcomes carry the earlier EIP-8037 field `charged_state_gas_address` that no upstream release has, so the outcomes' new field breaks no literal that compiled against the fork before. + Foundry also constructs `CallInputs` once by literal in its cheatcodes; the base's `CallInputs` has upstream's fields, so that literal is broken by this entry for the first time, in a file its outcome literals already break. ### The history allowance diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index 52cef5bb2c..1f373b3434 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -56,8 +56,8 @@ impl GasTracker { /// Draws `cost` bytes from the pool. /// /// Returns `false` if the pool cannot pay, leaving it untouched and setting the crossing - /// ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always succeeds. The draw is counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives - /// it back. + /// ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always succeeds. The draw is + /// counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives it back. #[inline] #[must_use = "a draw the pool cannot pay is the consumer's stop"] pub const fn record_bytes(&mut self, cost: u64) -> bool { From 4bb5dd12ae6ad5462fe92050bd00d05d85f865ed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:13:08 +0800 Subject: [PATCH 020/110] feat(handler): the first frame's settlement in one function a chain's handler calls `execution::settle_first_frame` makes every step of mainnet's `Handler::last_frame_result` but the final copy into the frame result: the spend and the settlement of the frame into the transaction-level gas, the EIP-2780 state-gas refund with its error handling, and the start charge refund, each with its halt rule. Mainnet's `last_frame_result` calls it, so a chain that overrides the method (op-revm) calls it too rather than copying the body, and a step the fork adds reaches it. Inlined, so the mainnet handler compiles to the code it had. --- crates/handler/src/execution.rs | 3 + crates/handler/src/execution/first_frame.rs | 100 ++++++++++++++++++++ crates/handler/src/handler.rs | 62 ++---------- 3 files changed, 113 insertions(+), 52 deletions(-) create mode 100644 crates/handler/src/execution/first_frame.rs diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index bd0b10d1c6..df1463c89e 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -12,6 +12,9 @@ use primitives::{Address, TxKind}; use state::Bytecode; use std::boxed::Box; +mod first_frame; +pub use first_frame::settle_first_frame; + /// Creates the first [`FrameInput`] from the transaction and the /// transaction-level `gas`, forwarding all remaining regular gas and the /// reservoir to the frame. diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs new file mode 100644 index 0000000000..f97c0fdcb3 --- /dev/null +++ b/crates/handler/src/execution/first_frame.rs @@ -0,0 +1,100 @@ +//! The settlement of the transaction's frame into the transaction-level gas, which +//! [`Handler::last_frame_result`](crate::Handler::last_frame_result) makes on mainnet and a chain's +//! own handler makes by calling it. + +use crate::{frame::handle_reservoir_remaining_gas, FrameResult}; +use context::result::FromStringError; +use context_interface::{context::take_error, ContextTr, Database}; +use interpreter::GasTracker; +use std::string::ToString; + +/// Settles the transaction's frame, the first frame, into the transaction-level `gas`, every step +/// of [`Handler::last_frame_result`](crate::Handler::last_frame_result) but the last: the copy of +/// `gas` into `frame_result`, which is the caller's. +/// +/// The steps, each with the halt rule it takes: +/// - `gas` spends all its regular gas, which was forwarded to the frame, and the frame settles +/// into it as a child settles into its caller ([`handle_reservoir_remaining_gas`]): a failing +/// frame rolls back its state gas, history gas and byte draws, a halt consumes its regular gas, +/// and what the frame left returns to `gas`; +/// - the EIP-2780 refundable first-frame charge is refunded when no account leaf was created, +/// priced through [`Host::state_gas_charge`](context_interface::Host::state_gas_charge) as it +/// was charged; after a halt the regular gas the refund credited is consumed; +/// - the start charge a consumer declared on the first frame's input +/// ([`FrameResult::refundable_start_charge`]) is refunded whole when the frame failed; after a +/// halt the regular gas the refund credited is consumed. +/// +/// A chain whose handler overrides `last_frame_result` calls this rather than copying the mainnet +/// body, so a step the fork adds here reaches its handler too. It applies its own rules to `gas` +/// after this returns and then copies `gas` into the frame's result, as op-revm's handler does +/// with its pre-Regolith deposit rule. +/// +/// Inlined, so `last_frame_result` compiles to the code it had while these steps were its body. +/// +/// # Errors +/// +/// A failure the context recorded before the EIP-2780 refund is returned first, so a failing +/// refund lookup cannot overwrite it. A failed lookup returns the cause the context recorded, or +/// an error saying the lookup failed. +#[inline(always)] +pub fn settle_first_frame( + context: &mut CTX, + frame_result: &mut FrameResult, + gas: &mut GasTracker, +) -> Result<(), ERROR> +where + CTX: ContextTr, + ERROR: From<::Error> + FromStringError, +{ + let instruction_result = frame_result.instruction_result(); + + // All regular gas was forwarded to the first frame: consume it on the + // transaction-level gas; the settle below returns the frame's unused + // part. + gas.spend_all(); + + // Settle the frame into the transaction-level gas like a parent frame. + handle_reservoir_remaining_gas( + instruction_result, + gas, + frame_result.gas_mut().tracker_mut(), + ); + + // Refund the EIP-2780 refundable first-frame charge when no account + // leaf was created, exactly like `EthFrame::return_result` refunds + // the upfront CALL/CREATE state charges of inner frames. + if let Some(charge) = frame_result.refundable_state_gas_charge() { + // A failure the frame already recorded (a failed code deposit lookup, say) is + // returned first, as `EthFrame::return_result` does for inner frames, so a failing + // refund lookup cannot overwrite it. + take_error::(context.error())?; + // Priced through the same hook the charge went through. A failed lookup surfaces as + // an external error: the hook recorded the cause. + let Some(charge) = context.state_gas_charge(charge) else { + take_error::(context.error())?; + return Err(ERROR::from_string( + "state gas price lookup failed".to_string(), + )); + }; + gas.refill_reservoir(charge); + // Unlike an inner frame's caller, the transaction ends here: an + // exceptional halt consumes all regular gas, including the + // spilled portion the refill just credited back to `remaining`. + if instruction_result.is_halt() { + gas.spend_all(); + } + } + + // Refund the start charge a consumer put on the first frame's input for what it charged + // the transaction's gas, whole, on the same condition and with the same halt rule, + // exactly like `EthFrame::return_result` refunds the start charges of inner frames. + if let Some(charge) = frame_result.refundable_start_charge() { + gas.refill_history(charge.history); + gas.refill_bytes(charge.bytes); + if instruction_result.is_halt() { + gas.spend_all(); + } + } + + Ok(()) +} diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index d0edfe49a4..28bf7ba755 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -1,7 +1,6 @@ use crate::{ evm::FrameTr, execution, - frame::handle_reservoir_remaining_gas, post_execution::{self, build_result_gas}, pre_execution::{self, apply_eip7702_auth_list, PreExecutionOutput}, validation, EvmTr, FrameResult, ItemOrResult, @@ -15,11 +14,10 @@ use context_interface::{ context::{take_error, ContextError}, journaled_state::JournalCheckpoint, result::{HaltReasonTr, InvalidHeader, InvalidTransaction, ResultGas}, - Cfg, ContextTr, Database, Host, JournalTr, Transaction, + Cfg, ContextTr, Database, JournalTr, Transaction, }; use interpreter::{interpreter_action::FrameInit, GasTracker, InitialAndFloorGas, SharedMemory}; use primitives::{TxKind, U256}; -use std::string::ToString; /// Trait for errors that can occur during EVM execution. /// @@ -502,6 +500,12 @@ pub trait Handler { /// /// The settled transaction-level gas is written back to the frame result, /// which carries it into the post-execution phase. + /// + /// The settlement is [`execution::settle_first_frame`], which also refunds + /// the first frame's start charge. An override calls it rather than copying + /// this body, and copies the gas into the frame result itself. + /// + /// [`handle_reservoir_remaining_gas`]: crate::handle_reservoir_remaining_gas #[inline] fn last_frame_result( &mut self, @@ -509,55 +513,9 @@ pub trait Handler { frame_result: &mut <::Frame as FrameTr>::FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - let instruction_result = frame_result.instruction_result(); - - // All regular gas was forwarded to the first frame: consume it on the - // transaction-level gas; the settle below returns the frame's unused - // part. - parent_gas.spend_all(); - - // Settle the frame into the transaction-level gas like a parent frame. - handle_reservoir_remaining_gas( - instruction_result, - parent_gas, - frame_result.gas_mut().tracker_mut(), - ); - - // Refund the EIP-2780 refundable first-frame charge when no account - // leaf was created, exactly like `EthFrame::return_result` refunds - // the upfront CALL/CREATE state charges of inner frames. - if let Some(charge) = frame_result.refundable_state_gas_charge() { - // A failure the frame already recorded (a failed code deposit lookup, say) is - // returned first, as `EthFrame::return_result` does for inner frames, so a failing - // refund lookup cannot overwrite it. - take_error::(evm.ctx().error())?; - // Priced through the same hook the charge went through. A failed lookup surfaces as - // an external error: the hook recorded the cause. - let Some(charge) = evm.ctx().state_gas_charge(charge) else { - take_error::(evm.ctx().error())?; - return Err(Self::Error::from_string( - "state gas price lookup failed".to_string(), - )); - }; - parent_gas.refill_reservoir(charge); - // Unlike an inner frame's caller, the transaction ends here: an - // exceptional halt consumes all regular gas, including the - // spilled portion the refill just credited back to `remaining`. - if instruction_result.is_halt() { - parent_gas.spend_all(); - } - } - - // Refund the start charge a consumer put on the first frame's input for what it charged - // the transaction's gas, whole, on the same condition and with the same halt rule, - // exactly like `EthFrame::return_result` refunds the start charges of inner frames. - if let Some(charge) = frame_result.refundable_start_charge() { - parent_gas.refill_history(charge.history); - parent_gas.refill_bytes(charge.bytes); - if instruction_result.is_halt() { - parent_gas.spend_all(); - } - } + // Settle the frame into the transaction-level gas like a parent frame, and refund what + // its failure gives back. + execution::settle_first_frame::<_, Self::Error>(evm.ctx(), frame_result, parent_gas)?; // The frame result carries the transaction-level gas onward to the // post-execution phase. From 23aad903188467a6750afe83a928bb2003c6fd10 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:15:29 +0800 Subject: [PATCH 021/110] fix(gas): bound the byte net to the signed range, asserted in debug builds The byte pool's net is an `i64` while draws and refills take `u64` amounts, as the gas nets are, but only the gas amounts had a documented bound. Document the same bound for bytes (every draw and refill, and the net with its children's merged in, within `i64`) and assert it with `debug_assert!` where the net moves: `record_bytes`, `refill_bytes` and `add_bytes_spent`. Release builds are unchanged. A test pins the boundary: a draw, a refill and a merged net of `i64::MAX` each roll back exactly, and a draw one byte past it panics in a debug build. --- crates/context/interface/src/cfg/gas.rs | 4 ++ .../interface/src/cfg/gas/byte_pool.rs | 64 +++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index ef38c4ca2b..00c5e820fa 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -67,6 +67,10 @@ pub use withheld::WithheldCrossing; /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). /// +/// The byte pool's net ([`bytes_spent`](Self::bytes_spent)) is an `i64` too, and assumes the same +/// bound on byte amounts: every draw and refill, and the net with its children's merged in, within +/// `i64`. A debug build asserts it where the net moves. +/// /// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and /// the byte pool's crossing, which share a word in memory, are encoded as an optional number and /// a `bool` in their own places. diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index 1f373b3434..2b949c571f 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -9,6 +9,15 @@ //! succeeds hands its net to its caller, so a caller's rollback undoes its children's draws too. //! The pool starts unlimited (`u64::MAX`), and nothing in this workspace draws it, so a consumer //! that sets no pool sees nothing of it. +//! +//! The net is an `i64`, as the gas nets are, while draws and refills take `u64` amounts. As the +//! tracker does for gas amounts, it assumes that every draw and refill is at most `i64::MAX` +//! bytes, and that the net, with the nets of the children merged into it, stays within `i64`; +//! the pool itself may be anything up to the unlimited `u64::MAX`. A release build does not check +//! it: past it the net saturates, and a rollback no longer restores the pool exactly. A debug +//! build asserts it wherever the net moves ([`record_bytes`](GasTracker::record_bytes), +//! [`refill_bytes`](GasTracker::refill_bytes), [`add_bytes_spent`](GasTracker::add_bytes_spent)). +//! Reaching it takes a transaction that appends about 9.2 × 10^18 bytes. use super::{saturating_signed, GasTracker}; @@ -35,6 +44,8 @@ impl GasTracker { /// /// Negative while the frame has refilled more than it drew, as /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. + /// It is exact while it stays within `i64` and no single draw or refill exceeds `i64::MAX` + /// bytes, which a debug build asserts. #[inline] pub const fn bytes_spent(&self) -> i64 { self.bytes_spent @@ -50,6 +61,10 @@ impl GasTracker { /// caller, so a later rollback of the caller undoes the child's draws too. #[inline] pub const fn add_bytes_spent(&mut self, delta: i64) { + debug_assert!( + self.bytes_spent.checked_add(delta).is_some(), + "the byte net leaves the signed range" + ); self.bytes_spent = self.bytes_spent.saturating_add(delta); } @@ -62,6 +77,10 @@ impl GasTracker { #[must_use = "a draw the pool cannot pay is the consumer's stop"] pub const fn record_bytes(&mut self, cost: u64) -> bool { if let Some(left) = self.bytes_remaining.checked_sub(cost) { + debug_assert!( + cost <= i64::MAX as u64 && self.bytes_spent.checked_add(cost as i64).is_some(), + "the byte net leaves the signed range" + ); self.bytes_remaining = left; self.bytes_spent = self.bytes_spent.saturating_add(saturating_signed(cost)); return true; @@ -76,6 +95,10 @@ impl GasTracker { /// which the merge on return reconciles, as [`refill_history`](Self::refill_history) does. #[inline] pub const fn refill_bytes(&mut self, amount: u64) { + debug_assert!( + amount <= i64::MAX as u64 && self.bytes_spent.checked_sub(amount as i64).is_some(), + "the byte net leaves the signed range" + ); self.bytes_remaining = self.bytes_remaining.saturating_add(amount); self.bytes_spent = self.bytes_spent.saturating_sub(saturating_signed(amount)); } @@ -372,6 +395,47 @@ mod tests { assert_eq!(unlimited.bytes_remaining(), u64::MAX); } + /// The net is exact up to `i64::MAX` bytes: a draw of it from the unlimited pool, a refill of + /// it, and a child's net of it merged into its caller each roll back to the pool they started + /// from. + #[test] + fn test_the_net_is_exact_up_to_the_signed_maximum() { + const MAX: u64 = i64::MAX as u64; + + let mut drawn = GasTracker::new(1_000, 1_000, 0); + assert!(drawn.record_bytes(MAX)); + assert_eq!(drawn.bytes_spent(), i64::MAX); + drawn.rollback_state_gas(); + assert_eq!(drawn.bytes_remaining(), u64::MAX); + + let mut refilled = GasTracker::new(1_000, 1_000, 0); + refilled.set_bytes_remaining(0); + refilled.refill_bytes(MAX); + assert_eq!(refilled.bytes_spent(), -i64::MAX); + refilled.rollback_state_gas(); + assert_eq!(refilled.bytes_remaining(), 0); + + let mut caller = GasTracker::new(1_000, 1_000, 0); + caller.forward_bytes(u64::MAX); + let mut child = GasTracker::new(500, 500, 0); + assert!(child.record_bytes(MAX)); + caller.add_bytes_spent(child.bytes_spent()); + caller.absorb_returned_bytes(child.bytes_remaining()); + assert_eq!(caller.bytes_spent(), i64::MAX); + caller.rollback_state_gas(); + assert_eq!(caller.bytes_remaining(), u64::MAX); + } + + /// One byte past it the net would saturate, and a rollback would leave the unlimited pool a + /// byte short: a debug build refuses the draw. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "the byte net leaves the signed range")] + fn test_a_draw_past_the_signed_maximum_panics_in_a_debug_build() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + let _ = tracker.record_bytes(i64::MAX as u64 + 1); + } + /// With the default pool, forwarding the whole pool and settling a child's return brings the /// caller back to the pool less what the child drew and kept: a failed child's draws come /// back whole. From c3df12ca83ed8deca06196b521f24a5d63eaeac0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:16:17 +0800 Subject: [PATCH 022/110] test: a precompile answer to a value call carries the history allowance --- crates/handler/tests/byte_pool.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/byte_pool.rs index 71f3fb8587..30028355ef 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/byte_pool.rs @@ -1105,6 +1105,32 @@ fn test_a_precompile_answer_keeps_what_its_provider_drew() { } } +/// A precompile's answer to a value call carries the history allowance the call instruction gave +/// the start, as a frame does, and an answer to a call without value carries none. +#[test] +fn test_a_precompile_answer_to_a_value_call_carries_the_allowance() { + let mut parent = call(ECRECOVER, 1); + parent.extend(call(ECRECOVER, 0)); + let run = Run::new(ends(parent)).allowance(ALLOWANCE); + + let (result, handler) = run.with(PoolHandler::new(None)); + + assert!(result.is_success(), "{result:?}"); + let allowances: Vec = handler.starts.iter().map(|start| start.2).collect(); + assert_eq!(allowances, [0, ALLOWANCE, 0]); + let answered = Returned::ended(InstructionResult::Return, u64::MAX, 0); + assert_eq!( + handler.returned[..2], + [ + Returned { + allowance: ALLOWANCE, + ..answered.clone() + }, + answered, + ] + ); +} + /// A start the handler refuses for the call depth gives its caller the whole share and the start /// charge back, as any start that fails does, for a call and a creation alike. The handler's loop /// starts the frame one past the call-stack limit, where a 1,025th nested start would be. From 89da5cb9741a05c5c893b02a94f572de0695c14a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:19:03 +0800 Subject: [PATCH 023/110] docs: older encodings decode with the new fields' defaults only in formats that carry field names A payload encoded before a field existed decodes with the field's `serde(default)` in a format that carries field names, such as JSON. A format that encodes a struct by position, such as bincode, reads the old fields in their places and then looks for the new ones, so it cannot read such a payload, as with upstream's own field additions. Every doc comment that said older encodings decode now says in which formats, on the byte pool's fields and on the fork's earlier ones (history gas, the withheld part, the failed-charge record, the charged state-gas address). `GasTracker`, the encoding mirror and the serde test modules state the positional limit, the mirror's test no longer says a positional format reads the encoding as before, and the JSON-only tests say JSON in their names. --- crates/context/interface/src/cfg/gas.rs | 28 ++++++++++++++----- .../interface/src/cfg/gas/byte_pool.rs | 6 ++-- .../context/interface/src/cfg/gas/encoding.rs | 17 ++++++++--- .../interface/src/cfg/gas/failed_charge.rs | 6 ++-- .../src/cfg/gas/history_allowance.rs | 4 +-- .../context/interface/src/cfg/gas/withheld.rs | 4 +-- .../src/interpreter_action/call_inputs.rs | 12 +++++--- .../src/interpreter_action/call_outcome.rs | 6 ++-- .../src/interpreter_action/create_inputs.rs | 12 +++++--- .../src/interpreter_action/create_outcome.rs | 6 ++-- crates/interpreter/tests/byte_pool_serde.rs | 16 ++++++----- .../tests/charged_state_gas_address_serde.rs | 13 +++++---- crates/interpreter/tests/history_gas_serde.rs | 11 +++++--- 13 files changed, 92 insertions(+), 49 deletions(-) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 00c5e820fa..e7fa2c39bd 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -74,6 +74,13 @@ pub use withheld::WithheldCrossing; /// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and /// the byte pool's crossing, which share a word in memory, are encoded as an optional number and /// a `bool` in their own places. +/// +/// A field the fork added decodes with its default from an encoding made before it existed only +/// in a format that carries field names, such as JSON, as each field says. A format that encodes +/// a struct by position, such as bincode, cannot read an encoding made before a field was added, +/// as with upstream's own field additions: it reads the old fields in their places and then +/// looks for the new ones, so a tracker persisted in such a format must not cross an upgrade of +/// this crate that adds a field. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr( feature = "serde", @@ -128,7 +135,8 @@ pub struct GasTracker { /// `code_deposit_history_gas` a price, so a chain that does not price history bytes behaves /// exactly as it did before this field existed. /// - /// Encodings made before this field existed decode it as zero. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. history_gas_spent: i64, /// Refunded gas. Used to refund the gas to the caller at the end of execution. refunded: i64, @@ -139,7 +147,8 @@ pub struct GasTracker { /// but never by a regular charge. Zero unless a consumer withholds gas; while it is zero, every /// method behaves as it did before this field existed. /// - /// Encodings made before this field existed decode it as zero. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. withheld: u64, /// The record of the last failed regular charge the withheld part would have paid /// ([`withheld_crossing`](Self::withheld_crossing)): the regular gas left before that @@ -157,7 +166,8 @@ pub struct GasTracker { /// failed ([`failed_charge_remaining`](Self::failed_charge_remaining)), if /// `failed_charge_recorded` is set, and zero otherwise. /// - /// Encodings made before this field existed decode it as `None`. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as `None`. failed_charge_remaining: u64, /// Whether `failed_charge_remaining` holds a record. A flag apart from the record rather than /// an `Option`, whose tag would take a word of its own, so it shares a word with @@ -166,24 +176,28 @@ pub struct GasTracker { /// The byte pool ([`bytes_remaining`](Self::bytes_remaining)): what this frame may still /// draw. Unlimited unless a consumer sets a pool; nothing in this workspace draws it. /// - /// Encodings made before this field existed decode it as unlimited. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as unlimited. bytes_remaining: u64, /// The frame's net draw of the pool ([`bytes_spent`](Self::bytes_spent)), signed as /// `history_gas_spent` is, so a rollback can give it back and a merge can hand it on. /// - /// Encodings made before this field existed decode it as zero. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. bytes_spent: i64, /// Whether a draw failed that the pool could not pay /// ([`bytes_crossing`](Self::bytes_crossing)). A bit, in the word `failed_charge_recorded` /// takes. /// - /// Encodings made before this field existed decode it as `false`. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as `false`. bytes_crossing: bool, /// History gas this frame may spend before it charges its budget /// ([`history_allowance`](Self::history_allowance)). Zero unless the schedule gives a value /// call's child one. /// - /// Encodings made before this field existed decode it as zero. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. history_allowance: u64, } diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index 2b949c571f..c1f259edad 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -467,11 +467,11 @@ mod tests { } } - /// Encodings made before the pool existed decode with an unlimited pool, nothing drawn and no - /// record; the pool's own encoding round-trips. + /// JSON encodings made before the pool existed decode with an unlimited pool, nothing drawn and + /// no record; the pool's own encoding round-trips. #[cfg(feature = "serde")] #[test] - fn test_serde_round_trip_and_older_payloads() { + fn test_serde_round_trip_and_older_json_payloads() { let mut tracker = pool_1000(); assert!(tracker.record_bytes(300)); assert!(!tracker.record_bytes(800)); diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index a187e8c6ec..a935d52bf8 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -4,11 +4,17 @@ //! byte pool's crossing. Encoded, the tracker keeps the fields, names and order the derived //! encoding had: the failed-charge record is an optional number in its place, and the crossing a //! `bool` in its own. +//! +//! A format that carries field names, such as JSON, decodes an encoding made before a field +//! existed with the field's default. A format that encodes by position, such as bincode, does not: +//! the fields that predate the pool keep their places, but an encoding made before the pool's +//! fields were added lacks them and cannot be read (see [`GasTracker`]). use super::{GasTracker, WithheldCrossing}; /// A [`GasTracker`] as it is encoded: its fields in their order, with the defaults an encoding -/// made before a field existed decodes to. Each field of the tracker documents its own. +/// made before a field existed decodes to in a format that carries field names. Each field of the +/// tracker documents its own. #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename = "GasTracker")] pub(super) struct Encoded { @@ -36,7 +42,8 @@ pub(super) struct Encoded { history_allowance: u64, } -/// The pool a tracker starts with, and an encoding that predates the pool decodes to. +/// The pool a tracker starts with, and the pool an encoding that predates it decodes to in a +/// format that carries field names. const fn unlimited_bytes() -> u64 { u64::MAX } @@ -107,8 +114,10 @@ mod tests { } /// The encoding has the fields, the names and the order it had before the failed-charge - /// record and the crossing shared a word, so a format that encodes by position reads it as - /// before; the failed-charge record is an optional number, and the crossing a `bool`. + /// record and the crossing shared a word, so a format that encodes by position finds every + /// field in the place it had then; the failed-charge record is an optional number, and the + /// crossing a `bool`. Such a format still cannot read an encoding made before the pool's + /// fields were added, which lacks them. #[test] fn test_the_encoding_keeps_its_fields_and_their_order() { assert_eq!( diff --git a/crates/context/interface/src/cfg/gas/failed_charge.rs b/crates/context/interface/src/cfg/gas/failed_charge.rs index 2c49159cf8..5c64f846e6 100644 --- a/crates/context/interface/src/cfg/gas/failed_charge.rs +++ b/crates/context/interface/src/cfg/gas/failed_charge.rs @@ -363,11 +363,11 @@ mod tests { assert_eq!(tracker.failed_charge_remaining(), None); } - /// The record round-trips, a zero included, and encodings made before it existed decode with - /// none. + /// The record round-trips, a zero included, and JSON encodings made before it existed decode + /// with none. #[cfg(feature = "serde")] #[test] - fn test_serde_round_trip_and_older_payloads() { + fn test_serde_round_trip_and_older_json_payloads() { for regular in [0, 400] { let mut tracker = GasTracker::new(1_000, regular, 0); fail(&mut tracker, regular + 1, false); diff --git a/crates/context/interface/src/cfg/gas/history_allowance.rs b/crates/context/interface/src/cfg/gas/history_allowance.rs index e9ba102516..9b42c3ee3c 100644 --- a/crates/context/interface/src/cfg/gas/history_allowance.rs +++ b/crates/context/interface/src/cfg/gas/history_allowance.rs @@ -79,10 +79,10 @@ mod tests { assert_eq!(tracker.history_gas_spent(), 0); } - /// Encodings made before the allowance existed decode with none. + /// JSON encodings made before the allowance existed decode with none. #[cfg(feature = "serde")] #[test] - fn test_serde_round_trip_and_older_payloads() { + fn test_serde_round_trip_and_older_json_payloads() { let mut tracker = GasTracker::new(1_000, 1_000, 0); tracker.set_history_allowance(160); let encoded = serde_json::to_value(tracker).unwrap(); diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 824d4e91ef..57756fa4e8 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -646,10 +646,10 @@ mod tests { assert_eq!(parts(&tracker), (650, 250, 900)); } - /// Encodings made before the withheld part existed decode with nothing withheld. + /// JSON encodings made before the withheld part existed decode with nothing withheld. #[cfg(feature = "serde")] #[test] - fn test_serde_round_trip_and_older_payloads() { + fn test_serde_round_trip_and_older_json_payloads() { let mut tracker = withheld_600(); assert!(!tracker.record_regular_cost(401)); let encoded = serde_json::to_value(tracker).unwrap(); diff --git a/crates/interpreter/src/interpreter_action/call_inputs.rs b/crates/interpreter/src/interpreter_action/call_inputs.rs index d46a9b536a..3a3980765f 100644 --- a/crates/interpreter/src/interpreter_action/call_inputs.rs +++ b/crates/interpreter/src/interpreter_action/call_inputs.rs @@ -178,26 +178,30 @@ pub struct CallInputs { /// back: history gas and bytes of the pool, refunded to the caller by `return_result` when /// the call does not succeed, as `charged_new_account_state_gas` is. /// - /// Encodings made before this field existed decode it as no charge. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, /// The share of the caller's byte pool the call receives: its pool when it starts. Taken out /// of the caller's pool by the call instruction, by the schedule's `bytes_forward_percent`, /// and given back with what the call left of it when it returns. /// - /// Encodings made before this field existed decode it as unlimited. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as unlimited. #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] pub bytes_share: u64, /// History gas the call may spend before it charges its budget: the schedule's /// `call_history_allowance` for a call that transfers value, set where the call instruction /// adds the call stipend, and zero otherwise. /// - /// Encodings made before this field existed decode it as zero. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. #[cfg_attr(feature = "serde", serde(default))] pub history_allowance: u64, } -/// The share an encoding that predates the byte pool decodes to. +/// The share an encoding that predates the byte pool decodes to in a format that carries field +/// names. #[cfg(feature = "serde")] const fn unlimited_bytes() -> u64 { u64::MAX diff --git a/crates/interpreter/src/interpreter_action/call_outcome.rs b/crates/interpreter/src/interpreter_action/call_outcome.rs index 2edaf67a63..304a58a8e7 100644 --- a/crates/interpreter/src/interpreter_action/call_outcome.rs +++ b/crates/interpreter/src/interpreter_action/call_outcome.rs @@ -36,14 +36,16 @@ pub struct CallOutcome { /// was taken even when the price varies per account. Meaningless while /// `charged_new_account_state_gas` is `false`. /// - /// Encodings made before this field existed decode it as [`Address::ZERO`]. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, /// Copied from `CallInputs::charged_start`: what the frame-start hook charged the caller for /// this call and the call's failure gives back, so the parent can refund it when the call /// does not succeed. /// - /// Encodings made before this field existed decode it as no charge. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, } diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index 507309ee8a..675ef36c32 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -26,21 +26,24 @@ pub struct CreateInputs { /// EIP-8037: the account `charged_create_state_gas` was priced for, so the refund re-prices /// the same address. Meaningless while `charged_create_state_gas` is `false`. /// - /// Encodings made before this field existed decode it as [`Address::ZERO`]. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] charged_state_gas_address: Address, /// What the frame-start hook charged the caller for this creation and the creation's failure /// gives back: history gas and bytes of the pool, refunded to the caller by `return_result` /// when the creation fails, as `charged_create_state_gas` is. /// - /// Encodings made before this field existed decode it as no charge. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] charged_start: StartCharge, /// The share of the caller's byte pool the creation receives: its pool when it starts. Taken /// out of the caller's pool by the creation instruction, by the schedule's /// `bytes_forward_percent`, and given back with what the creation left of it when it returns. /// - /// Encodings made before this field existed decode it as unlimited. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as unlimited. #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] bytes_share: u64, /// Cached created address. This is computed lazily and cached to avoid @@ -54,7 +57,8 @@ pub struct CreateInputs { cached_init_code_hash: OnceCell, } -/// The share an encoding that predates the byte pool decodes to. +/// The share an encoding that predates the byte pool decodes to in a format that carries field +/// names. #[cfg(feature = "serde")] const fn unlimited_bytes() -> u64 { u64::MAX diff --git a/crates/interpreter/src/interpreter_action/create_outcome.rs b/crates/interpreter/src/interpreter_action/create_outcome.rs index ffc9180f49..ee71dd688a 100644 --- a/crates/interpreter/src/interpreter_action/create_outcome.rs +++ b/crates/interpreter/src/interpreter_action/create_outcome.rs @@ -23,14 +23,16 @@ pub struct CreateOutcome { /// was taken even when the price varies per account. Meaningless while /// `charged_create_state_gas` is `false`. /// - /// Encodings made before this field existed decode it as [`Address::ZERO`]. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, /// Copied from `CreateInputs::charged_start`: what the frame-start hook charged the caller /// for this creation and the creation's failure gives back, so the parent can refund it when /// the creation fails. /// - /// Encodings made before this field existed decode it as no charge. + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, } diff --git a/crates/interpreter/tests/byte_pool_serde.rs b/crates/interpreter/tests/byte_pool_serde.rs index 4d2bdb6620..a31b0c079b 100644 --- a/crates/interpreter/tests/byte_pool_serde.rs +++ b/crates/interpreter/tests/byte_pool_serde.rs @@ -1,9 +1,11 @@ //! Serde encoding of the byte-pool fields on the frame inputs and outcomes: the child's share, //! the start charge and a call's history allowance. //! -//! New encodings carry the fields. Encodings made before they existed lack them and still decode: -//! to an unlimited share, no start charge and no allowance, which is what a frame of a consumer -//! that uses none of them carries. +//! New encodings carry the fields. In a format that carries field names, such as the JSON these +//! tests use, encodings made before they existed lack them and still decode: to an unlimited +//! share, no start charge and no allowance, which is what a frame of a consumer that uses none of +//! them carries. A format that encodes a struct by position, such as bincode, cannot read an +//! encoding made before they existed, as with upstream's own field additions. #![cfg(feature = "serde")] use core::fmt::Debug; @@ -51,7 +53,7 @@ const fn interpreter_result() -> InterpreterResult { } #[test] -fn test_call_inputs_decode_with_and_without_the_pool_fields() { +fn test_call_inputs_decode_from_json_with_and_without_the_pool_fields() { let inputs = |share, charge, allowance| CallInputs { input: CallInput::Bytes(Bytes::from_static(b"in")), return_memory_offset: 0..8, @@ -78,7 +80,7 @@ fn test_call_inputs_decode_with_and_without_the_pool_fields() { } #[test] -fn test_create_inputs_decode_with_and_without_the_pool_fields() { +fn test_create_inputs_decode_from_json_with_and_without_the_pool_fields() { let inputs = |share, charge| { let mut inputs = CreateInputs::new( address!("0x00000000000000000000000000000000000c0de0"), @@ -102,7 +104,7 @@ fn test_create_inputs_decode_with_and_without_the_pool_fields() { } #[test] -fn test_call_outcome_decodes_with_and_without_the_start_charge() { +fn test_call_outcome_decodes_from_json_with_and_without_the_start_charge() { let outcome = |charge| { let mut outcome = CallOutcome::new(interpreter_result(), 0..8); outcome.charged_start = charge; @@ -117,7 +119,7 @@ fn test_call_outcome_decodes_with_and_without_the_start_charge() { } #[test] -fn test_create_outcome_decodes_with_and_without_the_start_charge() { +fn test_create_outcome_decodes_from_json_with_and_without_the_start_charge() { let outcome = |charge| { let mut outcome = CreateOutcome::new(interpreter_result(), None); outcome.charged_start = charge; diff --git a/crates/interpreter/tests/charged_state_gas_address_serde.rs b/crates/interpreter/tests/charged_state_gas_address_serde.rs index fc098fd247..0d3f88c14e 100644 --- a/crates/interpreter/tests/charged_state_gas_address_serde.rs +++ b/crates/interpreter/tests/charged_state_gas_address_serde.rs @@ -1,7 +1,10 @@ //! Serde encoding of `charged_state_gas_address` on the frame inputs and outcomes. //! -//! New encodings carry the field. Encodings made before it existed lack it and still decode, to -//! [`Address::ZERO`], which is what a frame without a charge carries. +//! New encodings carry the field. In a format that carries field names, such as the JSON these +//! tests use, encodings made before it existed lack it and still decode, to [`Address::ZERO`], +//! which is what a frame without a charge carries. A format that encodes a struct by position, +//! such as bincode, cannot read an encoding made before it existed, as with upstream's own field +//! additions. #![cfg(feature = "serde")] use core::fmt::Debug; @@ -50,7 +53,7 @@ const fn interpreter_result() -> InterpreterResult { } #[test] -fn test_create_inputs_decode_with_and_without_the_charged_address() { +fn test_create_inputs_decode_from_json_with_and_without_the_charged_address() { let inputs = |charged_address| { let mut inputs = CreateInputs::new( address!("0x00000000000000000000000000000000000c0de0"), @@ -71,7 +74,7 @@ fn test_create_inputs_decode_with_and_without_the_charged_address() { } #[test] -fn test_call_outcome_decodes_with_and_without_the_charged_address() { +fn test_call_outcome_decodes_from_json_with_and_without_the_charged_address() { let outcome = |charged_address| { let mut outcome = CallOutcome::new(interpreter_result(), 0..8); outcome.charged_new_account_state_gas = true; @@ -83,7 +86,7 @@ fn test_call_outcome_decodes_with_and_without_the_charged_address() { } #[test] -fn test_create_outcome_decodes_with_and_without_the_charged_address() { +fn test_create_outcome_decodes_from_json_with_and_without_the_charged_address() { let outcome = |charged_address| { let created = address!("0x000000000000000000000000000000000000c4ea"); let mut outcome = CreateOutcome::new(interpreter_result(), Some(created)); diff --git a/crates/interpreter/tests/history_gas_serde.rs b/crates/interpreter/tests/history_gas_serde.rs index e120052867..44db2f1b0e 100644 --- a/crates/interpreter/tests/history_gas_serde.rs +++ b/crates/interpreter/tests/history_gas_serde.rs @@ -1,7 +1,10 @@ //! Serde encoding of the history gas counter on [`GasTracker`], and so on [`Gas`]. //! -//! New encodings carry the counter. Encodings made before it existed lack it and still decode, to -//! zero, which is what a tracker that never charged history gas carries. +//! New encodings carry the counter. In a format that carries field names, such as the JSON these +//! tests use, encodings made before it existed lack it and still decode, to zero, which is what a +//! tracker that never charged history gas carries. A format that encodes a struct by position, +//! such as bincode, cannot read an encoding made before it existed, as with upstream's own field +//! additions. #![cfg(feature = "serde")] use revm_interpreter::{Gas, GasTracker}; @@ -34,7 +37,7 @@ fn remove_field(tracker: &mut Value) -> Option { } #[test] -fn test_gas_tracker_decodes_with_and_without_the_history_counter() { +fn test_gas_tracker_decodes_from_json_with_and_without_the_history_counter() { let tracker = charged_tracker(); let mut encoded = serde_json::to_value(tracker).unwrap(); assert_eq!( @@ -50,7 +53,7 @@ fn test_gas_tracker_decodes_with_and_without_the_history_counter() { } #[test] -fn test_gas_decodes_with_and_without_the_history_counter() { +fn test_gas_decodes_from_json_with_and_without_the_history_counter() { let mut gas = Gas::new_with_regular_gas_and_reservoir(100_000, 20_000); assert!(gas.record_history_cost(CHARGED)); let mut encoded = serde_json::to_value(gas).unwrap(); From b5da5cf8f68e07e62464dd32619e24c5f9e02524 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:53:41 +0800 Subject: [PATCH 024/110] fix(gas): the byte net stays off i64::MIN, whose negation saturates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `adopt_bytes_share` negates the net, and the negation of `i64::MIN` saturates, so a share adopted against that net would be a byte short. The bound is now `±i64::MAX` for the net: the debug asserts in `refill_bytes` and `add_bytes_spent` also refuse a net of `i64::MIN`, and a test refills one byte past `-i64::MAX` and panics in a debug build. Release builds are unchanged. --- crates/context/interface/src/cfg/gas.rs | 4 +-- .../interface/src/cfg/gas/byte_pool.rs | 29 +++++++++++++++---- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index e7fa2c39bd..a614c2045a 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -68,8 +68,8 @@ pub use withheld::WithheldCrossing; /// (about 9.2 × 10^18). /// /// The byte pool's net ([`bytes_spent`](Self::bytes_spent)) is an `i64` too, and assumes the same -/// bound on byte amounts: every draw and refill, and the net with its children's merged in, within -/// `i64`. A debug build asserts it where the net moves. +/// bound on byte amounts: every draw and refill within `i64::MAX`, and the net with its children's +/// merged in within `±i64::MAX`. A debug build asserts it where the net moves. /// /// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and /// the byte pool's crossing, which share a word in memory, are encoded as an optional number and diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs index c1f259edad..e42937618e 100644 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ b/crates/context/interface/src/cfg/gas/byte_pool.rs @@ -12,8 +12,9 @@ //! //! The net is an `i64`, as the gas nets are, while draws and refills take `u64` amounts. As the //! tracker does for gas amounts, it assumes that every draw and refill is at most `i64::MAX` -//! bytes, and that the net, with the nets of the children merged into it, stays within `i64`; -//! the pool itself may be anything up to the unlimited `u64::MAX`. A release build does not check +//! bytes, and that the net, with the nets of the children merged into it, stays within +//! `±i64::MAX`, so it can be negated ([`adopt_bytes_share`](GasTracker::adopt_bytes_share)); the +//! pool itself may be anything up to the unlimited `u64::MAX`. A release build does not check //! it: past it the net saturates, and a rollback no longer restores the pool exactly. A debug //! build asserts it wherever the net moves ([`record_bytes`](GasTracker::record_bytes), //! [`refill_bytes`](GasTracker::refill_bytes), [`add_bytes_spent`](GasTracker::add_bytes_spent)). @@ -44,8 +45,8 @@ impl GasTracker { /// /// Negative while the frame has refilled more than it drew, as /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. - /// It is exact while it stays within `i64` and no single draw or refill exceeds `i64::MAX` - /// bytes, which a debug build asserts. + /// It is exact while it stays within `±i64::MAX` and no single draw or refill exceeds + /// `i64::MAX` bytes, which a debug build asserts. #[inline] pub const fn bytes_spent(&self) -> i64 { self.bytes_spent @@ -62,7 +63,7 @@ impl GasTracker { #[inline] pub const fn add_bytes_spent(&mut self, delta: i64) { debug_assert!( - self.bytes_spent.checked_add(delta).is_some(), + matches!(self.bytes_spent.checked_add(delta), Some(net) if net != i64::MIN), "the byte net leaves the signed range" ); self.bytes_spent = self.bytes_spent.saturating_add(delta); @@ -96,7 +97,11 @@ impl GasTracker { #[inline] pub const fn refill_bytes(&mut self, amount: u64) { debug_assert!( - amount <= i64::MAX as u64 && self.bytes_spent.checked_sub(amount as i64).is_some(), + amount <= i64::MAX as u64 + && matches!( + self.bytes_spent.checked_sub(amount as i64), + Some(net) if net != i64::MIN + ), "the byte net leaves the signed range" ); self.bytes_remaining = self.bytes_remaining.saturating_add(amount); @@ -436,6 +441,18 @@ mod tests { let _ = tracker.record_bytes(i64::MAX as u64 + 1); } + /// Below `-i64::MAX` the net would be `i64::MIN`, whose negation saturates, so a share + /// adopted against it would be a byte short: a debug build refuses the refill that gets there. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "the byte net leaves the signed range")] + fn test_a_refill_past_the_signed_minimum_panics_in_a_debug_build() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_bytes_remaining(0); + tracker.refill_bytes(i64::MAX as u64); + tracker.refill_bytes(1); + } + /// With the default pool, forwarding the whole pool and settling a child's return brings the /// caller back to the pool less what the child drew and kept: a failed child's draws come /// back whole. From 1009efc689affd90f9fad3900d900cc985e24c8c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 21 Oct 2026 23:54:02 +0800 Subject: [PATCH 025/110] docs: the shared first-frame settlement, consumers at revisions and encodings in MEGAETH-FORK.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The start charge: `execution::settle_first_frame` is the first frame's settlement, which a chain's handler that overrides `last_frame_result` calls (op-revm's does); measured at the same instruction count. Upstream's steps of that settlement now live in `execution/first_frame.rs`, where a pick that changes them lands. - The consumer inventory names each consumer at a revision: the op-revm fork (compiles, its next release calls the shared settlement), the legacy engine (`501cc7cc`, a production `CallInputs` literal and test literals), Satin W9 (`f1d1a48d`, production and test literals, its `frame_starting` and `admit_code_deposit` overrides), Foundry (on revm 43 at master) and mega-reth (`2dc2f44ac8`, `b97b508a0b`). The frame-start hook's `&mut FrameStart` is listed with the breaking items. - Serde: older encodings decode with the new fields' defaults only in formats that carry field names; a positional format cannot read them. - The byte pool: byte amounts are bounded as gas amounts are, the net to `±i64::MAX`, asserted in debug builds. - The history allowance: a precompile's answer carries the input's. --- MEGAETH-FORK.md | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index b56f470333..b1d41ed066 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -68,6 +68,9 @@ Each entry names the API a consumer uses and what the fork guarantees about it. A hook's default keeps upstream's behaviour: a consumer that does not use it sees the same results. Each entry's **Consumer** says who needs it and why it cannot be done outside the fork, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it. +A field a hook adds to a serialized type carries `serde(default)`, so in a format that carries field names, such as JSON, an encoding made before the field existed decodes with the default. +A format that encodes a struct by position, such as bincode, cannot read such an encoding, as with upstream's own field additions: it reads the old fields in their places and then looks for the new ones, so a value persisted in such a format must not cross an upgrade of the fork that adds a field. + ### State-gas price - **API.** `Host::state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option` and `Host::state_gas_charge(&mut self, charge: StateGasCharge) -> Option`. @@ -94,7 +97,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm charges history gas for the bytes a transaction appends to the chain's history. The code deposit is charged inside `return_create`, and only the tracker can unwind a frame's history charges with its state charges. - **Removal.** When upstream carries an equivalent gas dimension, or when mega-evm stops charging history gas. - **Default.** No schedule prices `code_deposit_history_gas`, and nothing else in the workspace charges history gas, so the counter stays zero and every result is upstream's. - The counter decodes as zero from encodings that predate it. + In a format that carries field names, the counter decodes as zero from encodings that predate it. ### Amsterdam opcodes and transfer logs below Amsterdam @@ -152,7 +155,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. It was two words as an `Option`: the tracker was 88 bytes with it, and a copy of the tracker, and of every `Gas` and frame result that holds one, 16 bytes larger. - It is now a number and a flag, and the flag shares its word with the byte pool's crossing (see The byte pool); the encoding is unchanged, an optional number in the same place. + It is now a number and a flag, and the flag shares its word with the byte pool's crossing (see The byte pool); the record's encoding is unchanged, an optional number in the same place. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. ### Precompile price @@ -199,7 +202,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th Inlined into a consumer's own function, the admitting default may shift its block layout; where measured, that cost one unconditional branch on one out-of-gas path and changed no success path. Where measured (callgrind, the fork's release profile), lending `gas` costs nothing: a top-level creation runs the same instruction count as without it, and a nested `CREATE` 0.06 fewer. The `gas` parameter changed this released hook's signature, an exception to rule 1 (`api:exception`): an override does not compile until it takes the parameter. - mega-evm's `MegaContext::admit_code_deposit` is the one override found; alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth do not override it, and nothing built against upstream revm can, since the hook is the fork's. + mega-evm's `MegaContext::admit_code_deposit` is the one override found, in Satin W9 (`cz/feat/satin-w9` at `f1d1a48d`, `crates/mega-evm/src/evm/context.rs:696`) and the W8 trees before it. + The legacy engine (`cz/feat/legacy-on-fork` at `501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do not override it, and nothing built against upstream revm can, since the hook is the fork's. ### revm 40.0.3's journal semantics @@ -240,6 +244,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), `CREATE` and `CREATE2` compile to the same code as without the hook, and a call runs one instruction more: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. + The hook takes `&mut FrameStart` since the start charge moved onto the start; its first version took `&FrameStart`. No release carries that version, so upstream's superset is untouched, but an override written against it does not compile until it takes `&mut`, a change `cargo semver-checks` cannot see; the pull request that makes it lists it with the `api:exception` items. + Satin W9 overrides it (`crates/mega-evm/src/evm/host.rs:376` at `f1d1a48d`); the legacy engine (`501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do not. ### The byte pool @@ -252,6 +258,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th The crossing is a bit: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. No halt touches the pool, so a halted frame's result still reads the pool as the failed draw found it, until its caller settles it. `refill_bytes(n)` gives bytes back and lowers the net, below zero when the draw was a caller's. + Byte amounts are bounded as the tracker bounds gas amounts: every draw and refill is at most `i64::MAX`, and the net with its children's nets merged in stays within `±i64::MAX`, so it can be negated; a debug build asserts it where the net moves, and past it a release build saturates the net, so a rollback no longer restores the pool exactly. A consumer draws deployed code's bytes where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). The transaction's frame gets the whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution. At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `bytes_forward_share` of the caller's pool out of it and puts it on the frame's input as `bytes_share`: the child's pool when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). @@ -260,7 +267,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th The settlement is in `handle_reservoir_remaining_gas` and follows the reservoir, not regular gas: a child that reverts or halts has its draws undone by `rollback_state_gas`, which now gives `bytes_spent` back to the pool, so what the caller absorbs is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame appends nothing; the caller kept what it did not forward. The child's net merges into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. `rollback_state_gas` rolls the pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pool back with it. - The first frame's return settles into the transaction's tracker the same way (`last_frame_result`), whose `bytes_spent` is then the transaction's net draw. + The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `bytes_spent` is then the transaction's net draw. A precompile's answer adopts the share as the pool it started with (`adopt_bytes_share`): its pool is the share less what its provider drew on it, so its pool and net add up to the share as a frame's do; a provider that draws on its answer starts the answer's pool at the input's `bytes_share` first, so a draw the share cannot pay fails. An outcome an inspector builds to answer a start carries whatever pool its gas was built with, an unlimited one with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs it as it is. A consumer that answers a start itself, without a frame or a provider, sets the answer's pool to the share it was given. @@ -268,7 +275,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm keeps a per-frame budget of the bytes a transaction appends to the state and the history, which a failed frame gives back and a successful one hands to its caller. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry a figure that moves with a frame's gas. - **Removal.** When upstream carries an equivalent per-frame budget on its gas, or when mega-evm stops limiting bytes per frame. - **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. - The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest. + The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); in a format that carries field names, encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 128 bytes (104), `InterpreterResult` 168 (144), `CallOutcome` and `FrameResult` 248 (208), `CreateOutcome` 232 (192), the outcomes with the start charge's two words. Where measured (callgrind, the fork's release profile, against the base without the pool, the start charge and the allowance), the three figures together cost a transfer 120 instructions (+2.2%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 151 (+1.9%), a transaction that calls a precompile 135 (+0.04%; 10 of them the answer's adopted share) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. @@ -277,10 +284,14 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **API.** The type `StartCharge` (`new`, `history`, `bytes`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`. `FrameStart::charge` (see Frame-start hook). `charged_start` on `CallInputs`, `CallOutcome` and `CreateOutcome` (fields) and on `CreateInputs` (`charged_start`, `set_charged_start`); `FrameResult::refundable_start_charge`. + `revm_handler::execution::settle_first_frame`, the settlement of the first frame. - **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and bytes of the pool. The `frame_starting` hook charges the caller's tracker and declares the refundable part on the start it is handed (`start.charge`); the instruction copies it onto the frame's input when the hook admits the start; a start the hook refuses discards the charge with the start, and what the hook charged stands. The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. + `last_frame_result` settles the first frame through `execution::settle_first_frame`, which is all of mainnet's settlement but the copy of the transaction's gas into the frame's result: the spend and the settlement of the frame, the EIP-2780 state-gas refund and the start-charge refund, each with its halt rule. + A chain whose handler overrides `last_frame_result` calls it rather than copying the mainnet body, so the start-charge refund and any later step reach it too, and applies its own rules between it and the copy, as the op-revm fork does with its pre-Regolith deposit rule. + Upstream's own steps of the settlement (the spend, `handle_reservoir_remaining_gas` and the EIP-2780 refund) live in `crates/handler/src/execution/first_frame.rs`, not in `handler.rs`: a pick or a base-line merge that changes upstream's `last_frame_result` body lands there, and records the move as its conflict resolution. A frame that succeeds keeps the charge. A precompile's answer and a start the handler refuses before any frame (call depth, balance) carry the input's charge, so they refund as a frame does. An outcome an inspector builds to answer a start carries no charge unless the inspector copies the input's (`CallOutcome::new` and `CreateOutcome::new` carry none), so the caller keeps the charge, as revm keeps its own upfront state charge on an outcome a tool builds; an outcome the inspector rewrites at `call_end` or `create_end` keeps the frame's charge, so a success rewritten into a failure is refunded. @@ -288,10 +299,19 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. - **Default.** The hook declares nothing, so the fields and the refund are zero. + `settle_first_frame` is inlined: where measured (callgrind, the fork's release profile), a transfer and a transaction of 64 calls run the same instruction count as when its steps were `last_frame_result`'s body. This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. - alloy-evm 0.36, revm-inspectors 0.40 and the op-revm fork construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. - Foundry constructs `CallOutcome` and `CreateOutcome` by literal in its cheatcodes and its inspector stack, and mega-reth's oracle executor constructs a `CallOutcome` by literal; both already fail against the fork's base, whose outcomes carry the earlier EIP-8037 field `charged_state_gas_address` that no upstream release has, so the outcomes' new field breaks no literal that compiled against the fork before. - Foundry also constructs `CallInputs` once by literal in its cheatcodes; the base's `CallInputs` has upstream's fields, so that literal is broken by this entry for the first time, in a file its outcome literals already break. + Their defaults are no charge (`StartCharge::default()`), an unlimited share (`u64::MAX`) and no allowance (`0`). + The consumers checked, each at a revision: + - alloy-evm 0.36 and revm-inspectors 0.40 construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. + - The op-revm fork (`v20.0.0-mega.3`) constructs them with `new` and compiles unchanged, but its `OpHandler::last_frame_result` copied mainnet's settlement and so missed the first frame's start-charge refund; its next release calls `settle_first_frame`, and a consumer that declares a first-frame charge needs that release. + - MegaETH's legacy engine (`cz/feat/legacy-on-fork` at `501cc7cc`) builds the first frame's `CallInputs` by literal in production (`crates/mega-evm/src/evm/execution.rs:724`) and in tests (`evm/execution.rs:2114`, `evm/precompiles.rs:432`, `limit/storage_call_stipend.rs:233`, `tests/rex5/call_too_deep_guard.rs:43`). It uses none of the new figures, but stops compiling: its repin names the three fields at their defaults and runs the legacy gate. + - Satin W9 (`cz/feat/satin-w9` at `f1d1a48d`) builds `CreateOutcome` and `CallOutcome` by literal in production (`crates/mega-evm/src/evm/frame.rs:73`, `:91`), `CallInputs` in unit and integration tests (ten sites), and `CreateOutcome` in two integration tests (`tests/system/keyless/differential.rs:950`, `tests/system/keyless/inspector.rs:69`). Its migration puts the input's charge and share on those answers, and the start-charge refund in `frame.rs`'s `settle_frame_result`, which mirrors the inner settlement. + - Foundry, master as fetched on 2026-10-21, constructs `CallOutcome` and `CreateOutcome` by literal in its cheatcodes and its inspector stack, and `CallInputs` once in its cheatcodes. It requests revm 43.0.2, alloy-evm 0.39.0 and revm-inspectors 0.44.1, so it cannot take this 40.0.3 fork through a version-satisfying patch: the literals are porting work, not a checked build. + - mega-reth's oracle executor constructs a `CallOutcome` by literal at `2dc2f44ac8`, which pins revm 27.1.0, and with `CallOutcome::new` at `b97b508a0b`, which pins revm 40.0.3. + + Foundry's and mega-reth's outcome literals already fail against the fork's base, whose outcomes carry the earlier EIP-8037 field `charged_state_gas_address` that no upstream release has; Satin W9's, production and test, were written against the fork and break here. + The base's `CallInputs` has upstream's fields, so every `CallInputs` literal (the legacy engine's, Satin W9's tests', Foundry's) breaks here for the first time. ### The history allowance @@ -300,6 +320,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th - **Contract.** The allowance is history gas a frame may spend before it charges its budget. A call that transfers value gives its child the schedule's `call_history_allowance`, decided where the call instruction adds the call stipend, carried on the input and set on the child's tracker when it starts, on the frame and on an answer alike; no other start gives one, and the transaction's frame has none. Only a consumer draws it: `draw_history_allowance(cost)` takes `min(cost, allowance)` and returns the part of `cost` the allowance did not cover, which the consumer charges as history. + A precompile's answer is given the input's allowance after its provider ran, so the allowance it carries back is the input's, whatever the provider drew. The allowance is the frame's alone: it is not returned, merged or rolled back. - **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. Only the call instruction knows which starts get the stipend. - **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. From e0d0f7ee70da15dff0a2bcd625908e3dbd1dc205 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:28:24 +0800 Subject: [PATCH 026/110] feat(interpreter): a creation's start carries the address it takes `FrameStart::target` was `None` for `CREATE` and `CREATE2`, so the frame-start hook could not tell whether the transaction had already changed the account a creation takes. It now carries that address. With EIP-8037 the instruction already computes the address into `CreateInputs`' cache before the hook. Without it, the instruction now reads the caller (the running frame's account, in the journal) and, after the same three checks the EIP-8037 branch makes (endowment, nonce, depth), computes the address into the same cache. The handler builds the frame from the cache, so the address and a `CREATE2`'s init-code hash are still computed once, and a creation the handler fails before it takes an address computes none and reaches the hook with `None`. --- .../interface/src/host/instruction_hooks.rs | 11 +- crates/inspector/tests/instruction_hooks.rs | 141 ++++++++++++++++- .../interpreter/src/instructions/contract.rs | 16 +- .../src/instructions/instruction_hooks.rs | 29 +++- .../src/interpreter_action/create_inputs.rs | 6 + crates/interpreter/tests/instruction_hooks.rs | 143 +++++++++++++++++- 6 files changed, 329 insertions(+), 17 deletions(-) diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index 7b325ce304..5e61d3e823 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -94,7 +94,16 @@ pub struct FrameStart { pub kind: FrameStartKind, /// The frame's caller: the account the frame sees as `CALLER`. pub caller: Address, - /// The account the frame runs as; `None` for a creation, whose address is decided later. + /// The account the frame runs as. For a `CALL` or `STATICCALL`, the account called; for a + /// `CALLCODE` or `DELEGATECALL`, the calling frame's own account, which runs the called + /// account's code. + /// + /// For a `CREATE` or `CREATE2`, the address the creation takes, computed once: the handler + /// builds the frame at the same address without computing it again. `None` only for a + /// creation the handler fails before it takes an address, which reaches the hook only when + /// EIP-8037 is off: an endowment above the caller's balance, a caller's nonce at its maximum, + /// or a creating frame at the depth limit. With EIP-8037 on, the instruction ends such a + /// creation before the hook. pub target: Option
, /// The value the start transfers; zero for `DELEGATECALL` and `STATICCALL`. pub value: U256, diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index aaeb246eae..4fcc4d6d78 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -27,7 +27,8 @@ use interpreter::{ SStoreResult, SelfDestructResult, StateLoad, }; use primitives::{ - address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, + KECCAK_EMPTY, U256, }; use revm_inspector::{InspectEvm, Inspector, NoOpInspector}; use state::{ @@ -107,6 +108,22 @@ struct Hooks { writes: Vec<(Write, GasTracker)>, /// Every start, with the gas as the hook found it. starts: Vec<(FrameStart, GasTracker)>, + /// Every start's target as the journal held it when the hook saw the start. + targets: Vec, +} + +/// An account as the journal holds it: its info and the info the transaction loaded it with, or +/// `None` for an account the transaction has not loaded. +type View = Option<(AccountInfo, AccountInfo)>; + +/// Whether the transaction has changed the account `view` shows: its nonce, balance or code differs +/// from what the transaction loaded. An account it has not loaded is unchanged. +fn changed(view: &View) -> bool { + view.as_ref().is_some_and(|(info, original)| { + info.nonce != original.nonce + || info.balance != original.balance + || info.code_hash != original.code_hash + }) } impl Hooks { @@ -118,6 +135,7 @@ impl Hooks { first_start_charge: 0, writes: Vec::new(), starts: Vec::new(), + targets: Vec::new(), } } } @@ -128,6 +146,17 @@ struct HookContext { hooks: Hooks, } +impl HookContext { + /// The account at `address` as the journal holds it. + fn view(&self, address: Address) -> View { + self.inner + .journal_ref() + .state + .get(&address) + .map(|account| (account.info.clone(), account.original_info())) + } +} + impl ContextTr for HookContext { type Block = BlockEnv; type Tx = TxEnv; @@ -190,6 +219,8 @@ impl Host for HookContext { fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { self.hooks.starts.push((*start, *gas)); + let target = start.target.and_then(|target| self.view(target)); + self.hooks.targets.push(target); if self.hooks.starts.len() == 1 && self.hooks.first_start_charge > 0 { assert!(gas.record_history_cost(self.hooks.first_start_charge)); } @@ -321,13 +352,20 @@ impl Host for HookContext { } } -/// The gas limit and reservoir of every frame the inspector saw start, the transaction's first. +/// What the inspector saw of the frames that started. #[derive(Default)] -struct Frames(Vec<(u64, u64)>); +struct Frames { + /// The gas limit and reservoir of every frame, the transaction's first. + gas: Vec<(u64, u64)>, + /// The address each creation's frame took, in the order the creations started. + created: Vec>, + /// The place in `created` of each creation that has not returned yet. + open: Vec, +} impl Inspector for Frames { fn call(&mut self, _context: &mut HookContext, inputs: &mut CallInputs) -> Option { - self.0.push((inputs.gas_limit, inputs.reservoir)); + self.gas.push((inputs.gas_limit, inputs.reservoir)); None } @@ -336,9 +374,21 @@ impl Inspector for Frames { _context: &mut HookContext, inputs: &mut CreateInputs, ) -> Option { - self.0.push((inputs.gas_limit(), inputs.reservoir())); + self.gas.push((inputs.gas_limit(), inputs.reservoir())); + self.open.push(self.created.len()); + self.created.push(None); None } + + fn create_end( + &mut self, + _context: &mut HookContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let started = self.open.pop().expect("a creation returns once it started"); + self.created[started] = outcome.address; + } } type HookEvm = Evm< @@ -447,8 +497,14 @@ impl Run { /// The transaction with `transact` and with `inspect_tx`, which must end the same way and /// reach the hooks at the same points with the same gas. Returns the outcome, what the hooks - /// saw, and the frames the inspector saw start. + /// saw, and the gas of the frames the inspector saw start. fn on_both_paths(&self) -> (ResultAndState, Hooks, Vec<(u64, u64)>) { + let (outcome, hooks, frames) = self.on_both_paths_with_frames(); + (outcome, hooks, frames.gas) + } + + /// [`on_both_paths`](Self::on_both_paths), with all the inspector saw of the frames. + fn on_both_paths_with_frames(&self) -> (ResultAndState, Hooks, Frames) { let mut plain = self.evm(); let transacted = plain.transact(Self::tx()).expect("the transaction runs"); let mut inspected = self.evm(); @@ -461,7 +517,7 @@ impl Run { inspected.ctx.hooks, plain.ctx.hooks, "both paths reach the hooks at the same points with the same gas" ); - (transacted, plain.ctx.hooks, inspected.inspector.0) + (transacted, plain.ctx.hooks, inspected.inspector) } } @@ -655,6 +711,77 @@ fn test_hooks_that_only_observe_change_nothing() { } } +/// A creation's start carries the address its frame takes, with EIP-8037 and without it: a `CREATE` +/// from the transaction's frame, one from the frame it created, whose nonce starts at 1, and a +/// `CREATE2`. +#[test] +fn test_a_creation_start_carries_the_address_its_frame_takes() { + let mut parent = create(CREATE, &ends(create(CREATE, &[]))); + parent.extend(ends(create(CREATE2, &[]))); + let first = PARENT.create(1); + let expected = vec![ + Some(first), + Some(first.create(1)), + Some(PARENT.create2(B256::from(U256::from(0x5a)), KECCAK_EMPTY)), + ]; + for spec in [SpecId::PRAGUE, SpecId::AMSTERDAM] { + let (outcome, hooks, frames) = Run::new(spec, parent.clone()).on_both_paths_with_frames(); + let targets: Vec> = + hooks.starts.iter().map(|(start, _)| start.target).collect(); + + assert!(outcome.result.is_success(), "{spec:?}"); + assert_eq!(frames.created, expected, "{spec:?}: the frames' addresses"); + assert_eq!( + targets, frames.created, + "{spec:?}: each start carries its frame's address" + ); + } +} + +/// At a creation's start, a consumer can tell whether the transaction has changed the account the +/// creation takes: one the transaction funded first is changed, one it has not touched is not. With +/// EIP-8037 the instruction has loaded the account before the hook; without it the account is not +/// loaded until the frame starts, and an account the transaction has not loaded is unchanged. +#[test] +fn test_a_creation_start_shows_whether_its_account_was_changed() { + let salt = B256::from(U256::from(0x5a)); + for (op, address) in [ + (CREATE, PARENT.create(1)), + (CREATE2, PARENT.create2(salt, KECCAK_EMPTY)), + ] { + for spec in [SpecId::PRAGUE, SpecId::AMSTERDAM] { + for funded in [false, true] { + let mut parent = if funded { + call(CALL, address, 0, 1) + } else { + Vec::new() + }; + parent.extend(ends(create(op, &[]))); + let (outcome, hooks, _) = Run::new(spec, parent).on_both_paths(); + let creation = hooks + .starts + .iter() + .position(|(start, _)| start.kind != FrameStartKind::Call) + .expect("the creation starts"); + let created = &outcome.state[&address].info; + + assert!(outcome.result.is_success(), "{op:#x} {spec:?} {funded}"); + assert_eq!(hooks.starts[creation].0.target, Some(address)); + assert_eq!( + changed(&hooks.targets[creation]), + funded, + "{op:#x} {spec:?}: the account was funded first: {funded}" + ); + assert_eq!( + (created.nonce, created.balance), + (1, U256::from(funded as u8)), + "{op:#x} {spec:?} {funded}: the frame took the account" + ); + } + } + } +} + /// `code` with its last instruction, which drops a result, replaced by `STOP`. fn stops_after(mut code: Vec) -> Vec { assert_eq!(code.pop(), Some(POP)); diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index e520e545b5..67a5696200 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -9,7 +9,7 @@ use call_helpers::load_acc_and_calc_forward; use crate::{ instructions::{ - instruction_hooks::{forward_bytes, frame_starting}, + instruction_hooks::{cache_created_address, forward_bytes, frame_starting}, utility::IntoAddress, }, interpreter_action::FrameInput, @@ -152,6 +152,12 @@ pub fn create( create_inputs.set_charged_create_state_gas(true); create_inputs.set_charged_state_gas_address(created_address); } + } else { + cache_created_address( + context.host, + &create_inputs, + context.interpreter.input.depth(), + )?; } let mut gas_limit = context.interpreter.gas.remaining(); @@ -181,7 +187,13 @@ pub fn create( } else { FrameStartKind::Create }; - let start = FrameStart::new(kind, create_inputs.caller(), None, value, gas_limit); + let start = FrameStart::new( + kind, + create_inputs.caller(), + create_inputs.cached_created_address(), + value, + gas_limit, + ); let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 3e36891813..89f7f483fe 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -3,11 +3,11 @@ use crate::{ interpreter_types::{InterpreterTypes as ITy, LoopControl}, - Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, InterpreterAction, - StartCharge, + CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, + InterpreterAction, StartCharge, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; -use primitives::{hints_util::cold_path, Bytes}; +use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Bytes}; /// Hands `write`, which the running instruction completed after its last charge, to /// [`Host::write_completed`] with the frame's gas, and applies the verdict: the instruction goes @@ -61,6 +61,29 @@ pub(crate) fn frame_starting( } } +/// Computes the address the creation `inputs` takes into their cache, for the frame-start hook, +/// when EIP-8037 is off; with it on, the creation instruction's EIP-8037 branch computes it. It does +/// so after the checks that branch makes, so a creation the handler fails before it takes an +/// address gets none: an endowment above the caller's balance, a caller's nonce at its maximum, or +/// a creating frame at `depth` the depth limit. The handler builds the frame from the cache, so the +/// address and a `CREATE2`'s init-code hash are computed once. The caller is the running frame's +/// account, which the journal holds, so reading its nonce loads nothing cold. +#[inline] +pub(crate) fn cache_created_address( + host: &mut H, + inputs: &CreateInputs, + depth: usize, +) -> Result { + let caller = host + .load_account_info_skip_cold_load(inputs.caller(), false, false)? + .account; + let (balance, nonce) = (caller.balance, caller.nonce); + if balance >= inputs.value() && nonce != u64::MAX && depth < CALL_STACK_LIMIT as usize { + inputs.created_address(nonce); + } + Ok(()) +} + /// Takes the child's share of the caller's byte pool out of `gas`, by the schedule's /// `bytes_forward_percent`, and returns it: the pool the child starts with. Called once the /// frame-start hook has answered, so the share is of the pool as the hook left it. diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index 675ef36c32..eaa875cc34 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -118,6 +118,12 @@ impl CreateInputs { }) } + /// The created address, if [`created_address`](Self::created_address) has computed it since + /// the caller, the scheme or the init code last changed. + pub(crate) fn cached_created_address(&self) -> Option
{ + self.cached_address.get().copied() + } + /// Returns the keccak256 hash of the init code. /// /// The result is cached so that `created_address()` and frame initialization diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index a2fee4502c..698fc634c1 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -15,7 +15,8 @@ use context_interface::{ journaled_state::AccountInfoLoad, }; use primitives::{ - address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, B256, U256, + address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, Log, StorageKey, + StorageValue, B256, KECCAK_EMPTY, U256, }; use revm_interpreter::{ host::DummyHost, @@ -80,6 +81,10 @@ struct HookHost { cold: bool, /// Every account is empty. empty: bool, + /// Every account's balance. + balance: U256, + /// Every account's nonce. + nonce: u64, /// The original and present value of every slot. slot: StorageValue, /// What `SELFDESTRUCT` finds. @@ -102,6 +107,8 @@ impl HookHost { dummy: DummyHost::new(spec), cold: false, empty: false, + balance: U256::from(AMPLE), + nonce: 0, slot: StorageValue::ZERO, destruct: SelfDestructResult::default(), price_fails: false, @@ -123,6 +130,16 @@ impl HookHost { self } + fn with_balance(mut self, balance: u64) -> Self { + self.balance = U256::from(balance); + self + } + + const fn with_nonce(mut self, nonce: u64) -> Self { + self.nonce = nonce; + self + } + fn holding(mut self, slot: u64) -> Self { self.slot = StorageValue::from(slot); self @@ -312,7 +329,7 @@ impl Host for HookHost { ) -> Result, LoadError> { self.refuses_cold(skip_cold_load)?; Ok(AccountInfoLoad { - account: Cow::Owned(AccountInfo::from_balance(U256::from(AMPLE))), + account: Cow::Owned(AccountInfo::from_balance(self.balance).with_nonce(self.nonce)), is_cold: self.cold, is_empty: self.empty, }) @@ -327,6 +344,18 @@ fn run( gas_limit: u64, reservoir: u64, host: &mut HookHost, +) -> (InterpreterAction, Gas) { + run_at_depth(spec, code, gas_limit, reservoir, 0, host) +} + +/// [`run`] in a frame at `depth`. +fn run_at_depth( + spec: SpecId, + code: &[u8], + gas_limit: u64, + reservoir: u64, + depth: usize, + host: &mut HookHost, ) -> (InterpreterAction, Gas) { let mut interpreter = Interpreter::::new( SharedMemory::new(), @@ -335,6 +364,7 @@ fn run( target_address: CONTRACT, caller_address: CALLER, call_value: U256::from(APPARENT_VALUE), + depth, ..Default::default() }, false, @@ -758,16 +788,36 @@ fn start_cases() -> Vec<(&'static str, Vec, FrameStart)> { ( "CREATE", create_code(CREATE, 0, 3), - start(FrameStartKind::Create, CONTRACT, None, value), + start( + FrameStartKind::Create, + CONTRACT, + Some(created(CREATE)), + value, + ), ), ( "CREATE2", create_code(CREATE2, 0, 3), - start(FrameStartKind::Create2, CONTRACT, None, value), + start( + FrameStartKind::Create2, + CONTRACT, + Some(created(CREATE2)), + value, + ), ), ] } +/// The address [`create_code`]`(op, 0, _)` creates at, [`CONTRACT`]'s nonce being `0`: `CREATE` +/// from the nonce, `CREATE2` from its salt `0x5a` and the hash of no init code. +fn created(op: u8) -> Address { + if op == CREATE2 { + CONTRACT.create2(B256::from(U256::from(0x5a)), KECCAK_EMPTY) + } else { + CONTRACT.create(0) + } +} + /// The gas limit and reservoir of a frame's input. fn input_gas(input: &FrameInput) -> (u64, u64) { match input { @@ -843,6 +893,91 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { } } +/// A creation's start carries the address the creation takes, with EIP-8037 and without it, up to +/// the frame below the depth limit, and the frame's input carries the same address, computed once: +/// the handler reuses it whatever nonce it reads. +#[test] +fn test_a_creation_start_carries_the_address_its_input_caches() { + for spec in [SpecId::OSAKA, SpecId::AMSTERDAM] { + for op in [CREATE, CREATE2] { + for depth in [0, CALL_STACK_LIMIT as usize - 1] { + let mut host = HookHost::new(spec); + let code = create_code(op, 0, 3); + let (action, _) = run_at_depth(spec, &code, AMPLE, 0, depth, &mut host); + let FrameInput::Create(inputs) = started(action) else { + panic!("{spec:?} {op:#x} at {depth}: a creation's input"); + }; + + assert_eq!( + host.start().0.target, + Some(created(op)), + "{spec:?} {op:#x} at {depth}" + ); + assert_eq!( + inputs.created_address(7), + created(op), + "{spec:?} {op:#x} at {depth}: the input carries the address the hook saw" + ); + } + } + } +} + +/// Without EIP-8037, a creation the handler fails before it takes an address reaches the hook with +/// none, and its input carries none: an endowment above the caller's balance, a caller's nonce at +/// its maximum, and a frame at the depth limit. With EIP-8037 the instruction ends each before the +/// hook and pushes zero. +#[test] +fn test_a_creation_that_fails_before_its_address_starts_without_one() { + let cases = |spec| { + [ + ( + "an endowment above the balance", + HookHost::new(spec).with_balance(2), + 0, + ), + ( + "a nonce at its maximum", + HookHost::new(spec).with_nonce(u64::MAX), + 0, + ), + ( + "the depth limit", + HookHost::new(spec), + CALL_STACK_LIMIT as usize, + ), + ] + }; + for op in [CREATE, CREATE2] { + let code = create_code(op, 0, 3); + for (name, mut host, depth) in cases(SpecId::OSAKA) { + let (action, _) = run_at_depth(SpecId::OSAKA, &code, AMPLE, 0, depth, &mut host); + let FrameInput::Create(inputs) = started(action) else { + panic!("{op:#x}, {name}: a creation's input"); + }; + + assert_eq!(host.start().0.target, None, "{op:#x}, {name}"); + if op == CREATE { + assert_eq!( + inputs.created_address(5), + CONTRACT.create(5), + "{name}: the input carries no address" + ); + } + } + for (name, mut host, depth) in cases(SpecId::AMSTERDAM) { + let (action, _) = run_at_depth(SpecId::AMSTERDAM, &code, AMPLE, 0, depth, &mut host); + + assert_eq!( + returned(action).0, + InstructionResult::Stop, + "{op:#x}, {name}" + ); + assert!(!host.reached(), "{op:#x}, {name}: the hook is not reached"); + } + } +} + /// A call's forward is the gas it names when that is below 63/64 of what the caller has left, and /// that cap otherwise, for every kind of call. #[test] From a27afdc2c97d4f3675dfcbc69d35f3f870da729a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:34:38 +0800 Subject: [PATCH 027/110] feat(interpreter): a SELFDESTRUCT's completed write carries the balance before it After the write, a source loaded with 5 and destructed from 7 looks the same as one destructed from 5: both hold 0 against an original 5, and `SelfDestructResult` says only that each had a value. A consumer that counts an account write record while the account's info differs from what the transaction loaded could not tell whether the write changed the source. `CompletedWrite::SelfDestruct` now carries `balance`, the balance the destructed account held before the write, read from the running frame's own account before `Host::selfdestruct` (warm, so no cold load). The write changes only balances, so with the journal at the hook it rebuilds both accounts before the write: the source's balance was `balance`, and a beneficiary that is another account held its balance less `balance`. The withheld-gas suite's cold host now holds the running account warm, as a journal does, so the read is not counted as a cold load there. --- .../interface/src/host/instruction_hooks.rs | 10 + crates/inspector/tests/instruction_hooks.rs | 422 +++++++++++++++++- crates/interpreter/src/instructions/host.rs | 8 + crates/interpreter/tests/instruction_hooks.rs | 18 +- crates/interpreter/tests/withheld_gas.rs | 14 +- 5 files changed, 456 insertions(+), 16 deletions(-) diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index 5e61d3e823..7e3c645a61 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -38,11 +38,21 @@ pub enum CompletedWrite<'a> { data_len: u64, }, /// `SELFDESTRUCT` destructed `address` in favour of `target`. + /// + /// The write changes no account's nonce or code, only balances: `address`'s info before it is + /// its info after it with [`balance`](CompletedWrite::SelfDestruct::balance) as its balance, + /// and `target`'s, when it is another account, its info after it less that balance. With the + /// journal at the hook, that gives both accounts' change across the write. SelfDestruct { /// The account destructed. address: Address, /// The beneficiary. target: Address, + /// The balance `address` held before the write. When `target` is another account, the + /// write moved all of it to `target`. When `target` is `address`, the write burned it or + /// left it, as the spec and EIP-6780 decide, and the account's balance after the write + /// tells which. + balance: U256, /// What the journal reported. result: &'a SelfDestructResult, }, diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index 4fcc4d6d78..6212a72783 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -33,8 +33,9 @@ use primitives::{ use revm_inspector::{InspectEvm, Inspector, NoOpInspector}; use state::{ bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, LOG0, LOG1, MSTORE, POP, PUSH0, PUSH1, - PUSH4, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + ADDRESS, CALL, CALLCODE, CALLVALUE, CREATE, CREATE2, DELEGATECALL, DUP6, JUMPDEST, JUMPI, + LOG0, LOG1, MSTORE, POP, PUSH0, PUSH1, PUSH32, PUSH4, RETURN, SELFDESTRUCT, SSTORE, + STATICCALL, STOP, }, AccountInfo, Bytecode, }; @@ -62,7 +63,7 @@ const STOP_OUTPUT: &[u8] = b"stop"; enum Write { Sstore(Address, StorageKey, SStoreResult), Log(Address, u8, u64), - SelfDestruct(Address, Address, SelfDestructResult), + SelfDestruct(Address, Address, U256, SelfDestructResult), } impl Write { @@ -81,8 +82,9 @@ impl Write { CompletedWrite::SelfDestruct { address, target, + balance, result, - } => Self::SelfDestruct(address, target, result.clone()), + } => Self::SelfDestruct(address, target, balance, result.clone()), } } @@ -110,6 +112,10 @@ struct Hooks { starts: Vec<(FrameStart, GasTracker)>, /// Every start's target as the journal held it when the hook saw the start. targets: Vec, + /// Every destruction's account and beneficiary as the journal held them before the write. + destructs: Vec<[View; 2]>, + /// Every destruction's account and beneficiary as the journal held them at the hook. + destructed: Vec<[View; 2]>, } /// An account as the journal holds it: its info and the info the transaction loaded it with, or @@ -136,6 +142,8 @@ impl Hooks { writes: Vec::new(), starts: Vec::new(), targets: Vec::new(), + destructs: Vec::new(), + destructed: Vec::new(), } } } @@ -211,6 +219,13 @@ impl ContextSetters for HookContext { impl Host for HookContext { fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { self.hooks.writes.push((Write::of(write), *gas)); + if let CompletedWrite::SelfDestruct { + address, target, .. + } = write + { + let accounts = [self.view(address), self.view(target)]; + self.hooks.destructed.push(accounts); + } if self.hooks.writes.len() == 1 && self.hooks.first_write_charge > 0 { assert!(gas.record_history_cost(self.hooks.first_write_charge)); } @@ -305,7 +320,12 @@ impl Host for HookContext { target: Address, skip_cold_load: bool, ) -> Result, LoadError> { - self.inner.selfdestruct(address, target, skip_cold_load) + let before = [self.view(address), self.view(target)]; + let result = self.inner.selfdestruct(address, target, skip_cold_load); + if result.is_ok() { + self.hooks.destructs.push(before); + } + result } fn log(&mut self, log: Log) { @@ -691,7 +711,7 @@ fn test_hooks_that_only_observe_change_nothing() { Write::Log(CHILD, 0, 0), Write::Log(PARENT, 0, 0), Write::Log(PARENT, 0, 0), - Write::SelfDestruct(PARENT, BENEFICIARY, destructed), + Write::SelfDestruct(PARENT, BENEFICIARY, U256::from(9), destructed), ], "{spec:?}: the static call's log fails before the hook" ); @@ -782,6 +802,396 @@ fn test_a_creation_start_shows_whether_its_account_was_changed() { } } +/// An account that destructs itself: its code stops when called with value, which funds it, and +/// self-destructs otherwise. +const DESTRUCTOR: Address = address!("0x00000000000000000000000000000000000de57e"); +/// An account with a balance of 4 that a destruction pays. +const PAYEE: Address = address!("0x00000000000000000000000000000000000ba1ee"); + +/// The account a destruction destructs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Source { + /// [`DESTRUCTOR`], which the transaction has not changed before. + Untouched, + /// [`DESTRUCTOR`], funded with 2 by the transaction first. + Funded, + /// An account the transaction creates with a [`DESTRUCTOR`]'s code (EIP-6780). + Created, +} + +/// The account a destruction pays. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Payee { + /// [`PAYEE`], which the transaction has not changed before. + Untouched, + /// [`PAYEE`], funded with 1 by the transaction first. + Funded, + /// [`BENEFICIARY`], which does not exist. + New, + /// The destructed account itself. + Itself, +} + +/// A destruction: the source and the beneficiary as the journal held them before the write and at +/// the hook, with what the hook was handed. +#[derive(Debug)] +struct Destruct { + address: Address, + target: Address, + balance: U256, + result: SelfDestructResult, + before: [View; 2], + after: [View; 2], +} + +/// An account's nonce, balance and code hash, and those it was loaded with. +type Facts = ((u64, U256, B256), (u64, U256, B256)); + +fn facts(view: &View) -> Option { + view.as_ref().map(|(info, original)| { + ( + (info.nonce, info.balance, info.code_hash), + (original.nonce, original.balance, original.code_hash), + ) + }) +} + +impl Destruct { + /// The source and the beneficiary before the write, as a consumer rebuilds them from the + /// journal at the hook and the hook's facts: the write changed no nonce and no code, the + /// source held `balance`, and a beneficiary that is another account got all of it. + fn rebuilt(&self) -> [View; 2] { + let with_balance = |view: &View, balance: U256| { + view.clone().map(|(mut info, original)| { + info.balance = balance; + (info, original) + }) + }; + let source = with_balance(&self.after[0], self.balance); + let target = if self.target == self.address { + source.clone() + } else { + let paid = self.after[1] + .as_ref() + .expect("the write loaded it") + .0 + .balance; + with_balance(&self.after[1], paid - self.balance) + }; + [source, target] + } + + /// How the write moved the records of the source and of a beneficiary that is another account, + /// with the accounts before it as `before` shows them: `1` for an account it changed from what + /// the transaction loaded, `-1` for one it put back, `0` otherwise. + fn records(&self, before: &[View; 2]) -> (i8, i8) { + let moved = |before: &View, after: &View| changed(after) as i8 - changed(before) as i8; + let target = if self.target == self.address { + 0 + } else { + moved(&before[1], &self.after[1]) + }; + (moved(&before[0], &self.after[0]), target) + } +} + +/// `PUSH32 word`, where `bytes` fill the word from the left. +fn push_word(bytes: &[u8]) -> Vec { + let mut word = [0u8; 32]; + word[..bytes.len()].copy_from_slice(bytes); + let mut code = vec![PUSH32]; + code.extend_from_slice(&word); + code +} + +/// `bytes` stored in memory from offset 0. +fn mstore_bytes(bytes: &[u8]) -> Vec { + let mut code = Vec::new(); + for (word, chunk) in bytes.chunks(32).enumerate() { + code.extend(push_word(chunk)); + code.extend_from_slice(&[PUSH1, (word * 32) as u8, MSTORE]); + } + code +} + +/// A [`DESTRUCTOR`]'s code, paying `payee`, or the account itself when `None`. +fn destructor(payee: Option
) -> Vec { + let pay = payee.map_or(vec![ADDRESS], push_address); + let stop = 5 + pay.len() as u8; + let mut code = vec![CALLVALUE, PUSH1, stop, JUMPI]; + code.extend(pay); + code.extend_from_slice(&[SELFDESTRUCT, JUMPDEST, STOP]); + code +} + +/// Init code that deploys `runtime`. +fn deploying(runtime: &[u8]) -> Vec { + let mut code = mstore_bytes(runtime); + code.extend_from_slice(&[PUSH1, runtime.len() as u8, PUSH0, RETURN]); + code +} + +/// `CREATE` of `initcode` endowed with `value`, leaving the address on the stack. +fn create_keeping(initcode: &[u8], value: u8) -> Vec { + let mut code = mstore_bytes(initcode); + code.extend_from_slice(&[PUSH1, initcode.len() as u8, PUSH0, PUSH1, value, CREATE]); + code +} + +/// A `CALL` with `value` and all the gas the cap allows to the address on top of the stack, which +/// stays there. +fn call_top(value: u8) -> Vec { + vec![ + PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, DUP6, PUSH4, 0xff, 0xff, 0xff, 0xff, CALL, POP, + ] +} + +/// The transaction [`PARENT`] runs for a destruction of `source` holding `held` that pays +/// `payee`, done once or twice: the second time after the transaction funded the source with 3. +/// Returns each destruction. +fn destructions( + spec: SpecId, + source: Source, + held: u8, + payee: Payee, + twice: bool, +) -> Vec { + let pays = match payee { + Payee::Untouched | Payee::Funded => Some(PAYEE), + Payee::New => Some(BENEFICIARY), + Payee::Itself => None, + }; + let code = destructor(pays); + let call_source = |value: u8| match source { + Source::Created => call_top(value), + Source::Untouched | Source::Funded => call(CALL, DESTRUCTOR, u32::MAX, value), + }; + let mut parent = Vec::new(); + if source == Source::Created { + parent.extend(create_keeping(&deploying(&code), held)); + } + if payee == Payee::Funded { + parent.extend(call(CALL, PAYEE, 0, 1)); + } + if source == Source::Funded { + parent.extend(call_source(2)); + } + parent.extend(call_source(0)); + if twice { + parent.extend(call_source(3)); + parent.extend(call_source(0)); + } + parent.push(STOP); + + let mut run = Run::new(spec, parent).with(PAYEE, Vec::new(), 4); + run.accounts[0].2 = 100; + if source != Source::Created { + run = run.with(DESTRUCTOR, code, u64::from(held)); + } + let (outcome, hooks, _) = run.on_both_paths(); + let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!( + hooks.destructs.len(), + hooks.destructed.len(), + "{case}: every destruction reaches the hook" + ); + let writes = hooks + .writes + .into_iter() + .filter_map(|(write, _)| match write { + Write::SelfDestruct(address, target, balance, result) => { + Some((address, target, balance, result)) + } + _ => None, + }); + writes + .zip(hooks.destructs.into_iter().zip(hooks.destructed)) + .map( + |((address, target, balance, result), (before, after))| Destruct { + address, + target, + balance, + result, + before, + after, + }, + ) + .collect() +} + +/// For every destruction, the facts the completed-write hook is handed and the journal at the +/// hook are enough to rebuild both accounts as they were before the write, so a consumer can tell +/// how the write moved each account's record: the source's balance before the write is what the +/// hook sees, and rebuilding from it agrees with the journal before the write. Over a source equal +/// to its beneficiary or not, created in the transaction or not (EIP-6780) and changed before or +/// not; its balance zero or not; a beneficiary unchanged, changed or new; a first destruction and +/// a second (destroyed before); on a spec before EIP-6780, one with it, and one with EIP-8246. +#[test] +fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { + let mut seen = 0; + for spec in [SpecId::SHANGHAI, SpecId::PRAGUE, SpecId::AMSTERDAM] { + for source in [Source::Untouched, Source::Funded, Source::Created] { + for held in [0, 5] { + for payee in [Payee::Untouched, Payee::Funded, Payee::New, Payee::Itself] { + for twice in [false, true] { + let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); + let destructs = destructions(spec, source, held, payee, twice); + assert_eq!(destructs.len(), 1 + twice as usize, "{case}"); + for (n, destruct) in destructs.iter().enumerate() { + let rebuilt = destruct.rebuilt(); + let held_before = facts(&destruct.before[0]).map(|(info, _)| info.1); + + assert_eq!( + Some(destruct.balance), + held_before, + "{case} #{n}: the hook sees the source's balance" + ); + assert_eq!( + facts(&rebuilt[0]), + facts(&destruct.before[0]), + "{case} #{n}" + ); + if destruct.before[1].is_some() { + assert_eq!( + facts(&rebuilt[1]), + facts(&destruct.before[1]), + "{case} #{n}" + ); + } else { + assert!(!changed(&rebuilt[1]), "{case} #{n}: loaded unchanged"); + } + assert_eq!( + destruct.records(&rebuilt), + destruct.records(&destruct.before), + "{case} #{n}" + ); + seen += 1; + } + } + } + } + } + } + assert_eq!(seen, 3 * 3 * 2 * 4 * 3); +} + +/// Worked examples of how a destruction moves the source's and a beneficiary's records, from the +/// rule that an account is a record while its nonce, balance or code differs from what the +/// transaction loaded: each row is `(spec, source, held, payee, twice)` and the moves of each +/// destruction. The first two rows leave the source the same after the write (loaded with 5, now +/// 0) and report the same result, but one changed it and one did not: only the balance before the +/// write tells them apart. +#[test] +fn test_a_destruction_moves_records_as_its_accounts_changed() { + type Row = (SpecId, Source, u8, Payee, bool, &'static [(i8, i8)]); + let rows: [Row; 11] = [ + ( + SpecId::PRAGUE, + Source::Untouched, + 5, + Payee::New, + false, + &[(1, 1)], + ), + ( + SpecId::PRAGUE, + Source::Funded, + 5, + Payee::New, + false, + &[(0, 1)], + ), + ( + SpecId::PRAGUE, + Source::Funded, + 0, + Payee::New, + false, + &[(-1, 1)], + ), + ( + SpecId::PRAGUE, + Source::Untouched, + 0, + Payee::New, + false, + &[(0, 0)], + ), + ( + SpecId::PRAGUE, + Source::Untouched, + 5, + Payee::Funded, + false, + &[(1, 0)], + ), + ( + SpecId::PRAGUE, + Source::Untouched, + 5, + Payee::Untouched, + false, + &[(1, 1)], + ), + ( + SpecId::PRAGUE, + Source::Untouched, + 5, + Payee::Itself, + false, + &[(0, 0)], + ), + ( + SpecId::SHANGHAI, + Source::Untouched, + 5, + Payee::Itself, + false, + &[(1, 0)], + ), + ( + SpecId::AMSTERDAM, + Source::Created, + 5, + Payee::Itself, + false, + &[(0, 0)], + ), + ( + SpecId::PRAGUE, + Source::Created, + 5, + Payee::New, + false, + &[(0, 1)], + ), + ( + SpecId::PRAGUE, + Source::Created, + 5, + Payee::New, + true, + &[(0, 1), (0, 0)], + ), + ]; + let mut afters = Vec::new(); + for (spec, source, held, payee, twice, moves) in rows { + let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); + let destructs = destructions(spec, source, held, payee, twice); + let seen: Vec<(i8, i8)> = destructs + .iter() + .map(|destruct| destruct.records(&destruct.rebuilt())) + .collect(); + + assert_eq!(seen, moves, "{case}"); + afters.push((facts(&destructs[0].after[0]), destructs[0].result.clone())); + } + assert_eq!(afters[0], afters[1], "the same after the write"); + let second = destructions(SpecId::PRAGUE, Source::Created, 5, Payee::New, true); + assert!(second[1].result.previously_destroyed); +} + /// `code` with its last instruction, which drops a result, replaced by `STOP`. fn stops_after(mut code: Vec) -> Vec { assert_eq!(code.pop(), Some(POP)); diff --git a/crates/interpreter/src/instructions/host.rs b/crates/interpreter/src/instructions/host.rs index 4ec45b944b..2996690996 100644 --- a/crates/interpreter/src/instructions/host.rs +++ b/crates/interpreter/src/instructions/host.rs @@ -364,6 +364,13 @@ pub fn selfdestruct(context: Ictx<'_, H, IT>) -> Resu let cold_load_gas = context.host.gas_params().selfdestruct_cold_cost(); let skip_cold_load = context.interpreter.gas.remaining() < cold_load_gas; + // The account's balance before the write, for the completed-write hook. The account is the + // running frame's, which the journal holds, so reading it loads nothing cold. + let balance = context + .host + .load_account_info_skip_cold_load(context.interpreter.input.target_address(), false, false)? + .account + .balance; let res = context.host.selfdestruct( context.interpreter.input.target_address(), target, @@ -408,6 +415,7 @@ pub fn selfdestruct(context: Ictx<'_, H, IT>) -> Resu let write = CompletedWrite::SelfDestruct { address: context.interpreter.input.target_address(), target, + balance, result: &res.data, }; write_completed(context.interpreter, context.host, write)?; diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index 698fc634c1..d5f30b9678 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -47,7 +47,7 @@ const STOP_OUTPUT: &[u8] = b"stop"; enum Write { Sstore(Address, StorageKey, SStoreResult), Log(Address, u8, u64), - SelfDestruct(Address, Address, SelfDestructResult), + SelfDestruct(Address, Address, U256, SelfDestructResult), } impl Write { @@ -66,8 +66,9 @@ impl Write { CompletedWrite::SelfDestruct { address, target, + balance, result, - } => Self::SelfDestruct(address, target, result.clone()), + } => Self::SelfDestruct(address, target, balance, result.clone()), } } } @@ -81,7 +82,7 @@ struct HookHost { cold: bool, /// Every account is empty. empty: bool, - /// Every account's balance. + /// Every account's balance; `SELFDESTRUCT` moves it out. balance: U256, /// Every account's nonce. nonce: u64, @@ -280,6 +281,8 @@ impl Host for HookHost { skip_cold_load: bool, ) -> Result, LoadError> { self.refuses_cold(skip_cold_load)?; + // The write moves the balance out. + self.balance = U256::ZERO; Ok(StateLoad::new(self.destruct.clone(), self.cold)) } @@ -520,8 +523,13 @@ fn write_cases() -> Vec { ( "SELFDESTRUCT", selfdestruct_code(), - |spec| HookHost::new(spec).cold().destructs_into_a_new_account(), - Write::SelfDestruct(CONTRACT, TARGET, destruct), + |spec| { + HookHost::new(spec) + .cold() + .destructs_into_a_new_account() + .with_balance(5) + }, + Write::SelfDestruct(CONTRACT, TARGET, U256::from(5), destruct), InstructionResult::OutOfGas, ), ] diff --git a/crates/interpreter/tests/withheld_gas.rs b/crates/interpreter/tests/withheld_gas.rs index a6b58886d7..6c30918f3c 100644 --- a/crates/interpreter/tests/withheld_gas.rs +++ b/crates/interpreter/tests/withheld_gas.rs @@ -34,8 +34,9 @@ const CONTRACT: Address = address!("0x00000000000000000000000000000000000c0de0") /// Account the `CALL` tests call. const CALLEE: Address = address!("0x00000000000000000000000000000000000ca11e"); -/// A host whose accounts and slots are all cold, and that records whether each load was made or -/// skipped because the frame could not pay for it. +/// A host whose accounts and slots are all cold but the running frame's own account, which a +/// journal holds warm, and that records whether each cold load was made or skipped because the +/// frame could not pay for it. #[derive(Debug)] struct ColdHost { gas_params: GasParams, @@ -187,13 +188,16 @@ impl Host for ColdHost { fn load_account_info_skip_cold_load( &mut self, - _address: Address, + address: Address, _load_code: bool, skip_cold_load: bool, ) -> Result, LoadError> { - self.load(skip_cold_load)?; + let is_cold = address != CONTRACT; + if is_cold { + self.load(skip_cold_load)?; + } Ok(AccountInfoLoad { - is_cold: true, + is_cold, ..Default::default() }) } From a739944ec309462647f8077e2c0e5ba8ee19abad Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:35:50 +0800 Subject: [PATCH 028/110] test: a destruction that puts a drained beneficiary back as loaded takes its record back --- crates/inspector/tests/instruction_hooks.rs | 52 ++++++++++++++++++--- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index 6212a72783..f80487a1d9 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -807,6 +807,9 @@ fn test_a_creation_start_shows_whether_its_account_was_changed() { const DESTRUCTOR: Address = address!("0x00000000000000000000000000000000000de57e"); /// An account with a balance of 4 that a destruction pays. const PAYEE: Address = address!("0x00000000000000000000000000000000000ba1ee"); +/// An account with a balance of 5 whose code self-destructs in favour of [`PARENT`], which a +/// destruction then pays. +const DRAINED: Address = address!("0x00000000000000000000000000000000000d4a1d"); /// The account a destruction destructs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -828,6 +831,9 @@ enum Payee { Funded, /// [`BENEFICIARY`], which does not exist. New, + /// [`DRAINED`], which the transaction drained first by calling it, so a destruction that pays + /// it 5 puts it back as it was loaded. + Drained, /// The destructed account itself. Itself, } @@ -959,6 +965,7 @@ fn destructions( let pays = match payee { Payee::Untouched | Payee::Funded => Some(PAYEE), Payee::New => Some(BENEFICIARY), + Payee::Drained => Some(DRAINED), Payee::Itself => None, }; let code = destructor(pays); @@ -973,6 +980,9 @@ fn destructions( if payee == Payee::Funded { parent.extend(call(CALL, PAYEE, 0, 1)); } + if payee == Payee::Drained { + parent.extend(call(CALL, DRAINED, u32::MAX, 0)); + } if source == Source::Funded { parent.extend(call_source(2)); } @@ -983,7 +993,10 @@ fn destructions( } parent.push(STOP); - let mut run = Run::new(spec, parent).with(PAYEE, Vec::new(), 4); + let mut run = + Run::new(spec, parent) + .with(PAYEE, Vec::new(), 4) + .with(DRAINED, selfdestruct(PARENT), 5); run.accounts[0].2 = 100; if source != Source::Created { run = run.with(DESTRUCTOR, code, u64::from(held)); @@ -1033,11 +1046,18 @@ fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { for spec in [SpecId::SHANGHAI, SpecId::PRAGUE, SpecId::AMSTERDAM] { for source in [Source::Untouched, Source::Funded, Source::Created] { for held in [0, 5] { - for payee in [Payee::Untouched, Payee::Funded, Payee::New, Payee::Itself] { + for payee in [ + Payee::Untouched, + Payee::Funded, + Payee::New, + Payee::Drained, + Payee::Itself, + ] { for twice in [false, true] { let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); let destructs = destructions(spec, source, held, payee, twice); - assert_eq!(destructs.len(), 1 + twice as usize, "{case}"); + let drains = (payee == Payee::Drained) as usize; + assert_eq!(destructs.len(), drains + 1 + twice as usize, "{case}"); for (n, destruct) in destructs.iter().enumerate() { let rebuilt = destruct.rebuilt(); let held_before = facts(&destruct.before[0]).map(|(info, _)| info.1); @@ -1073,7 +1093,9 @@ fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { } } } - assert_eq!(seen, 3 * 3 * 2 * 4 * 3); + // Per spec, source and balance: three destructions for each of five beneficiaries, and the + // drained one's own two. + assert_eq!(seen, 3 * 3 * 2 * (5 * 3 + 2)); } /// Worked examples of how a destruction moves the source's and a beneficiary's records, from the @@ -1081,11 +1103,11 @@ fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { /// transaction loaded: each row is `(spec, source, held, payee, twice)` and the moves of each /// destruction. The first two rows leave the source the same after the write (loaded with 5, now /// 0) and report the same result, but one changed it and one did not: only the balance before the -/// write tells them apart. +/// write tells them apart. A beneficiary the write puts back as loaded takes its record back. #[test] fn test_a_destruction_moves_records_as_its_accounts_changed() { type Row = (SpecId, Source, u8, Payee, bool, &'static [(i8, i8)]); - let rows: [Row; 11] = [ + let rows: [Row; 13] = [ ( SpecId::PRAGUE, Source::Untouched, @@ -1174,6 +1196,24 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { true, &[(0, 1), (0, 0)], ), + // The drained account's own destruction first, then one that puts it back as loaded, or + // pays it nothing and leaves it changed. + ( + SpecId::PRAGUE, + Source::Untouched, + 5, + Payee::Drained, + false, + &[(1, 1), (1, -1)], + ), + ( + SpecId::PRAGUE, + Source::Untouched, + 0, + Payee::Drained, + false, + &[(1, 1), (0, 0)], + ), ]; let mut afters = Vec::new(); for (spec, source, held, payee, twice, moves) in rows { From 83065963aec35eb7014a90bcc44b4f24262fafd2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:52:36 +0800 Subject: [PATCH 029/110] chore(interpreter): one helper reads the running account for both hooks' facts `SELFDESTRUCT` read its balance before the write inline in `host.rs`, and the creation instruction read the caller in `cache_created_address`. Both now call `instruction_hooks::running_account`, so `host.rs`, an upstream file, gets a call site rather than the read itself. The doc of `cache_created_address` no longer garbles the depth limit. --- crates/interpreter/src/instructions/host.rs | 11 +++----- .../src/instructions/instruction_hooks.rs | 25 +++++++++++++------ 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/crates/interpreter/src/instructions/host.rs b/crates/interpreter/src/instructions/host.rs index 2996690996..11bfca24eb 100644 --- a/crates/interpreter/src/instructions/host.rs +++ b/crates/interpreter/src/instructions/host.rs @@ -1,6 +1,6 @@ use crate::{ instructions::{ - instruction_hooks::write_completed, + instruction_hooks::{running_account, write_completed}, utility::{IntoAddress, IntoU256}, }, interpreter_types::{InputsTr, InterpreterTypes as ITy, MemoryTr, RuntimeFlag, StackTr}, @@ -364,13 +364,8 @@ pub fn selfdestruct(context: Ictx<'_, H, IT>) -> Resu let cold_load_gas = context.host.gas_params().selfdestruct_cold_cost(); let skip_cold_load = context.interpreter.gas.remaining() < cold_load_gas; - // The account's balance before the write, for the completed-write hook. The account is the - // running frame's, which the journal holds, so reading it loads nothing cold. - let balance = context - .host - .load_account_info_skip_cold_load(context.interpreter.input.target_address(), false, false)? - .account - .balance; + // The account's balance before the write, for the completed-write hook. + let (balance, _) = running_account(context.host, context.interpreter.input.target_address())?; let res = context.host.selfdestruct( context.interpreter.input.target_address(), target, diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 89f7f483fe..e28c8d1d63 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -7,7 +7,7 @@ use crate::{ InterpreterAction, StartCharge, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; -use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Bytes}; +use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Address, Bytes, U256}; /// Hands `write`, which the running instruction completed after its last charge, to /// [`Host::write_completed`] with the frame's gas, and applies the verdict: the instruction goes @@ -65,25 +65,34 @@ pub(crate) fn frame_starting( /// when EIP-8037 is off; with it on, the creation instruction's EIP-8037 branch computes it. It does /// so after the checks that branch makes, so a creation the handler fails before it takes an /// address gets none: an endowment above the caller's balance, a caller's nonce at its maximum, or -/// a creating frame at `depth` the depth limit. The handler builds the frame from the cache, so the -/// address and a `CREATE2`'s init-code hash are computed once. The caller is the running frame's -/// account, which the journal holds, so reading its nonce loads nothing cold. +/// a creating frame (at `depth`) at the depth limit. The handler builds the frame from the cache, +/// so the address and a `CREATE2`'s init-code hash are computed once. #[inline] pub(crate) fn cache_created_address( host: &mut H, inputs: &CreateInputs, depth: usize, ) -> Result { - let caller = host - .load_account_info_skip_cold_load(inputs.caller(), false, false)? - .account; - let (balance, nonce) = (caller.balance, caller.nonce); + let (balance, nonce) = running_account(host, inputs.caller())?; if balance >= inputs.value() && nonce != u64::MAX && depth < CALL_STACK_LIMIT as usize { inputs.created_address(nonce); } Ok(()) } +/// The balance and nonce of `address`, the running frame's own account, for a hook's facts. The +/// journal holds that account warm, so reading it loads nothing cold. +#[inline] +pub(crate) fn running_account( + host: &mut H, + address: Address, +) -> core::result::Result<(U256, u64), InstructionResult> { + let account = host + .load_account_info_skip_cold_load(address, false, false)? + .account; + Ok((account.balance, account.nonce)) +} + /// Takes the child's share of the caller's byte pool out of `gas`, by the schedule's /// `bytes_forward_percent`, and returns it: the pool the child starts with. Called once the /// frame-start hook has answered, so the share is of the pool as the hook left it. From 48dc2115370a4941ca9ea5ad81461af366051fff Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:54:26 +0800 Subject: [PATCH 030/110] test: a creation's input holds the address and a CREATE2's init-code hash as computed, or nothing --- crates/interpreter/tests/instruction_hooks.rs | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index d5f30b9678..e1932319b1 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -903,7 +903,9 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { /// A creation's start carries the address the creation takes, with EIP-8037 and without it, up to /// the frame below the depth limit, and the frame's input carries the same address, computed once: -/// the handler reuses it whatever nonce it reads. +/// the handler reuses it whatever nonce it reads. The input holds the address, and a `CREATE2`'s +/// init-code hash, as computed: a copy that has computed nothing differs from it until it computes +/// the address for the nonce the instruction read. #[test] fn test_a_creation_start_carries_the_address_its_input_caches() { for spec in [SpecId::OSAKA, SpecId::AMSTERDAM] { @@ -926,15 +928,23 @@ fn test_a_creation_start_carries_the_address_its_input_caches() { created(op), "{spec:?} {op:#x} at {depth}: the input carries the address the hook saw" ); + let mut uncached = (*inputs).clone(); + uncached.set_init_code(uncached.init_code().clone()); + assert_ne!(uncached, *inputs, "{spec:?} {op:#x} at {depth}"); + assert_eq!(uncached.created_address(0), created(op)); + assert_eq!( + uncached, *inputs, + "{spec:?} {op:#x} at {depth}: the address and a CREATE2's hash were computed" + ); } } } } /// Without EIP-8037, a creation the handler fails before it takes an address reaches the hook with -/// none, and its input carries none: an endowment above the caller's balance, a caller's nonce at -/// its maximum, and a frame at the depth limit. With EIP-8037 the instruction ends each before the -/// hook and pushes zero. +/// none, and its input holds nothing computed, neither the address nor a `CREATE2`'s init-code +/// hash: an endowment above the caller's balance, a caller's nonce at its maximum, and a frame at +/// the depth limit. With EIP-8037 the instruction ends each before the hook and pushes zero. #[test] fn test_a_creation_that_fails_before_its_address_starts_without_one() { let cases = |spec| { @@ -965,13 +975,12 @@ fn test_a_creation_that_fails_before_its_address_starts_without_one() { }; assert_eq!(host.start().0.target, None, "{op:#x}, {name}"); - if op == CREATE { - assert_eq!( - inputs.created_address(5), - CONTRACT.create(5), - "{name}: the input carries no address" - ); - } + let mut uncached = (*inputs).clone(); + uncached.set_init_code(uncached.init_code().clone()); + assert_eq!( + uncached, *inputs, + "{op:#x}, {name}: the input holds nothing computed" + ); } for (name, mut host, depth) in cases(SpecId::AMSTERDAM) { let (action, _) = run_at_depth(SpecId::AMSTERDAM, &code, AMPLE, 0, depth, &mut host); From f29bac26ba9b225554c6dca0a6e4d4901b91eef5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:54:26 +0800 Subject: [PATCH 031/110] test: the destruction tests assert the rebuilt balances, not mega-evm's record moves The worked examples asserted how mega-evm's record rule moves on each destruction, which is MegaETH behaviour and belongs in mega-evm. They now assert the balances a consumer rebuilds from the hook's facts, literal for each case, and still show that the first two cases look the same after the write. The exhaustive test drops its record comparison, which followed from the rebuilt accounts it already checks. The two snapshot lists get names that tell them apart. --- crates/inspector/tests/instruction_hooks.rs | 112 ++++++++++---------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/crates/inspector/tests/instruction_hooks.rs b/crates/inspector/tests/instruction_hooks.rs index f80487a1d9..588daeb6dd 100644 --- a/crates/inspector/tests/instruction_hooks.rs +++ b/crates/inspector/tests/instruction_hooks.rs @@ -113,9 +113,9 @@ struct Hooks { /// Every start's target as the journal held it when the hook saw the start. targets: Vec, /// Every destruction's account and beneficiary as the journal held them before the write. - destructs: Vec<[View; 2]>, + destructions_before: Vec<[View; 2]>, /// Every destruction's account and beneficiary as the journal held them at the hook. - destructed: Vec<[View; 2]>, + destructions_at_hook: Vec<[View; 2]>, } /// An account as the journal holds it: its info and the info the transaction loaded it with, or @@ -142,8 +142,8 @@ impl Hooks { writes: Vec::new(), starts: Vec::new(), targets: Vec::new(), - destructs: Vec::new(), - destructed: Vec::new(), + destructions_before: Vec::new(), + destructions_at_hook: Vec::new(), } } } @@ -224,7 +224,7 @@ impl Host for HookContext { } = write { let accounts = [self.view(address), self.view(target)]; - self.hooks.destructed.push(accounts); + self.hooks.destructions_at_hook.push(accounts); } if self.hooks.writes.len() == 1 && self.hooks.first_write_charge > 0 { assert!(gas.record_history_cost(self.hooks.first_write_charge)); @@ -323,7 +323,7 @@ impl Host for HookContext { let before = [self.view(address), self.view(target)]; let result = self.inner.selfdestruct(address, target, skip_cold_load); if result.is_ok() { - self.hooks.destructs.push(before); + self.hooks.destructions_before.push(before); } result } @@ -886,19 +886,6 @@ impl Destruct { }; [source, target] } - - /// How the write moved the records of the source and of a beneficiary that is another account, - /// with the accounts before it as `before` shows them: `1` for an account it changed from what - /// the transaction loaded, `-1` for one it put back, `0` otherwise. - fn records(&self, before: &[View; 2]) -> (i8, i8) { - let moved = |before: &View, after: &View| changed(after) as i8 - changed(before) as i8; - let target = if self.target == self.address { - 0 - } else { - moved(&before[1], &self.after[1]) - }; - (moved(&before[0], &self.after[0]), target) - } } /// `PUSH32 word`, where `bytes` fill the word from the left. @@ -1005,8 +992,8 @@ fn destructions( let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); assert_eq!( - hooks.destructs.len(), - hooks.destructed.len(), + hooks.destructions_before.len(), + hooks.destructions_at_hook.len(), "{case}: every destruction reaches the hook" ); let writes = hooks @@ -1019,7 +1006,12 @@ fn destructions( _ => None, }); writes - .zip(hooks.destructs.into_iter().zip(hooks.destructed)) + .zip( + hooks + .destructions_before + .into_iter() + .zip(hooks.destructions_at_hook), + ) .map( |((address, target, balance, result), (before, after))| Destruct { address, @@ -1035,8 +1027,9 @@ fn destructions( /// For every destruction, the facts the completed-write hook is handed and the journal at the /// hook are enough to rebuild both accounts as they were before the write, so a consumer can tell -/// how the write moved each account's record: the source's balance before the write is what the -/// hook sees, and rebuilding from it agrees with the journal before the write. Over a source equal +/// whether each was changed from what the transaction loaded before the write and after it: the +/// source's balance before the write is what the hook sees, and rebuilding from it agrees with the +/// journal before the write. Over a source equal /// to its beneficiary or not, created in the transaction or not (EIP-6780) and changed before or /// not; its balance zero or not; a beneficiary unchanged, changed or new; a first destruction and /// a second (destroyed before); on a spec before EIP-6780, one with it, and one with EIP-8246. @@ -1081,11 +1074,6 @@ fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { } else { assert!(!changed(&rebuilt[1]), "{case} #{n}: loaded unchanged"); } - assert_eq!( - destruct.records(&rebuilt), - destruct.records(&destruct.before), - "{case} #{n}" - ); seen += 1; } } @@ -1098,15 +1086,23 @@ fn test_a_destruction_hands_the_hook_what_rebuilds_both_accounts() { assert_eq!(seen, 3 * 3 * 2 * (5 * 3 + 2)); } -/// Worked examples of how a destruction moves the source's and a beneficiary's records, from the -/// rule that an account is a record while its nonce, balance or code differs from what the -/// transaction loaded: each row is `(spec, source, held, payee, twice)` and the moves of each -/// destruction. The first two rows leave the source the same after the write (loaded with 5, now -/// 0) and report the same result, but one changed it and one did not: only the balance before the -/// write tells them apart. A beneficiary the write puts back as loaded takes its record back. +/// Worked examples of the balances a consumer rebuilds from a destruction's facts: each row is +/// `(spec, source, held, payee, twice)` and, for each destruction in turn, the source's balance and +/// the beneficiary's (none when it is the source) before the write. The first two rows leave the +/// source the same after the write (loaded with 5, now 0) and report the same result, but one +/// destructed it from 5, as loaded, and the other from 7, after the transaction funded it: only the +/// balance before the write tells them apart. A drained beneficiary the write pays rebuilds to the +/// nothing it held. #[test] -fn test_a_destruction_moves_records_as_its_accounts_changed() { - type Row = (SpecId, Source, u8, Payee, bool, &'static [(i8, i8)]); +fn test_a_destruction_rebuilds_to_the_balances_before_it() { + type Row = ( + SpecId, + Source, + u8, + Payee, + bool, + &'static [(u64, Option)], + ); let rows: [Row; 13] = [ ( SpecId::PRAGUE, @@ -1114,7 +1110,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::New, false, - &[(1, 1)], + &[(5, Some(0))], ), ( SpecId::PRAGUE, @@ -1122,7 +1118,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::New, false, - &[(0, 1)], + &[(7, Some(0))], ), ( SpecId::PRAGUE, @@ -1130,7 +1126,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 0, Payee::New, false, - &[(-1, 1)], + &[(2, Some(0))], ), ( SpecId::PRAGUE, @@ -1138,7 +1134,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 0, Payee::New, false, - &[(0, 0)], + &[(0, Some(0))], ), ( SpecId::PRAGUE, @@ -1146,7 +1142,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::Funded, false, - &[(1, 0)], + &[(5, Some(5))], ), ( SpecId::PRAGUE, @@ -1154,7 +1150,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::Untouched, false, - &[(1, 1)], + &[(5, Some(4))], ), ( SpecId::PRAGUE, @@ -1162,7 +1158,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::Itself, false, - &[(0, 0)], + &[(5, None)], ), ( SpecId::SHANGHAI, @@ -1170,7 +1166,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::Itself, false, - &[(1, 0)], + &[(5, None)], ), ( SpecId::AMSTERDAM, @@ -1178,7 +1174,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::Itself, false, - &[(0, 0)], + &[(5, None)], ), ( SpecId::PRAGUE, @@ -1186,7 +1182,7 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::New, false, - &[(0, 1)], + &[(5, Some(0))], ), ( SpecId::PRAGUE, @@ -1194,17 +1190,16 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 5, Payee::New, true, - &[(0, 1), (0, 0)], + &[(5, Some(0)), (3, Some(5))], ), - // The drained account's own destruction first, then one that puts it back as loaded, or - // pays it nothing and leaves it changed. + // The drained account's own destruction in favour of `PARENT` comes first. ( SpecId::PRAGUE, Source::Untouched, 5, Payee::Drained, false, - &[(1, 1), (1, -1)], + &[(5, Some(100)), (5, Some(0))], ), ( SpecId::PRAGUE, @@ -1212,19 +1207,24 @@ fn test_a_destruction_moves_records_as_its_accounts_changed() { 0, Payee::Drained, false, - &[(1, 1), (0, 0)], + &[(5, Some(100)), (0, Some(0))], ), ]; + let balance = |view: &View| view.as_ref().expect("loaded").0.balance.to::(); let mut afters = Vec::new(); - for (spec, source, held, payee, twice, moves) in rows { + for (spec, source, held, payee, twice, balances) in rows { let case = format!("{spec:?} {source:?} {held} {payee:?} {twice}"); let destructs = destructions(spec, source, held, payee, twice); - let seen: Vec<(i8, i8)> = destructs + let seen: Vec<(u64, Option)> = destructs .iter() - .map(|destruct| destruct.records(&destruct.rebuilt())) + .map(|destruct| { + let rebuilt = destruct.rebuilt(); + let paid = (destruct.target != destruct.address).then(|| balance(&rebuilt[1])); + (balance(&rebuilt[0]), paid) + }) .collect(); - assert_eq!(seen, moves, "{case}"); + assert_eq!(seen, balances, "{case}"); afters.push((facts(&destructs[0].after[0]), destructs[0].result.clone())); } assert_eq!(afters[0], afters[1], "the same after the write"); From 2bd45ea1146dbc281450c8a962f0c53b6677ee41 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:54:50 +0800 Subject: [PATCH 032/110] docs: the creation start's address and the destruction's prior balance in MEGAETH-FORK.md Frame-start hook: what `target` is for each kind, when a creation's is `None`, that the address is computed once and fixed when the hook sees it, what it costs with EIP-8037 off, the starts that compute it for the hook alone, `CreateInputs`' `PartialEq`, and the meaning change listed with the `api:exception` items. Completed-write hook: what `SelfDestruct`'s `balance` is, how it rebuilds both accounts before the write, its cost, and the consumers that build or fully match the variant. --- MEGAETH-FORK.md | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index b1d41ed066..4824d7a085 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -217,16 +217,21 @@ A format that encodes a struct by position, such as bincode, cannot read such an ### Completed-write hook - **API.** `Host::write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, whose default continues. - `CompletedWrite` (`Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. + `CompletedWrite` (`Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it; `SelfDestruct` also carries `balance`, the destructed account's balance before the write) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. `CompletedWrite` is exhaustive on purpose: mega-evm matches it to meter each write, so a new kind is a compile error in every consumer that matches it rather than a write that passes a wildcard arm un-metered, and adding one is an `api:exception` change. - **Contract.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call it once the write is in the journal and every charge the instruction makes has been made, its refund included, so only on the instruction's success path, on the plain and the inspected path. `gas` is the running frame's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook. A charge the hook makes that fails records as any failed charge does (see The failed-charge record), whatever the verdict. `Continue` ends the instruction as it would have ended. `OutOfGas` fails it as a failed charge does: the frame halts out of gas, and the halt records the regular gas the hook left unless a failed charge already did. `Revert(output)` ends the frame as a `Revert` with `output`, on its gas as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct. Only these instructions call it: a write the journal records any other way (a value transfer and its log, deployed code, an inspector's or a precompile's write) is not offered. + A destruction changes only balances, no nonce and no code. So with the journal at the hook, `SelfDestruct`'s `balance` rebuilds both accounts as they were before the write: the destructed account held `balance`, and a beneficiary that is another account held its balance less `balance`, since it got all of it. + When the beneficiary is the destructed account itself, the account's balance after the write says whether the spec burned the balance or left it. - **Consumer.** mega-evm meters each completed write against its per-transaction limits and charges its history. Without the hook it wraps the three instructions and stages what its `Host` saw. + It counts an account's write record while the account's info differs from what the transaction loaded. A destruction's two accounts can look the same after the write whether or not they had changed before it (loaded with 5, now 0, from 5 or from 7), so it needs the balance before the write, which only the instruction reads before the write. - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops metering writes. -- **Default.** Continues and touches nothing; the facts are references to values the instruction holds anyway. - Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook, and `SELFDESTRUCT`'s is laid out differently and runs one instruction fewer. +- **Default.** Continues and touches nothing. The facts are references to values the instruction holds anyway, except `SelfDestruct`'s `balance`, which the instruction reads for the hook from the running frame's own account just before the write. The journal holds that account warm, so the read loads nothing cold. + Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook. The read costs a `SELFDESTRUCT` 119 instructions, one warm journal lookup (+1.5% of a transaction that self-destructs a contract). It is a `Host::load_account_info_skip_cold_load` call the instruction did not make before, so a `Host` that counts or refuses loads sees one more. + `balance` was added to the variant after the hook's first version, which no release carries, so upstream's superset is untouched. A consumer that builds the variant, or matches it naming every field without `..`, does not compile until it names `balance`; the pull request that adds it lists it with the `api:exception` items. + Satin W9 (`cz/feat/satin-w9` at `5b490695`) does both: it matches the variant with every field in `crates/mega-evm/src/limit/record.rs:129`, and builds it in tests (`limit/record.rs:168`, `limit/ledger.rs:1442`, `evm/journal.rs:999`). The legacy engine (`501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do neither. ### Frame-start hook @@ -234,18 +239,30 @@ A format that encodes a struct by position, such as bincode, cannot read such an `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, and `charge`, which `new` leaves empty) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. - `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`; `target` is the account the frame runs as, `None` for a creation. + `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`. + `target` is the account the frame runs as: the account called for `CALL` and `STATICCALL`, the calling frame's own for `CALLCODE` and `DELEGATECALL`, and for `CREATE` and `CREATE2` the address the creation takes. + A creation's address is computed once, into the creation's input, and the handler builds the frame at it without computing it again. With EIP-8037 on, the instruction's EIP-8037 branch computes it. With EIP-8037 off, the instruction computes it after the same checks, reading the caller's balance and nonce from the journal. + It is `None` only for a creation the handler fails before it takes an address: an endowment above the caller's balance, a caller's nonce at its maximum, or a creating frame at the depth limit. Such a creation reaches the hook only with EIP-8037 off; with it on, the instruction ends the creation before the hook. + The address is fixed when the hook sees it. Something that changes the caller's nonce between the instruction and the frame does not move it, as on upstream's EIP-8037 path. An inspector that changes the creation's caller, scheme or init code (`CreateInputs::set_call`, `set_scheme`, `set_init_code`) clears it, and the handler computes the new one. `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. `start` is the hook's to declare the start charge on (`charge`, see The start charge); the instruction reads nothing else back from it. After the hook the instruction copies that charge onto the frame's input and takes the child's share of the byte pool off `gas` for it (see The byte pool); the share is of the pool as the hook left it. `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. + It counts the created account's record only when the transaction has not changed that account already (funded it, say), so it needs the address at the start. A `CREATE2`'s address depends on the init-code hash, which only the instruction has. - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. - Where measured (callgrind, the fork's release profile), `CREATE` and `CREATE2` compile to the same code as without the hook, and a call runs one instruction more: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. + Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. + `CREATE` and `CREATE2` compiled to the same code as without the hook until a creation's start carried its address (measured with EIP-8037 off, the default spec's path). + With EIP-8037 off, the address now costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call the instruction did not make before, so a `Host` that counts or refuses loads sees one more. + The address and a `CREATE2`'s init-code hash moved from the handler into the instruction. A creation the handler builds or fails computes no more hashes than before; the keccak instruction counts are unchanged. + A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. + With EIP-8037 on, the start reads the address the EIP-8037 branch already computed from the input; that path was not measured. + `CreateInputs`' derived `PartialEq` compares the cached address and hash. With EIP-8037 off, a creation's input now holds them, as it already did with EIP-8037 on, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache. The hook takes `&mut FrameStart` since the start charge moved onto the start; its first version took `&FrameStart`. No release carries that version, so upstream's superset is untouched, but an override written against it does not compile until it takes `&mut`, a change `cargo semver-checks` cannot see; the pull request that makes it lists it with the `api:exception` items. Satin W9 overrides it (`crates/mega-evm/src/evm/host.rs:376` at `f1d1a48d`); the legacy engine (`501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do not. + A creation's `target` was `None` in the hook's first version; it is now the created address. That changes the meaning of a field no release carries, so the pull request that makes the change lists it with the `api:exception` items. A consumer that reads `None` as "a creation" gets the address instead. Satin W9 (`5b490695`) reads `target` only for calls (`crates/mega-evm/src/evm/journal.rs:224`) and tells creations by `kind`, so it is unaffected; its count of the created account can now use the address. ### The byte pool From 42e4c3543af170ca911cbb52e68de1ecd8cd443e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 00:54:50 +0800 Subject: [PATCH 033/110] docs: REVIEW.md's serde(default) line keeps the format caveat --- REVIEW.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index 37bd3d8fa4..2fa8bb24fe 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -21,7 +21,7 @@ It is read by the automated reviewer as well as by people. | Label | Look for | |---|---| | `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream — `) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep <tag>` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along | -| `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)` so payloads that predate it still decode | +| `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)`, so that in a format that carries field names (JSON) payloads that predate it decode with the default; a positional format (bincode) cannot read them whatever the attribute, as `MEGAETH-FORK.md` (Hooks) says | | `mega:vendor` | The vendored crate keeps its upstream version number and a note of the upstream commit it was taken from; its own tests run in CI | | `mega:ci` | Workflows pin action SHAs; nothing requires a secret the repository does not have; the local equivalent of every job is documented | | `mega:rebase` | `scripts/mega/base.txt`, `scripts/mega/crates.txt`, `rust-toolchain.toml` and the baseline table move together; the upstream tag comes in as a merge commit, not a rebase; the merged tree is compared with the new tag and carried picks reconciled; the PR carries `api:exception` for upstream's own API changes | From 04e294d016308f7ec3be8a7970c1fde7e93e5984 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 09:31:21 +0800 Subject: [PATCH 034/110] docs: MEGAETH-FORK.md states the consumer rules, not a consumer inventory The hook entries named consumer trees at revisions, internal branches, local file references and a dated fetch of Foundry, and told the history of the hooks' unreleased first versions. Each such passage becomes the rule a consumer follows: what an override of `admit_code_deposit` must take, that `CompletedWrite`'s variant fields are exhaustive, that a creation is told by `kind`, what a literal of `CallInputs`, `CallOutcome` or `CreateOutcome` must name and at which defaults, and that a handler copying mainnet's settlement misses the first frame's start-charge refund. The inventory itself moves to the pull request. --- MEGAETH-FORK.md | 53 ++++++++++++++++++++----------------------------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 4824d7a085..9ab706e562 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -154,8 +154,8 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns. - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. - It was two words as an `Option<u64>`: the tracker was 88 bytes with it, and a copy of the tracker, and of every `Gas` and frame result that holds one, 16 bytes larger. - It is now a number and a flag, and the flag shares its word with the byte pool's crossing (see The byte pool); the record's encoding is unchanged, an optional number in the same place. + It takes two words of the tracker, a number and a flag, and the flag's word also holds the byte pool's crossing (see The byte pool); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words. + Encoded, the record is an optional number in the field's place. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. ### Precompile price @@ -201,9 +201,9 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Default.** `return_create` compiles to the same code, on its own and inlined into the handler on the plain and the inspected path. Inlined into a consumer's own function, the admitting default may shift its block layout; where measured, that cost one unconditional branch on one out-of-gas path and changed no success path. Where measured (callgrind, the fork's release profile), lending `gas` costs nothing: a top-level creation runs the same instruction count as without it, and a nested `CREATE` 0.06 fewer. - The `gas` parameter changed this released hook's signature, an exception to rule 1 (`api:exception`): an override does not compile until it takes the parameter. - mega-evm's `MegaContext::admit_code_deposit` is the one override found, in Satin W9 (`cz/feat/satin-w9` at `f1d1a48d`, `crates/mega-evm/src/evm/context.rs:696`) and the W8 trees before it. - The legacy engine (`cz/feat/legacy-on-fork` at `501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do not override it, and nothing built against upstream revm can, since the hook is the fork's. + The `gas` parameter is an exception to rule 1 (`api:exception`): an override written for the signature without it does not compile until it takes `gas: &mut GasTracker`, and an override that leaves `gas` alone behaves as it did without it. + A context that forwards the method to another forwards `gas` with it. + Nothing built against upstream revm overrides the hook, since the hook is the fork's. ### revm 40.0.3's journal semantics @@ -219,6 +219,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **API.** `Host::write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, whose default continues. `CompletedWrite` (`Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it; `SelfDestruct` also carries `balance`, the destructed account's balance before the write) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`. `CompletedWrite` is exhaustive on purpose: mega-evm matches it to meter each write, so a new kind is a compile error in every consumer that matches it rather than a write that passes a wildcard arm un-metered, and adding one is an `api:exception` change. + Its variants' fields are exhaustive too: a consumer that builds a variant, or matches one naming every field without `..`, names every field, `SelfDestruct`'s `balance` included, and a field added to a variant is an `api:exception` change as a new kind is. - **Contract.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call it once the write is in the journal and every charge the instruction makes has been made, its refund included, so only on the instruction's success path, on the plain and the inspected path. `gas` is the running frame's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook. A charge the hook makes that fails records as any failed charge does (see The failed-charge record), whatever the verdict. `Continue` ends the instruction as it would have ended. `OutOfGas` fails it as a failed charge does: the frame halts out of gas, and the halt records the regular gas the hook left unless a failed charge already did. `Revert(output)` ends the frame as a `Revert` with `output`, on its gas as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct. @@ -229,9 +230,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an It counts an account's write record while the account's info differs from what the transaction loaded. A destruction's two accounts can look the same after the write whether or not they had changed before it (loaded with 5, now 0, from 5 or from 7), so it needs the balance before the write, which only the instruction reads before the write. - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops metering writes. - **Default.** Continues and touches nothing. The facts are references to values the instruction holds anyway, except `SelfDestruct`'s `balance`, which the instruction reads for the hook from the running frame's own account just before the write. The journal holds that account warm, so the read loads nothing cold. - Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook. The read costs a `SELFDESTRUCT` 119 instructions, one warm journal lookup (+1.5% of a transaction that self-destructs a contract). It is a `Host::load_account_info_skip_cold_load` call the instruction did not make before, so a `Host` that counts or refuses loads sees one more. - `balance` was added to the variant after the hook's first version, which no release carries, so upstream's superset is untouched. A consumer that builds the variant, or matches it naming every field without `..`, does not compile until it names `balance`; the pull request that adds it lists it with the `api:exception` items. - Satin W9 (`cz/feat/satin-w9` at `5b490695`) does both: it matches the variant with every field in `crates/mega-evm/src/limit/record.rs:129`, and builds it in tests (`limit/record.rs:168`, `limit/ledger.rs:1442`, `evm/journal.rs:999`). The legacy engine (`501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do neither. + Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook. The read costs a `SELFDESTRUCT` 119 instructions, one warm journal lookup (+1.5% of a transaction that self-destructs a contract). It is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per `SELFDESTRUCT`. ### Frame-start hook @@ -254,15 +253,13 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. - `CREATE` and `CREATE2` compiled to the same code as without the hook until a creation's start carried its address (measured with EIP-8037 off, the default spec's path). - With EIP-8037 off, the address now costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call the instruction did not make before, so a `Host` that counts or refuses loads sees one more. - The address and a `CREATE2`'s init-code hash moved from the handler into the instruction. A creation the handler builds or fails computes no more hashes than before; the keccak instruction counts are unchanged. + For `CREATE` and `CREATE2` the hook's only cost is the start's address; the byte pool's forward is counted under The byte pool. + With EIP-8037 off, the default spec's path, the address costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per creation. + The instruction computes the address and a `CREATE2`'s init-code hash, and the handler reuses them, so a creation the handler builds or fails computes the same hashes as upstream's. A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. With EIP-8037 on, the start reads the address the EIP-8037 branch already computed from the input; that path was not measured. - `CreateInputs`' derived `PartialEq` compares the cached address and hash. With EIP-8037 off, a creation's input now holds them, as it already did with EIP-8037 on, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache. - The hook takes `&mut FrameStart` since the start charge moved onto the start; its first version took `&FrameStart`. No release carries that version, so upstream's superset is untouched, but an override written against it does not compile until it takes `&mut`, a change `cargo semver-checks` cannot see; the pull request that makes it lists it with the `api:exception` items. - Satin W9 overrides it (`crates/mega-evm/src/evm/host.rs:376` at `f1d1a48d`); the legacy engine (`501cc7cc`), alloy-evm 0.36, revm-inspectors 0.40, the op-revm fork and mega-reth (`2dc2f44ac8`, `b97b508a0b`) do not. - A creation's `target` was `None` in the hook's first version; it is now the created address. That changes the meaning of a field no release carries, so the pull request that makes the change lists it with the `api:exception` items. A consumer that reads `None` as "a creation" gets the address instead. Satin W9 (`5b490695`) reads `target` only for calls (`crates/mega-evm/src/evm/journal.rs:224`) and tells creations by `kind`, so it is unaffected; its count of the created account can now use the address. + `CreateInputs`' derived `PartialEq` compares the cached address and hash, which the input of a creation the instruction starts holds with EIP-8037 on and off, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache. + A consumer tells a creation from a call by `kind`, not by `target`: `target` is `None` only for the creations the Contract names, and an address for every other start. ### The byte pool @@ -281,7 +278,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `bytes_forward_share` of the caller's pool out of it and puts it on the frame's input as `bytes_share`: the child's pool when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). `bytes_forward_share` is `bytes_forward_percent` per cent of the pool, rounded down; a hundred or more forwards the whole pool. A forward is not a draw. - The settlement is in `handle_reservoir_remaining_gas` and follows the reservoir, not regular gas: a child that reverts or halts has its draws undone by `rollback_state_gas`, which now gives `bytes_spent` back to the pool, so what the caller absorbs is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame appends nothing; the caller kept what it did not forward. + The settlement is in `handle_reservoir_remaining_gas` and follows the reservoir, not regular gas: a child that reverts or halts has its draws undone by `rollback_state_gas`, which also gives `bytes_spent` back to the pool, so what the caller absorbs is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame appends nothing; the caller kept what it did not forward. The child's net merges into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. `rollback_state_gas` rolls the pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pool back with it. The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `bytes_spent` is then the transaction's net draw. @@ -294,7 +291,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); in a format that carries field names, encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 128 bytes (104), `InterpreterResult` 168 (144), `CallOutcome` and `FrameResult` 248 (208), `CreateOutcome` 232 (192), the outcomes with the start charge's two words. - Where measured (callgrind, the fork's release profile, against the base without the pool, the start charge and the allowance), the three figures together cost a transfer 120 instructions (+2.2%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 151 (+1.9%), a transaction that calls a precompile 135 (+0.04%; 10 of them the answer's adopted share) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. + Where measured (callgrind, the fork's release profile, against the fork without the pool, the start charge and the allowance), the three figures together cost a transfer 120 instructions (+2.2%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 151 (+1.9%), a transaction that calls a precompile 135 (+0.04%; 10 of them the answer's adopted share) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. ### The start charge @@ -307,7 +304,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. `last_frame_result` settles the first frame through `execution::settle_first_frame`, which is all of mainnet's settlement but the copy of the transaction's gas into the frame's result: the spend and the settlement of the frame, the EIP-2780 state-gas refund and the start-charge refund, each with its halt rule. - A chain whose handler overrides `last_frame_result` calls it rather than copying the mainnet body, so the start-charge refund and any later step reach it too, and applies its own rules between it and the copy, as the op-revm fork does with its pre-Regolith deposit rule. + A chain whose handler overrides `last_frame_result` calls it rather than copying the mainnet body, so the start-charge refund and any later step reach it too, and applies its own rules between it and the copy, such as the op-revm fork's pre-Regolith deposit rule. Upstream's own steps of the settlement (the spend, `handle_reservoir_remaining_gas` and the EIP-2780 refund) live in `crates/handler/src/execution/first_frame.rs`, not in `handler.rs`: a pick or a base-line merge that changes upstream's `last_frame_result` body lands there, and records the move as its conflict resolution. A frame that succeeds keeps the charge. A precompile's answer and a start the handler refuses before any frame (call depth, balance) carry the input's charge, so they refund as a frame does. @@ -316,19 +313,13 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. - **Default.** The hook declares nothing, so the fields and the refund are zero. - `settle_first_frame` is inlined: where measured (callgrind, the fork's release profile), a transfer and a transaction of 64 calls run the same instruction count as when its steps were `last_frame_result`'s body. - This entry breaks rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and gain fields (`charged_start`, and `CallInputs` also `bytes_share` and `history_allowance`), so a consumer that constructs them by literal does not compile until it names the new fields. - Their defaults are no charge (`StartCharge::default()`), an unlimited share (`u64::MAX`) and no allowance (`0`). - The consumers checked, each at a revision: - - alloy-evm 0.36 and revm-inspectors 0.40 construct them with `new` and are unaffected; `CreateInputs` has private fields and is unaffected. - - The op-revm fork (`v20.0.0-mega.3`) constructs them with `new` and compiles unchanged, but its `OpHandler::last_frame_result` copied mainnet's settlement and so missed the first frame's start-charge refund; its next release calls `settle_first_frame`, and a consumer that declares a first-frame charge needs that release. - - MegaETH's legacy engine (`cz/feat/legacy-on-fork` at `501cc7cc`) builds the first frame's `CallInputs` by literal in production (`crates/mega-evm/src/evm/execution.rs:724`) and in tests (`evm/execution.rs:2114`, `evm/precompiles.rs:432`, `limit/storage_call_stipend.rs:233`, `tests/rex5/call_too_deep_guard.rs:43`). It uses none of the new figures, but stops compiling: its repin names the three fields at their defaults and runs the legacy gate. - - Satin W9 (`cz/feat/satin-w9` at `f1d1a48d`) builds `CreateOutcome` and `CallOutcome` by literal in production (`crates/mega-evm/src/evm/frame.rs:73`, `:91`), `CallInputs` in unit and integration tests (ten sites), and `CreateOutcome` in two integration tests (`tests/system/keyless/differential.rs:950`, `tests/system/keyless/inspector.rs:69`). Its migration puts the input's charge and share on those answers, and the start-charge refund in `frame.rs`'s `settle_frame_result`, which mirrors the inner settlement. - - Foundry, master as fetched on 2026-10-21, constructs `CallOutcome` and `CreateOutcome` by literal in its cheatcodes and its inspector stack, and `CallInputs` once in its cheatcodes. It requests revm 43.0.2, alloy-evm 0.39.0 and revm-inspectors 0.44.1, so it cannot take this 40.0.3 fork through a version-satisfying patch: the literals are porting work, not a checked build. - - mega-reth's oracle executor constructs a `CallOutcome` by literal at `2dc2f44ac8`, which pins revm 27.1.0, and with `CallOutcome::new` at `b97b508a0b`, which pins revm 40.0.3. - - Foundry's and mega-reth's outcome literals already fail against the fork's base, whose outcomes carry the earlier EIP-8037 field `charged_state_gas_address` that no upstream release has; Satin W9's, production and test, were written against the fork and break here. - The base's `CallInputs` has upstream's fields, so every `CallInputs` literal (the legacy engine's, Satin W9's tests', Foundry's) breaks here for the first time. + `settle_first_frame` is inlined: where measured (callgrind, the fork's release profile), a transfer and a transaction of 64 calls run the same instruction count as with its steps written out in `last_frame_result`. + A handler that overrides `last_frame_result` with a copy of mainnet's settlement instead of calling `settle_first_frame` compiles, but does not refund the first frame's start charge; that matters only to a consumer that declares one. + This entry is an exception to rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and carry fields upstream's do not (`charged_start`, and on `CallInputs` also `bytes_share` and `history_allowance`), so a literal written for upstream's fields does not compile until it names them. + A consumer that uses none of the figures names them at their defaults, no charge (`StartCharge::default()`), an unlimited share (`u64::MAX`) and no allowance (`0`), and keeps upstream's behaviour. + A consumer that answers a start with an outcome it builds itself sets the answer's charge as the Contract says and its pool as The byte pool says. + The outcomes also carry the state-gas refund's `charged_state_gas_address` (see State-gas price), which upstream's do not, so an outcome literal written for upstream's fields does not compile against the fork whatever this entry adds; `CallInputs` has upstream's fields apart from this entry's, so this entry is what breaks its literals. + `CreateInputs` has private fields and is built with `CreateInputs::new`, so its new fields break no literal. ### The history allowance From f9a7e195a31a6e0c9c39108bdf5f2e2569088d20 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 09:44:51 +0800 Subject: [PATCH 035/110] feat(gas): resource pools in place of the byte pool, and a reservoir forward share GasTracker carries PoolId::COUNT (three) consumer-defined pools in place of the one byte pool: each has what remains, a signed net and a crossing bit, and its own forward share (GasId::pool_forward_percent, ids 252 to 250, default 100). Each is forwarded, rolled back, merged, adopted by a precompile's answer and refunded with a start charge as the byte pool was. StartCharge carries an amount per pool (PoolAmounts) beside its history, and GasTracker::refill_start_charge refunds it. A frame start takes the schedule's share of the caller's EIP-8037 reservoir out of the caller's tracker as well (GasId::reservoir_forward_percent, id 254, default 100), and GasTracker::absorb_returned_reservoir adds the child's reservoir to what the caller kept instead of replacing the caller's. The first frame takes the whole reservoir and every whole pool (GasTracker::forward_all_to_child). At the defaults every result is upstream's. --- crates/context/interface/src/cfg/gas.rs | 120 ++- .../interface/src/cfg/gas/byte_pool.rs | 511 ----------- .../context/interface/src/cfg/gas/encoding.rs | 68 +- .../context/interface/src/cfg/gas/forward.rs | 176 ++++ crates/context/interface/src/cfg/gas/pools.rs | 831 ++++++++++++++++++ .../interface/src/cfg/gas/start_charge.rs | 77 +- .../context/interface/src/cfg/gas/withheld.rs | 16 +- .../context/interface/src/cfg/gas_params.rs | 216 +++-- crates/context/interface/src/context.rs | 4 +- .../interface/src/host/instruction_hooks.rs | 19 +- crates/handler/src/execution.rs | 41 +- crates/handler/src/execution/first_frame.rs | 8 +- crates/handler/src/frame.rs | 248 ++++-- crates/handler/src/frame_data.rs | 2 +- .../handler/tests/code_deposit_admission.rs | 14 +- .../tests/{byte_pool.rs => resource_pools.rs} | 48 +- .../tests/{byte_pool.rs => resource_pools.rs} | 48 +- crates/interpreter/src/gas.rs | 2 +- crates/interpreter/src/gas/byte_pool.rs | 108 --- crates/interpreter/src/gas/pools.rs | 108 +++ .../interpreter/src/instructions/contract.rs | 14 +- .../src/instructions/instruction_hooks.rs | 18 +- .../src/interpreter_action/call_inputs.rs | 29 +- .../src/interpreter_action/call_outcome.rs | 4 +- .../src/interpreter_action/create_inputs.rs | 47 +- .../src/interpreter_action/create_outcome.rs | 4 +- crates/interpreter/src/lib.rs | 2 +- crates/interpreter/tests/instruction_hooks.rs | 21 +- .../tests/{byte_pool.rs => resource_pools.rs} | 50 +- ..._pool_serde.rs => resource_pools_serde.rs} | 42 +- 30 files changed, 1875 insertions(+), 1021 deletions(-) delete mode 100644 crates/context/interface/src/cfg/gas/byte_pool.rs create mode 100644 crates/context/interface/src/cfg/gas/forward.rs create mode 100644 crates/context/interface/src/cfg/gas/pools.rs rename crates/handler/tests/{byte_pool.rs => resource_pools.rs} (96%) rename crates/inspector/tests/{byte_pool.rs => resource_pools.rs} (94%) delete mode 100644 crates/interpreter/src/gas/byte_pool.rs create mode 100644 crates/interpreter/src/gas/pools.rs rename crates/interpreter/tests/{byte_pool.rs => resource_pools.rs} (91%) rename crates/interpreter/tests/{byte_pool_serde.rs => resource_pools_serde.rs} (75%) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index a614c2045a..32a48a0685 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -3,14 +3,17 @@ use crate::{cfg::gas_params, cfg::GasParams, Transaction}; use primitives::hardfork::SpecId; -mod byte_pool; #[cfg(feature = "serde")] mod encoding; mod failed_charge; +mod forward; mod history_allowance; +mod pools; mod start_charge; mod withheld; +pub use forward::ChildShares; +pub use pools::{PoolAmounts, PoolId}; pub use start_charge::StartCharge; pub use withheld::WithheldCrossing; @@ -53,10 +56,16 @@ pub use withheld::WithheldCrossing; /// spendable part, so a consumer that caps a creating frame must not release before /// `return_create`, or those charges escape the cap. /// -/// Beside the gas, the tracker carries two figures of the fork that are inert until a consumer -/// uses them: the byte pool ([`bytes_remaining`](Self::bytes_remaining), unlimited by default, -/// forwarded to a child frame and settled with its gas) and the history allowance -/// ([`history_allowance`](Self::history_allowance), zero by default). +/// Beside the gas, the tracker carries figures of the fork that are inert until a consumer uses +/// them: [`PoolId::COUNT`] resource pools ([`pool_remaining`](Self::pool_remaining), unlimited by +/// default, each forwarded to a child frame by its own share and settled with its gas) and the +/// history allowance ([`history_allowance`](Self::history_allowance), zero by default). +/// +/// A child frame starts with a share of its caller's reservoir and pools, which the caller's +/// tracker gives up while the child runs ([`forward_to_child`](Self::forward_to_child)); the +/// child's return adds what it left to what the caller kept +/// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)). Every schedule defined here +/// forwards the whole reservoir and every whole pool. /// /// The net counters (`state_gas_spent`, `history_gas_spent`) are `i64`, while charges and refills /// take `u64` amounts and convert them with saturation. The tracker assumes that the transaction @@ -67,13 +76,13 @@ pub use withheld::WithheldCrossing; /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). /// -/// The byte pool's net ([`bytes_spent`](Self::bytes_spent)) is an `i64` too, and assumes the same -/// bound on byte amounts: every draw and refill within `i64::MAX`, and the net with its children's -/// merged in within `±i64::MAX`. A debug build asserts it where the net moves. +/// Each pool's net ([`pool_spent`](Self::pool_spent)) is an `i64` too, and assumes the same bound +/// on its amounts: every draw and refill within `i64::MAX`, and the net with its children's merged +/// in within `±i64::MAX`. A debug build asserts it where a net moves. /// /// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and -/// the byte pool's crossing, which share a word in memory, are encoded as an optional number and -/// a `bool` in their own places. +/// the pools' crossings, which share a word in memory, are encoded as an optional number and a +/// `bool` per pool in their own places. /// /// A field the fork added decodes with its default from an encoding made before it existed only /// in a format that carries field names, such as JSON, as each field says. A format that encodes @@ -171,27 +180,26 @@ pub struct GasTracker { failed_charge_remaining: u64, /// Whether `failed_charge_remaining` holds a record. A flag apart from the record rather than /// an `Option`, whose tag would take a word of its own, so it shares a word with - /// `bytes_crossing`. + /// `pool_crossings`. failed_charge_recorded: bool, - /// The byte pool ([`bytes_remaining`](Self::bytes_remaining)): what this frame may still - /// draw. Unlimited unless a consumer sets a pool; nothing in this workspace draws it. + /// The pools ([`pool_remaining`](Self::pool_remaining)): what this frame may still draw from + /// each. Unlimited unless a consumer sets a pool; nothing in this workspace draws one. /// /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as unlimited. - bytes_remaining: u64, - /// The frame's net draw of the pool ([`bytes_spent`](Self::bytes_spent)), signed as + /// decode it as every pool unlimited. + pools_remaining: [u64; PoolId::COUNT], + /// The frame's net draw of each pool ([`pool_spent`](Self::pool_spent)), signed as /// `history_gas_spent` is, so a rollback can give it back and a merge can hand it on. /// /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as zero. - bytes_spent: i64, - /// Whether a draw failed that the pool could not pay - /// ([`bytes_crossing`](Self::bytes_crossing)). A bit, in the word `failed_charge_recorded` - /// takes. + /// decode it as zero for every pool. + pools_spent: [i64; PoolId::COUNT], + /// Whether a draw failed that a pool could not pay ([`pool_crossing`](Self::pool_crossing)), + /// a bit per pool, in the word `failed_charge_recorded` takes. /// /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as `false`. - bytes_crossing: bool, + /// decode it as no crossing on any pool. + pool_crossings: u8, /// History gas this frame may spend before it charges its budget /// ([`history_allowance`](Self::history_allowance)). Zero unless the schedule gives a value /// call's child one. @@ -202,7 +210,7 @@ pub struct GasTracker { } impl Default for GasTracker { - /// A tracker with no gas, as [`new`](Self::new) builds it, so the pool starts unlimited. + /// A tracker with no gas, as [`new`](Self::new) builds it, so the pools start unlimited. #[inline] fn default() -> Self { Self::new(0, 0, 0) @@ -225,9 +233,9 @@ impl GasTracker { withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, - bytes_remaining: u64::MAX, - bytes_spent: 0, - bytes_crossing: false, + pools_remaining: [u64::MAX; PoolId::COUNT], + pools_spent: [0; PoolId::COUNT], + pool_crossings: 0, history_allowance: 0, } } @@ -292,15 +300,22 @@ impl GasTracker { self.reservoir = val; } - /// Adopts a reservoir returned by a child frame and reconciles it with any - /// outstanding state gas spilled into regular gas. + /// Adds a reservoir returned by a child frame to the part of the reservoir this (parent) + /// frame kept, and reconciles it with any outstanding state gas spilled into regular gas. + /// + /// The child started with a share of this frame's reservoir, which this frame gave up for it + /// ([`forward_to_child`](Self::forward_to_child)); what it returns is that share, less what it + /// spent, plus what it refilled. Every schedule defined here forwards the whole reservoir, so + /// this frame kept nothing and its reservoir becomes the child's, as upstream's settlement, + /// which replaced the parent's reservoir with the child's, made it. /// /// A successful child can refill state gas charged by an ancestor (for /// example, by clearing a slot created by a sibling). Since the child does /// not inherit the ancestor's [`Self::state_gas_spilled`] counter, that /// refill initially lands in the child's reservoir. On return it must first /// restore the parent's regular gas in last-in-first-out order; only the - /// excess remains in the reservoir. + /// excess joins the reservoir. The spill is unwound from the returned reservoir only; the + /// part this frame kept stays in its reservoir. /// /// This only reconciles the funding pools. The child's signed /// `state_gas_spent` has already accounted for the refill and is merged @@ -314,7 +329,7 @@ impl GasTracker { }; self.remaining = self.remaining.saturating_add(to_remaining); self.state_gas_spilled -= to_remaining; - self.reservoir = reservoir - to_remaining; + self.reservoir = self.reservoir.saturating_add(reservoir - to_remaining); } /// Returns the state gas spent. @@ -517,10 +532,9 @@ impl GasTracker { /// pays for bytes the failing frame no longer appends. The term is zero on any chain that /// never calls [`record_history_cost`](Self::record_history_cost). /// - /// The byte pool unwinds here too: the frame's net draw ([`bytes_spent`](Self::bytes_spent)) - /// goes back to the pool, which then reads as the pool the frame started with, for the same - /// reason, and the term is zero on any chain that never calls - /// [`record_bytes`](Self::record_bytes). + /// The pools unwind here too: each pool's net draw ([`pool_spent`](Self::pool_spent)) goes + /// back to it, which then reads as the pool the frame started with, for the same reason, and + /// the term is zero on any chain that never calls [`record_pool`](Self::record_pool). /// /// On revert the resulting `remaining` (including the refilled spill) is /// returned to the parent; on halt the caller additionally zeroes `remaining` @@ -539,7 +553,7 @@ impl GasTracker { self.state_gas_spent = 0; self.state_gas_spilled = 0; self.history_gas_spent = 0; - self.rollback_bytes(); + self.rollback_pools(); } /// Refills the reservoir with state gas that is returned by 0→x→0 storage @@ -738,13 +752,15 @@ mod tests { /// A child that refills history its parent charged goes below zero, and merging it into the /// parent on success nets the two out. The merge follows the handler's order: the signed figure /// is read, added and written back, as the state counter's is, and then the parent absorbs the - /// child's reservoir. + /// child's reservoir, which the parent forwarded whole. #[test] fn test_a_child_refill_of_a_parent_charge_nets_out_on_merge() { let mut parent = GasTracker::new(1_000, 1_000, 500); assert!(parent.record_history_cost(100)); - let mut child = GasTracker::new(300, 300, parent.reservoir()); + let share = parent.reservoir(); + parent.forward_reservoir(share); + let mut child = GasTracker::new(300, 300, share); child.refill_history(100); assert_eq!(child.history_gas_spent(), -100); @@ -823,6 +839,34 @@ mod tests { assert_eq!(gas.state_gas_spilled(), 0); assert_eq!(gas.state_gas_spent(), 400); } + + /// A caller that kept part of its reservoir when it forwarded a share gets the child's + /// reservoir added to what it kept, and the returned reservoir, not the kept part, unwinds + /// the caller's outstanding spill. With nothing kept the result is the child's reservoir, as + /// a settlement that replaced the caller's reservoir gave. + #[test] + fn returned_reservoir_joins_the_part_the_caller_kept() { + // Kept 20 of 1,000, the child returns 700 of its 980. + let mut kept = GasTracker::new(1_000, 1_000, 1_000); + kept.forward_reservoir(980); + kept.absorb_returned_reservoir(700); + assert_eq!((kept.reservoir(), kept.remaining()), (720, 1_000)); + + // A spill of 150 outstanding (a successful child's, merged before the absorb): the + // returned 100 unwinds 100 of it, and the 20 kept stays in the reservoir. + let mut spilled = GasTracker::new(1_000, 850, 20); + spilled.add_state_gas_spilled(150); + spilled.absorb_returned_reservoir(100); + assert_eq!(spilled.reservoir(), 20); + assert_eq!(spilled.remaining(), 950); + assert_eq!(spilled.state_gas_spilled(), 50); + + // Nothing kept: the child's reservoir, whatever the caller held before the forward. + let mut whole = GasTracker::new(1_000, 1_000, 1_000); + whole.forward_reservoir(1_000); + whole.absorb_returned_reservoir(300); + assert_eq!(whole.reservoir(), 300); + } } /// Gas cost for operations that consume zero gas. diff --git a/crates/context/interface/src/cfg/gas/byte_pool.rs b/crates/context/interface/src/cfg/gas/byte_pool.rs deleted file mode 100644 index e42937618e..0000000000 --- a/crates/context/interface/src/cfg/gas/byte_pool.rs +++ /dev/null @@ -1,511 +0,0 @@ -//! The byte pool of a [`GasTracker`]: a budget of bytes a frame may append, forwarded to a child -//! frame and settled with the frame's gas. -//! -//! The pool is a figure beside the gas: `bytes_remaining` is what the frame may still draw, and -//! `bytes_spent` is the frame's net draw so far, signed as the state and history nets are. A draw -//! ([`record_bytes`](GasTracker::record_bytes)) the pool cannot pay fails, takes nothing and sets -//! the crossing ([`bytes_crossing`](GasTracker::bytes_crossing)). A frame that reverts or halts -//! gives its draws back ([`rollback_state_gas`](GasTracker::rollback_state_gas)), and a frame that -//! succeeds hands its net to its caller, so a caller's rollback undoes its children's draws too. -//! The pool starts unlimited (`u64::MAX`), and nothing in this workspace draws it, so a consumer -//! that sets no pool sees nothing of it. -//! -//! The net is an `i64`, as the gas nets are, while draws and refills take `u64` amounts. As the -//! tracker does for gas amounts, it assumes that every draw and refill is at most `i64::MAX` -//! bytes, and that the net, with the nets of the children merged into it, stays within -//! `±i64::MAX`, so it can be negated ([`adopt_bytes_share`](GasTracker::adopt_bytes_share)); the -//! pool itself may be anything up to the unlimited `u64::MAX`. A release build does not check -//! it: past it the net saturates, and a rollback no longer restores the pool exactly. A debug -//! build asserts it wherever the net moves ([`record_bytes`](GasTracker::record_bytes), -//! [`refill_bytes`](GasTracker::refill_bytes), [`add_bytes_spent`](GasTracker::add_bytes_spent)). -//! Reaching it takes a transaction that appends about 9.2 × 10^18 bytes. - -use super::{saturating_signed, GasTracker}; - -impl GasTracker { - /// The byte pool: what this frame may still draw. - /// - /// Starts at `u64::MAX`, an unlimited pool, in every tracker. A consumer that limits bytes - /// sets the transaction's pool ([`set_bytes_remaining`](Self::set_bytes_remaining)); every - /// child frame then receives a share of its caller's pool when it starts, and the caller keeps - /// the rest. - #[inline] - pub const fn bytes_remaining(&self) -> u64 { - self.bytes_remaining - } - - /// Sets the byte pool. The net draw ([`bytes_spent`](Self::bytes_spent)) is left as it is. - #[inline] - pub const fn set_bytes_remaining(&mut self, val: u64) { - self.bytes_remaining = val; - } - - /// The frame's net draw of the pool so far: draws less refills, plus the nets of the children - /// that succeeded. - /// - /// Negative while the frame has refilled more than it drew, as - /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. - /// It is exact while it stays within `±i64::MAX` and no single draw or refill exceeds - /// `i64::MAX` bytes, which a debug build asserts. - #[inline] - pub const fn bytes_spent(&self) -> i64 { - self.bytes_spent - } - - /// Sets the net draw. - #[inline] - pub const fn set_bytes_spent(&mut self, val: i64) { - self.bytes_spent = val; - } - - /// Adds `delta` to the net draw, saturating. Used to merge a successful child's net into its - /// caller, so a later rollback of the caller undoes the child's draws too. - #[inline] - pub const fn add_bytes_spent(&mut self, delta: i64) { - debug_assert!( - matches!(self.bytes_spent.checked_add(delta), Some(net) if net != i64::MIN), - "the byte net leaves the signed range" - ); - self.bytes_spent = self.bytes_spent.saturating_add(delta); - } - - /// Draws `cost` bytes from the pool. - /// - /// Returns `false` if the pool cannot pay, leaving it untouched and setting the crossing - /// ([`bytes_crossing`](Self::bytes_crossing)). A draw of zero always succeeds. The draw is - /// counted on [`bytes_spent`](Self::bytes_spent), so a rollback gives it back. - #[inline] - #[must_use = "a draw the pool cannot pay is the consumer's stop"] - pub const fn record_bytes(&mut self, cost: u64) -> bool { - if let Some(left) = self.bytes_remaining.checked_sub(cost) { - debug_assert!( - cost <= i64::MAX as u64 && self.bytes_spent.checked_add(cost as i64).is_some(), - "the byte net leaves the signed range" - ); - self.bytes_remaining = left; - self.bytes_spent = self.bytes_spent.saturating_add(saturating_signed(cost)); - return true; - } - self.bytes_crossing = true; - false - } - - /// Gives `amount` bytes back to the pool, for a draw the frame took back. - /// - /// The net draw falls by the same amount, below zero when the matching draw was a caller's, - /// which the merge on return reconciles, as [`refill_history`](Self::refill_history) does. - #[inline] - pub const fn refill_bytes(&mut self, amount: u64) { - debug_assert!( - amount <= i64::MAX as u64 - && matches!( - self.bytes_spent.checked_sub(amount as i64), - Some(net) if net != i64::MIN - ), - "the byte net leaves the signed range" - ); - self.bytes_remaining = self.bytes_remaining.saturating_add(amount); - self.bytes_spent = self.bytes_spent.saturating_sub(saturating_signed(amount)); - } - - /// Takes `share` out of the pool for a child frame, which starts with it as its pool. - /// - /// Not a draw: the net is unchanged, since the share comes back when the child returns - /// ([`absorb_returned_bytes`](Self::absorb_returned_bytes)). `share` is at most the pool, - /// which the schedule's forward share guarantees; more saturates at an empty pool. - #[inline] - pub const fn forward_bytes(&mut self, share: u64) { - self.bytes_remaining = self.bytes_remaining.saturating_sub(share); - } - - /// Adds back what a returning child left of its pool: its remaining pool when it succeeded, - /// the whole share it was given when it reverted or halted, since its rollback restored it. - #[inline] - pub const fn absorb_returned_bytes(&mut self, remaining: u64) { - self.bytes_remaining = self.bytes_remaining.saturating_add(remaining); - } - - /// Takes `share` as the pool this tracker started with: the pool becomes `share` less the net - /// drawn so far, so that the pool and the net add up to `share`, as a frame's do. - /// - /// For a tracker built outside a frame, such as a precompile's answer, which may have drawn - /// before it learns the share its caller forwarded. A rollback then restores `share`. A net - /// above `share` leaves an empty pool. - #[inline] - pub const fn adopt_bytes_share(&mut self, share: u64) { - self.bytes_remaining = share.saturating_add_signed(self.bytes_spent.saturating_neg()); - } - - /// The crossing: whether a draw failed that the pool could not pay, since the record was last - /// cleared, or a consumer set it with [`set_bytes_crossing`](Self::set_bytes_crossing). - /// - /// A consumer reads it from a halted frame's result to tell a frame that ran out of bytes from - /// one that ran out of gas, and turns it into a stop of its own class. The record says that a - /// draw failed, not what it asked for: the hook that drew knows its cost when the draw fails. - /// The failed draw took nothing, and no halt touches the pool, so the pool itself still reads - /// as it was at the failure until the frame's rollback. The record survives - /// [`spend_all`](Self::spend_all), starts empty in every child, and is not taken over by a - /// caller. It is a bit beside the failed-charge record - /// ([`failed_charge_remaining`](Self::failed_charge_remaining)), and each is set and cleared - /// apart from the other. - #[inline] - pub const fn bytes_crossing(&self) -> bool { - self.bytes_crossing - } - - /// Clears the record returned by [`bytes_crossing`](Self::bytes_crossing). - #[inline] - pub const fn clear_bytes_crossing(&mut self) { - self.bytes_crossing = false; - } - - /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing); `false` clears it. - /// The pool is left as it is. - /// - /// For a consumer that marks a result it produced itself, such as an answer it gave without - /// running a frame, as a failed draw, so a classifier reading the record treats it as one the - /// tracker recorded. - #[inline] - pub const fn set_bytes_crossing(&mut self, crossing: bool) { - self.bytes_crossing = crossing; - } - - /// Gives the frame's net draw back to the pool, which then reads as the pool the frame - /// started with, and zeroes the net. Part of [`rollback_state_gas`](Self::rollback_state_gas). - #[inline] - pub(super) const fn rollback_bytes(&mut self) { - self.bytes_remaining = self.bytes_remaining.saturating_add_signed(self.bytes_spent); - self.bytes_spent = 0; - } -} - -#[cfg(test)] -mod tests { - use super::GasTracker; - - /// A tracker with a pool of 1,000 bytes. - fn pool_1000() -> GasTracker { - let mut tracker = GasTracker::new(1_000, 1_000, 300); - tracker.set_bytes_remaining(1_000); - tracker - } - - /// Every tracker starts with an unlimited pool, nothing drawn and no record; `Default` is - /// `new(0, 0, 0)`. - #[test] - fn test_a_new_tracker_has_an_unlimited_pool() { - let tracker = GasTracker::new(1_000, 1_000, 300); - assert_eq!(tracker.bytes_remaining(), u64::MAX); - assert_eq!(tracker.bytes_spent(), 0); - assert!(!tracker.bytes_crossing()); - assert_eq!(GasTracker::default(), GasTracker::new(0, 0, 0)); - assert_eq!(GasTracker::default().bytes_remaining(), u64::MAX); - } - - /// The crossing shares a word with the failed-charge record and is a record of its own: a - /// failed draw records no failed charge, a failed charge records no crossing, and setting or - /// clearing either leaves the other as it is. - #[test] - fn test_the_crossing_and_the_failed_charge_record_are_independent() { - let mut tracker = pool_1000(); - assert!(!tracker.record_bytes(1_001)); - assert!(tracker.bytes_crossing()); - assert_eq!(tracker.failed_charge_remaining(), None); - - tracker.clear_bytes_crossing(); - assert!(!tracker.record_regular_cost(1_001)); - assert_eq!(tracker.failed_charge_remaining(), Some(1_000)); - assert!(!tracker.bytes_crossing()); - - tracker.set_bytes_crossing(true); - tracker.set_failed_charge_remaining(None); - assert!(tracker.bytes_crossing()); - tracker.set_failed_charge_remaining(Some(0)); - tracker.clear_bytes_crossing(); - assert_eq!(tracker.failed_charge_remaining(), Some(0)); - } - - #[test] - fn test_record_bytes_draws_the_pool_and_counts_the_draw() { - let mut tracker = pool_1000(); - - assert!(tracker.record_bytes(300)); - assert!(tracker.record_bytes(200)); - - assert_eq!(tracker.bytes_remaining(), 500); - assert_eq!(tracker.bytes_spent(), 500); - assert!(!tracker.bytes_crossing()); - } - - /// A draw the pool cannot pay takes nothing and leaves the record. - #[test] - fn test_a_draw_beyond_the_pool_fails_and_records_the_crossing() { - let mut tracker = pool_1000(); - assert!(tracker.record_bytes(900)); - - assert!(!tracker.record_bytes(101)); - - assert_eq!( - tracker.bytes_remaining(), - 100, - "the failed draw took nothing" - ); - assert_eq!(tracker.bytes_spent(), 900); - assert!(tracker.bytes_crossing()); - } - - /// A draw of exactly the pool succeeds, and a draw of zero succeeds on an empty pool. - #[test] - fn test_a_draw_of_the_whole_pool_succeeds_and_zero_always_does() { - let mut tracker = pool_1000(); - assert!(tracker.record_bytes(1_000)); - assert_eq!(tracker.bytes_remaining(), 0); - assert!(tracker.record_bytes(0)); - assert!(!tracker.bytes_crossing()); - assert!(!tracker.record_bytes(1)); - assert!(tracker.bytes_crossing()); - } - - /// The record stays until it is cleared: a later draw that succeeds leaves it, and a consumer - /// clears or sets it, which leaves the pool as it is. - #[test] - fn test_the_record_stays_until_cleared() { - let mut tracker = pool_1000(); - assert!(!tracker.record_bytes(1_001)); - assert!(tracker.record_bytes(10)); - assert!(tracker.bytes_crossing()); - - tracker.clear_bytes_crossing(); - assert!(!tracker.bytes_crossing()); - - tracker.set_bytes_crossing(true); - assert!(tracker.bytes_crossing()); - tracker.set_bytes_crossing(false); - assert!(!tracker.bytes_crossing()); - assert_eq!( - tracker.bytes_remaining(), - 990, - "setting the record leaves the pool" - ); - } - - /// The halt that follows a failed draw zeroes the regular gas and nothing else: the record - /// and the pool are still readable after it. - #[test] - fn test_the_record_and_the_pool_survive_spend_all() { - let mut tracker = pool_1000(); - assert!(tracker.record_bytes(600)); - assert!(!tracker.record_bytes(500)); - - tracker.spend_all(); - - assert_eq!(tracker.remaining(), 0); - assert_eq!(tracker.bytes_remaining(), 400); - assert!(tracker.bytes_crossing()); - } - - /// A refill gives bytes back and lowers the net, below zero when the draw was a caller's. - #[test] - fn test_refill_bytes_gives_bytes_back_and_can_take_the_net_below_zero() { - let mut tracker = pool_1000(); - assert!(tracker.record_bytes(300)); - - tracker.refill_bytes(500); - - assert_eq!(tracker.bytes_remaining(), 1_200); - assert_eq!(tracker.bytes_spent(), -200); - } - - /// Rolling a frame back gives its net draw back, so the pool reads as the pool the frame - /// started with, and nothing else of the rollback changes. - #[test] - fn test_rollback_restores_the_pool_the_frame_started_with() { - let mut tracker = pool_1000(); - assert!(tracker.record_state_cost(200)); - assert!(tracker.record_bytes(300)); - tracker.refill_bytes(100); - assert!(tracker.record_bytes(50)); - assert_eq!(tracker.bytes_remaining(), 750); - - tracker.rollback_state_gas(); - - assert_eq!(tracker.bytes_remaining(), 1_000); - assert_eq!(tracker.bytes_spent(), 0); - assert_eq!(tracker.reservoir(), 300, "the state rollback is as it was"); - assert_eq!(tracker.state_gas_spent(), 0); - } - - /// A rollback of a frame that refilled a caller's draw takes the refill back out. - #[test] - fn test_rollback_undoes_a_refill_of_a_callers_draw() { - let mut tracker = pool_1000(); - tracker.refill_bytes(100); - assert_eq!(tracker.bytes_remaining(), 1_100); - - tracker.rollback_state_gas(); - - assert_eq!(tracker.bytes_remaining(), 1_000); - assert_eq!(tracker.bytes_spent(), 0); - } - - /// The forward takes the share out of the pool without counting it as a draw; the child's - /// return adds back what it left. - #[test] - fn test_forward_takes_the_share_and_the_return_adds_back_what_the_child_left() { - let mut parent = pool_1000(); - parent.forward_bytes(980); - assert_eq!(parent.bytes_remaining(), 20); - assert_eq!(parent.bytes_spent(), 0, "a forward is not a draw"); - - parent.absorb_returned_bytes(700); - assert_eq!(parent.bytes_remaining(), 720); - } - - /// A tracker that adopts a share keeps its net and takes the share less the net as its pool, - /// so a rollback restores the share: after draws, after a refill below zero, and after none. - #[test] - fn test_an_adopted_share_less_the_net_is_the_pool() { - for (name, draws, refills, pool) in [ - ("drew", 40, 0, 860), - ("refilled", 0, 25, 925), - ("nothing", 0, 0, 900), - ] { - let mut answer = GasTracker::new(500, 500, 0); - assert!(answer.record_bytes(draws)); - answer.refill_bytes(refills); - let spent = answer.bytes_spent(); - - answer.adopt_bytes_share(900); - - assert_eq!(answer.bytes_remaining(), pool, "{name}"); - assert_eq!(answer.bytes_spent(), spent, "{name}: the net is kept"); - answer.rollback_state_gas(); - assert_eq!( - answer.bytes_remaining(), - 900, - "{name}: a rollback restores the share" - ); - } - } - - /// A forward above the pool and a return above `u64::MAX` saturate rather than wrap. - #[test] - fn test_forward_and_return_saturate() { - let mut tracker = pool_1000(); - tracker.forward_bytes(5_000); - assert_eq!(tracker.bytes_remaining(), 0); - - let mut unlimited = GasTracker::new(1, 1, 0); - unlimited.absorb_returned_bytes(1); - assert_eq!(unlimited.bytes_remaining(), u64::MAX); - } - - /// The net is exact up to `i64::MAX` bytes: a draw of it from the unlimited pool, a refill of - /// it, and a child's net of it merged into its caller each roll back to the pool they started - /// from. - #[test] - fn test_the_net_is_exact_up_to_the_signed_maximum() { - const MAX: u64 = i64::MAX as u64; - - let mut drawn = GasTracker::new(1_000, 1_000, 0); - assert!(drawn.record_bytes(MAX)); - assert_eq!(drawn.bytes_spent(), i64::MAX); - drawn.rollback_state_gas(); - assert_eq!(drawn.bytes_remaining(), u64::MAX); - - let mut refilled = GasTracker::new(1_000, 1_000, 0); - refilled.set_bytes_remaining(0); - refilled.refill_bytes(MAX); - assert_eq!(refilled.bytes_spent(), -i64::MAX); - refilled.rollback_state_gas(); - assert_eq!(refilled.bytes_remaining(), 0); - - let mut caller = GasTracker::new(1_000, 1_000, 0); - caller.forward_bytes(u64::MAX); - let mut child = GasTracker::new(500, 500, 0); - assert!(child.record_bytes(MAX)); - caller.add_bytes_spent(child.bytes_spent()); - caller.absorb_returned_bytes(child.bytes_remaining()); - assert_eq!(caller.bytes_spent(), i64::MAX); - caller.rollback_state_gas(); - assert_eq!(caller.bytes_remaining(), u64::MAX); - } - - /// One byte past it the net would saturate, and a rollback would leave the unlimited pool a - /// byte short: a debug build refuses the draw. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "the byte net leaves the signed range")] - fn test_a_draw_past_the_signed_maximum_panics_in_a_debug_build() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - let _ = tracker.record_bytes(i64::MAX as u64 + 1); - } - - /// Below `-i64::MAX` the net would be `i64::MIN`, whose negation saturates, so a share - /// adopted against it would be a byte short: a debug build refuses the refill that gets there. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "the byte net leaves the signed range")] - fn test_a_refill_past_the_signed_minimum_panics_in_a_debug_build() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_bytes_remaining(0); - tracker.refill_bytes(i64::MAX as u64); - tracker.refill_bytes(1); - } - - /// With the default pool, forwarding the whole pool and settling a child's return brings the - /// caller back to the pool less what the child drew and kept: a failed child's draws come - /// back whole. - #[test] - fn test_an_unlimited_pool_forwarded_whole_comes_back_less_the_childs_draws() { - for fails in [false, true] { - let mut parent = GasTracker::new(1_000, 1_000, 0); - let share = parent.bytes_remaining(); - parent.forward_bytes(share); - assert_eq!(parent.bytes_remaining(), 0); - - let mut child = GasTracker::new(500, 500, 0); - child.set_bytes_remaining(share); - assert!(child.record_bytes(100)); - if fails { - child.rollback_state_gas(); - } else { - parent.add_bytes_spent(child.bytes_spent()); - } - parent.absorb_returned_bytes(child.bytes_remaining()); - - let (pool, spent) = if fails { - (u64::MAX, 0) - } else { - (u64::MAX - 100, 100) - }; - assert_eq!(parent.bytes_remaining(), pool, "fails: {fails}"); - assert_eq!(parent.bytes_spent(), spent, "fails: {fails}"); - } - } - - /// JSON encodings made before the pool existed decode with an unlimited pool, nothing drawn and - /// no record; the pool's own encoding round-trips. - #[cfg(feature = "serde")] - #[test] - fn test_serde_round_trip_and_older_json_payloads() { - let mut tracker = pool_1000(); - assert!(tracker.record_bytes(300)); - assert!(!tracker.record_bytes(800)); - let encoded = serde_json::to_value(tracker).unwrap(); - assert_eq!( - serde_json::from_value::<GasTracker>(encoded.clone()).unwrap(), - tracker - ); - - let mut older = encoded; - let fields = older.as_object_mut().unwrap(); - fields.remove("bytes_remaining"); - fields.remove("bytes_spent"); - fields.remove("bytes_crossing"); - let decoded = serde_json::from_value::<GasTracker>(older).unwrap(); - assert_eq!(decoded.bytes_remaining(), u64::MAX); - assert_eq!(decoded.bytes_spent(), 0); - assert!(!decoded.bytes_crossing()); - } -} diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index a935d52bf8..bf2d8ecbdf 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -1,16 +1,16 @@ //! The encoding of a [`GasTracker`]. //! //! In memory the failed-charge record is a number and a flag, and the flag shares a word with the -//! byte pool's crossing. Encoded, the tracker keeps the fields, names and order the derived -//! encoding had: the failed-charge record is an optional number in its place, and the crossing a -//! `bool` in its own. +//! pools' crossings, a bit each. Encoded, the tracker keeps the fields, names and order the derived +//! encoding had: the failed-charge record is an optional number in its place, and the crossings a +//! `bool` per pool in their own. //! //! A format that carries field names, such as JSON, decodes an encoding made before a field //! existed with the field's default. A format that encodes by position, such as bincode, does not: -//! the fields that predate the pool keep their places, but an encoding made before the pool's +//! the fields that predate the pools keep their places, but an encoding made before the pools' //! fields were added lacks them and cannot be read (see [`GasTracker`]). -use super::{GasTracker, WithheldCrossing}; +use super::{GasTracker, PoolId, WithheldCrossing}; /// A [`GasTracker`] as it is encoded: its fields in their order, with the defaults an encoding /// made before a field existed decodes to in a format that carries field names. Each field of the @@ -32,20 +32,20 @@ pub(super) struct Encoded { withheld_crossing: Option<WithheldCrossing>, #[serde(default)] failed_charge_remaining: Option<u64>, - #[serde(default = "unlimited_bytes")] - bytes_remaining: u64, + #[serde(default = "unlimited_pools")] + pools_remaining: [u64; PoolId::COUNT], #[serde(default)] - bytes_spent: i64, + pools_spent: [i64; PoolId::COUNT], #[serde(default)] - bytes_crossing: bool, + pool_crossings: [bool; PoolId::COUNT], #[serde(default)] history_allowance: u64, } -/// The pool a tracker starts with, and the pool an encoding that predates it decodes to in a +/// The pools a tracker starts with, and the pools an encoding that predates them decodes to in a /// format that carries field names. -const fn unlimited_bytes() -> u64 { - u64::MAX +const fn unlimited_pools() -> [u64; PoolId::COUNT] { + [u64::MAX; PoolId::COUNT] } impl From<GasTracker> for Encoded { @@ -61,9 +61,9 @@ impl From<GasTracker> for Encoded { withheld: tracker.withheld, withheld_crossing: tracker.withheld_crossing, failed_charge_remaining: tracker.failed_charge_remaining(), - bytes_remaining: tracker.bytes_remaining, - bytes_spent: tracker.bytes_spent, - bytes_crossing: tracker.bytes_crossing, + pools_remaining: tracker.pools_remaining, + pools_spent: tracker.pools_spent, + pool_crossings: PoolId::ALL.map(|pool| tracker.pool_crossing(pool)), history_allowance: tracker.history_allowance, } } @@ -83,41 +83,48 @@ impl From<Encoded> for GasTracker { withheld_crossing: encoded.withheld_crossing, failed_charge_remaining: 0, failed_charge_recorded: false, - bytes_remaining: encoded.bytes_remaining, - bytes_spent: encoded.bytes_spent, - bytes_crossing: encoded.bytes_crossing, + pools_remaining: encoded.pools_remaining, + pools_spent: encoded.pools_spent, + pool_crossings: 0, history_allowance: encoded.history_allowance, }; tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); + for (pool, crossing) in PoolId::ALL.into_iter().zip(encoded.pool_crossings) { + tracker.set_pool_crossing(pool, crossing); + } tracker } } #[cfg(test)] mod tests { - use super::super::GasTracker; + use super::super::{GasTracker, PoolId}; /// A tracker with every field away from its default: part of its regular gas withheld, a /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a refund, - /// a pool drawn and a draw refused, and an allowance. + /// a pool drawn, a draw refused on another, a pool refilled below zero, and an allowance. fn every_field_set() -> GasTracker { let mut tracker = GasTracker::new(1_000, 400, 300); tracker.withhold(100); assert!(!tracker.record_regular_cost(350)); assert!(tracker.record_state_cost(500)); - tracker.set_bytes_remaining(900); - assert!(tracker.record_bytes(20)); - assert!(!tracker.record_bytes(10_000)); + let [first, second, third] = PoolId::ALL; + tracker.set_pool_remaining(first, 900); + assert!(tracker.record_pool(first, 20)); + tracker.set_pool_remaining(second, 7); + assert!(!tracker.record_pool(second, 10_000)); + tracker.set_pool_remaining(third, 0); + tracker.refill_pool(third, 5); tracker.set_history_allowance(160); tracker.record_refund(-3); tracker } /// The encoding has the fields, the names and the order it had before the failed-charge - /// record and the crossing shared a word, so a format that encodes by position finds every + /// record and the crossings shared a word, so a format that encodes by position finds every /// field in the place it had then; the failed-charge record is an optional number, and the - /// crossing a `bool`. Such a format still cannot read an encoding made before the pool's - /// fields were added, which lacks them. + /// crossings a `bool` per pool. Such a format still cannot read an encoding made before the + /// pools' fields were added, which lacks them. #[test] fn test_the_encoding_keeps_its_fields_and_their_order() { assert_eq!( @@ -126,8 +133,8 @@ mod tests { r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#, r#""state_gas_spilled":200,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#, - r#""bytes_remaining":880,"bytes_spent":20,"bytes_crossing":true,"#, - r#""history_allowance":160}"#, + r#""pools_remaining":[880,7,5],"pools_spent":[20,0,-5],"#, + r#""pool_crossings":[false,true,false],"history_allowance":160}"#, ) ); assert_eq!( @@ -136,8 +143,9 @@ mod tests { r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#, r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#, r#""withheld_crossing":null,"failed_charge_remaining":null,"#, - r#""bytes_remaining":18446744073709551615,"bytes_spent":0,"bytes_crossing":false,"#, - r#""history_allowance":0}"#, + r#""pools_remaining":[18446744073709551615,18446744073709551615,"#, + r#"18446744073709551615],"pools_spent":[0,0,0],"#, + r#""pool_crossings":[false,false,false],"history_allowance":0}"#, ) ); } diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs new file mode 100644 index 0000000000..4cf527a3fb --- /dev/null +++ b/crates/context/interface/src/cfg/gas/forward.rs @@ -0,0 +1,176 @@ +//! What a frame start takes out of its caller's [`GasTracker`] for the child frame, beside the +//! regular gas: a share of the EIP-8037 reservoir and of each pool. +//! +//! The caller keeps the rest while the child runs, and the child's return adds what the child left +//! back to what the caller kept ([`absorb_returned_reservoir`](GasTracker::absorb_returned_reservoir), +//! [`absorb_returned_pools`](GasTracker::absorb_returned_pools)). The shares are the schedule's +//! ([`GasParams::reservoir_forward_share`], [`GasParams::pool_forward_share`]); every schedule +//! defined here forwards the whole reservoir and every whole pool, which is upstream's forward. + +use super::{GasTracker, PoolAmounts, PoolId}; +use crate::cfg::GasParams; + +/// What a child frame's tracker starts with beside its regular gas, taken out of its caller's: its +/// reservoir and its pools. +/// +/// Returned by [`GasTracker::forward_to_child`] and [`GasTracker::forward_all_to_child`]; the +/// frame's input carries it (`reservoir` and `pool_shares`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct ChildShares { + /// The child's reservoir. + pub reservoir: u64, + /// The child's pools. + pub pools: PoolAmounts, +} + +impl GasTracker { + /// Takes `share` out of the reservoir for a child frame, which starts with it as its + /// reservoir. + /// + /// Not a charge: no counter moves, since the share comes back when the child returns + /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)). `share` is at most the + /// reservoir, which the schedule's forward share guarantees; more saturates at an empty + /// reservoir. + #[inline] + pub const fn forward_reservoir(&mut self, share: u64) { + self.reservoir = self.reservoir.saturating_sub(share); + } + + /// Takes the schedule's shares of the reservoir and of each pool out of this, the caller's, + /// tracker for a child frame, and returns them: what the child's tracker starts with. + /// + /// The `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` instructions + /// call it once the frame-start hook has answered, so the shares are of the reservoir and the + /// pools as the hook left them. A consumer that builds a child frame's input itself calls it + /// too, so that the child's return, which adds what the child left to what the caller kept, + /// gives the caller back exactly what it forwarded. + #[inline] + pub fn forward_to_child(&mut self, params: &GasParams) -> ChildShares { + let reservoir = params.reservoir_forward_share(self.reservoir); + self.forward_reservoir(reservoir); + let mut pools = PoolAmounts::ZERO; + for pool in PoolId::ALL { + let share = params.pool_forward_share(pool, self.pool_remaining(pool)); + self.forward_pool(pool, share); + pools.set(pool, share); + } + ChildShares { reservoir, pools } + } + + /// Takes the whole reservoir and every whole pool out of this tracker for a child frame, and + /// returns them. + /// + /// For the transaction's frame, which takes everything the transaction's tracker holds: the + /// schedule's shares apply to the frames below it. + #[inline] + pub const fn forward_all_to_child(&mut self) -> ChildShares { + let shares = ChildShares { + reservoir: self.reservoir, + pools: self.pools_remaining(), + }; + self.reservoir = 0; + self.set_pools_remaining(PoolAmounts::ZERO); + shares + } +} + +#[cfg(test)] +mod tests { + use super::{ChildShares, GasTracker, PoolAmounts, PoolId}; + use crate::cfg::{GasId, GasParams}; + use primitives::hardfork::SpecId; + + /// A caller with a reservoir of 1,000 and pools of 1,000, 500 and 100. + fn caller() -> GasTracker { + let mut tracker = GasTracker::new(10_000, 10_000, 1_000); + for (pool, amount) in PoolId::ALL.into_iter().zip([1_000, 500, 100]) { + tracker.set_pool_remaining(pool, amount); + } + tracker + } + + /// Every schedule forwards everything: the child gets the whole reservoir and every whole + /// pool, and the caller keeps nothing of them while the child runs. + #[test] + fn test_every_schedule_forwards_everything() { + for spec in [SpecId::FRONTIER, SpecId::OSAKA, SpecId::AMSTERDAM] { + let params = GasParams::new_spec(spec); + let mut tracker = caller(); + + let shares = tracker.forward_to_child(¶ms); + + assert_eq!(shares.reservoir, 1_000, "{spec:?}"); + assert_eq!( + PoolId::ALL.map(|pool| shares.pools.get(pool)), + [1_000, 500, 100], + "{spec:?}" + ); + assert_eq!(tracker.reservoir(), 0, "{spec:?}"); + assert_eq!(tracker.pools_remaining(), PoolAmounts::ZERO, "{spec:?}"); + assert_eq!( + tracker.remaining(), + 10_000, + "{spec:?}: regular gas is not touched" + ); + } + } + + /// Each figure is forwarded by its own share, rounded down, and the caller keeps the rest. + #[test] + fn test_each_share_is_the_schedules() { + let mut params = GasParams::new_spec(SpecId::AMSTERDAM); + params.override_gas([ + (GasId::reservoir_forward_percent(), 98), + (GasId::pool_forward_percent(PoolId::new(0)), 98), + (GasId::pool_forward_percent(PoolId::new(1)), 50), + (GasId::pool_forward_percent(PoolId::new(2)), 0), + ]); + let mut tracker = caller(); + assert!(tracker.record_state_cost(1)); + + let shares = tracker.forward_to_child(¶ms); + + // 98% of 999 is 979.02; 98% of 1,000 is 980; half of 500 is 250. + assert_eq!(shares.reservoir, 979); + assert_eq!( + PoolId::ALL.map(|pool| shares.pools.get(pool)), + [980, 250, 0] + ); + assert_eq!(tracker.reservoir(), 20); + assert_eq!( + PoolId::ALL.map(|pool| tracker.pool_remaining(pool)), + [20, 250, 100] + ); + assert_eq!(tracker.state_gas_spent(), 1, "a forward is not a charge"); + } + + /// The transaction's frame takes everything, whatever the schedule. + #[test] + fn test_the_first_frame_takes_everything() { + let mut tracker = caller(); + + let shares = tracker.forward_all_to_child(); + + assert_eq!( + shares, + ChildShares { + reservoir: 1_000, + pools: PoolAmounts::ZERO + .with(PoolId::new(0), 1_000) + .with(PoolId::new(1), 500) + .with(PoolId::new(2), 100), + } + ); + assert_eq!(tracker.reservoir(), 0); + assert_eq!(tracker.pools_remaining(), PoolAmounts::ZERO); + } + + /// A forward above the reservoir saturates at an empty reservoir. + #[test] + fn test_a_reservoir_forward_saturates() { + let mut tracker = caller(); + tracker.forward_reservoir(5_000); + assert_eq!(tracker.reservoir(), 0); + } +} diff --git a/crates/context/interface/src/cfg/gas/pools.rs b/crates/context/interface/src/cfg/gas/pools.rs new file mode 100644 index 0000000000..38e121b4d6 --- /dev/null +++ b/crates/context/interface/src/cfg/gas/pools.rs @@ -0,0 +1,831 @@ +//! The resource pools of a [`GasTracker`]: budgets beside the gas, each forwarded to a child frame +//! by its own share and settled with the frame's gas. +//! +//! A tracker carries [`PoolId::COUNT`] pools, which a consumer gives their meaning (bytes appended, +//! records written, entries created); the fork knows them only by index. Each pool is a figure +//! beside the gas: `pool_remaining` is what the frame may still draw, and `pool_spent` the frame's +//! net draw so far, signed as the state and history nets are. A draw +//! ([`record_pool`](GasTracker::record_pool)) the pool cannot pay fails, takes nothing and sets +//! the pool's crossing ([`pool_crossing`](GasTracker::pool_crossing)). A frame that reverts or +//! halts gives its draws on every pool back ([`rollback_state_gas`](GasTracker::rollback_state_gas)), +//! and a frame that succeeds hands its nets to its caller, so a caller's rollback undoes its +//! children's draws too. Every pool starts unlimited (`u64::MAX`), and nothing in this workspace +//! draws one, so a consumer that sets no pool sees nothing of them. +//! +//! The nets are `i64`, as the gas nets are, while draws and refills take `u64` amounts. As the +//! tracker does for gas amounts, it assumes that every draw and refill is at most `i64::MAX`, and +//! that each net, with the nets of the children merged into it, stays within `±i64::MAX`, so it can +//! be negated ([`adopt_pool_share`](GasTracker::adopt_pool_share)); a pool itself may be anything +//! up to the unlimited `u64::MAX`. A release build does not check it: past it the net saturates, +//! and a rollback no longer restores the pool exactly. A debug build asserts it wherever a net +//! moves ([`record_pool`](GasTracker::record_pool), [`refill_pool`](GasTracker::refill_pool), +//! [`add_pool_spent`](GasTracker::add_pool_spent)). Reaching it takes about 9.2 × 10^18 units. + +use super::{saturating_signed, GasTracker}; + +/// One of a tracker's resource pools, by index. +/// +/// A consumer names the pools it uses with constants (`const PAGES: PoolId = PoolId::new(0);`); +/// [`new`](Self::new) refuses an index the tracker has no pool for, so such a constant does not +/// compile. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PoolId(u8); + +impl PoolId { + /// How many pools a tracker carries. + pub const COUNT: usize = 3; + + /// Every pool, in index order. + pub const ALL: [Self; Self::COUNT] = [Self(0), Self(1), Self(2)]; + + /// The pool at `index`. + /// + /// # Panics + /// + /// If `index` is not below [`COUNT`](Self::COUNT); in a constant, that is a compile error. + #[inline] + pub const fn new(index: usize) -> Self { + assert!(index < Self::COUNT, "a tracker has no pool at this index"); + Self(index as u8) + } + + /// The pool's index, below [`COUNT`](Self::COUNT). + #[inline] + pub const fn index(self) -> usize { + self.0 as usize + } +} + +/// An amount for each of a tracker's pools: the shares a child frame's pools start with +/// ([`ChildShares::pools`](super::ChildShares::pools)), or what a frame start drew from its +/// caller's pools ([`StartCharge::pools`](super::StartCharge::pools)). +/// +/// Encoded as a sequence of one number per pool, in index order. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr( + feature = "serde", + derive(serde::Serialize, serde::Deserialize), + serde(transparent) +)] +pub struct PoolAmounts([u64; PoolId::COUNT]); + +impl PoolAmounts { + /// Nothing in any pool. The default. + pub const ZERO: Self = Self([0; PoolId::COUNT]); + + /// Every pool unlimited: what a tracker starts with, and the share of a child whose caller + /// limits nothing. + pub const UNLIMITED: Self = Self([u64::MAX; PoolId::COUNT]); + + /// The amount for `pool`. + #[inline] + pub const fn get(&self, pool: PoolId) -> u64 { + self.0[pool.index()] + } + + /// Sets the amount for `pool`. + #[inline] + pub const fn set(&mut self, pool: PoolId, amount: u64) { + self.0[pool.index()] = amount; + } + + /// These amounts, with `amount` for `pool`. + #[inline] + #[must_use] + pub const fn with(mut self, pool: PoolId, amount: u64) -> Self { + self.set(pool, amount); + self + } + + /// Whether every amount is zero. + #[inline] + pub const fn is_zero(&self) -> bool { + let mut index = 0; + while index < PoolId::COUNT { + if self.0[index] != 0 { + return false; + } + index += 1; + } + true + } +} + +impl GasTracker { + /// The pool: what this frame may still draw from it. + /// + /// Starts at `u64::MAX`, an unlimited pool, in every tracker. A consumer that limits the pool + /// sets the transaction's ([`set_pool_remaining`](Self::set_pool_remaining)); every child + /// frame then receives a share of its caller's pool when it starts, and the caller keeps the + /// rest. + #[inline] + pub const fn pool_remaining(&self, pool: PoolId) -> u64 { + self.pools_remaining[pool.index()] + } + + /// Sets the pool. Its net draw ([`pool_spent`](Self::pool_spent)) is left as it is. + #[inline] + pub const fn set_pool_remaining(&mut self, pool: PoolId, val: u64) { + self.pools_remaining[pool.index()] = val; + } + + /// Every pool: what this frame may still draw from each. + #[inline] + pub const fn pools_remaining(&self) -> PoolAmounts { + PoolAmounts(self.pools_remaining) + } + + /// Sets every pool, as a child frame's are set to the shares its caller forwarded. The nets + /// are left as they are. + #[inline] + pub const fn set_pools_remaining(&mut self, pools: PoolAmounts) { + self.pools_remaining = pools.0; + } + + /// The frame's net draw of the pool so far: draws less refills, plus the nets of the children + /// that succeeded. + /// + /// Negative while the frame has refilled more than it drew, as + /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. + /// It is exact while it stays within `±i64::MAX` and no single draw or refill exceeds + /// `i64::MAX`, which a debug build asserts. + #[inline] + pub const fn pool_spent(&self, pool: PoolId) -> i64 { + self.pools_spent[pool.index()] + } + + /// Sets the pool's net draw. + #[inline] + pub const fn set_pool_spent(&mut self, pool: PoolId, val: i64) { + self.pools_spent[pool.index()] = val; + } + + /// Adds `delta` to the pool's net draw, saturating. Used to merge a successful child's net + /// into its caller, so a later rollback of the caller undoes the child's draws too. + #[inline] + pub const fn add_pool_spent(&mut self, pool: PoolId, delta: i64) { + let spent = &mut self.pools_spent[pool.index()]; + debug_assert!( + matches!(spent.checked_add(delta), Some(net) if net != i64::MIN), + "a pool's net leaves the signed range" + ); + *spent = spent.saturating_add(delta); + } + + /// Draws `cost` from the pool. + /// + /// Returns `false` if the pool cannot pay, leaving it untouched and setting its crossing + /// ([`pool_crossing`](Self::pool_crossing)). A draw of zero always succeeds. The draw is + /// counted on [`pool_spent`](Self::pool_spent), so a rollback gives it back. + #[inline] + #[must_use = "a draw the pool cannot pay is the consumer's stop"] + pub const fn record_pool(&mut self, pool: PoolId, cost: u64) -> bool { + let index = pool.index(); + if let Some(left) = self.pools_remaining[index].checked_sub(cost) { + debug_assert!( + cost <= i64::MAX as u64 + && self.pools_spent[index].checked_add(cost as i64).is_some(), + "a pool's net leaves the signed range" + ); + self.pools_remaining[index] = left; + self.pools_spent[index] = + self.pools_spent[index].saturating_add(saturating_signed(cost)); + return true; + } + self.pool_crossings |= 1 << index; + false + } + + /// Gives `amount` back to the pool, for a draw the frame took back. + /// + /// The net draw falls by the same amount, below zero when the matching draw was a caller's, + /// which the merge on return reconciles, as [`refill_history`](Self::refill_history) does. + #[inline] + pub const fn refill_pool(&mut self, pool: PoolId, amount: u64) { + let index = pool.index(); + debug_assert!( + amount <= i64::MAX as u64 + && matches!( + self.pools_spent[index].checked_sub(amount as i64), + Some(net) if net != i64::MIN + ), + "a pool's net leaves the signed range" + ); + self.pools_remaining[index] = self.pools_remaining[index].saturating_add(amount); + self.pools_spent[index] = self.pools_spent[index].saturating_sub(saturating_signed(amount)); + } + + /// Takes `share` out of the pool for a child frame, which starts with it as its pool. + /// + /// Not a draw: the net is unchanged, since the share comes back when the child returns + /// ([`absorb_returned_pool`](Self::absorb_returned_pool)). `share` is at most the pool, which + /// the schedule's forward share guarantees; more saturates at an empty pool. + #[inline] + pub const fn forward_pool(&mut self, pool: PoolId, share: u64) { + let remaining = &mut self.pools_remaining[pool.index()]; + *remaining = remaining.saturating_sub(share); + } + + /// Adds back what a returning child left of its pool: its remaining pool when it succeeded, + /// the whole share it was given when it reverted or halted, since its rollback restored it. + #[inline] + pub const fn absorb_returned_pool(&mut self, pool: PoolId, remaining: u64) { + let own = &mut self.pools_remaining[pool.index()]; + *own = own.saturating_add(remaining); + } + + /// Takes `share` as the pool this tracker started with: the pool becomes `share` less the net + /// drawn so far, so that the pool and the net add up to `share`, as a frame's do. + /// + /// For a tracker built outside a frame, such as a precompile's answer, which may have drawn + /// before it learns the share its caller forwarded. A rollback then restores `share`. A net + /// above `share` leaves an empty pool. + #[inline] + pub const fn adopt_pool_share(&mut self, pool: PoolId, share: u64) { + let index = pool.index(); + self.pools_remaining[index] = + share.saturating_add_signed(self.pools_spent[index].saturating_neg()); + } + + /// [`adopt_pool_share`](Self::adopt_pool_share) for every pool. + #[inline] + pub const fn adopt_pool_shares(&mut self, shares: PoolAmounts) { + let mut index = 0; + while index < PoolId::COUNT { + self.adopt_pool_share(PoolId::ALL[index], shares.0[index]); + index += 1; + } + } + + /// Settles every pool of a returning child into this, its caller's, tracker: the child's nets + /// merge into this tracker's when `kept` (the child succeeded), and what the child left of + /// each pool is absorbed back whatever its end, as + /// [`absorb_returned_pool`](Self::absorb_returned_pool) says. A child that failed has already + /// rolled its draws back. + #[inline] + pub const fn absorb_returned_pools(&mut self, child: &Self, kept: bool) { + let mut index = 0; + while index < PoolId::COUNT { + let pool = PoolId::ALL[index]; + if kept { + self.add_pool_spent(pool, child.pools_spent[index]); + } + self.absorb_returned_pool(pool, child.pools_remaining[index]); + index += 1; + } + } + + /// The pool's crossing: whether a draw failed that the pool could not pay, since the record + /// was last cleared, or a consumer set it with [`set_pool_crossing`](Self::set_pool_crossing). + /// + /// A consumer reads it from a halted frame's result to tell a frame that ran out of the pool + /// from one that ran out of gas, and turns it into a stop of its own class. The record says + /// that a draw failed, not what it asked for: the hook that drew knows its cost when the draw + /// fails. The failed draw took nothing, and no halt touches a pool, so the pool itself still + /// reads as it was at the failure until the frame's rollback. The record survives + /// [`spend_all`](Self::spend_all), starts empty in every child, and is not taken over by a + /// caller. Each pool's is a bit beside the failed-charge record + /// ([`failed_charge_remaining`](Self::failed_charge_remaining)), and each is set and cleared + /// apart from the others. + #[inline] + pub const fn pool_crossing(&self, pool: PoolId) -> bool { + self.pool_crossings & (1 << pool.index()) != 0 + } + + /// Clears the record returned by [`pool_crossing`](Self::pool_crossing). + #[inline] + pub const fn clear_pool_crossing(&mut self, pool: PoolId) { + self.pool_crossings &= !(1 << pool.index()); + } + + /// Sets the record returned by [`pool_crossing`](Self::pool_crossing); `false` clears it. The + /// pool is left as it is. + /// + /// For a consumer that marks a result it produced itself, such as an answer it gave without + /// running a frame, as a failed draw, so a classifier reading the record treats it as one the + /// tracker recorded. + #[inline] + pub const fn set_pool_crossing(&mut self, pool: PoolId, crossing: bool) { + if crossing { + self.pool_crossings |= 1 << pool.index(); + } else { + self.clear_pool_crossing(pool); + } + } + + /// Gives every pool's net draw back to it, which then reads as the pool the frame started + /// with, and zeroes the nets. Part of [`rollback_state_gas`](Self::rollback_state_gas). + #[inline] + pub(super) const fn rollback_pools(&mut self) { + let mut index = 0; + while index < PoolId::COUNT { + self.pools_remaining[index] = + self.pools_remaining[index].saturating_add_signed(self.pools_spent[index]); + self.pools_spent[index] = 0; + index += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::{GasTracker, PoolAmounts, PoolId}; + + /// A tracker with every pool at 1,000. + fn pools_1000() -> GasTracker { + let mut tracker = GasTracker::new(1_000, 1_000, 300); + for pool in PoolId::ALL { + tracker.set_pool_remaining(pool, 1_000); + } + tracker + } + + /// The pools other than `pool` as they were set: 1,000, nothing drawn, no record. + fn assert_untouched_but(tracker: &GasTracker, pool: PoolId) { + for other in PoolId::ALL.into_iter().filter(|&other| other != pool) { + assert_eq!(tracker.pool_remaining(other), 1_000, "{other:?}"); + assert_eq!(tracker.pool_spent(other), 0, "{other:?}"); + assert!(!tracker.pool_crossing(other), "{other:?}"); + } + } + + /// The tracker has the pools `ALL` names, each by its index; an index past them is refused. + #[test] + fn test_the_pools_are_named_by_index() { + assert_eq!(PoolId::COUNT, 3); + for (index, pool) in PoolId::ALL.into_iter().enumerate() { + assert_eq!(pool, PoolId::new(index)); + assert_eq!(pool.index(), index); + } + } + + #[test] + #[should_panic(expected = "a tracker has no pool at this index")] + fn test_an_index_past_the_pools_is_refused() { + let _ = PoolId::new(PoolId::COUNT); + } + + /// Amounts are read and set by pool; zero is the default and unlimited is every pool at + /// `u64::MAX`. + #[test] + fn test_pool_amounts_are_read_and_set_by_pool() { + assert_eq!(PoolAmounts::default(), PoolAmounts::ZERO); + assert!(PoolAmounts::ZERO.is_zero()); + let amounts = PoolAmounts::ZERO.with(PoolId::new(1), 40); + assert!(!amounts.is_zero()); + assert_eq!( + PoolId::ALL.map(|pool| amounts.get(pool)), + [0, 40, 0], + "only the pool set moves" + ); + assert_eq!( + PoolId::ALL.map(|pool| PoolAmounts::UNLIMITED.get(pool)), + [u64::MAX; 3] + ); + } + + /// Every tracker starts with every pool unlimited, nothing drawn and no record; `Default` is + /// `new(0, 0, 0)`. + #[test] + fn test_a_new_tracker_has_unlimited_pools() { + let tracker = GasTracker::new(1_000, 1_000, 300); + assert_eq!(tracker.pools_remaining(), PoolAmounts::UNLIMITED); + for pool in PoolId::ALL { + assert_eq!(tracker.pool_spent(pool), 0); + assert!(!tracker.pool_crossing(pool)); + } + assert_eq!(GasTracker::default(), GasTracker::new(0, 0, 0)); + assert_eq!( + GasTracker::default().pools_remaining(), + PoolAmounts::UNLIMITED + ); + } + + /// Each pool is a figure of its own: a draw, a failed draw, a refill, a forward and a record + /// on one leave the others as they were. + #[test] + fn test_each_pool_moves_alone() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(pool, 300)); + assert!(!tracker.record_pool(pool, 800)); + tracker.refill_pool(pool, 50); + tracker.forward_pool(pool, 100); + tracker.absorb_returned_pool(pool, 20); + tracker.add_pool_spent(pool, 7); + + assert_eq!(tracker.pool_remaining(pool), 670, "{pool:?}"); + assert_eq!(tracker.pool_spent(pool), 257, "{pool:?}"); + assert!(tracker.pool_crossing(pool), "{pool:?}"); + assert_untouched_but(&tracker, pool); + + tracker.clear_pool_crossing(pool); + assert!(!tracker.pool_crossing(pool), "{pool:?}"); + tracker.set_pool_crossing(pool, true); + assert_untouched_but(&tracker, pool); + } + } + + /// A pool's crossing shares a word with the failed-charge record and is a record of its own: a + /// failed draw records no failed charge, a failed charge records no crossing, and setting or + /// clearing either leaves the other as it is. + #[test] + fn test_the_crossings_and_the_failed_charge_record_are_independent() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(!tracker.record_pool(pool, 1_001)); + assert!(tracker.pool_crossing(pool)); + assert_eq!(tracker.failed_charge_remaining(), None); + + tracker.clear_pool_crossing(pool); + assert!(!tracker.record_regular_cost(1_001)); + assert_eq!(tracker.failed_charge_remaining(), Some(1_000)); + assert!(!tracker.pool_crossing(pool)); + + tracker.set_pool_crossing(pool, true); + tracker.set_failed_charge_remaining(None); + assert!(tracker.pool_crossing(pool)); + tracker.set_failed_charge_remaining(Some(0)); + tracker.clear_pool_crossing(pool); + assert_eq!(tracker.failed_charge_remaining(), Some(0)); + } + } + + #[test] + fn test_record_pool_draws_the_pool_and_counts_the_draw() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + + assert!(tracker.record_pool(pool, 300)); + assert!(tracker.record_pool(pool, 200)); + + assert_eq!(tracker.pool_remaining(pool), 500); + assert_eq!(tracker.pool_spent(pool), 500); + assert!(!tracker.pool_crossing(pool)); + } + } + + /// A draw the pool cannot pay takes nothing and leaves the record. + #[test] + fn test_a_draw_beyond_the_pool_fails_and_records_the_crossing() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(pool, 900)); + + assert!(!tracker.record_pool(pool, 101)); + + assert_eq!( + tracker.pool_remaining(pool), + 100, + "the failed draw took nothing" + ); + assert_eq!(tracker.pool_spent(pool), 900); + assert!(tracker.pool_crossing(pool)); + } + } + + /// A draw of exactly the pool succeeds, and a draw of zero succeeds on an empty pool. + #[test] + fn test_a_draw_of_the_whole_pool_succeeds_and_zero_always_does() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(pool, 1_000)); + assert_eq!(tracker.pool_remaining(pool), 0); + assert!(tracker.record_pool(pool, 0)); + assert!(!tracker.pool_crossing(pool)); + assert!(!tracker.record_pool(pool, 1)); + assert!(tracker.pool_crossing(pool)); + } + } + + /// The record stays until it is cleared: a later draw that succeeds leaves it, and a consumer + /// clears or sets it, which leaves the pool as it is. + #[test] + fn test_the_record_stays_until_cleared() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(!tracker.record_pool(pool, 1_001)); + assert!(tracker.record_pool(pool, 10)); + assert!(tracker.pool_crossing(pool)); + + tracker.clear_pool_crossing(pool); + assert!(!tracker.pool_crossing(pool)); + + tracker.set_pool_crossing(pool, true); + assert!(tracker.pool_crossing(pool)); + tracker.set_pool_crossing(pool, false); + assert!(!tracker.pool_crossing(pool)); + assert_eq!( + tracker.pool_remaining(pool), + 990, + "setting the record leaves the pool" + ); + } + } + + /// The halt that follows a failed draw zeroes the regular gas and nothing else: the record + /// and the pool are still readable after it. + #[test] + fn test_the_record_and_the_pool_survive_spend_all() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(pool, 600)); + assert!(!tracker.record_pool(pool, 500)); + + tracker.spend_all(); + + assert_eq!(tracker.remaining(), 0); + assert_eq!(tracker.pool_remaining(pool), 400); + assert!(tracker.pool_crossing(pool)); + } + } + + /// A refill gives back and lowers the net, below zero when the draw was a caller's. + #[test] + fn test_refill_pool_gives_back_and_can_take_the_net_below_zero() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(pool, 300)); + + tracker.refill_pool(pool, 500); + + assert_eq!(tracker.pool_remaining(pool), 1_200); + assert_eq!(tracker.pool_spent(pool), -200); + } + } + + /// Rolling a frame back gives every pool's net draw back, so each reads as the pool the frame + /// started with, and nothing else of the rollback changes. + #[test] + fn test_rollback_restores_every_pool_the_frame_started_with() { + let mut tracker = pools_1000(); + assert!(tracker.record_state_cost(200)); + let [first, second, third] = PoolId::ALL; + assert!(tracker.record_pool(first, 300)); + tracker.refill_pool(first, 100); + assert!(tracker.record_pool(first, 50)); + assert!(tracker.record_pool(second, 999)); + tracker.refill_pool(third, 40); + assert_eq!( + PoolId::ALL.map(|pool| tracker.pool_remaining(pool)), + [750, 1, 1_040] + ); + + tracker.rollback_state_gas(); + + for pool in PoolId::ALL { + assert_eq!(tracker.pool_remaining(pool), 1_000, "{pool:?}"); + assert_eq!(tracker.pool_spent(pool), 0, "{pool:?}"); + } + assert_eq!(tracker.reservoir(), 300, "the state rollback is as it was"); + assert_eq!(tracker.state_gas_spent(), 0); + } + + /// A rollback of a frame that refilled a caller's draw takes the refill back out. + #[test] + fn test_rollback_undoes_a_refill_of_a_callers_draw() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + tracker.refill_pool(pool, 100); + assert_eq!(tracker.pool_remaining(pool), 1_100); + + tracker.rollback_state_gas(); + + assert_eq!(tracker.pool_remaining(pool), 1_000); + assert_eq!(tracker.pool_spent(pool), 0); + } + } + + /// The forward takes the share out of the pool without counting it as a draw; the child's + /// return adds back what it left. + #[test] + fn test_forward_takes_the_share_and_the_return_adds_back_what_the_child_left() { + for pool in PoolId::ALL { + let mut parent = pools_1000(); + parent.forward_pool(pool, 980); + assert_eq!(parent.pool_remaining(pool), 20); + assert_eq!(parent.pool_spent(pool), 0, "a forward is not a draw"); + + parent.absorb_returned_pool(pool, 700); + assert_eq!(parent.pool_remaining(pool), 720); + } + } + + /// A child's pools settle into its caller's: on success its nets merge and what it left comes + /// back; on failure its rollback gave its draws back first, and no net merges. + #[test] + fn test_the_pools_of_a_returning_child_settle_into_its_caller() { + for kept in [true, false] { + let mut parent = pools_1000(); + let shares = [900, 500, 1_000]; + let mut child = GasTracker::new(500, 500, 0); + for (pool, share) in PoolId::ALL.into_iter().zip(shares) { + parent.forward_pool(pool, share); + child.set_pool_remaining(pool, share); + } + let [first, second, third] = PoolId::ALL; + assert!(child.record_pool(first, 100)); + assert!(child.record_pool(second, 20)); + child.refill_pool(third, 5); + if !kept { + child.rollback_state_gas(); + } + + parent.absorb_returned_pools(&child, kept); + + let (pools, spent) = if kept { + ([900, 980, 1_005], [100, 20, -5]) + } else { + ([1_000; 3], [0; 3]) + }; + assert_eq!( + PoolId::ALL.map(|pool| parent.pool_remaining(pool)), + pools, + "kept: {kept}" + ); + assert_eq!( + PoolId::ALL.map(|pool| parent.pool_spent(pool)), + spent, + "kept: {kept}" + ); + } + } + + /// A tracker that adopts a share keeps its net and takes the share less the net as its pool, + /// so a rollback restores the share: after draws, after a refill below zero, and after none. + #[test] + fn test_an_adopted_share_less_the_net_is_the_pool() { + for pool in PoolId::ALL { + for (name, draws, refills, expected) in [ + ("drew", 40, 0, 860), + ("refilled", 0, 25, 925), + ("nothing", 0, 0, 900), + ] { + let mut answer = GasTracker::new(500, 500, 0); + assert!(answer.record_pool(pool, draws)); + answer.refill_pool(pool, refills); + let spent = answer.pool_spent(pool); + + answer.adopt_pool_share(pool, 900); + + assert_eq!(answer.pool_remaining(pool), expected, "{pool:?} {name}"); + assert_eq!( + answer.pool_spent(pool), + spent, + "{pool:?} {name}: the net is kept" + ); + answer.rollback_state_gas(); + assert_eq!( + answer.pool_remaining(pool), + 900, + "{pool:?} {name}: a rollback restores the share" + ); + } + } + } + + /// Every pool adopts its own share. + #[test] + fn test_adopted_shares_go_to_their_pools() { + let mut answer = GasTracker::new(500, 500, 0); + let [first, ..] = PoolId::ALL; + assert!(answer.record_pool(first, 40)); + + answer.adopt_pool_shares(PoolAmounts::ZERO.with(first, 900).with(PoolId::new(2), 7)); + + assert_eq!( + PoolId::ALL.map(|pool| answer.pool_remaining(pool)), + [860, 0, 7] + ); + } + + /// A forward above the pool and a return above `u64::MAX` saturate rather than wrap. + #[test] + fn test_forward_and_return_saturate() { + for pool in PoolId::ALL { + let mut tracker = pools_1000(); + tracker.forward_pool(pool, 5_000); + assert_eq!(tracker.pool_remaining(pool), 0); + + let mut unlimited = GasTracker::new(1, 1, 0); + unlimited.absorb_returned_pool(pool, 1); + assert_eq!(unlimited.pool_remaining(pool), u64::MAX); + } + } + + /// The net is exact up to `i64::MAX`: a draw of it from the unlimited pool, a refill of it, + /// and a child's net of it merged into its caller each roll back to the pool they started + /// from. + #[test] + fn test_the_net_is_exact_up_to_the_signed_maximum() { + const MAX: u64 = i64::MAX as u64; + for pool in PoolId::ALL { + let mut drawn = GasTracker::new(1_000, 1_000, 0); + assert!(drawn.record_pool(pool, MAX)); + assert_eq!(drawn.pool_spent(pool), i64::MAX); + drawn.rollback_state_gas(); + assert_eq!(drawn.pool_remaining(pool), u64::MAX); + + let mut refilled = GasTracker::new(1_000, 1_000, 0); + refilled.set_pool_remaining(pool, 0); + refilled.refill_pool(pool, MAX); + assert_eq!(refilled.pool_spent(pool), -i64::MAX); + refilled.rollback_state_gas(); + assert_eq!(refilled.pool_remaining(pool), 0); + + let mut caller = GasTracker::new(1_000, 1_000, 0); + caller.forward_pool(pool, u64::MAX); + let mut child = GasTracker::new(500, 500, 0); + assert!(child.record_pool(pool, MAX)); + caller.absorb_returned_pools(&child, true); + assert_eq!(caller.pool_spent(pool), i64::MAX); + caller.rollback_state_gas(); + assert_eq!(caller.pool_remaining(pool), u64::MAX); + } + } + + /// One unit past it the net would saturate, and a rollback would leave the unlimited pool one + /// short: a debug build refuses the draw. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "a pool's net leaves the signed range")] + fn test_a_draw_past_the_signed_maximum_panics_in_a_debug_build() { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + let _ = tracker.record_pool(PoolId::new(2), i64::MAX as u64 + 1); + } + + /// Below `-i64::MAX` the net would be `i64::MIN`, whose negation saturates, so a share + /// adopted against it would be one short: a debug build refuses the refill that gets there. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "a pool's net leaves the signed range")] + fn test_a_refill_past_the_signed_minimum_panics_in_a_debug_build() { + let pool = PoolId::new(1); + let mut tracker = GasTracker::new(1_000, 1_000, 0); + tracker.set_pool_remaining(pool, 0); + tracker.refill_pool(pool, i64::MAX as u64); + tracker.refill_pool(pool, 1); + } + + /// With the default pools, forwarding every pool whole and settling a child's return brings + /// the caller back to each pool less what the child drew and kept: a failed child's draws + /// come back whole. + #[test] + fn test_unlimited_pools_forwarded_whole_come_back_less_the_childs_draws() { + for fails in [false, true] { + let mut parent = GasTracker::new(1_000, 1_000, 0); + let shares = parent.pools_remaining(); + for pool in PoolId::ALL { + parent.forward_pool(pool, shares.get(pool)); + } + assert_eq!(parent.pools_remaining(), PoolAmounts::ZERO); + + let mut child = GasTracker::new(500, 500, 0); + child.set_pools_remaining(shares); + for pool in PoolId::ALL { + assert!(child.record_pool(pool, 100)); + } + if fails { + child.rollback_state_gas(); + } + parent.absorb_returned_pools(&child, !fails); + + let (remaining, spent) = if fails { + (u64::MAX, 0) + } else { + (u64::MAX - 100, 100) + }; + for pool in PoolId::ALL { + assert_eq!(parent.pool_remaining(pool), remaining, "fails: {fails}"); + assert_eq!(parent.pool_spent(pool), spent, "fails: {fails}"); + } + } + } + + /// JSON encodings made before the pools existed decode with unlimited pools, nothing drawn and + /// no record; the pools' own encoding round-trips. + #[cfg(feature = "serde")] + #[test] + fn test_serde_round_trip_and_older_json_payloads() { + let mut tracker = pools_1000(); + assert!(tracker.record_pool(PoolId::new(0), 300)); + assert!(!tracker.record_pool(PoolId::new(2), 1_800)); + let encoded = serde_json::to_value(tracker).unwrap(); + assert_eq!( + serde_json::from_value::<GasTracker>(encoded.clone()).unwrap(), + tracker + ); + + let mut older = encoded; + let fields = older.as_object_mut().unwrap(); + fields.remove("pools_remaining"); + fields.remove("pools_spent"); + fields.remove("pool_crossings"); + let decoded = serde_json::from_value::<GasTracker>(older).unwrap(); + assert_eq!(decoded.pools_remaining(), PoolAmounts::UNLIMITED); + for pool in PoolId::ALL { + assert_eq!(decoded.pool_spent(pool), 0); + assert!(!decoded.pool_crossing(pool)); + } + } +} diff --git a/crates/context/interface/src/cfg/gas/start_charge.rs b/crates/context/interface/src/cfg/gas/start_charge.rs index 16bac4676e..94fce17e02 100644 --- a/crates/context/interface/src/cfg/gas/start_charge.rs +++ b/crates/context/interface/src/cfg/gas/start_charge.rs @@ -6,10 +6,12 @@ //! failure gives back is the start charge. The hook declares it on the start //! ([`FrameStart::charge`](crate::host::FrameStart::charge)), the instruction copies it onto the //! frame's input when the hook admits the start, and the handler refunds it to the caller when the -//! frame fails. +//! frame fails ([`GasTracker::refill_start_charge`]). -/// What a frame start charged its caller and the frame's failure gives back: history gas and -/// bytes of the pool. +use super::{GasTracker, PoolAmounts, PoolId}; + +/// What a frame start charged its caller and the frame's failure gives back: history gas and an +/// amount of each pool. /// /// Built with [`StartCharge::new`], so a later field is not a breaking change. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -17,23 +19,76 @@ #[non_exhaustive] pub struct StartCharge { /// History gas the start charged, refilled with - /// [`refill_history`](super::GasTracker::refill_history) when the frame fails. + /// [`refill_history`](GasTracker::refill_history) when the frame fails. pub history: u64, - /// Bytes the start drew from the pool, refilled with - /// [`refill_bytes`](super::GasTracker::refill_bytes) when the frame fails. - pub bytes: u64, + /// What the start drew from each of the caller's pools, refilled with + /// [`refill_pool`](GasTracker::refill_pool) when the frame fails. + pub pools: PoolAmounts, } impl StartCharge { - /// A start charge of `history` gas and `bytes` of the pool. + /// A start charge of `history` gas and `pools` from the caller's pools. #[inline] - pub const fn new(history: u64, bytes: u64) -> Self { - Self { history, bytes } + pub const fn new(history: u64, pools: PoolAmounts) -> Self { + Self { history, pools } } /// Nothing to refund. #[inline] pub const fn is_zero(&self) -> bool { - self.history == 0 && self.bytes == 0 + self.history == 0 && self.pools.is_zero() + } +} + +impl GasTracker { + /// Gives `charge` back to this, the caller's, tracker: its history gas with + /// [`refill_history`](Self::refill_history), and each pool's amount with + /// [`refill_pool`](Self::refill_pool). + /// + /// The handler calls it when a frame whose start charged `charge` fails + /// (`FrameResult::refundable_start_charge`); a consumer that settles a frame's result itself + /// calls it on the same condition. + #[inline] + pub const fn refill_start_charge(&mut self, charge: StartCharge) { + self.refill_history(charge.history); + let mut index = 0; + while index < PoolId::COUNT { + let pool = PoolId::ALL[index]; + self.refill_pool(pool, charge.pools.get(pool)); + index += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::{GasTracker, PoolAmounts, PoolId, StartCharge}; + + /// The refill gives the history back the way `refill_history` does and each pool's amount to + /// its own pool, so a caller that drew them is where it was before the start. + #[test] + fn test_a_refilled_start_charge_puts_the_caller_back() { + let mut caller = GasTracker::new(10_000, 10_000, 0); + for pool in PoolId::ALL { + caller.set_pool_remaining(pool, 1_000); + } + let before = caller; + let charge = StartCharge::new( + 3_520, + PoolAmounts::ZERO + .with(PoolId::new(0), 40) + .with(PoolId::new(1), 1), + ); + assert!(caller.record_history_cost(charge.history)); + for pool in PoolId::ALL { + assert!(caller.record_pool(pool, charge.pools.get(pool))); + } + + caller.refill_start_charge(charge); + + assert_eq!(caller, before); + assert!(!charge.is_zero()); + assert!(StartCharge::default().is_zero()); + assert!(!StartCharge::new(0, PoolAmounts::ZERO.with(PoolId::new(2), 1)).is_zero()); } } diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 57756fa4e8..4c71cddd7c 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,14 +236,14 @@ mod tests { assert_eq!(size_of::<Option<WithheldCrossing>>(), size_of::<u64>()); } - /// The tracker is 112 bytes: 72 with the withheld part and its record, two words more for the - /// failed-charge record, whose second word also holds the byte pool's crossing, and three more - /// for the byte pool and its net and the history allowance. Copies of the tracker, and of - /// every `Gas` and frame result that holds one, grow with it, so a new field is measured - /// before this changes. - #[test] - fn test_the_tracker_is_112_bytes() { - assert_eq!(size_of::<GasTracker>(), 112); + /// The tracker is 144 bytes: 72 with the withheld part and its record, two words more for the + /// failed-charge record, whose second word also holds the pools' crossings, two words for + /// each of the three pools (the pool and its net), and one for the history allowance. Copies + /// of the tracker, and of every `Gas` and frame result that holds one, grow with it, so a new + /// field is measured before this changes. + #[test] + fn test_the_tracker_is_144_bytes() { + assert_eq!(size_of::<GasTracker>(), 144); } /// Withholding moves gas between the parts and leaves the total alone. diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index 6885bee849..fda49d41b4 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -1,7 +1,7 @@ //! Gas table for dynamic gas constants. use crate::{ - cfg::gas::{self, get_tokens_in_calldata, InitialAndFloorGas}, + cfg::gas::{self, get_tokens_in_calldata, InitialAndFloorGas, PoolId}, context::SStoreResult, transaction::AccessListItemTr as _, Transaction, TransactionType, @@ -232,9 +232,12 @@ impl GasParams { gas::NON_ZERO_BYTE_MULTIPLIER; table[GasId::tx_token_cost().as_usize()] = gas::STANDARD_TOKEN_COST; table[GasId::tx_base_stipend().as_usize()] = 21000; - // The fork's entries: a child frame receives the whole byte pool, and a value call's - // child no history allowance, on every spec. - table[GasId::bytes_forward_percent().as_usize()] = 100; + // The fork's entries: a child frame receives the whole reservoir and every whole pool, + // and a value call's child no history allowance, on every spec. + table[GasId::reservoir_forward_percent().as_usize()] = 100; + for pool in PoolId::ALL { + table[GasId::pool_forward_percent(pool).as_usize()] = 100; + } if spec.is_enabled_in(SpecId::HOMESTEAD) { table[GasId::tx_create_cost().as_usize()] = gas::CREATE; @@ -817,19 +820,24 @@ impl GasParams { .saturating_mul(len as u64) } - /// The share of a caller's byte pool a child frame receives when it starts: - /// [`bytes_forward_percent`](GasId::bytes_forward_percent) per cent of `pool`, rounded down. + /// The share of a caller's `remaining` in `pool` a child frame receives when it starts: + /// [`pool_forward_percent`](GasId::pool_forward_percent) per cent of it, rounded down. /// /// A hundred or more, which every schedule here sets, forwards the whole pool. #[inline] - pub fn bytes_forward_share(&self, pool: u64) -> u64 { - let percent = self.get(GasId::bytes_forward_percent()); - if percent >= 100 { - return pool; - } - // `floor(pool * percent / 100)` without widening: the quotient's part is exact, and the - // remainder's part is below a hundred times a hundred. - pool / 100 * percent + pool % 100 * percent / 100 + pub fn pool_forward_share(&self, pool: PoolId, remaining: u64) -> u64 { + percent_of(remaining, self.get(GasId::pool_forward_percent(pool))) + } + + /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: + /// [`reservoir_forward_percent`](GasId::reservoir_forward_percent) per cent of it, rounded + /// down. The caller keeps the rest while the child runs. + /// + /// A hundred or more, which every schedule here sets, forwards the whole reservoir, as + /// EIP-8037 does. + #[inline] + pub fn reservoir_forward_share(&self, reservoir: u64) -> u64 { + percent_of(reservoir, self.get(GasId::reservoir_forward_percent())) } /// History gas a value call's child may spend before it charges its budget @@ -1301,8 +1309,11 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", - x if x == Self::bytes_forward_percent().as_u8() => "bytes_forward_percent", + x if x == Self::reservoir_forward_percent().as_u8() => "reservoir_forward_percent", x if x == Self::call_history_allowance().as_u8() => "call_history_allowance", + x if x == Self::pool_forward_percent(PoolId::new(0)).as_u8() => "pool0_forward_percent", + x if x == Self::pool_forward_percent(PoolId::new(1)).as_u8() => "pool1_forward_percent", + x if x == Self::pool_forward_percent(PoolId::new(2)).as_u8() => "pool2_forward_percent", _ => "unknown", } } @@ -1378,8 +1389,11 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), - "bytes_forward_percent" => Some(Self::bytes_forward_percent()), + "reservoir_forward_percent" => Some(Self::reservoir_forward_percent()), "call_history_allowance" => Some(Self::call_history_allowance()), + "pool0_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(0))), + "pool1_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(1))), + "pool2_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(2))), _ => None, } } @@ -1671,14 +1685,14 @@ impl GasId { Self::new(255) } - /// The share of a caller's byte pool a child frame receives when it starts, in per cent of - /// the pool, rounded down ([`GasParams::bytes_forward_share`]). A hundred, the whole pool, - /// on every schedule defined here; a chain that keeps part of the pool for the caller lowers - /// it. + /// The share of a caller's EIP-8037 reservoir a child frame receives when it starts, in per + /// cent of the reservoir, rounded down ([`GasParams::reservoir_forward_share`]). A hundred, + /// the whole reservoir as EIP-8037 forwards it, on every schedule defined here; a chain that + /// keeps part of the reservoir for the caller while the child runs lowers it. /// /// A fork id, allocated from the top of the table below /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). - pub const fn bytes_forward_percent() -> GasId { + pub const fn reservoir_forward_percent() -> GasId { Self::new(254) } @@ -1688,10 +1702,32 @@ impl GasId { /// schedule defined here. /// /// A fork id, allocated from the top of the table below - /// [`bytes_forward_percent`](Self::bytes_forward_percent). + /// [`reservoir_forward_percent`](Self::reservoir_forward_percent). pub const fn call_history_allowance() -> GasId { Self::new(253) } + + /// The share of a caller's `pool` a child frame receives when it starts, in per cent of what + /// the caller has left of it, rounded down ([`GasParams::pool_forward_share`]). A hundred, + /// the whole pool, on every schedule defined here; a chain that keeps part of a pool for the + /// caller lowers it. + /// + /// Fork ids, one per pool, allocated from the top of the table below + /// [`call_history_allowance`](Self::call_history_allowance): pool `i` at `252 - i`. + pub const fn pool_forward_percent(pool: PoolId) -> GasId { + Self::new(252 - pool.index() as u8) + } +} + +/// `percent` per cent of `value`, rounded down; a hundred or more is the whole of it. +#[inline] +const fn percent_of(value: u64, percent: u64) -> u64 { + if percent >= 100 { + return value; + } + // `floor(value * percent / 100)` without widening: the quotient's part is exact, and the + // remainder's part is below a hundred times a hundred. + value / 100 * percent + value % 100 * percent / 100 } #[cfg(test)] @@ -1766,23 +1802,25 @@ mod tests { // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated // from the top of the table so upstream's next sequential id does not collide with them: - // `code_deposit_history_gas` at 255, `bytes_forward_percent` at 254 and - // `call_history_allowance` at 253. Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain([253, 254, 255]).collect(); + // `code_deposit_history_gas` at 255, `reservoir_forward_percent` at 254, + // `call_history_allowance` at 253 and the three pools' forward percents at 252, 251 and + // 250. Every one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain(250..=255).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), - 52, - "Expected 52 unique GasIds, found {}", + 55, + "Expected 55 unique GasIds, found {}", unique_names.len() ); } - /// Every schedule forwards the whole pool: the share is the pool itself, `u64::MAX` - /// included. A schedule that sets a percentage forwards that much, rounded down, and one at - /// or above a hundred forwards the whole pool. + /// Every schedule forwards every whole pool and the whole reservoir: the share is the amount + /// itself, `u64::MAX` included. A schedule that sets a percentage forwards that much, rounded + /// down, and one at or above a hundred forwards the whole amount. #[test] - fn test_bytes_forward_share_defaults_to_the_whole_pool() { + fn test_forward_shares_default_to_the_whole_amount() { + let amounts = [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX]; for spec in [ SpecId::FRONTIER, SpecId::LONDON, @@ -1791,42 +1829,110 @@ mod tests { SpecId::default(), ] { let params = GasParams::new_spec(spec); - assert_eq!(params.get(GasId::bytes_forward_percent()), 100, "{spec:?}"); - for pool in [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX] { - assert_eq!(params.bytes_forward_share(pool), pool, "{spec:?} {pool}"); + assert_eq!( + params.get(GasId::reservoir_forward_percent()), + 100, + "{spec:?}" + ); + for amount in amounts { + assert_eq!(params.reservoir_forward_share(amount), amount, "{spec:?}"); + } + for pool in PoolId::ALL { + assert_eq!( + params.get(GasId::pool_forward_percent(pool)), + 100, + "{spec:?} {pool:?}" + ); + for amount in amounts { + assert_eq!( + params.pool_forward_share(pool, amount), + amount, + "{spec:?} {pool:?} {amount}" + ); + } } } + // Each entry is its own: the reservoir at 98, the pools at 98, 50 and 0. let mut params = GasParams::new_spec(SpecId::OSAKA); - params.override_gas([(GasId::bytes_forward_percent(), 98)]); - assert_eq!(params.bytes_forward_share(0), 0); - assert_eq!(params.bytes_forward_share(1), 0); - assert_eq!(params.bytes_forward_share(100), 98); - assert_eq!(params.bytes_forward_share(149), 146, "rounded down"); - assert_eq!(params.bytes_forward_share(1_000), 980); + params.override_gas([ + (GasId::reservoir_forward_percent(), 98), + (GasId::pool_forward_percent(PoolId::new(0)), 98), + (GasId::pool_forward_percent(PoolId::new(1)), 50), + (GasId::pool_forward_percent(PoolId::new(2)), 0), + ]); + let share = |amount| { + ( + params.reservoir_forward_share(amount), + PoolId::ALL.map(|pool| params.pool_forward_share(pool, amount)), + ) + }; + assert_eq!(share(0), (0, [0, 0, 0])); + assert_eq!(share(1), (0, [0, 0, 0])); + assert_eq!(share(100), (98, [98, 50, 0])); + assert_eq!(share(149), (146, [146, 74, 0]), "rounded down"); + assert_eq!(share(1_000), (980, [980, 500, 0])); + let max_98 = (u64::MAX as u128 * 98 / 100) as u64; assert_eq!( - params.bytes_forward_share(u64::MAX), - (u64::MAX as u128 * 98 / 100) as u64, + share(u64::MAX), + (max_98, [max_98, u64::MAX / 2, 0]), "no overflow" ); - params.override_gas([(GasId::bytes_forward_percent(), 0)]); - assert_eq!(params.bytes_forward_share(1_000), 0); - params.override_gas([(GasId::bytes_forward_percent(), 250)]); + params.override_gas([(GasId::reservoir_forward_percent(), 250)]); assert_eq!( - params.bytes_forward_share(1_000), + params.reservoir_forward_share(1_000), 1_000, - "capped at the whole pool" + "capped at the whole reservoir" ); - assert_eq!( - GasId::from_name("bytes_forward_percent"), - Some(GasId::bytes_forward_percent()) - ); - assert_eq!( - GasId::bytes_forward_percent().name(), - "bytes_forward_percent" - ); + for (id, name) in [ + ( + GasId::reservoir_forward_percent(), + "reservoir_forward_percent", + ), + ( + GasId::pool_forward_percent(PoolId::new(0)), + "pool0_forward_percent", + ), + ( + GasId::pool_forward_percent(PoolId::new(1)), + "pool1_forward_percent", + ), + ( + GasId::pool_forward_percent(PoolId::new(2)), + "pool2_forward_percent", + ), + ] { + assert_eq!(GasId::from_name(name), Some(id)); + assert_eq!(id.name(), name); + } + } + + /// REX's forward of regular gas to a child, `remaining - remaining * 2 / 100` rounded down, is + /// upstream's `call_stipend_reduction` with the quotient 50 in place of EIP-150's 64: the two + /// agree on every amount, so a chain that forwards 98/100 of its regular gas needs no fork + /// change, only the schedule entry. + #[test] + fn test_a_call_stipend_reduction_of_50_forwards_98_per_cent() { + let mut params = GasParams::new_spec(SpecId::OSAKA); + params.override_gas([(GasId::call_stipend_reduction(), 50)]); + let rex = |remaining: u64| (remaining as u128 - remaining as u128 * 2 / 100) as u64; + let amounts = (0..10_000) + .chain([1_000_000, 16_777_216, 30_000_000, 1 << 40]) + .chain([u64::MAX - 49, u64::MAX - 1, u64::MAX]); + for remaining in amounts { + assert_eq!( + params.call_stipend_reduction(remaining), + rex(remaining), + "{remaining}" + ); + } + // Worked examples: 98% of 1,000 is 980; of 1,049 is 1,028.02, kept as 1,029 by REX's + // rule, which takes 2% rounded down (20) away. + assert_eq!(params.call_stipend_reduction(1_000), 980); + assert_eq!(params.call_stipend_reduction(1_049), 1_029); + assert_eq!(params.call_stipend_reduction(99), 98); } /// No schedule gives a value call's child a history allowance. diff --git a/crates/context/interface/src/context.rs b/crates/context/interface/src/context.rs index 946595bcb1..9c98f740f2 100644 --- a/crates/context/interface/src/context.rs +++ b/crates/context/interface/src/context.rs @@ -183,8 +183,8 @@ pub trait ContextTr: Host { /// /// `gas` is the creating frame's tracker, as [`gas_after`](CodeDeposit::gas_after) reads it /// when the hook is called. The hook may debit and credit it, for instance draw the deployed - /// code's bytes from the frame's byte pool - /// ([`GasTracker::record_bytes`](crate::cfg::gas::GasTracker::record_bytes)); a charge it + /// code from one of the frame's pools + /// ([`GasTracker::record_pool`](crate::cfg::gas::GasTracker::record_pool)); a charge it /// makes that fails records as any failed charge does. /// /// - `Ok(())` admits it: the checkpoint is committed and the code is written, as without this diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index 7e3c645a61..363edf6679 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -7,7 +7,7 @@ //! nothing and let the instruction go on. use crate::{ - cfg::gas::StartCharge, + cfg::gas::{PoolAmounts, StartCharge}, context::{SStoreResult, SelfDestructResult}, }; use primitives::{Address, Bytes, StorageKey, U256}; @@ -108,12 +108,15 @@ pub struct FrameStart { /// `CALLCODE` or `DELEGATECALL`, the calling frame's own account, which runs the called /// account's code. /// - /// For a `CREATE` or `CREATE2`, the address the creation takes, computed once: the handler - /// builds the frame at the same address without computing it again. `None` only for a - /// creation the handler fails before it takes an address, which reaches the hook only when - /// EIP-8037 is off: an endowment above the caller's balance, a caller's nonce at its maximum, - /// or a creating frame at the depth limit. With EIP-8037 on, the instruction ends such a - /// creation before the hook. + /// For a `CREATE` or `CREATE2`, the address the creation would take, computed once: the + /// handler builds the frame at the same address without computing it again. Whether the + /// creation takes it is the outcome's to say (`CreateOutcome::address`): a creation that + /// lands on an account that already has code or a nonce, one the handler refuses after the + /// hook, and one an inspector or a consumer answers without a frame take none, though the + /// start named the address. `None` only for a creation the handler fails before it takes an + /// address, which reaches the hook only when EIP-8037 is off: an endowment above the caller's + /// balance, a caller's nonce at its maximum, or a creating frame at the depth limit. With + /// EIP-8037 on, the instruction ends such a creation before the hook. pub target: Option<Address>, /// The value the start transfers; zero for `DELEGATECALL` and `STATICCALL`. pub value: U256, @@ -142,7 +145,7 @@ impl FrameStart { target, value, forward, - charge: StartCharge::new(0, 0), + charge: StartCharge::new(0, PoolAmounts::ZERO), } } } diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index df1463c89e..aa8767410e 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -6,7 +6,7 @@ use context_interface::{ }; use interpreter::{ CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - GasTracker, StartCharge, + GasTracker, PoolAmounts, StartCharge, }; use primitives::{Address, TxKind}; use state::Bytecode; @@ -16,8 +16,11 @@ mod first_frame; pub use first_frame::settle_first_frame; /// Creates the first [`FrameInput`] from the transaction and the -/// transaction-level `gas`, forwarding all remaining regular gas and the -/// reservoir to the frame. +/// transaction-level `gas`, forwarding all remaining regular gas, the +/// reservoir and every pool to the frame. The reservoir and the pools are taken +/// out of `gas` ([`GasTracker::forward_all_to_child`]), as a frame start takes +/// a child's shares out of its caller's, and come back when the frame settles +/// into `gas`. /// /// Under EIP-2780 this completes the runtime gas phase started at /// pre-execution (the authorization charges): the target is loaded once and @@ -122,6 +125,9 @@ pub fn create_init_frame<CTX: ContextTr>( } } + // The transaction's frame gets the whole reservoir and every whole pool, taken out + // of the transaction's gas: the schedule's shares are for the frames below it. + let shares = gas.forward_all_to_child(); Ok(Some(FrameInput::Call(Box::new(CallInputs { input: CallInput::Bytes(input), gas_limit: gas.remaining(), @@ -133,14 +139,13 @@ pub fn create_init_frame<CTX: ContextTr>( scheme: CallScheme::Call, is_static: false, return_memory_offset: 0..0, - reservoir: gas.reservoir(), + reservoir: shares.reservoir, charged_new_account_state_gas, - // The transaction's frame gets the whole pool. It has no start charge until a - // consumer that charged the transaction's gas for it puts one on this input - // (`Handler::first_frame_input`), and no allowance, which is a value call's below - // the transaction. - charged_start: StartCharge::new(0, 0), - bytes_share: forward_whole_pool(gas), + // No start charge until a consumer that charged the transaction's gas for the + // frame puts one on this input (`Handler::first_frame_input`), and no allowance, + // which is a value call's below the transaction. + charged_start: StartCharge::new(0, PoolAmounts::ZERO), + pool_shares: shares.pools, history_allowance: 0, })))) } @@ -176,33 +181,23 @@ pub fn create_init_frame<CTX: ContextTr>( } } let tx = ctx.tx(); + let shares = gas.forward_all_to_child(); let mut inputs = CreateInputs::new( tx.caller(), CreateScheme::Create, tx.value(), input, gas.remaining(), - gas.reservoir(), + shares.reservoir, ); inputs.set_charged_create_state_gas(charged_create_state_gas); inputs.set_charged_state_gas_address(charged_state_gas_address); - inputs.set_bytes_share(forward_whole_pool(gas)); + inputs.set_pool_shares(shares.pools); Ok(Some(FrameInput::Create(Box::new(inputs)))) } } } -/// Takes the whole byte pool out of the transaction-level `gas` for the transaction's frame and -/// returns it: the frame's pool. The schedule's share applies to the frames below it; the -/// transaction's frame is the pool's first holder. `last_frame_result` adds back what the frame -/// leaves, as a caller does. -#[inline] -const fn forward_whole_pool(gas: &mut GasTracker) -> u64 { - let pool = gas.bytes_remaining(); - gas.forward_bytes(pool); - pool -} - /// Unwinds the EIP-2780 runtime gas phase after first-frame creation ran out /// of gas ([`create_init_frame`] returned `None`): reverts the phase's /// journal checkpoint — dropping all runtime state changes, including applied diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index f97c0fdcb3..f06eed0705 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -15,8 +15,9 @@ use std::string::ToString; /// The steps, each with the halt rule it takes: /// - `gas` spends all its regular gas, which was forwarded to the frame, and the frame settles /// into it as a child settles into its caller ([`handle_reservoir_remaining_gas`]): a failing -/// frame rolls back its state gas, history gas and byte draws, a halt consumes its regular gas, -/// and what the frame left returns to `gas`; +/// frame rolls back its state gas, history gas and pool draws, a halt consumes its regular gas, +/// and what the frame left returns to `gas`, its reservoir and its pools added to what `gas` +/// kept, which is nothing, since the frame took them whole; /// - the EIP-2780 refundable first-frame charge is refunded when no account leaf was created, /// priced through [`Host::state_gas_charge`](context_interface::Host::state_gas_charge) as it /// was charged; after a halt the regular gas the refund credited is consumed; @@ -89,8 +90,7 @@ where // the transaction's gas, whole, on the same condition and with the same halt rule, // exactly like `EthFrame::return_result` refunds the start charges of inner frames. if let Some(charge) = frame_result.refundable_start_charge() { - gas.refill_history(charge.history); - gas.refill_bytes(charge.bytes); + gas.refill_start_charge(charge); if instruction_result.is_halt() { gas.spend_all(); } diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 36d3a62ac2..7632f6bd1b 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -160,14 +160,14 @@ impl EthFrame<EthInterpreter> { let charged_new_account_state_gas = inputs.charged_new_account_state_gas; let charged_state_gas_address = inputs.target_address; let charged_start = inputs.charged_start; - // The child's byte pool is the share its caller forwarded, and its history allowance - // what the call instruction gave it; both ride on the frame's gas, as the reservoir - // does, whether the handler runs the frame or answers the start without one. - let bytes_share = inputs.bytes_share; + // The child's pools are the shares its caller forwarded, and its history allowance what + // the call instruction gave it; both ride on the frame's gas, as the reservoir does, + // whether the handler runs the frame or answers the start without one. + let pool_shares = inputs.pool_shares; let history_allowance = inputs.history_allowance; let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas); - gas.set_bytes_remaining(bytes_share); + gas.tracker_mut().set_pools_remaining(pool_shares); gas.set_history_allowance(history_allowance); let return_result = |instruction_result: InstructionResult| { @@ -220,10 +220,10 @@ impl EthFrame<EthInterpreter> { if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { // The provider built the answer's gas from the inputs' regular gas and reservoir. The - // answer takes the caller's share as the pool it started with, less what the provider - // drew on it, and the allowance the input carries, so the caller's settlement gets the - // share back from the answer as it would from a frame. - result.gas.tracker_mut().adopt_bytes_share(bytes_share); + // answer takes the caller's shares as the pools it started with, less what the + // provider drew on them, and the allowance the input carries, so the caller's + // settlement gets the shares back from the answer as it would from a frame. + result.gas.tracker_mut().adopt_pool_shares(pool_shares); result.gas.set_history_allowance(history_allowance); let mut logs = Vec::new(); if result.result.is_ok() { @@ -273,7 +273,11 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); - frame.interpreter.gas.set_bytes_remaining(bytes_share); + frame + .interpreter + .gas + .tracker_mut() + .set_pools_remaining(pool_shares); frame .interpreter .gas @@ -305,16 +309,16 @@ impl EthFrame<EthInterpreter> { // — because the created address is not derivable here on the early-fail paths. let charged_state_gas_address = inputs.charged_state_gas_address(); let charged_start = inputs.charged_start(); - // The creation's byte pool is the share its caller forwarded; it rides on the frame's + // The creation's pools are the shares its caller forwarded; they ride on the frame's // gas, as the reservoir does, on an early failure too, so the caller's settlement gets - // it back. - let bytes_share = inputs.bytes_share(); + // them back. + let pool_shares = inputs.pool_shares(); let return_error = |e| { let mut gas = Gas::new_with_regular_gas_and_reservoir( inputs.gas_limit(), reservoir_remaining_gas, ); - gas.set_bytes_remaining(bytes_share); + gas.tracker_mut().set_pools_remaining(pool_shares); Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome { result: InterpreterResult { result: e, @@ -400,7 +404,11 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); - frame.interpreter.gas.set_bytes_remaining(bytes_share); + frame + .interpreter + .gas + .tracker_mut() + .set_pools_remaining(pool_shares); Ok(ItemOrResult::Item(this.consume())) } @@ -646,8 +654,10 @@ impl EthFrame<EthInterpreter> { self.interpreter.gas.refill_reservoir(charge); } if let Some(charge) = refund_start_charge { - self.interpreter.gas.refill_history(charge.history); - self.interpreter.gas.refill_bytes(charge.bytes); + self.interpreter + .gas + .tracker_mut() + .refill_start_charge(charge); } Ok(()) @@ -667,18 +677,20 @@ impl EthFrame<EthInterpreter> { /// Then the parent *merges* the settled child: /// - unused regular gas (`remaining`, including any spill returned on revert) /// flows back to the parent on success or revert; a halt consumes it. -/// - the reservoir, a shared state-gas pool the child inherited at call time, is -/// always adopted from the child (restored to the inherited value on -/// revert/halt). Any returned reservoir first unwinds the parent's outstanding -/// spilled state gas in LIFO order. +/// - the reservoir, the share of the parent's state-gas pool the child was given +/// at call time, is always added back from the child to what the parent kept +/// (restored to the inherited value on revert/halt). Every schedule defined +/// here forwards the whole reservoir, so the parent kept nothing and its +/// reservoir becomes the child's. Any returned reservoir first unwinds the +/// parent's outstanding spilled state gas in LIFO order. /// - net state gas, net history gas, the spilled portion, and the refund counter /// persist only on success; on revert/halt the child's state changes roll back /// and contribute nothing. -/// - the byte pool settles as the reservoir does, not as regular gas: the child's -/// rollback gives its draws back to its pool, so what it hands back is its +/// - each pool settles as the reservoir does, not as regular gas: the child's +/// rollback gives its draws back to its pools, so what it hands back is its /// remaining pool on success and the whole share it was given on revert *and on -/// halt*, since a halted frame appends nothing; the parent, which kept what it -/// did not forward, always absorbs it. The child's net draw merges into the +/// halt*, since a halted frame draws nothing; the parent, which kept what it +/// did not forward, always absorbs it. The child's net draws merge into the /// parent's on success only, as the history net does, so a later rollback of /// the parent undoes the child's draws too. With no pool set, every figure here /// is the unlimited pool going out and coming back. @@ -725,10 +737,9 @@ pub const fn handle_reservoir_remaining_gas( .saturating_add(child_gas.history_gas_spent()), ); parent_gas.record_refund(child_gas.refunded()); - parent_gas.add_bytes_spent(child_gas.bytes_spent()); } parent_gas.absorb_returned_reservoir(child_gas.reservoir()); - parent_gas.absorb_returned_bytes(child_gas.bytes_remaining()); + parent_gas.absorb_returned_pools(child_gas, instruction_result.is_ok()); } /// Handles the result of a CREATE operation, including validation and state updates. @@ -895,6 +906,7 @@ pub fn return_create<CTX: ContextTr>( #[cfg(test)] mod tests { use super::*; + use interpreter::PoolId; #[test] fn sibling_refill_restores_parent_regular_gas() { @@ -931,45 +943,64 @@ mod tests { assert_eq!(parent.state_gas_spilled(), 0); } - /// A child with a share of its caller's pool. + /// A child with `share` of each of its caller's pools. fn child_with_share(parent: &mut GasTracker, share: u64) -> GasTracker { - parent.forward_bytes(share); let mut child = GasTracker::new(500, 500, 0); - child.set_bytes_remaining(share); + for pool in PoolId::ALL { + parent.forward_pool(pool, share); + child.set_pool_remaining(pool, share); + } child } - /// A child that succeeds hands back what it left of its share and its net draw; one that - /// reverts or halts hands back the whole share, its draws undone, and no net. The caller - /// kept what it did not forward either way. + /// A tracker with every pool at 1,000. + fn pools_1000() -> GasTracker { + let mut tracker = GasTracker::new(1_000, 1_000, 0); + for pool in PoolId::ALL { + tracker.set_pool_remaining(pool, 1_000); + } + tracker + } + + /// `(remaining, spent)` of every pool. + fn pools(tracker: &GasTracker) -> [(u64, i64); PoolId::COUNT] { + PoolId::ALL.map(|pool| (tracker.pool_remaining(pool), tracker.pool_spent(pool))) + } + + /// A child that succeeds hands back what it left of each share and its net draws; one that + /// reverts or halts hands back the whole shares, its draws undone, and no net. The caller + /// kept what it did not forward either way, and each pool settles alone. #[test] - fn test_the_pool_settles_like_the_reservoir_not_like_regular_gas() { + fn test_the_pools_settle_like_the_reservoir_not_like_regular_gas() { for result in [ InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas, ] { - let mut parent = GasTracker::new(1_000, 1_000, 0); - parent.set_bytes_remaining(1_000); - assert!(parent.record_bytes(100)); + let mut parent = pools_1000(); + for pool in PoolId::ALL { + assert!(parent.record_pool(pool, 100)); + } let mut child = child_with_share(&mut parent, 800); - assert_eq!(parent.bytes_remaining(), 100, "{result:?}: kept back"); - assert!(child.record_bytes(300)); + assert_eq!(pools(&parent), [(100, 100); 3], "{result:?}: kept back"); + let [first, second, third] = PoolId::ALL; + assert!(child.record_pool(first, 300)); + assert!(child.record_pool(second, 1)); + child.refill_pool(third, 10); handle_reservoir_remaining_gas(result, &mut parent, &mut child); - let (pool, spent) = if result.is_ok() { - (600, 400) + if result.is_ok() { + assert_eq!(pools(&parent), [(600, 400), (899, 101), (910, 90)]); + assert_eq!(pools(&child), [(500, 300), (799, 1), (810, -10)]); } else { - (900, 100) - }; - assert_eq!(parent.bytes_remaining(), pool, "{result:?}"); - assert_eq!(parent.bytes_spent(), spent, "{result:?}"); - assert_eq!( - child.bytes_remaining(), - if result.is_ok() { 500 } else { 800 }, - "{result:?}: a failed child's pool reads as its share" - ); + assert_eq!(pools(&parent), [(900, 100); 3], "{result:?}"); + assert_eq!( + pools(&child), + [(800, 0); 3], + "{result:?}: a failed child's pools read as its shares" + ); + } } } @@ -977,18 +1008,21 @@ mod tests { /// gives A back the whole share it forwarded, C's draws included. #[test] fn test_a_callers_rollback_undoes_a_successful_childs_draws() { - let mut a = GasTracker::new(1_000, 1_000, 0); - a.set_bytes_remaining(1_000); + let mut a = pools_1000(); let mut b = child_with_share(&mut a, 1_000); - assert!(b.record_bytes(100)); + for pool in PoolId::ALL { + assert!(b.record_pool(pool, 100)); + } let mut c = child_with_share(&mut b, 900); - assert!(c.record_bytes(100)); + for pool in PoolId::ALL { + assert!(c.record_pool(pool, 100)); + } handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); - assert_eq!((b.bytes_remaining(), b.bytes_spent()), (800, 200)); + assert_eq!(pools(&b), [(800, 200); 3]); handle_reservoir_remaining_gas(InstructionResult::Revert, &mut a, &mut b); - assert_eq!((a.bytes_remaining(), a.bytes_spent()), (1_000, 0)); + assert_eq!(pools(&a), [(1_000, 0); 3]); } /// A child that gives back a draw its caller made goes below zero, and merging it into the @@ -997,47 +1031,109 @@ mod tests { #[test] fn test_a_childs_refill_of_a_callers_draw_nets_out_on_success_only() { for result in [InstructionResult::Stop, InstructionResult::Revert] { - let mut parent = GasTracker::new(1_000, 1_000, 0); - parent.set_bytes_remaining(1_000); - assert!(parent.record_bytes(100)); + let mut parent = pools_1000(); + for pool in PoolId::ALL { + assert!(parent.record_pool(pool, 100)); + } let mut child = child_with_share(&mut parent, 900); - child.refill_bytes(100); - assert_eq!( - (child.bytes_remaining(), child.bytes_spent()), - (1_000, -100) - ); + for pool in PoolId::ALL { + child.refill_pool(pool, 100); + } + assert_eq!(pools(&child), [(1_000, -100); 3]); handle_reservoir_remaining_gas(result, &mut parent, &mut child); - let (pool, spent) = if result.is_ok() { + let settled = if result.is_ok() { (1_000, 0) } else { (900, 100) }; - assert_eq!(parent.bytes_remaining(), pool, "{result:?}"); - assert_eq!(parent.bytes_spent(), spent, "{result:?}"); + assert_eq!(pools(&parent), [settled; 3], "{result:?}"); } } - /// With no pool set, the unlimited pool goes out whole and comes back, less only what was + /// With no pool set, the unlimited pools go out whole and come back, less only what was /// drawn and kept, and the regular-gas settlement is what it was. #[test] - fn test_an_unset_pool_settles_to_the_same_regular_gas() { + fn test_unset_pools_settle_to_the_same_regular_gas() { for result in [InstructionResult::Stop, InstructionResult::OutOfGas] { let mut parent = GasTracker::new(1_000, 1_000, 0); assert!(parent.record_regular_cost(500)); - let mut with_pool = parent; - let pool = with_pool.bytes_remaining(); - let mut child = child_with_share(&mut with_pool, pool); + let mut with_pools = parent; + let mut child = child_with_share(&mut with_pools, u64::MAX); assert!(child.record_regular_cost(200)); let mut plain_child = child; - handle_reservoir_remaining_gas(result, &mut with_pool, &mut child); + handle_reservoir_remaining_gas(result, &mut with_pools, &mut child); handle_reservoir_remaining_gas(result, &mut parent, &mut plain_child); - assert_eq!(with_pool.remaining(), parent.remaining(), "{result:?}"); - assert_eq!(with_pool.bytes_remaining(), u64::MAX, "{result:?}"); - assert_eq!(with_pool.bytes_spent(), 0, "{result:?}"); + assert_eq!(with_pools.remaining(), parent.remaining(), "{result:?}"); + assert_eq!(pools(&with_pools), [(u64::MAX, 0); 3], "{result:?}"); } } + + /// A caller that forwarded a share of its reservoir and kept the rest gets back, on top of + /// what it kept: what the child left when it succeeded, the whole share when it reverted or + /// halted, the child's state charges undone. Regular gas settles as it did. + #[test] + fn test_the_reservoir_a_child_returns_joins_what_its_caller_kept() { + for result in [ + InstructionResult::Stop, + InstructionResult::Revert, + InstructionResult::OutOfGas, + ] { + let mut parent = GasTracker::new(10_000, 10_000, 1_000); + assert!(parent.record_regular_cost(5_000)); + // 98% of 1,000 forwarded, 20 kept. + parent.forward_reservoir(980); + let mut child = GasTracker::new(5_000, 5_000, 980); + assert!(child.record_state_cost(300)); + + handle_reservoir_remaining_gas(result, &mut parent, &mut child); + + let (reservoir, state) = if result.is_ok() { + (700, 300) + } else { + (1_000, 0) + }; + assert_eq!(parent.reservoir(), reservoir, "{result:?}"); + assert_eq!(parent.state_gas_spent(), state, "{result:?}"); + let regular = if result.is_ok_or_revert() { + 10_000 + } else { + 5_000 + }; + assert_eq!(parent.remaining(), regular, "{result:?}"); + } + } + + /// A child that spends more than its share spills onto its regular gas, as a frame with no + /// reservoir left does, though its caller kept part of the reservoir: the share is the + /// child's whole reservoir. A caller's later rollback restores the reservoir it started with + /// and gives the spill back to regular gas. + #[test] + fn test_a_child_spills_past_its_share_and_a_rollback_restores_the_callers_reservoir() { + let mut a = GasTracker::new(10_000, 10_000, 1_000); + assert!(a.record_regular_cost(10_000)); + a.forward_reservoir(1_000); + let mut b = GasTracker::new(10_000, 10_000, 1_000); + assert!(b.record_regular_cost(5_000)); + b.forward_reservoir(980); + let mut c = GasTracker::new(5_000, 5_000, 980); + assert!(c.record_state_cost(1_000)); + assert_eq!( + (c.reservoir(), c.remaining(), c.state_gas_spilled()), + (0, 4_980, 20) + ); + + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); + assert_eq!(b.reservoir(), 20, "the part B kept is still there"); + assert_eq!(b.state_gas_spilled(), 20); + assert_eq!(b.remaining(), 9_980); + + handle_reservoir_remaining_gas(InstructionResult::Revert, &mut a, &mut b); + assert_eq!(a.reservoir(), 1_000); + assert_eq!(a.remaining(), 10_000); + assert_eq!(a.state_gas_spent(), 0); + } } diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index c7b44463e0..fd3a8c3c16 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -182,7 +182,7 @@ impl FrameResult { /// the outcome's `charged_start`. The decision is the one /// [`Self::refundable_state_gas_charge`] makes: a call refunds when it did not succeed, a /// creation also when no contract address was deployed. The charge is refunded whole, with - /// `refill_history` and `refill_bytes`. + /// `GasTracker::refill_start_charge`. #[inline] pub fn refundable_start_charge(&self) -> Option<StartCharge> { let (failed, charge) = match self { diff --git a/crates/handler/tests/code_deposit_admission.rs b/crates/handler/tests/code_deposit_admission.rs index 79e24f628a..a4587bbdd6 100644 --- a/crates/handler/tests/code_deposit_admission.rs +++ b/crates/handler/tests/code_deposit_admission.rs @@ -26,7 +26,7 @@ use context_interface::{ }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ - Gas, InstructionResult, InterpreterResult, SStoreResult, SelfDestructResult, StateLoad, + Gas, InstructionResult, InterpreterResult, PoolId, SStoreResult, SelfDestructResult, StateLoad, }; use primitives::{ address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, @@ -43,6 +43,8 @@ type DbError = <Db as Database>::Error; type Outcome = Result<ResultAndState, EVMError<DbError>>; /// Contract the call transactions call. +/// The pool the tests draw: any of the tracker's pools behaves the same. +const FIRST: PoolId = PoolId::new(0); const CONTRACT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Nonce of [`CONTRACT`], so the address its `CREATE` deploys at is known. const CONTRACT_NONCE: u64 = 1; @@ -138,7 +140,7 @@ impl ContextTr for AdmissionContext { gas: &mut GasTracker, ) -> Result<(), Bytes> { // A draw the pool cannot pay records the crossing on `gas`, as any failed draw does. - let _ = gas.record_bytes(self.draw); + let _ = gas.record_pool(FIRST, self.draw); self.offered.push(Offered { address: deposit.address, code: deposit.code.clone(), @@ -745,7 +747,7 @@ fn test_a_pre_homestead_deposit_the_frame_cannot_pay_is_offered_with_its_crossin fn test_the_hook_draws_the_deposit_from_the_frames_pool() { const POOL: u64 = 1_000; let mut gas = Gas::new(100_000); - gas.set_bytes_remaining(POOL); + gas.set_pool_remaining(FIRST, POOL); let code = Bytes::from_static(&[0; 32]); // OSAKA: the deposit is one regular charge, 200 per byte. let charged = { @@ -755,9 +757,9 @@ fn test_the_hook_draws_the_deposit_from_the_frames_pool() { }; let pool = |gas: &Gas| { ( - gas.bytes_remaining(), - gas.bytes_spent(), - gas.bytes_crossing(), + gas.pool_remaining(FIRST), + gas.pool_spent(FIRST), + gas.pool_crossing(FIRST), ) }; diff --git a/crates/handler/tests/byte_pool.rs b/crates/handler/tests/resource_pools.rs similarity index 96% rename from crates/handler/tests/byte_pool.rs rename to crates/handler/tests/resource_pools.rs index 30028355ef..8839e3dd3f 100644 --- a/crates/handler/tests/byte_pool.rs +++ b/crates/handler/tests/resource_pools.rs @@ -32,7 +32,7 @@ use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, FrameInput, GasTracker, Instruction, InstructionContext, InstructionExecResult, InstructionResult, InterpreterResult, - SStoreResult, SelfDestructResult, StartCharge, StateLoad, + PoolAmounts, PoolId, SStoreResult, SelfDestructResult, StartCharge, StateLoad, }; use primitives::{ address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, AddressSet, Bytes, Log, @@ -63,8 +63,10 @@ const GAS_LIMIT: u64 = 3_000_000; const POOL: u64 = 1_000; /// What `DRAW` draws. const DRAW_BYTES: u64 = 100; +/// The pool the tests draw: any of the tracker's pools behaves the same. +const FIRST: PoolId = PoolId::new(0); /// What the start hook charges and declares after `DECLARE`. -const DECLARED: StartCharge = StartCharge::new(3_520, 160); +const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); /// What `LOG` charges as history. const HISTORY_COST: u64 = 100; /// A value call's history allowance on a chain that gives one. @@ -96,7 +98,7 @@ const LOG: u8 = 0x0e; const fn draw( context: InstructionContext<'_, TestContext, EthInterpreter>, ) -> InstructionExecResult { - if context.interpreter.gas.record_bytes(DRAW_BYTES) { + if context.interpreter.gas.record_pool(FIRST, DRAW_BYTES) { Ok(()) } else { Err(InstructionResult::OutOfGas) @@ -142,9 +144,9 @@ impl Returned { let gas = result.gas(); Self { result: result.instruction_result(), - pool: gas.bytes_remaining(), - spent: gas.bytes_spent(), - crossing: gas.bytes_crossing(), + pool: gas.pool_remaining(FIRST), + spent: gas.pool_spent(FIRST), + crossing: gas.pool_crossing(FIRST), history: gas.history_gas_spent(), allowance: gas.history_allowance(), } @@ -237,7 +239,7 @@ impl ContextTr for DeclaringContext { Deposit::Drawn => false, Deposit::DrawnAndRefused => true, }; - assert!(gas.record_bytes(deposit.code.len() as u64)); + assert!(gas.record_pool(FIRST, deposit.code.len() as u64)); if refuses { Err(Bytes::new()) } else { @@ -260,7 +262,7 @@ impl Host for DeclaringContext { fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { if core::mem::take(&mut self.declare_next) { assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_bytes(DECLARED.bytes)); + assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); start.charge = DECLARED; } true @@ -413,8 +415,10 @@ impl PrecompileProvider<TestContext> for DrawingPrecompiles { ) -> Result<Option<InterpreterResult>, String> { let mut answer = self.inner.run(context, inputs)?; if let Some(answer) = answer.as_mut().filter(|_| self.draw > 0) { - answer.gas.set_bytes_remaining(inputs.bytes_share); - assert!(answer.gas.record_bytes(self.draw)); + answer + .gas + .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); + assert!(answer.gas.record_pool(FIRST, self.draw)); } Ok(answer) } @@ -430,11 +434,11 @@ type Started = (u64, StartCharge, u64); fn started(input: &FrameInput) -> Started { match input { FrameInput::Call(inputs) => ( - inputs.bytes_share, + inputs.pool_shares.get(FIRST), inputs.charged_start, inputs.history_allowance, ), - FrameInput::Create(inputs) => (inputs.bytes_share(), inputs.charged_start(), 0), + FrameInput::Create(inputs) => (inputs.pool_shares().get(FIRST), inputs.charged_start(), 0), FrameInput::Empty => unreachable!(), } } @@ -484,11 +488,11 @@ impl Handler for PoolHandler { fn tx_gas(&self, evm: &mut TestEvm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { let mut gas = self.mainnet.tx_gas(evm, init_and_floor_gas); if let Some(pool) = self.pool { - gas.set_bytes_remaining(pool); + gas.set_pool_remaining(FIRST, pool); } if self.declare { assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_bytes(DECLARED.bytes)); + assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); } gas } @@ -556,8 +560,8 @@ impl Handler for PoolHandler { // `post_execution` takes `&self`; the record goes through a cell. SETTLED.with(|settled| { settled.set(Some(( - gas.bytes_remaining(), - gas.bytes_spent(), + gas.pool_remaining(FIRST), + gas.pool_spent(FIRST), gas.history_gas_spent(), ))) }); @@ -720,7 +724,7 @@ impl Run { .override_gas([(GasId::call_history_allowance(), allowance)]); if let Some(percent) = forward_percent { cfg.gas_params - .override_gas([(GasId::bytes_forward_percent(), percent)]); + .override_gas([(GasId::pool_forward_percent(FIRST), percent)]); } }); let ctx = DeclaringContext { @@ -895,14 +899,14 @@ fn test_the_start_charge_is_refunded_when_the_frame_fails() { assert_eq!(handler.starts.len(), 2, "{name}"); assert_eq!( handler.starts[1], - (POOL - DECLARED.bytes, DECLARED, 0), + (POOL - DECLARED.pools.get(FIRST), DECLARED, 0), "{name}: the charge rides on the input" ); let settled = handler.settled.expect(name); if fails { assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); } else { - let drawn = DECLARED.bytes + DRAW_BYTES; + let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; assert_eq!( settled, (POOL - drawn, drawn as i64, DECLARED.history as i64), @@ -940,14 +944,14 @@ fn test_the_first_frame_gets_the_pool_and_its_start_charge() { assert_eq!(result.is_success(), !fails, "{name}: {result:?}"); assert_eq!( handler.starts, - [(POOL - DECLARED.bytes, DECLARED, 0)], + [(POOL - DECLARED.pools.get(FIRST), DECLARED, 0)], "{name}" ); let settled = handler.settled.expect(name); if fails { assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); } else { - let drawn = DECLARED.bytes + DRAW_BYTES; + let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; assert_eq!( settled, (POOL - drawn, drawn as i64, DECLARED.history as i64), @@ -1145,7 +1149,7 @@ fn test_a_start_refused_for_the_depth_gives_the_share_and_the_start_charge_back( let (result, handler) = Run::new(ends(parent)).with(handler); assert!(result.is_success(), "{name}: {result:?}"); - let share = POOL - DRAW_BYTES - DECLARED.bytes; + let share = POOL - DRAW_BYTES - DECLARED.pools.get(FIRST); assert_eq!(handler.starts[1], (share, DECLARED, 0), "{name}"); assert_eq!( handler.returned[0], diff --git a/crates/inspector/tests/byte_pool.rs b/crates/inspector/tests/resource_pools.rs similarity index 94% rename from crates/inspector/tests/byte_pool.rs rename to crates/inspector/tests/resource_pools.rs index 9add294130..916977b188 100644 --- a/crates/inspector/tests/byte_pool.rs +++ b/crates/inspector/tests/resource_pools.rs @@ -29,7 +29,8 @@ use handler::{ use interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, GasTracker, Instruction, InstructionContext, InstructionExecResult, InstructionResult, - InterpreterResult, SStoreResult, SelfDestructResult, StartCharge, StateLoad, + InterpreterResult, PoolAmounts, PoolId, SStoreResult, SelfDestructResult, StartCharge, + StateLoad, }; use primitives::{ address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, @@ -51,8 +52,10 @@ const SPEC: SpecId = SpecId::OSAKA; const GAS_LIMIT: u64 = 3_000_000; /// What `DRAW` draws. const DRAW_BYTES: u64 = 100; +/// The pool the tests draw: any of the tracker's pools behaves the same. +const FIRST: PoolId = PoolId::new(0); /// What the start hook charges and declares after `DECLARE`. -const DECLARED: StartCharge = StartCharge::new(3_520, 160); +const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); /// What `LOG` charges as history. const HISTORY_COST: u64 = 100; /// A value call's history allowance on a chain that gives one. @@ -85,7 +88,7 @@ const DRAIN: u8 = 0x0f; const LIMIT: u8 = 0x10; const fn draw(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - if context.interpreter.gas.record_bytes(DRAW_BYTES) { + if context.interpreter.gas.record_pool(FIRST, DRAW_BYTES) { Ok(()) } else { Err(InstructionResult::OutOfGas) @@ -93,7 +96,7 @@ const fn draw(context: InstructionContext<'_, Ctx, EthInterpreter>) -> Instructi } const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - if context.interpreter.gas.record_bytes(u64::MAX) { + if context.interpreter.gas.record_pool(FIRST, u64::MAX) { Ok(()) } else { Err(InstructionResult::OutOfGas) @@ -102,7 +105,7 @@ const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> Instruct /// Sets the frame's pool to [`LIMITED`], as a consumer sets the transaction's. const fn limit(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - context.interpreter.gas.set_bytes_remaining(LIMITED); + context.interpreter.gas.set_pool_remaining(FIRST, LIMITED); Ok(()) } @@ -186,7 +189,7 @@ impl Host for DeclaringContext { fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { if core::mem::take(&mut self.declare_next) { assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_bytes(DECLARED.bytes)); + assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); start.charge = DECLARED; } true @@ -342,7 +345,7 @@ impl Ended { crossing: false, history: 0, allowance: 0, - charged_start: StartCharge::new(0, 0), + charged_start: StartCharge::new(0, PoolAmounts::ZERO.with(FIRST, 0)), } } } @@ -374,9 +377,9 @@ impl Figures { fn end(&mut self, result: InstructionResult, gas: &Gas, charged: StartCharge) { self.ends.push(Ended { result, - pool: gas.bytes_remaining(), - spent: gas.bytes_spent(), - crossing: gas.bytes_crossing(), + pool: gas.pool_remaining(FIRST), + spent: gas.pool_spent(FIRST), + crossing: gas.pool_crossing(FIRST), history: gas.history_gas_spent(), allowance: gas.history_allowance(), charged_start: charged, @@ -387,7 +390,7 @@ impl Figures { impl Inspector<Ctx, EthInterpreter> for Figures { fn call(&mut self, _context: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { self.starts.push(( - inputs.bytes_share, + inputs.pool_shares.get(FIRST), inputs.charged_start, inputs.history_allowance, )); @@ -402,7 +405,10 @@ impl Inspector<Ctx, EthInterpreter> for Figures { ); let mut outcome = CallOutcome::new(revert, inputs.return_memory_offset.clone()); if self.answer == Answer::WithShareAndCharge { - outcome.result.gas.set_bytes_remaining(inputs.bytes_share); + outcome + .result + .gas + .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); outcome.charged_start = inputs.charged_start; } Some(outcome) @@ -410,7 +416,7 @@ impl Inspector<Ctx, EthInterpreter> for Figures { fn create(&mut self, _context: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { self.starts - .push((inputs.bytes_share(), inputs.charged_start(), 0)); + .push((inputs.pool_shares().get(FIRST), inputs.charged_start(), 0)); None } @@ -649,7 +655,7 @@ fn test_both_paths_refund_the_start_charge_when_the_frame_fails() { assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); assert_eq!( figures.starts[1], - (UNLIMITED - DECLARED.bytes, DECLARED, 0), + (UNLIMITED - DECLARED.pools.get(FIRST), DECLARED, 0), "{name}: the charge rides on the input" ); assert_eq!( @@ -664,7 +670,7 @@ fn test_both_paths_refund_the_start_charge_when_the_frame_fails() { "{name}: refunded whole" ); } else { - let drawn = DECLARED.bytes + DRAW_BYTES; + let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; assert_eq!( (parent_end.pool, parent_end.spent, parent_end.history), (UNLIMITED - drawn, drawn as i64, DECLARED.history as i64), @@ -736,12 +742,16 @@ fn limited_call_to_ok(answer: Answer) -> (u64, Ended, (u64, i64, i64)) { /// caller gets the share and the charge back. #[test] fn test_an_outcome_the_inspector_builds_settles_as_built() { - let share = LIMITED - DECLARED.bytes; + let share = LIMITED - DECLARED.pools.get(FIRST); for (answer, answered, kept) in [ ( Answer::AsBuilt, Ended::with(InstructionResult::Revert, UNLIMITED, 0), - (UNLIMITED, DECLARED.bytes as i64, DECLARED.history as i64), + ( + UNLIMITED, + DECLARED.pools.get(FIRST) as i64, + DECLARED.history as i64, + ), ), ( Answer::WithShareAndCharge, @@ -765,8 +775,8 @@ fn test_an_outcome_the_inspector_builds_settles_as_built() { /// revert would; the frame left alone keeps both. #[test] fn test_a_success_the_inspector_rewrites_into_a_revert_refunds_the_start_charge() { - let share = LIMITED - DECLARED.bytes; - let drawn = DECLARED.bytes + DRAW_BYTES; + let share = LIMITED - DECLARED.pools.get(FIRST); + let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; for (answer, result, kept) in [ ( Answer::Runs, diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index 6aa20b09c3..49f0a62126 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -2,8 +2,8 @@ pub use context_interface::cfg::gas::*; -mod byte_pool; mod failed_charge; +mod pools; mod withheld; /// Represents the state of gas during execution. diff --git a/crates/interpreter/src/gas/byte_pool.rs b/crates/interpreter/src/gas/byte_pool.rs deleted file mode 100644 index d7f7b97439..0000000000 --- a/crates/interpreter/src/gas/byte_pool.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! The byte pool and the history allowance, on [`Gas`]. -//! -//! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which -//! documents it. - -use super::Gas; - -impl Gas { - /// The byte pool: what this frame may still draw. Unlimited unless a consumer set a pool. - /// - /// See [`GasTracker::bytes_remaining`](super::GasTracker::bytes_remaining). - #[inline] - pub const fn bytes_remaining(&self) -> u64 { - self.tracker.bytes_remaining() - } - - /// Sets the byte pool. - /// - /// See [`GasTracker::set_bytes_remaining`](super::GasTracker::set_bytes_remaining). - #[inline] - pub const fn set_bytes_remaining(&mut self, val: u64) { - self.tracker.set_bytes_remaining(val); - } - - /// The frame's net draw of the pool so far, signed. - /// - /// See [`GasTracker::bytes_spent`](super::GasTracker::bytes_spent). - #[inline] - pub const fn bytes_spent(&self) -> i64 { - self.tracker.bytes_spent() - } - - /// Sets the net draw. - /// - /// See [`GasTracker::set_bytes_spent`](super::GasTracker::set_bytes_spent). - #[inline] - pub const fn set_bytes_spent(&mut self, val: i64) { - self.tracker.set_bytes_spent(val); - } - - /// Draws `cost` bytes from the pool; `false` if the pool cannot pay, which sets the crossing - /// ([`bytes_crossing`](Self::bytes_crossing)). - /// - /// See [`GasTracker::record_bytes`](super::GasTracker::record_bytes). - #[inline] - #[must_use = "a draw the pool cannot pay is the consumer's stop"] - pub const fn record_bytes(&mut self, cost: u64) -> bool { - self.tracker.record_bytes(cost) - } - - /// Gives `amount` bytes back to the pool. - /// - /// See [`GasTracker::refill_bytes`](super::GasTracker::refill_bytes). - #[inline] - pub const fn refill_bytes(&mut self, amount: u64) { - self.tracker.refill_bytes(amount); - } - - /// Whether a draw failed that the pool could not pay, since the record was last cleared. - /// - /// See [`GasTracker::bytes_crossing`](super::GasTracker::bytes_crossing). - #[inline] - pub const fn bytes_crossing(&self) -> bool { - self.tracker.bytes_crossing() - } - - /// Clears the record returned by [`bytes_crossing`](Self::bytes_crossing). - /// - /// See [`GasTracker::clear_bytes_crossing`](super::GasTracker::clear_bytes_crossing). - #[inline] - pub const fn clear_bytes_crossing(&mut self) { - self.tracker.clear_bytes_crossing(); - } - - /// Sets the record returned by [`bytes_crossing`](Self::bytes_crossing). - /// - /// See [`GasTracker::set_bytes_crossing`](super::GasTracker::set_bytes_crossing). - #[inline] - pub const fn set_bytes_crossing(&mut self, crossing: bool) { - self.tracker.set_bytes_crossing(crossing); - } - - /// History gas this frame may spend before it charges its budget. - /// - /// See [`GasTracker::history_allowance`](super::GasTracker::history_allowance). - #[inline] - pub const fn history_allowance(&self) -> u64 { - self.tracker.history_allowance() - } - - /// Sets the history allowance. - /// - /// See [`GasTracker::set_history_allowance`](super::GasTracker::set_history_allowance). - #[inline] - pub const fn set_history_allowance(&mut self, val: u64) { - self.tracker.set_history_allowance(val); - } - - /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` it did not - /// cover. - /// - /// See [`GasTracker::draw_history_allowance`](super::GasTracker::draw_history_allowance). - #[inline] - #[must_use = "the part of the cost the allowance did not cover is still to be charged"] - pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { - self.tracker.draw_history_allowance(cost) - } -} diff --git a/crates/interpreter/src/gas/pools.rs b/crates/interpreter/src/gas/pools.rs new file mode 100644 index 0000000000..e9a26cf32a --- /dev/null +++ b/crates/interpreter/src/gas/pools.rs @@ -0,0 +1,108 @@ +//! The resource pools and the history allowance, on [`Gas`]. +//! +//! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which +//! documents it. + +use super::{Gas, PoolId}; + +impl Gas { + /// The pool: what this frame may still draw from it. Unlimited unless a consumer set it. + /// + /// See [`GasTracker::pool_remaining`](super::GasTracker::pool_remaining). + #[inline] + pub const fn pool_remaining(&self, pool: PoolId) -> u64 { + self.tracker.pool_remaining(pool) + } + + /// Sets the pool. + /// + /// See [`GasTracker::set_pool_remaining`](super::GasTracker::set_pool_remaining). + #[inline] + pub const fn set_pool_remaining(&mut self, pool: PoolId, val: u64) { + self.tracker.set_pool_remaining(pool, val); + } + + /// The frame's net draw of the pool so far, signed. + /// + /// See [`GasTracker::pool_spent`](super::GasTracker::pool_spent). + #[inline] + pub const fn pool_spent(&self, pool: PoolId) -> i64 { + self.tracker.pool_spent(pool) + } + + /// Sets the pool's net draw. + /// + /// See [`GasTracker::set_pool_spent`](super::GasTracker::set_pool_spent). + #[inline] + pub const fn set_pool_spent(&mut self, pool: PoolId, val: i64) { + self.tracker.set_pool_spent(pool, val); + } + + /// Draws `cost` from the pool; `false` if the pool cannot pay, which sets its crossing + /// ([`pool_crossing`](Self::pool_crossing)). + /// + /// See [`GasTracker::record_pool`](super::GasTracker::record_pool). + #[inline] + #[must_use = "a draw the pool cannot pay is the consumer's stop"] + pub const fn record_pool(&mut self, pool: PoolId, cost: u64) -> bool { + self.tracker.record_pool(pool, cost) + } + + /// Gives `amount` back to the pool. + /// + /// See [`GasTracker::refill_pool`](super::GasTracker::refill_pool). + #[inline] + pub const fn refill_pool(&mut self, pool: PoolId, amount: u64) { + self.tracker.refill_pool(pool, amount); + } + + /// Whether a draw failed that the pool could not pay, since the record was last cleared. + /// + /// See [`GasTracker::pool_crossing`](super::GasTracker::pool_crossing). + #[inline] + pub const fn pool_crossing(&self, pool: PoolId) -> bool { + self.tracker.pool_crossing(pool) + } + + /// Clears the record returned by [`pool_crossing`](Self::pool_crossing). + /// + /// See [`GasTracker::clear_pool_crossing`](super::GasTracker::clear_pool_crossing). + #[inline] + pub const fn clear_pool_crossing(&mut self, pool: PoolId) { + self.tracker.clear_pool_crossing(pool); + } + + /// Sets the record returned by [`pool_crossing`](Self::pool_crossing). + /// + /// See [`GasTracker::set_pool_crossing`](super::GasTracker::set_pool_crossing). + #[inline] + pub const fn set_pool_crossing(&mut self, pool: PoolId, crossing: bool) { + self.tracker.set_pool_crossing(pool, crossing); + } + + /// History gas this frame may spend before it charges its budget. + /// + /// See [`GasTracker::history_allowance`](super::GasTracker::history_allowance). + #[inline] + pub const fn history_allowance(&self) -> u64 { + self.tracker.history_allowance() + } + + /// Sets the history allowance. + /// + /// See [`GasTracker::set_history_allowance`](super::GasTracker::set_history_allowance). + #[inline] + pub const fn set_history_allowance(&mut self, val: u64) { + self.tracker.set_history_allowance(val); + } + + /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` it did not + /// cover. + /// + /// See [`GasTracker::draw_history_allowance`](super::GasTracker::draw_history_allowance). + #[inline] + #[must_use = "the part of the cost the allowance did not cover is still to be charged"] + pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { + self.tracker.draw_history_allowance(cost) + } +} diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 67a5696200..6c2ca81460 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -9,7 +9,7 @@ use call_helpers::load_acc_and_calc_forward; use crate::{ instructions::{ - instruction_hooks::{cache_created_address, forward_bytes, frame_starting}, + instruction_hooks::{cache_created_address, forward_to_child, frame_starting}, utility::IntoAddress, }, interpreter_action::FrameInput, @@ -195,12 +195,12 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( gas_limit, ); let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); + let shares = forward_to_child(&mut context.interpreter.gas, context.host); create_inputs.set_gas_limit(gas_limit); - create_inputs.set_reservoir(context.interpreter.gas.reservoir()); + create_inputs.set_reservoir(shares.reservoir); create_inputs.set_charged_start(charged_start); - create_inputs.set_bytes_share(bytes_share); + create_inputs.set_pool_shares(shares.pools); context .interpreter .bytecode @@ -286,7 +286,7 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let bytes_share = forward_bytes(&mut context.interpreter.gas, context.host); + let shares = forward_to_child(&mut context.interpreter.gas, context.host); // Call host to interact with target contract context @@ -304,10 +304,10 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, scheme, is_static, return_memory_offset, - reservoir: context.interpreter.gas.reservoir(), + reservoir: shares.reservoir, charged_new_account_state_gas, charged_start, - bytes_share, + pool_shares: shares.pools, history_allowance, }, )))); diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index e28c8d1d63..9c44f87775 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -3,8 +3,8 @@ use crate::{ interpreter_types::{InterpreterTypes as ITy, LoopControl}, - CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, - InterpreterAction, StartCharge, + ChildShares, CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, + Interpreter, InterpreterAction, StartCharge, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Address, Bytes, U256}; @@ -93,12 +93,12 @@ pub(crate) fn running_account<H: Host + ?Sized>( Ok((account.balance, account.nonce)) } -/// Takes the child's share of the caller's byte pool out of `gas`, by the schedule's -/// `bytes_forward_percent`, and returns it: the pool the child starts with. Called once the -/// frame-start hook has answered, so the share is of the pool as the hook left it. +/// Takes the child's shares of the caller's reservoir and pools out of `gas`, by the schedule's +/// `reservoir_forward_percent` and `pool_forward_percent`s, and returns them: what the child's +/// tracker starts with ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). +/// Called once the frame-start hook has answered, so the shares are of the reservoir and the pools +/// as the hook left them. #[inline] -pub(crate) fn forward_bytes<H: Host + ?Sized>(gas: &mut Gas, host: &H) -> u64 { - let share = host.gas_params().bytes_forward_share(gas.bytes_remaining()); - gas.tracker_mut().forward_bytes(share); - share +pub(crate) fn forward_to_child<H: Host + ?Sized>(gas: &mut Gas, host: &H) -> ChildShares { + gas.tracker_mut().forward_to_child(host.gas_params()) } diff --git a/crates/interpreter/src/interpreter_action/call_inputs.rs b/crates/interpreter/src/interpreter_action/call_inputs.rs index 3a3980765f..deee076431 100644 --- a/crates/interpreter/src/interpreter_action/call_inputs.rs +++ b/crates/interpreter/src/interpreter_action/call_inputs.rs @@ -1,5 +1,8 @@ use crate::interpreter_types::MemoryTr; -use context_interface::{cfg::gas::StartCharge, ContextTr, LocalContextTr}; +use context_interface::{ + cfg::gas::{PoolAmounts, StartCharge}, + ContextTr, LocalContextTr, +}; use core::ops::Range; use primitives::{Address, Bytes, B256, U256}; use state::Bytecode; @@ -175,21 +178,22 @@ pub struct CallInputs { /// to the reservoir, matching the CREATE pattern. pub charged_new_account_state_gas: bool, /// What the frame-start hook charged the caller for this call and the call's failure gives - /// back: history gas and bytes of the pool, refunded to the caller by `return_result` when - /// the call does not succeed, as `charged_new_account_state_gas` is. + /// back: history gas and an amount of each pool, refunded to the caller by `return_result` + /// when the call does not succeed, as `charged_new_account_state_gas` is. /// /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, - /// The share of the caller's byte pool the call receives: its pool when it starts. Taken out - /// of the caller's pool by the call instruction, by the schedule's `bytes_forward_percent`, - /// and given back with what the call left of it when it returns. + /// The share of each of the caller's pools the call receives: its pools when it starts. + /// Taken out of the caller's pools by the call instruction, by the schedule's + /// `pool_forward_percent` of each, and given back with what the call left of them when it + /// returns. /// /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as unlimited. - #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] - pub bytes_share: u64, + /// decode it as every pool unlimited. + #[cfg_attr(feature = "serde", serde(default = "unlimited_pools"))] + pub pool_shares: PoolAmounts, /// History gas the call may spend before it charges its budget: the schedule's /// `call_history_allowance` for a call that transfers value, set where the call instruction /// adds the call stipend, and zero otherwise. @@ -200,11 +204,10 @@ pub struct CallInputs { pub history_allowance: u64, } -/// The share an encoding that predates the byte pool decodes to in a format that carries field -/// names. +/// The shares an encoding that predates the pools decodes to in a format that carries field names. #[cfg(feature = "serde")] -const fn unlimited_bytes() -> u64 { - u64::MAX +const fn unlimited_pools() -> PoolAmounts { + PoolAmounts::UNLIMITED } impl CallInputs { diff --git a/crates/interpreter/src/interpreter_action/call_outcome.rs b/crates/interpreter/src/interpreter_action/call_outcome.rs index 304a58a8e7..3c9271422e 100644 --- a/crates/interpreter/src/interpreter_action/call_outcome.rs +++ b/crates/interpreter/src/interpreter_action/call_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, PoolAmounts, StartCharge}; use core::ops::Range; use primitives::{Address, Bytes, Log}; use std::vec::Vec; @@ -67,7 +67,7 @@ impl CallOutcome { precompile_call_logs: Vec::new(), charged_new_account_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, 0), + charged_start: StartCharge::new(0, PoolAmounts::ZERO), } } diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index eaa875cc34..1e6c09dc72 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -1,4 +1,7 @@ -use context_interface::{cfg::gas::StartCharge, CreateScheme}; +use context_interface::{ + cfg::gas::{PoolAmounts, StartCharge}, + CreateScheme, +}; use core::cell::OnceCell; use primitives::{keccak256, Address, Bytes, B256, U256}; @@ -31,21 +34,22 @@ pub struct CreateInputs { #[cfg_attr(feature = "serde", serde(default))] charged_state_gas_address: Address, /// What the frame-start hook charged the caller for this creation and the creation's failure - /// gives back: history gas and bytes of the pool, refunded to the caller by `return_result` - /// when the creation fails, as `charged_create_state_gas` is. + /// gives back: history gas and an amount of each pool, refunded to the caller by + /// `return_result` when the creation fails, as `charged_create_state_gas` is. /// /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] charged_start: StartCharge, - /// The share of the caller's byte pool the creation receives: its pool when it starts. Taken - /// out of the caller's pool by the creation instruction, by the schedule's - /// `bytes_forward_percent`, and given back with what the creation left of it when it returns. + /// The share of each of the caller's pools the creation receives: its pools when it starts. + /// Taken out of the caller's pools by the creation instruction, by the schedule's + /// `pool_forward_percent` of each, and given back with what the creation left of them when + /// it returns. /// /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as unlimited. - #[cfg_attr(feature = "serde", serde(default = "unlimited_bytes"))] - bytes_share: u64, + /// decode it as every pool unlimited. + #[cfg_attr(feature = "serde", serde(default = "unlimited_pools"))] + pool_shares: PoolAmounts, /// Cached created address. This is computed lazily and cached to avoid /// redundant keccak computations when inspectors call `created_address`. #[cfg_attr(feature = "serde", serde(skip))] @@ -57,15 +61,14 @@ pub struct CreateInputs { cached_init_code_hash: OnceCell<B256>, } -/// The share an encoding that predates the byte pool decodes to in a format that carries field -/// names. +/// The shares an encoding that predates the pools decodes to in a format that carries field names. #[cfg(feature = "serde")] -const fn unlimited_bytes() -> u64 { - u64::MAX +const fn unlimited_pools() -> PoolAmounts { + PoolAmounts::UNLIMITED } impl Default for CreateInputs { - /// Empty inputs, as [`new`](Self::new) builds them, so the share starts unlimited. + /// Empty inputs, as [`new`](Self::new) builds them, so the shares start unlimited. #[inline] fn default() -> Self { Self::new( @@ -98,8 +101,8 @@ impl CreateInputs { reservoir, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, 0), - bytes_share: u64::MAX, + charged_start: StartCharge::new(0, PoolAmounts::ZERO), + pool_shares: PoolAmounts::UNLIMITED, cached_address: OnceCell::new(), cached_init_code_hash: OnceCell::new(), } @@ -232,13 +235,13 @@ impl CreateInputs { self.charged_start = charge; } - /// The share of the caller's byte pool the creation receives: its pool when it starts. - pub const fn bytes_share(&self) -> u64 { - self.bytes_share + /// The share of each of the caller's pools the creation receives: its pools when it starts. + pub const fn pool_shares(&self) -> PoolAmounts { + self.pool_shares } - /// Sets the share of the caller's byte pool the creation receives. - pub const fn set_bytes_share(&mut self, share: u64) { - self.bytes_share = share; + /// Sets the share of each of the caller's pools the creation receives. + pub const fn set_pool_shares(&mut self, shares: PoolAmounts) { + self.pool_shares = shares; } } diff --git a/crates/interpreter/src/interpreter_action/create_outcome.rs b/crates/interpreter/src/interpreter_action/create_outcome.rs index ee71dd688a..200508bb1a 100644 --- a/crates/interpreter/src/interpreter_action/create_outcome.rs +++ b/crates/interpreter/src/interpreter_action/create_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, PoolAmounts, StartCharge}; use primitives::{Address, Bytes}; /// Represents the outcome of a create operation in an interpreter. @@ -54,7 +54,7 @@ impl CreateOutcome { address, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, 0), + charged_start: StartCharge::new(0, PoolAmounts::ZERO), } } diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 79828853b7..22d3eadcce 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,7 +36,7 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{Gas, GasTracker, StartCharge}; +pub use gas::{ChildShares, Gas, GasTracker, PoolAmounts, PoolId, StartCharge}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index e1932319b1..7934dec745 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -24,7 +24,7 @@ use revm_interpreter::{ instructions::gas_table_spec, interpreter::{EthInterpreter, ExtBytecode}, FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, SharedMemory, + InterpreterAction, PoolAmounts, SharedMemory, }; use state::AccountInfo; use std::borrow::Cow; @@ -881,11 +881,13 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { "{name}: the hook sees the forward taken" ); let mut after_the_forward = at_hook; - after_the_forward.set_bytes_remaining(0); + after_the_forward.set_reservoir(0); + after_the_forward.set_pools_remaining(PoolAmounts::ZERO); assert_eq!( *gas.tracker(), after_the_forward, - "{name}: nothing is charged after the hook; the whole pool is forwarded" + "{name}: nothing is charged after the hook; the whole reservoir and every whole pool \ + are forwarded" ); let stipend = if matches!(op, CALL | CALLCODE) { params.call_stipend() @@ -1037,9 +1039,10 @@ fn test_the_value_stipend_is_not_part_of_the_forward() { } } -/// The frame's input copies the reservoir as the hook left it, for every kind of start. A charge the -/// reservoir covers leaves the forward and the caller's regular gas alone; one that spills draws the -/// caller's regular gas and empties the reservoir, and the forward is still what was taken before. +/// The frame's input takes the reservoir as the hook left it, for every kind of start, out of the +/// caller's, which forwards the whole of it by default. A charge the reservoir covers leaves the +/// forward and the caller's regular gas alone; one that spills draws the caller's regular gas and +/// empties the reservoir, and the forward is still what was taken before. #[test] fn test_the_input_copies_the_reservoir_the_hook_left() { let spec = SpecId::AMSTERDAM; @@ -1055,7 +1058,11 @@ fn test_the_input_copies_the_reservoir_the_hook_left() { assert_eq!(host.start().1.reservoir(), 10_000, "{name}"); assert_eq!(input_reservoir, reservoir, "{name}, charge {charge}"); - assert_eq!(gas.reservoir(), reservoir, "{name}, charge {charge}"); + assert_eq!( + gas.reservoir(), + 0, + "{name}, charge {charge}: the caller forwarded the whole reservoir" + ); assert_eq!( gas_limit, quiet_limit, "{name}, charge {charge}: the forward" diff --git a/crates/interpreter/tests/byte_pool.rs b/crates/interpreter/tests/resource_pools.rs similarity index 91% rename from crates/interpreter/tests/byte_pool.rs rename to crates/interpreter/tests/resource_pools.rs index f90a3a826a..f0cd3c1296 100644 --- a/crates/interpreter/tests/byte_pool.rs +++ b/crates/interpreter/tests/resource_pools.rs @@ -24,7 +24,7 @@ use revm_interpreter::{ instructions::gas_table_spec, interpreter::{EthInterpreter, ExtBytecode}, FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, SharedMemory, StartCharge, + InterpreterAction, PoolAmounts, PoolId, SharedMemory, StartCharge, }; use state::AccountInfo; use std::borrow::Cow; @@ -39,8 +39,10 @@ const TARGET: Address = address!("0x0000000000000000000000000000000000007a59"); const AMPLE: u64 = 1_000_000; /// The pool the frame starts with, unless a test leaves it unlimited. const POOL: u64 = 1_000; +/// The pool the tests draw: any of the tracker's pools behaves the same. +const FIRST: PoolId = PoolId::new(0); /// A start charge a hook declares. -const DECLARED: StartCharge = StartCharge::new(3_520, 160); +const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); /// What a chain's schedule sets: the child's share and a value call's allowance. const PERCENT: u64 = 98; const ALLOWANCE: u64 = 160; @@ -77,7 +79,7 @@ impl PoolHost { /// call's child an allowance. fn on_a_chains_schedule(mut self) -> Self { self.params.override_gas([ - (GasId::bytes_forward_percent(), PERCENT), + (GasId::pool_forward_percent(FIRST), PERCENT), (GasId::call_history_allowance(), ALLOWANCE), ]); self @@ -112,7 +114,7 @@ impl Host for PoolHost { fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { let found = (*start, *gas); - let paid = gas.record_bytes(self.draw); + let paid = gas.record_pool(FIRST, self.draw); start.charge = self.declare; self.starts.push((found.0, found.1, paid)); self.admit && paid @@ -247,7 +249,7 @@ fn run(code: &[u8], pool: Option<u64>, host: &mut PoolHost) -> (InterpreterActio AMPLE, ); if let Some(pool) = pool { - interpreter.gas.set_bytes_remaining(pool); + interpreter.gas.set_pool_remaining(FIRST, pool); } let table = instruction_table::<EthInterpreter, PoolHost>(); let action = interpreter.run_plain(&table, &gas_table_spec(spec), host); @@ -275,11 +277,11 @@ fn returned(action: InterpreterAction) -> InstructionResult { fn figures(input: &FrameInput) -> (u64, StartCharge, u64) { match input { FrameInput::Call(inputs) => ( - inputs.bytes_share, + inputs.pool_shares.get(FIRST), inputs.charged_start, inputs.history_allowance, ), - FrameInput::Create(inputs) => (inputs.bytes_share(), inputs.charged_start(), 0), + FrameInput::Create(inputs) => (inputs.pool_shares().get(FIRST), inputs.charged_start(), 0), FrameInput::Empty => unreachable!(), } } @@ -336,12 +338,16 @@ fn test_every_start_forwards_the_whole_pool_by_default() { "{kind:?}" ); assert_eq!( - gas.bytes_remaining(), + gas.pool_remaining(FIRST), 0, "{kind:?}: the caller keeps nothing" ); - assert_eq!(gas.bytes_spent(), 0, "{kind:?}: a forward is not a draw"); - assert!(!gas.bytes_crossing(), "{kind:?}"); + assert_eq!( + gas.pool_spent(FIRST), + 0, + "{kind:?}: a forward is not a draw" + ); + assert!(!gas.pool_crossing(FIRST), "{kind:?}"); } } @@ -354,7 +360,7 @@ fn test_an_unlimited_pool_is_forwarded_unlimited() { let (share, _, _) = figures(&started(action)); assert_eq!(share, u64::MAX, "{kind:?}"); - assert_eq!(gas.bytes_remaining(), 0, "{kind:?}"); + assert_eq!(gas.pool_remaining(FIRST), 0, "{kind:?}"); } } @@ -371,7 +377,7 @@ fn test_the_share_follows_the_schedule_after_the_hooks_draw() { let (_, found, paid) = host.start(); assert_eq!( - found.bytes_remaining(), + found.pool_remaining(FIRST), POOL, "{kind:?}: the hook found the pool" ); @@ -379,11 +385,15 @@ fn test_the_share_follows_the_schedule_after_the_hooks_draw() { // 800 left after the draw; 98% of it, rounded down. assert_eq!(share, 784, "{kind:?}"); assert_eq!( - gas.bytes_remaining(), + gas.pool_remaining(FIRST), 16, "{kind:?}: the caller keeps the rest" ); - assert_eq!(gas.bytes_spent(), 200, "{kind:?}: the hook's draw stays"); + assert_eq!( + gas.pool_spent(FIRST), + 200, + "{kind:?}: the hook's draw stays" + ); } } @@ -414,12 +424,12 @@ fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); assert_eq!( - gas.bytes_remaining(), + gas.pool_remaining(FIRST), POOL - 200, "{kind:?}: no share taken" ); - assert_eq!(gas.bytes_spent(), 200, "{kind:?}"); - assert!(!gas.bytes_crossing(), "{kind:?}"); + assert_eq!(gas.pool_spent(FIRST), 200, "{kind:?}"); + assert!(!gas.pool_crossing(FIRST), "{kind:?}"); } } @@ -439,12 +449,12 @@ fn test_a_draw_the_pool_cannot_pay_records_a_crossing_that_survives_the_halt() { "{kind:?}: the halt zeroed the regular gas" ); assert_eq!( - gas.bytes_remaining(), + gas.pool_remaining(FIRST), POOL, "{kind:?}: the failed draw took nothing" ); - assert_eq!(gas.bytes_spent(), 0, "{kind:?}"); - assert!(gas.bytes_crossing(), "{kind:?}"); + assert_eq!(gas.pool_spent(FIRST), 0, "{kind:?}"); + assert!(gas.pool_crossing(FIRST), "{kind:?}"); } } diff --git a/crates/interpreter/tests/byte_pool_serde.rs b/crates/interpreter/tests/resource_pools_serde.rs similarity index 75% rename from crates/interpreter/tests/byte_pool_serde.rs rename to crates/interpreter/tests/resource_pools_serde.rs index a31b0c079b..7156d850b5 100644 --- a/crates/interpreter/tests/byte_pool_serde.rs +++ b/crates/interpreter/tests/resource_pools_serde.rs @@ -1,9 +1,9 @@ -//! Serde encoding of the byte-pool fields on the frame inputs and outcomes: the child's share, -//! the start charge and a call's history allowance. +//! Serde encoding of the pool fields on the frame inputs and outcomes: the child's shares of the +//! pools, the start charge and a call's history allowance. //! //! New encodings carry the fields. In a format that carries field names, such as the JSON these -//! tests use, encodings made before they existed lack them and still decode: to an unlimited -//! share, no start charge and no allowance, which is what a frame of a consumer that uses none of +//! tests use, encodings made before they existed lack them and still decode: to unlimited +//! shares, no start charge and no allowance, which is what a frame of a consumer that uses none of //! them carries. A format that encodes a struct by position, such as bincode, cannot read an //! encoding made before they existed, as with upstream's own field additions. #![cfg(feature = "serde")] @@ -12,13 +12,22 @@ use core::fmt::Debug; use primitives::{address, Bytes, U256}; use revm_interpreter::{ CallInput, CallInputs, CallOutcome, CallScheme, CallValue, CreateInputs, CreateOutcome, - CreateScheme, Gas, InstructionResult, InterpreterResult, StartCharge, + CreateScheme, Gas, InstructionResult, InterpreterResult, PoolAmounts, PoolId, StartCharge, }; use serde::{de::DeserializeOwned, Serialize}; use serde_json::Value; use state::Bytecode; -const CHARGE: StartCharge = StartCharge::new(3_520, 160); +/// The pool the tests draw: any of the tracker's pools behaves the same. +const FIRST: PoolId = PoolId::new(0); +const CHARGE: StartCharge = StartCharge::new( + 3_520, + PoolAmounts::ZERO.with(FIRST, 160).with(PoolId::new(2), 1), +); +/// Shares that differ by pool. +const SHARES: PoolAmounts = PoolAmounts::UNLIMITED + .with(FIRST, 980) + .with(PoolId::new(1), 0); /// Checks that `value` round-trips, and decodes to `without` once `fields` are removed from its /// encoding. @@ -68,14 +77,14 @@ fn test_call_inputs_decode_from_json_with_and_without_the_pool_fields() { is_static: false, charged_new_account_state_gas: true, charged_start: charge, - bytes_share: share, + pool_shares: share, history_allowance: allowance, }; assert_decodes_with_and_without( - &inputs(980, CHARGE, 160), - &["bytes_share", "charged_start", "history_allowance"], - &inputs(u64::MAX, StartCharge::default(), 0), + &inputs(SHARES, CHARGE, 160), + &["pool_shares", "charged_start", "history_allowance"], + &inputs(PoolAmounts::UNLIMITED, StartCharge::default(), 0), ); } @@ -90,17 +99,20 @@ fn test_create_inputs_decode_from_json_with_and_without_the_pool_fields() { 100_000, 50_000, ); - inputs.set_bytes_share(share); + inputs.set_pool_shares(share); inputs.set_charged_start(charge); inputs }; assert_decodes_with_and_without( - &inputs(980, CHARGE), - &["bytes_share", "charged_start"], - &inputs(u64::MAX, StartCharge::default()), + &inputs(SHARES, CHARGE), + &["pool_shares", "charged_start"], + &inputs(PoolAmounts::UNLIMITED, StartCharge::default()), + ); + assert_eq!( + CreateInputs::default().pool_shares(), + PoolAmounts::UNLIMITED ); - assert_eq!(CreateInputs::default().bytes_share(), u64::MAX); } #[test] From cc9956fa715901fe37c56ff4e49cc3d904d767ac Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 09:58:11 +0800 Subject: [PATCH 036/110] test: each pool and the reservoir are forwarded by their own shares at every start and at depth --- crates/handler/tests/resource_pools.rs | 101 +++++++++++++++++-- crates/interpreter/tests/resource_pools.rs | 110 ++++++++++++++++++++- 2 files changed, 202 insertions(+), 9 deletions(-) diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs index 8839e3dd3f..883db9e580 100644 --- a/crates/handler/tests/resource_pools.rs +++ b/crates/handler/tests/resource_pools.rs @@ -98,11 +98,18 @@ const LOG: u8 = 0x0e; const fn draw( context: InstructionContext<'_, TestContext, EthInterpreter>, ) -> InstructionExecResult { - if context.interpreter.gas.record_pool(FIRST, DRAW_BYTES) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) + let mut index = 0; + while index < PoolId::COUNT { + if !context + .interpreter + .gas + .record_pool(PoolId::ALL[index], DRAW_BYTES) + { + return Err(InstructionResult::OutOfGas); + } + index += 1; } + Ok(()) } /// Has the start hook charge and declare [`DECLARED`] at the start that follows. @@ -431,6 +438,15 @@ impl PrecompileProvider<TestContext> for DrawingPrecompiles { /// The figures of a frame's input as it started: its share, its start charge and its allowance. type Started = (u64, StartCharge, u64); +/// Every pool's share on a frame's input. +fn pool_shares(input: &FrameInput) -> PoolAmounts { + match input { + FrameInput::Call(inputs) => inputs.pool_shares, + FrameInput::Create(inputs) => inputs.pool_shares(), + FrameInput::Empty => unreachable!(), + } +} + fn started(input: &FrameInput) -> Started { match input { FrameInput::Call(inputs) => ( @@ -462,6 +478,11 @@ struct PoolHandler { starts: Vec<Started>, returned: Vec<Returned>, settled: Option<Settled>, + /// Every pool's share as each frame started. + pool_starts: Vec<PoolAmounts>, + /// Every pool of the transaction's gas, `(remaining, spent)`, after the first frame settled + /// into it. + settled_pools: Option<[(u64, i64); PoolId::COUNT]>, } impl PoolHandler { @@ -474,6 +495,8 @@ impl PoolHandler { starts: Vec::new(), returned: Vec::new(), settled: None, + pool_starts: Vec::new(), + settled_pools: None, } } } @@ -488,7 +511,9 @@ impl Handler for PoolHandler { fn tx_gas(&self, evm: &mut TestEvm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { let mut gas = self.mainnet.tx_gas(evm, init_and_floor_gas); if let Some(pool) = self.pool { - gas.set_pool_remaining(FIRST, pool); + for each in PoolId::ALL { + gas.set_pool_remaining(each, pool); + } } if self.declare { assert!(gas.record_history_cost(DECLARED.history)); @@ -523,6 +548,8 @@ impl Handler for PoolHandler { first_frame_input: FrameInit, ) -> Result<FrameResult, TestError> { self.starts.push(started(&first_frame_input.frame_input)); + self.pool_starts + .push(pool_shares(&first_frame_input.frame_input)); if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { self.returned.push(Returned::of(&result)); return Ok(result); @@ -531,6 +558,7 @@ impl Handler for PoolHandler { let result = match evm.frame_run()? { ItemOrResult::Item(mut init) => { self.starts.push(started(&init.frame_input)); + self.pool_starts.push(pool_shares(&init.frame_input)); if self.too_deep { init.depth = CALL_STACK_LIMIT as usize + 1; } @@ -565,6 +593,11 @@ impl Handler for PoolHandler { gas.history_gas_spent(), ))) }); + SETTLED_POOLS.with(|settled| { + settled.set(Some( + PoolId::ALL.map(|pool| (gas.pool_remaining(pool), gas.pool_spent(pool))), + )) + }); self.mainnet .post_execution(evm, exec_result, init_and_floor_gas, eip7702_refund) } @@ -572,6 +605,8 @@ impl Handler for PoolHandler { thread_local! { static SETTLED: core::cell::Cell<Option<Settled>> = const { core::cell::Cell::new(None) }; + static SETTLED_POOLS: core::cell::Cell<Option<[(u64, i64); PoolId::COUNT]>> = + const { core::cell::Cell::new(None) }; } /// `CALL(100_000, to, value, 0, 0, 0, 0)`, dropping the success flag. @@ -625,8 +660,10 @@ struct Run { deposit: Deposit, /// What the precompile provider draws on each answer. precompile_draw: u64, - /// `bytes_forward_percent` in the schedule, if not the default. + /// [`FIRST`]'s `pool_forward_percent` in the schedule, if not the default. forward_percent: Option<u64>, + /// Every pool's `pool_forward_percent` in the schedule, if not the default. + pool_percents: Option<[u64; PoolId::COUNT]>, /// Whether the transaction creates a contract from `parent` instead of calling [`PARENT`]. creates: bool, } @@ -641,6 +678,7 @@ impl Run { deposit: Deposit::Untouched, precompile_draw: 0, forward_percent: None, + pool_percents: None, creates: false, } } @@ -652,6 +690,11 @@ impl Run { run } + const fn pool_percents(mut self, percents: [u64; PoolId::COUNT]) -> Self { + self.pool_percents = Some(percents); + self + } + const fn forward_percent(mut self, percent: u64) -> Self { self.forward_percent = Some(percent); self @@ -716,12 +759,19 @@ impl Run { fn evm(&self) -> TestEvm { let allowance = self.allowance; let forward_percent = self.forward_percent; + let pool_percents = self.pool_percents; let inner = Context::mainnet() .with_db(self.db()) .modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); cfg.gas_params .override_gas([(GasId::call_history_allowance(), allowance)]); + if let Some(percents) = pool_percents { + for (pool, percent) in PoolId::ALL.into_iter().zip(percents) { + cfg.gas_params + .override_gas([(GasId::pool_forward_percent(pool), percent)]); + } + } if let Some(percent) = forward_percent { cfg.gas_params .override_gas([(GasId::pool_forward_percent(FIRST), percent)]); @@ -761,8 +811,10 @@ impl Run { /// recorded. fn with(&self, mut handler: PoolHandler) -> (ExecutionResult, PoolHandler) { SETTLED.with(|settled| settled.set(None)); + SETTLED_POOLS.with(|settled| settled.set(None)); let result = handler.run(&mut self.evm()).expect("the transaction runs"); handler.settled = SETTLED.with(|settled| settled.get()); + handler.settled_pools = SETTLED_POOLS.with(|settled| settled.get()); (result, handler) } @@ -1206,3 +1258,40 @@ fn test_a_share_below_the_whole_pool_is_forwarded_and_settled_at_depth() { ); assert_eq!(handler.settled, Some((800, 200, 0))); } + +/// Each pool is forwarded by its own share and settles alone: with the pools' percentages at 98, +/// 50 and 100, every start forwards that much of what its caller has left of each pool, rounded +/// down, and the caller keeps the rest of each; what a child hands back of each pool adds to what +/// its caller kept, so every pool ends where the whole-pool forward ends it. +#[test] +fn test_each_pool_is_forwarded_by_its_own_share_and_settled_at_depth() { + let (result, handler) = at_depth() + .pool_percents([98, 50, 100]) + .with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{result:?}"); + // PARENT drew 100 of each pool before each start; OK drew 100 and handed back the rest, so + // PARENT holds 800 of each for the later starts. NESTER drew 100 of each of its shares (784, + // 400, 800) before calling OK. + let each = |shares: [u64; PoolId::COUNT]| { + PoolAmounts::ZERO + .with(PoolId::new(0), shares[0]) + .with(PoolId::new(1), shares[1]) + .with(PoolId::new(2), shares[2]) + }; + assert_eq!( + handler.pool_starts, + [ + each([POOL; 3]), + // 98%, 50% and 100% of 900. + each([882, 450, 900]), + // Of 800. + each([784, 400, 800]), + each([784, 400, 800]), + each([784, 400, 800]), + // Of 684, 300 and 700: 98% of 684 is 670.32. + each([670, 150, 700]), + ] + ); + assert_eq!(handler.settled_pools, Some([(800, 200); 3])); +} diff --git a/crates/interpreter/tests/resource_pools.rs b/crates/interpreter/tests/resource_pools.rs index f0cd3c1296..27e62687ed 100644 --- a/crates/interpreter/tests/resource_pools.rs +++ b/crates/interpreter/tests/resource_pools.rs @@ -235,6 +235,19 @@ impl Host for PoolHost { /// Runs `code` as [`CONTRACT`], called by [`CALLER`], with [`AMPLE`] gas and a byte pool of /// `pool`, if given, and returns what the frame asked for and its gas. fn run(code: &[u8], pool: Option<u64>, host: &mut PoolHost) -> (InterpreterAction, Gas) { + run_on(code, host, |gas| { + if let Some(pool) = pool { + gas.set_pool_remaining(FIRST, pool); + } + }) +} + +/// Runs `code` as [`run`] does, on the gas `prepare` leaves. +fn run_on( + code: &[u8], + host: &mut PoolHost, + prepare: impl FnOnce(&mut Gas), +) -> (InterpreterAction, Gas) { let spec = host.spec; let mut interpreter = Interpreter::<EthInterpreter>::new( SharedMemory::new(), @@ -248,9 +261,7 @@ fn run(code: &[u8], pool: Option<u64>, host: &mut PoolHost) -> (InterpreterActio spec, AMPLE, ); - if let Some(pool) = pool { - interpreter.gas.set_pool_remaining(FIRST, pool); - } + prepare(&mut interpreter.gas); let table = instruction_table::<EthInterpreter, PoolHost>(); let action = interpreter.run_plain(&table, &gas_table_spec(spec), host); (action, interpreter.gas) @@ -482,3 +493,96 @@ fn test_the_history_allowance_is_set_on_a_value_call_only() { assert_eq!(found, 0, "{name}: none on the default schedule"); } } + +/// The pools a frame holds in the tests of every pool, and its reservoir. +const POOLS: [u64; PoolId::COUNT] = [1_000, 500, 100]; +const RESERVOIR: u64 = 1_000; + +/// The reservoir and every pool's share of a started frame's input. +fn shares(input: &FrameInput) -> (u64, PoolAmounts) { + match input { + FrameInput::Call(inputs) => (inputs.reservoir, inputs.pool_shares), + FrameInput::Create(inputs) => (inputs.reservoir(), inputs.pool_shares()), + FrameInput::Empty => unreachable!(), + } +} + +/// [`POOLS`] and [`RESERVOIR`] on the frame's gas. +fn with_pools(gas: &mut Gas) { + for (pool, amount) in PoolId::ALL.into_iter().zip(POOLS) { + gas.set_pool_remaining(pool, amount); + } + gas.set_reservoir(RESERVOIR); +} + +/// `(reservoir, pools)` of `gas`. +fn held(gas: &GasTracker) -> (u64, [u64; PoolId::COUNT]) { + ( + gas.reservoir(), + PoolId::ALL.map(|pool| gas.pool_remaining(pool)), + ) +} + +/// By default every start forwards the whole reservoir and every whole pool, each taken out of +/// the caller, which holds none of them while the child runs; with the reservoir and each pool +/// given its own percentage, each is forwarded by its own share, rounded down, and the caller +/// keeps the rest of each. +#[test] +fn test_every_start_forwards_the_reservoir_and_each_pool_by_its_own_share() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA); + let (action, gas) = run_on(&code, &mut host, with_pools); + let (reservoir, pools) = shares(&started(action)); + assert_eq!( + (reservoir, PoolId::ALL.map(|pool| pools.get(pool))), + (RESERVOIR, POOLS), + "{kind:?}: everything forwarded" + ); + assert_eq!( + held(gas.tracker()), + (0, [0; 3]), + "{kind:?}: the caller holds none" + ); + assert_eq!( + held(&host.start().1), + (RESERVOIR, POOLS), + "{kind:?}: the hook found all" + ); + + let mut host = PoolHost::new(SpecId::OSAKA); + host.params.override_gas([ + (GasId::reservoir_forward_percent(), 98), + (GasId::pool_forward_percent(PoolId::new(0)), 98), + (GasId::pool_forward_percent(PoolId::new(1)), 50), + (GasId::pool_forward_percent(PoolId::new(2)), 0), + ]); + let (action, gas) = run_on(&code, &mut host, with_pools); + let (reservoir, pools) = shares(&started(action)); + assert_eq!( + (reservoir, PoolId::ALL.map(|pool| pools.get(pool))), + (980, [980, 250, 0]), + "{kind:?}: each by its share" + ); + assert_eq!( + held(gas.tracker()), + (20, [20, 250, 100]), + "{kind:?}: the caller keeps the rest" + ); + } +} + +/// A start the hook refuses takes no share of the reservoir or of any pool. +#[test] +fn test_a_refused_start_forwards_no_reservoir_and_no_pool() { + for (kind, code) in start_cases() { + let mut host = PoolHost::new(SpecId::OSAKA).refusing(); + let (action, gas) = run_on(&code, &mut host, with_pools); + + assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); + assert_eq!( + held(gas.tracker()), + (RESERVOIR, POOLS), + "{kind:?}: nothing taken" + ); + } +} From ec7c08063d631672eef251fc3daaeaa80449b25f Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 09:58:11 +0800 Subject: [PATCH 037/110] test: the reservoir share at depth, past the share, on a restoration, answers, a system call and an inspector's outcome --- crates/handler/tests/reservoir_share.rs | 671 ++++++++++++++++++++++ crates/inspector/tests/reservoir_share.rs | 171 ++++++ 2 files changed, 842 insertions(+) create mode 100644 crates/handler/tests/reservoir_share.rs create mode 100644 crates/inspector/tests/reservoir_share.rs diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs new file mode 100644 index 0000000000..235827ca50 --- /dev/null +++ b/crates/handler/tests/reservoir_share.rs @@ -0,0 +1,671 @@ +//! The share of its caller's EIP-8037 reservoir a child frame receives, as the mainnet handler +//! forwards and settles it. +//! +//! A frame start takes the schedule's `reservoir_forward_percent` of its caller's reservoir out of +//! the caller's tracker for the child, and the child's return adds what the child left to what the +//! caller kept. Every schedule forwards the whole reservoir, which is upstream's forward; these +//! tests set 98, a chain that keeps 2% of the reservoir for the caller, and compare with it. +//! +//! The transactions run on Amsterdam with a gas limit [`RESERVOIR`] above the regular cap, so they +//! start with a reservoir. The frames charge state gas through an instruction of the test's own, +//! `CHARGE`, which stands in for a write's state charge, and through `SSTORE`. The handler is the +//! mainnet one, observed through overrides that leave its behaviour alone: each frame's reservoir +//! as it starts, and as it returns before its caller settles it. + +use bytecode::opcode::{ + CALL, DELEGATECALL, INVALID, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, SSTORE, STOP, +}; +use context::{ + result::{EVMError, ExecutionResult}, + Context, ContextSetters, ContextTr, Evm, TxEnv, +}; +use context_interface::{ + cfg::{gas::InitialAndFloorGas, GasId}, + Cfg, Database, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, +}; +use primitives::{ + address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, TxKind, U256, +}; +use revm_handler::{ + instructions::EthInstructions, system_call::SystemCallTx, EthFrame, EthPrecompiles, EvmTr, + FrameResult, Handler, ItemOrResult, MainContext, MainnetContext, MainnetHandler, +}; +use state::{AccountInfo, Bytecode}; + +type Db = CacheDB<EmptyDB>; +type DbError = <Db as Database>::Error; +type TestContext = MainnetContext<Db>; +type TestEvm = + Evm<TestContext, (), EthInstructions<EthInterpreter, TestContext>, EthPrecompiles, EthFrame>; +type TestError = EVMError<DbError>; +type Mainnet = MainnetHandler<TestEvm, TestError, EthFrame<EthInterpreter>>; + +const SPEC: SpecId = SpecId::AMSTERDAM; +const GAS_LIMIT: u64 = 3_000_000; +/// The reservoir a transaction starts with: the regular cap is set this far below +/// [`GAS_LIMIT`], and no transaction here pays state gas in its intrinsic cost. +const RESERVOIR: u64 = 1_000_000; +/// What `CHARGE` charges as state gas. +const CHARGED: u64 = 1_000; +/// The share of a caller's reservoir a chain that keeps part of it forwards. +const PERCENT: u64 = 98; +/// State gas of a new storage slot on Amsterdam's schedule. +const SLOT: u64 = 97_920; + +/// The account the transaction calls. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Charges and stops. +const OK: Address = address!("0x0000000000000000000000000000000000000c00"); +/// Charges and reverts. +const REVERTER: Address = address!("0x000000000000000000000000000000000000c0fd"); +/// Charges and halts. +const HALTER: Address = address!("0x000000000000000000000000000000000000c0fe"); +/// Charges, calls [`OK`] and reverts. +const NESTER: Address = address!("0x000000000000000000000000000000000000c0e5"); +/// Charges a thousand times what `CHARGE` does, past any share here. +const SPENDER: Address = address!("0x000000000000000000000000000000000000c5e0"); +/// Clears its caller's slot 0 and stops, run by `DELEGATECALL` on the caller's storage. +const RESTORER: Address = address!("0x000000000000000000000000000000000000c0e0"); +/// Clears its caller's slot 0 and reverts. +const RESTORER_REVERTS: Address = address!("0x000000000000000000000000000000000000c0e1"); +/// The `ECRECOVER` precompile. +const ECRECOVER: Address = address!("0x0000000000000000000000000000000000000001"); + +/// The test's instruction, on an opcode the EVM does not assign. +const CHARGE: u8 = 0x0c; + +/// Charges [`CHARGED`] of state gas on the frame, reservoir first, as a write's state charge +/// does; a charge the frame cannot pay is its out-of-gas. +const fn charge( + context: InstructionContext<'_, TestContext, EthInterpreter>, +) -> InstructionExecResult { + if context.interpreter.gas.record_state_cost(CHARGED) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } +} + +/// A frame's figures as it returned, before its caller settled it: its result, its reservoir and +/// its net state gas. +type Returned = (InstructionResult, u64, i64); + +fn returned(result: &FrameResult) -> Returned { + let gas = result.gas(); + ( + result.instruction_result(), + gas.reservoir(), + gas.state_gas_spent(), + ) +} + +fn reservoir_of(input: &FrameInput) -> u64 { + match input { + FrameInput::Call(inputs) => inputs.reservoir, + FrameInput::Create(inputs) => inputs.reservoir(), + FrameInput::Empty => unreachable!(), + } +} + +/// The mainnet handler, recording every frame's reservoir as it starts and its figures as it +/// returns, and the transaction's gas once the first frame settled into it. +struct ShareHandler { + mainnet: Mainnet, + /// Whether every frame below the transaction's starts one past the call-stack limit, where a + /// 1,025th nested start would. + too_deep: bool, + /// A reservoir to give the transaction's gas, as a consumer that splits a system call's gas + /// does; mainnet gives a system call none. + system_reservoir: Option<u64>, + starts: Vec<u64>, + returned: Vec<Returned>, + /// The transaction's reservoir and net state gas after the first frame settled into it. + settled: Option<(u64, i64)>, +} + +impl ShareHandler { + fn new() -> Self { + Self { + mainnet: Mainnet::default(), + too_deep: false, + system_reservoir: None, + starts: Vec::new(), + returned: Vec::new(), + settled: None, + } + } +} + +impl Handler for ShareHandler { + type Evm = TestEvm; + type Error = TestError; + type HaltReason = context::result::HaltReason; + + fn tx_gas(&self, evm: &mut TestEvm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.mainnet.tx_gas(evm, init_and_floor_gas); + if let Some(reservoir) = self.system_reservoir { + gas.set_remaining(gas.remaining() - reservoir); + gas.set_reservoir(reservoir); + } + gas + } + + /// The default loop, recording each frame's reservoir as it starts and its figures as it + /// returns, and starting the frames below the transaction's past the call-stack limit if told + /// to. + fn run_exec_loop( + &mut self, + evm: &mut TestEvm, + first_frame_input: FrameInit, + ) -> Result<FrameResult, TestError> { + self.starts + .push(reservoir_of(&first_frame_input.frame_input)); + if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { + self.returned.push(returned(&result)); + return Ok(result); + } + loop { + let result = match evm.frame_run()? { + ItemOrResult::Item(mut init) => { + self.starts.push(reservoir_of(&init.frame_input)); + if self.too_deep { + init.depth = CALL_STACK_LIMIT as usize + 1; + } + match evm.frame_init(init)? { + ItemOrResult::Item(_) => continue, + ItemOrResult::Result(result) => result, + } + } + ItemOrResult::Result(result) => result, + }; + self.returned.push(returned(&result)); + if let Some(result) = evm.frame_return_result(result)? { + return Ok(result); + } + } + } + + /// The default, recording the transaction's gas as the first frame left it. + fn last_frame_result( + &mut self, + evm: &mut TestEvm, + frame_result: &mut FrameResult, + gas: &mut GasTracker, + ) -> Result<(), TestError> { + self.mainnet.last_frame_result(evm, frame_result, gas)?; + self.settled = Some((gas.reservoir(), gas.state_gas_spent())); + Ok(()) + } +} + +/// `op(gas, to, value, 0, 0, 0, 0)` for `CALL`, `op(gas, to, 0, 0, 0, 0)` for `DELEGATECALL`, +/// dropping the success flag. +fn call_with(op: u8, to: Address, value: u8, gas: u32) -> Vec<u8> { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0]; + if op == CALL { + code.extend_from_slice(&[PUSH1, value]); + } + code.push(PUSH20); + code.extend_from_slice(to.as_slice()); + code.push(PUSH3); + code.extend_from_slice(&gas.to_be_bytes()[1..]); + code.extend_from_slice(&[op, POP]); + code +} + +/// `CALL(100_000, to, 0, 0, 0, 0, 0)`, dropping the success flag. +fn call(to: Address) -> Vec<u8> { + call_with(CALL, to, 0, 100_000) +} + +fn ends(mut code: Vec<u8>) -> Vec<u8> { + code.push(STOP); + code +} + +/// A transaction that calls [`PARENT`], which holds `parent`. +struct Run { + parent: Vec<u8>, + parent_balance: u64, + /// `reservoir_forward_percent` in the schedule, if not the default. + percent: Option<u64>, +} + +impl Run { + const fn new(parent: Vec<u8>) -> Self { + Self { + parent, + parent_balance: 10, + percent: None, + } + } + + const fn percent(mut self, percent: u64) -> Self { + self.percent = Some(percent); + self + } + + const fn penniless(mut self) -> Self { + self.parent_balance = 0; + self + } + + fn db(&self) -> Db { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut nester = vec![CHARGE]; + nester.extend(call(OK)); + nester.extend_from_slice(&[PUSH0, PUSH0, REVERT]); + let accounts: [(Address, Vec<u8>, u64); 8] = [ + (PARENT, self.parent.clone(), self.parent_balance), + (OK, vec![CHARGE, STOP], 0), + (REVERTER, vec![CHARGE, PUSH0, PUSH0, REVERT], 0), + (HALTER, vec![CHARGE, INVALID], 0), + (NESTER, nester, 0), + ( + SPENDER, + [CHARGE; 1_000].into_iter().chain([STOP]).collect(), + 0, + ), + (RESTORER, vec![PUSH0, PUSH0, SSTORE, STOP], 0), + ( + RESTORER_REVERTS, + vec![PUSH0, PUSH0, SSTORE, PUSH0, PUSH0, REVERT], + 0, + ), + ]; + for (address, code, balance) in accounts { + let info = AccountInfo::from_balance(U256::from(balance)) + .with_nonce(1) + .with_code(Bytecode::new_raw(Bytes::from(code))); + db.insert_account_info(address, info); + } + db + } + + fn evm(&self) -> TestEvm { + let percent = self.percent; + let ctx = Context::mainnet() + .with_db(self.db()) + .modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SPEC); + cfg.tx_gas_limit_cap = Some(GAS_LIMIT - RESERVOIR); + if let Some(percent) = percent { + cfg.gas_params + .override_gas([(GasId::reservoir_forward_percent(), percent)]); + } + }); + let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); + instructions.insert_instruction(CHARGE, Instruction::new(charge), 0); + let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(SPEC)); + evm.ctx.set_tx( + TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(), + ); + evm + } + + /// Runs the transaction with `handler` and returns its result and the handler, with what it + /// recorded. + fn with(&self, mut handler: ShareHandler) -> (ExecutionResult, ShareHandler) { + let result = handler.run(&mut self.evm()).expect("the transaction runs"); + (result, handler) + } + + fn run(&self) -> (ExecutionResult, ShareHandler) { + self.with(ShareHandler::new()) + } +} + +/// [`PARENT`] charges, then calls a child that stops, one that reverts, one that halts and one +/// that calls a child of its own and reverts, each after a charge of its own. +fn at_depth() -> Run { + let mut parent = vec![CHARGE]; + for child in [OK, REVERTER, HALTER, NESTER] { + parent.extend(call(child)); + } + Run::new(ends(parent)) +} + +/// 98% of `reservoir`, rounded down. +const fn share(reservoir: u64) -> u64 { + reservoir * PERCENT / 100 +} + +/// Every start forwards 98% of its caller's reservoir, rounded down, and the caller keeps the +/// rest; what a child hands back adds to what its caller kept: what it left when it succeeded, +/// the whole share when it reverted or halted, a successful grandchild's charge included. The +/// transaction's frame takes the whole reservoir. No frame here spends past its share, so the +/// transaction ends with the figures the whole forward gives, and the same result. +#[test] +fn test_the_reservoir_is_forwarded_by_its_share_and_settled_at_depth() { + let (result, handler) = at_depth().percent(PERCENT).run(); + + assert!(result.is_success(), "{result:?}"); + // PARENT charged 1,000 of its 1,000,000 before each start below. + let after_parent = RESERVOIR - CHARGED; + assert_eq!(share(after_parent), 979_020); + // OK returns 978,020, so PARENT holds 19,980 + 978,020 = 998,000 for each later start. + let before_each = after_parent - CHARGED; + assert_eq!(share(before_each), 978_040); + // NESTER charged 1,000 of its 978,040 before calling OK: 98% of 977,040 is 957,499.2. + let nester_after = share(before_each) - CHARGED; + assert_eq!(share(nester_after), 957_499); + assert_eq!( + handler.starts, + [ + RESERVOIR, + share(after_parent), + share(before_each), + share(before_each), + share(before_each), + share(nester_after), + ] + ); + let charged = CHARGED as i64; + assert_eq!( + handler.returned, + [ + ( + InstructionResult::Stop, + share(after_parent) - CHARGED, + charged + ), + ( + InstructionResult::Revert, + share(before_each) - CHARGED, + charged + ), + ( + InstructionResult::InvalidFEOpcode, + share(before_each) - CHARGED, + charged + ), + // OK under NESTER: 957,499 less its charge. + ( + InstructionResult::Stop, + share(nester_after) - CHARGED, + charged + ), + // NESTER kept 19,541 and got back 956,499: 976,040, two charges net. + (InstructionResult::Revert, 976_040, 2 * charged), + ( + InstructionResult::Stop, + RESERVOIR - 2 * CHARGED, + 2 * charged + ), + ] + ); + assert_eq!( + handler.settled, + Some((RESERVOIR - 2 * CHARGED, 2 * charged)) + ); + + let (whole, whole_handler) = at_depth().run(); + assert_eq!(result, whole, "the shares change no result here"); + assert_eq!(whole_handler.settled, handler.settled); +} + +/// The whole forward is upstream's: every start passes on all its caller has, and the caller +/// holds none while the child runs. +#[test] +fn test_every_start_forwards_the_whole_reservoir_by_default() { + let (result, handler) = at_depth().run(); + + assert!(result.is_success(), "{result:?}"); + let before_each = RESERVOIR - 2 * CHARGED; + assert_eq!( + handler.starts, + [ + RESERVOIR, + RESERVOIR - CHARGED, + before_each, + before_each, + before_each, + before_each - CHARGED, + ] + ); + let charged = CHARGED as i64; + // NESTER and its OK each charged once on what NESTER started with. + assert_eq!( + handler.returned[4], + ( + InstructionResult::Revert, + before_each - 2 * CHARGED, + 2 * charged + ) + ); + assert_eq!(handler.settled, Some((before_each, 2 * charged))); +} + +/// A child whose charges pass its share spills onto its regular gas, as a frame whose reservoir +/// is empty does, though its caller holds the 2% it kept: the share is all the child has. On +/// return the caller holds what it kept beside the child's spill; when the caller's own frame +/// returns, its reservoir unwinds that spill first, as any returned reservoir does (last in, first +/// out), so the transaction ends as the whole forward ends it. +#[test] +fn test_a_child_spends_past_its_share_onto_its_regular_gas() { + let parent = ends(call(SPENDER)); + let (result, handler) = Run::new(parent.clone()).percent(PERCENT).run(); + let (whole, whole_handler) = Run::new(parent).run(); + + assert!( + result.is_success() && whole.is_success(), + "{result:?} {whole:?}" + ); + let spent = (1_000 * CHARGED) as i64; + // The share is 980,000 of 1,000,000: 20,000 of the million charged spill. + assert_eq!(handler.starts, [RESERVOIR, share(RESERVOIR)]); + assert_eq!( + handler.returned, + [ + (InstructionResult::Stop, 0, spent), + (InstructionResult::Stop, RESERVOIR - share(RESERVOIR), spent), + ], + "the share is spent and the rest spilled; PARENT holds what it kept" + ); + // With the whole reservoir forwarded, the million fits it exactly and nothing spills. + assert_eq!( + whole_handler.returned, + [ + (InstructionResult::Stop, 0, spent), + (InstructionResult::Stop, 0, spent) + ] + ); + assert_eq!(handler.settled, Some((0, spent))); + assert_eq!(whole_handler.settled, handler.settled); + assert_eq!(result, whole); +} + +/// The share is what the child may draw from the reservoir while it runs: a child that needs the +/// whole reservoir and has too little regular gas to pay past its share runs out of gas at 98%, +/// and its failure gives the share back, where the whole forward lets it finish. +#[test] +fn test_a_child_that_cannot_pay_past_its_share_runs_out_of_gas() { + let parent = ends(call_with(CALL, SPENDER, 0, 10_000)); + let (result, handler) = Run::new(parent.clone()).percent(PERCENT).run(); + let (whole, whole_handler) = Run::new(parent).run(); + + assert!( + result.is_success() && whole.is_success(), + "{result:?} {whole:?}" + ); + // 980 charges spend the share, ten more spill its 10,000 of regular gas, the 991st fails. + assert_eq!( + handler.returned[0], + ( + InstructionResult::OutOfGas, + 0, + (991 * CHARGED - CHARGED) as i64 + ) + ); + assert_eq!( + handler.settled, + Some((RESERVOIR, 0)), + "nothing charged in the end" + ); + let spent = (1_000 * CHARGED) as i64; + assert_eq!( + whole_handler.returned[0], + (InstructionResult::Stop, 0, spent) + ); + assert_eq!(whole_handler.settled, Some((0, spent))); +} + +/// A child that clears a slot its caller created gets the slot's state gas back as an EIP-8037 +/// restoration, into its own reservoir; when it succeeds, the caller adds it with the rest of the +/// share to what it kept, and is back where it was before it created the slot. When it reverts, +/// the restoration is undone with the rest of its frame and the caller gets the share back. +#[test] +fn test_a_restoration_in_the_child_comes_back_to_its_caller() { + for (restorer, kept) in [(RESTORER, true), (RESTORER_REVERTS, false)] { + let mut parent = vec![PUSH1, 1, PUSH0, SSTORE]; + parent.extend(call_with(DELEGATECALL, restorer, 0, 100_000)); + let (result, handler) = Run::new(ends(parent)).percent(PERCENT).run(); + + assert!(result.is_success(), "{restorer}: {result:?}"); + let created = RESERVOIR - SLOT; + assert_eq!(handler.starts, [RESERVOIR, share(created)], "{restorer}"); + if kept { + assert_eq!( + handler.returned[0], + ( + InstructionResult::Stop, + share(created) + SLOT, + -(SLOT as i64) + ), + "the restoration lands in the child's reservoir" + ); + assert_eq!( + handler.settled, + Some((RESERVOIR, 0)), + "nothing charged in all" + ); + } else { + assert_eq!( + handler.returned[0], + ( + InstructionResult::Revert, + share(created) + SLOT, + -(SLOT as i64) + ), + ); + assert_eq!( + handler.settled, + Some((created, SLOT as i64)), + "the slot stays, and its charge" + ); + } + } +} + +/// A precompile's answer carries the share it was given, which comes back whole; so does a start +/// the handler refuses before any frame: a transfer the caller cannot pay, and a start one past +/// the call-stack limit. +#[test] +fn test_an_answer_without_a_frame_hands_the_share_back() { + let mut precompile = vec![CHARGE]; + precompile.extend(call(ECRECOVER)); + let mut transfer = vec![CHARGE]; + transfer.extend(call_with(CALL, OK, 1, 100_000)); + let mut deep = vec![CHARGE]; + deep.extend(call(OK)); + for (name, run, too_deep, answer) in [ + ( + "a precompile", + Run::new(ends(precompile)), + false, + InstructionResult::Return, + ), + ( + "an unpaid transfer", + Run::new(ends(transfer)).penniless(), + false, + InstructionResult::OutOfFunds, + ), + ( + "too deep", + Run::new(ends(deep)), + true, + InstructionResult::CallTooDeep, + ), + ] { + let mut handler = ShareHandler::new(); + handler.too_deep = too_deep; + let (result, handler) = run.percent(PERCENT).with(handler); + + assert!(result.is_success(), "{name}: {result:?}"); + let before = RESERVOIR - CHARGED; + assert_eq!(handler.starts, [RESERVOIR, share(before)], "{name}"); + assert_eq!( + handler.returned[0], + (answer, share(before), 0), + "{name}: the answer carries the share" + ); + assert_eq!( + handler.settled, + Some((before, CHARGED as i64)), + "{name}: PARENT's reservoir whole again" + ); + } +} + +/// A system call's frame takes the whole reservoir its gas holds, a consumer's split of the +/// system call's gas, and its children their shares, as a transaction's do. +#[test] +fn test_a_system_call_forwards_and_settles_its_reservoir() { + for percent in [None, Some(PERCENT)] { + let mut run = Run::new(ends(call(OK))); + run.percent = percent; + let mut evm = run.evm(); + evm.ctx.set_tx(TxEnv::new_system_tx(PARENT, Bytes::new())); + let mut handler = ShareHandler::new(); + handler.system_reservoir = Some(RESERVOIR); + + let result = handler + .run_system_call(&mut evm) + .expect("the system call runs"); + + assert!(result.is_success(), "{percent:?}: {result:?}"); + let child = if percent.is_some() { + share(RESERVOIR) + } else { + RESERVOIR + }; + assert_eq!(handler.starts, [RESERVOIR, child], "{percent:?}"); + assert_eq!( + handler.returned[0], + (InstructionResult::Stop, child - CHARGED, CHARGED as i64), + "{percent:?}" + ); + assert_eq!( + handler.settled, + Some((RESERVOIR - CHARGED, CHARGED as i64)), + "{percent:?}" + ); + } +} + +/// The schedule's entry is upstream's forward on every spec. +#[test] +fn test_the_schedule_forwards_the_whole_reservoir() { + let evm = Run::new(ends(Vec::new())).evm(); + assert_eq!( + evm.ctx + .cfg() + .gas_params() + .get(GasId::reservoir_forward_percent()), + 100 + ); +} diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs new file mode 100644 index 0000000000..ffe01db019 --- /dev/null +++ b/crates/inspector/tests/reservoir_share.rs @@ -0,0 +1,171 @@ +//! An outcome an inspector builds to answer a start settles its reservoir as built, on top of +//! what the caller kept when it forwarded its share. +//! +//! The caller's start takes the schedule's share of its reservoir out of its tracker, and the +//! answer's reservoir is added back to what the caller kept, as a frame's is. An answer built on +//! `Gas::new` carries no reservoir: with the whole reservoir forwarded, which every schedule does, +//! the caller is left with none, as upstream's settlement, which put the answer's reservoir in +//! place of the caller's, leaves it; with 98% forwarded, the caller is left with the 2% it kept. +//! An answer that carries the input's reservoir gives the caller back what it forwarded. + +use context::{context_interface::cfg::GasId, Context, Evm, TxEnv}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + instructions::EthInstructions, EthFrame, EthPrecompiles, MainContext, MainnetContext, +}; +use interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{InspectEvm, Inspector}; +use state::{ + bytecode::opcode::{CALL, POP, PUSH0, PUSH1, PUSH20, PUSH3, SSTORE, STOP}, + AccountInfo, Bytecode, +}; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; + +const SPEC: SpecId = SpecId::AMSTERDAM; +const GAS_LIMIT: u64 = 3_000_000; +/// The reservoir the transaction starts with: the regular cap is this far below [`GAS_LIMIT`]. +const RESERVOIR: u64 = 1_000_000; +/// State gas of a new storage slot on Amsterdam's schedule, which [`PARENT`] pays. +const SLOT: u64 = 97_920; +/// What [`PARENT`] holds when it calls [`OK`]. +const BEFORE_THE_CALL: u64 = RESERVOIR - SLOT; +/// 98% of it, rounded down: 884,038.4. +const SHARE: u64 = 884_038; + +/// Writes a new slot, calls [`OK`] and stops. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Stops, when it runs. +const OK: Address = address!("0x0000000000000000000000000000000000000c00"); + +/// What the inspector does with the call to [`OK`]. +#[derive(Clone, Copy, Debug)] +enum Answer { + /// Lets it run. + Runs, + /// Answers it with a revert built on `Gas::new`, as a tool does. + AsBuilt, + /// Answers it with a revert that carries the input's reservoir and pool shares. + WithTheShares, +} + +/// Answers the call to [`OK`] as told, and records the reservoir the call was given and +/// [`PARENT`]'s reservoir as its frame returned, before the transaction settled it. +struct Answering { + answer: Answer, + given: Option<u64>, + parent_returned: Option<u64>, +} + +impl Inspector<Ctx, EthInterpreter> for Answering { + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + if inputs.target_address != OK { + return None; + } + self.given = Some(inputs.reservoir); + let gas = match self.answer { + Answer::Runs => return None, + Answer::AsBuilt => Gas::new(inputs.gas_limit), + Answer::WithTheShares => { + let mut gas = + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares); + gas + } + }; + Some(CallOutcome::new( + InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + )) + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address == PARENT { + self.parent_returned = Some(outcome.result.gas.reservoir()); + } + } +} + +/// [`PARENT`]'s reservoir as its frame returned, and the reservoir the call to [`OK`] was given, +/// with `percent` as the schedule's `reservoir_forward_percent`. +fn run(answer: Answer, percent: Option<u64>) -> (u64, u64) { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut parent = vec![ + PUSH1, 1, PUSH0, SSTORE, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20, + ]; + parent.extend_from_slice(OK.as_slice()); + parent.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP, STOP]); + for (address, code) in [(PARENT, parent), (OK, vec![STOP])] { + db.insert_account_info( + address, + AccountInfo::default() + .with_nonce(1) + .with_code(Bytecode::new_raw(code.into())), + ); + } + let ctx = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SPEC); + cfg.tx_gas_limit_cap = Some(GAS_LIMIT - RESERVOIR); + if let Some(percent) = percent { + cfg.gas_params + .override_gas([(GasId::reservoir_forward_percent(), percent)]); + } + }); + let mut evm: Evm< + Ctx, + Answering, + EthInstructions<EthInterpreter, Ctx>, + EthPrecompiles, + EthFrame, + > = Evm::new_with_inspector( + ctx, + Answering { + answer, + given: None, + parent_returned: None, + }, + EthInstructions::new_mainnet_with_spec(SPEC), + EthPrecompiles::new(SPEC), + ); + let tx = TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(); + let outcome = evm.inspect_tx(tx).expect("the transaction runs"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + ( + evm.inspector.parent_returned.expect("PARENT returned"), + evm.inspector.given.expect("the call to OK started"), + ) +} + +#[test] +fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { + for (answer, whole, kept_98) in [ + (Answer::Runs, BEFORE_THE_CALL, BEFORE_THE_CALL), + // Upstream's settlement gives the caller the answer's empty reservoir in place of its + // own; the whole forward left the caller nothing to add it to, so the same. + (Answer::AsBuilt, 0, BEFORE_THE_CALL - SHARE), + (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), + ] { + assert_eq!( + run(answer, None), + (whole, BEFORE_THE_CALL), + "{answer:?}, the whole reservoir forwarded" + ); + assert_eq!( + run(answer, Some(98)), + (kept_98, SHARE), + "{answer:?}, 98% forwarded" + ); + } +} From 3549ea9724f62f490072c24f00a41aae4adccbd1 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:07:47 +0800 Subject: [PATCH 038/110] docs: resource pools, the reservoir share and a creation start's would-be address in MEGAETH-FORK.md --- MEGAETH-FORK.md | 118 ++++++++++++++++++++++++++++++------------------ 1 file changed, 74 insertions(+), 44 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 9ab706e562..baf0124c0a 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -154,7 +154,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns. - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. - It takes two words of the tracker, a number and a flag, and the flag's word also holds the byte pool's crossing (see The byte pool); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words. + It takes two words of the tracker, a number and a flag, and the flag's word also holds the pools' crossings (see Resource pools); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words. Encoded, the record is an optional number in the field's place. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. @@ -189,7 +189,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an A creation `return_create` fails itself, out of gas on a deposit charge included, is never offered. Before Homestead a deposit the frame cannot pay does not fail: `return_create` deploys empty code instead, and offers that deposit with empty code and no charge. If the failed charge was a crossing of the frame's withheld gas, `gas_after` carries its crossing record and `gas_before` does not, so an admitted deposit keeps the record and a refusal discards it. - `gas` is the creating frame's tracker, which `gas_after` reads a copy of: the hook may debit and credit it, for instance draw the deployed code's bytes from the frame's pool (see The byte pool), and a charge it makes that fails records as any failed charge does. + `gas` is the creating frame's tracker, which `gas_after` reads a copy of: the hook may debit and credit it, for instance draw the deployed code from one of the frame's pools (see Resource pools), and a charge it makes that fails records as any failed charge does. `Ok(())` admits, and the frame returns with `gas` as the hook left it. `Err(output)` refuses: the checkpoint is reverted, the frame's gas is put back to `gas_before`, which undoes whatever the hook did to `gas`, a crossing its failed draw recorded included, and the creation ends as a `Revert` with `output`, settling as a creation whose init code reverted. A hook that fails fatally records the cause in the context error and refuses; the transaction returns the error. @@ -239,13 +239,14 @@ A format that encodes a struct by position, such as bincode, cannot read such an `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`. - `target` is the account the frame runs as: the account called for `CALL` and `STATICCALL`, the calling frame's own for `CALLCODE` and `DELEGATECALL`, and for `CREATE` and `CREATE2` the address the creation takes. + `target` is the account the frame runs as: the account called for `CALL` and `STATICCALL`, the calling frame's own for `CALLCODE` and `DELEGATECALL`, and for `CREATE` and `CREATE2` the address the creation would take. + Whether a creation takes it is the outcome's to say (`CreateOutcome::address`): a creation that lands on an account that already has code or a nonce, one the handler refuses after the hook (an inspector changed the caller's balance), and one an inspector's `create` or a consumer's `frame_init` answers without a frame take none, though their start named the address. A consumer that counts the created account from `target` settles that count on the outcome. A creation's address is computed once, into the creation's input, and the handler builds the frame at it without computing it again. With EIP-8037 on, the instruction's EIP-8037 branch computes it. With EIP-8037 off, the instruction computes it after the same checks, reading the caller's balance and nonce from the journal. It is `None` only for a creation the handler fails before it takes an address: an endowment above the caller's balance, a caller's nonce at its maximum, or a creating frame at the depth limit. Such a creation reaches the hook only with EIP-8037 off; with it on, the instruction ends the creation before the hook. The address is fixed when the hook sees it. Something that changes the caller's nonce between the instruction and the frame does not move it, as on upstream's EIP-8037 path. An inspector that changes the creation's caller, scheme or init code (`CreateInputs::set_call`, `set_scheme`, `set_init_code`) clears it, and the handler computes the new one. - `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies its reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from the reservoir the hook left. A charge the hook makes that fails records as any failed charge does, whatever the answer. + `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input takes its share of the reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from a share of the reservoir the hook left (see The reservoir share). A charge the hook makes that fails records as any failed charge does, whatever the answer. `start` is the hook's to declare the start charge on (`charge`, see The start charge); the instruction reads nothing else back from it. - After the hook the instruction copies that charge onto the frame's input and takes the child's share of the byte pool off `gas` for it (see The byte pool); the share is of the pool as the hook left it. + After the hook the instruction copies that charge onto the frame's input and takes the child's shares of the reservoir and of each pool off `gas` for it (`GasTracker::forward_to_child`, see The reservoir share and Resource pools); the shares are of the reservoir and the pools as the hook left them. `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. @@ -259,50 +260,77 @@ A format that encodes a struct by position, such as bincode, cannot read such an A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. With EIP-8037 on, the start reads the address the EIP-8037 branch already computed from the input; that path was not measured. `CreateInputs`' derived `PartialEq` compares the cached address and hash, which the input of a creation the instruction starts holds with EIP-8037 on and off, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache. - A consumer tells a creation from a call by `kind`, not by `target`: `target` is `None` only for the creations the Contract names, and an address for every other start. - -### The byte pool - -- **API.** On `GasTracker`, forwarded on `Gas`: `bytes_remaining`, `set_bytes_remaining`, `bytes_spent`, `set_bytes_spent`, `record_bytes`, `refill_bytes`, `bytes_crossing`, `clear_bytes_crossing`, `set_bytes_crossing`. - On `GasTracker` alone, the fork's own plumbing: `add_bytes_spent`, `forward_bytes`, `absorb_returned_bytes`, `adopt_bytes_share`. - `GasId::bytes_forward_percent` and `GasParams::bytes_forward_share(pool)`. - `bytes_share` on `CallInputs` (a field) and `CreateInputs` (`bytes_share`, `set_bytes_share`). -- **Contract.** The pool is a budget of bytes a frame may append, beside its gas: `bytes_remaining` is what the frame may still draw, `bytes_spent` its net draw, signed as `history_gas_spent` is. - `record_bytes(n)` draws; a draw the pool cannot pay takes nothing, returns `false` and sets the crossing (`bytes_crossing()` is `true`), which survives `spend_all`, starts clear in every child, is not taken over by a caller, and stays until cleared; a consumer marks a result it produced itself with `set_bytes_crossing`. - The crossing is a bit: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. - No halt touches the pool, so a halted frame's result still reads the pool as the failed draw found it, until its caller settles it. - `refill_bytes(n)` gives bytes back and lowers the net, below zero when the draw was a caller's. - Byte amounts are bounded as the tracker bounds gas amounts: every draw and refill is at most `i64::MAX`, and the net with its children's nets merged in stays within `±i64::MAX`, so it can be negated; a debug build asserts it where the net moves, and past it a release build saturates the net, so a rollback no longer restores the pool exactly. - A consumer draws deployed code's bytes where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). - The transaction's frame gets the whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution. - At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `bytes_forward_share` of the caller's pool out of it and puts it on the frame's input as `bytes_share`: the child's pool when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). - `bytes_forward_share` is `bytes_forward_percent` per cent of the pool, rounded down; a hundred or more forwards the whole pool. + A consumer tells a creation from a call by `kind`, not by `target`: `target` is `None` only for the creations the Contract names, and for every other start an address, which for a creation is the one it would take. + +### Resource pools + +- **API.** `PoolId` (`new(index)`, `index`, `COUNT` = 3, `ALL`) and `PoolAmounts` (an amount per pool: `ZERO`, `UNLIMITED`, `get`, `set`, `with`, `is_zero`), in `revm_context_interface::cfg::gas`, re-exported from `revm_interpreter`. + On `GasTracker`, forwarded on `Gas`: `pool_remaining`, `set_pool_remaining`, `pool_spent`, `set_pool_spent`, `record_pool`, `refill_pool`, `pool_crossing`, `clear_pool_crossing`, `set_pool_crossing`, each taking the `PoolId`. + On `GasTracker` alone, the fork's own plumbing: `pools_remaining`, `set_pools_remaining`, `add_pool_spent`, `forward_pool`, `absorb_returned_pool`, `absorb_returned_pools`, `adopt_pool_share`, `adopt_pool_shares`, and `forward_to_child` and `forward_all_to_child` with their `ChildShares` (see The reservoir share). + `GasId::pool_forward_percent(pool)` (ids 252, 251 and 250) and `GasParams::pool_forward_share(pool, remaining)`. + `pool_shares` on `CallInputs` (a field) and `CreateInputs` (`pool_shares`, `set_pool_shares`). +- **Contract.** A tracker carries `PoolId::COUNT` pools, budgets beside its gas whose meaning the consumer gives (bytes a frame may append, records it may write, entries it may create); the fork knows them by index only. + For each pool, `pool_remaining` is what the frame may still draw and `pool_spent` its net draw, signed as `history_gas_spent` is. + `record_pool(pool, n)` draws; a draw the pool cannot pay takes nothing, returns `false` and sets the pool's crossing (`pool_crossing(pool)` is `true`), which survives `spend_all`, starts clear in every child, is not taken over by a caller, and stays until cleared; a consumer marks a result it produced itself with `set_pool_crossing`. + A crossing is a bit per pool: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. + No halt touches a pool, so a halted frame's result still reads each pool as the failed draw found it, until its caller settles it. + `refill_pool(pool, n)` gives back and lowers the net, below zero when the draw was a caller's. + Amounts are bounded as the tracker bounds gas amounts: every draw and refill is at most `i64::MAX`, and each net with its children's nets merged in stays within `±i64::MAX`, so it can be negated; a debug build asserts it where a net moves, and past it a release build saturates the net, so a rollback no longer restores the pool exactly. + Each pool is a figure of its own: nothing the fork does to one moves another, and a consumer that draws several for one write draws them one by one, in the order its rules give. + A consumer draws deployed code where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). + The transaction's frame gets every whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution (`forward_all_to_child`, from `create_init_frame`). + At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `pool_forward_share(pool, …)` of each of the caller's pools out of it and puts the shares on the frame's input as `pool_shares`: the child's pools when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). + `pool_forward_share` is the pool's `pool_forward_percent` per cent of what the caller has left of it, rounded down; a hundred or more forwards the whole pool. A forward is not a draw. - The settlement is in `handle_reservoir_remaining_gas` and follows the reservoir, not regular gas: a child that reverts or halts has its draws undone by `rollback_state_gas`, which also gives `bytes_spent` back to the pool, so what the caller absorbs is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame appends nothing; the caller kept what it did not forward. - The child's net merges into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. - `rollback_state_gas` rolls the pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pool back with it. - The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `bytes_spent` is then the transaction's net draw. - A precompile's answer adopts the share as the pool it started with (`adopt_bytes_share`): its pool is the share less what its provider drew on it, so its pool and net add up to the share as a frame's do; a provider that draws on its answer starts the answer's pool at the input's `bytes_share` first, so a draw the share cannot pay fails. - An outcome an inspector builds to answer a start carries whatever pool its gas was built with, an unlimited one with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs it as it is. - A consumer that answers a start itself, without a frame or a provider, sets the answer's pool to the share it was given. - The pool is not reported on `ResultGas`. -- **Consumer.** mega-evm keeps a per-frame budget of the bytes a transaction appends to the state and the history, which a failed frame gives back and a successful one hands to its caller. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry a figure that moves with a frame's gas. -- **Removal.** When upstream carries an equivalent per-frame budget on its gas, or when mega-evm stops limiting bytes per frame. -- **Default.** Every tracker starts with an unlimited pool (`u64::MAX`), every schedule forwards the whole pool, and nothing in the workspace draws it, so every figure of the pool is the unlimited pool going out and coming back and every result is upstream's. - The tracker is 112 bytes, 88 without the pool: the pool and its net take a word each, the allowance (see The history allowance) a third, and the crossing a bit in the word the failed-charge record's flag takes (see The failed-charge record); in a format that carries field names, encodings that predate the fields decode with an unlimited pool, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). - `Gas` is 128 bytes (104), `InterpreterResult` 168 (144), `CallOutcome` and `FrameResult` 248 (208), `CreateOutcome` 232 (192), the outcomes with the start charge's two words. - Where measured (callgrind, the fork's release profile, against the fork without the pool, the start charge and the allowance), the three figures together cost a transfer 120 instructions (+2.2%), a creation 144 (+0.8%), a `SELFDESTRUCT` transaction 151 (+1.9%), a transaction that calls a precompile 135 (+0.04%; 10 of them the answer's adopted share) and each `CALL` about 139 (+6.3% on a transaction of 64 calls), most of it in moving the larger frame results; snailtracer is unchanged. + The settlement is in `handle_reservoir_remaining_gas` (`absorb_returned_pools`) and follows the reservoir, not regular gas: a child that reverts or halts has its draws on every pool undone by `rollback_state_gas`, which gives each pool's net back to it, so what the caller absorbs of each pool is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame draws nothing; the caller kept what it did not forward. + The child's nets merge into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. + `rollback_state_gas` rolls every pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pools back with it. + The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `pool_spent` of each pool is then the transaction's net draw. + A precompile's answer adopts the shares as the pools it started with (`adopt_pool_shares`): each pool is the share less what its provider drew on it, so its pools and nets add up to the shares as a frame's do; a provider that draws on its answer starts the answer's pools at the input's `pool_shares` first, so a draw a share cannot pay fails. + An outcome an inspector builds to answer a start carries whatever pools its gas was built with, unlimited ones with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs them as they are. + A consumer that answers a start itself, without a frame or a provider, sets the answer's pools to the shares it was given (`set_pools_remaining(inputs.pool_shares)`), and a consumer that builds a child's input itself takes the child's shares with `forward_to_child`. + The pools are not reported on `ResultGas`. +- **Consumer.** mega-evm keeps per-frame budgets of what a transaction adds to the chain: the bytes it appends to the state and the history, the write records it makes and the state entries it creates, each forwarded to a child at 98/100 of what its caller has left, each given back by a failed frame and handed to its caller by a successful one, and each held to a per-transaction and a per-block limit. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry figures that move with a frame's gas. +- **Removal.** When upstream carries equivalent per-frame budgets on its gas, or when mega-evm stops limiting these per frame. +- **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. + Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. `PoolId::COUNT` is one constant: a later pool is a size change, not an API change. + The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). + `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). + Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 213 instructions more (+3.9%), each `CALL` about 264 more (+11.2% on a transaction of 64 calls), a top-level creation 275 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 278 more (+3.4%). + Nearly all of it is the size: the same code with one pool, at the earlier sizes, costs 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. + Against the base without any of the fork's figures, a transfer costs 334 more (+6.2%) and each `CALL` about 404 more (+18.1% on a transaction of 64 calls). + +### The reservoir share + +- **API.** `GasId::reservoir_forward_percent` (id 254) and `GasParams::reservoir_forward_share(reservoir)`. + On `GasTracker`: `forward_reservoir(share)`, and `forward_to_child(&GasParams)` and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). +- **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. + `reservoir_forward_share` is `reservoir_forward_percent` per cent of the reservoir, rounded down; a hundred or more forwards the whole reservoir, as EIP-8037 does. + The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. + On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. + A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. + The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too. + A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. + An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. + A consumer that builds a child's input itself takes the child's shares from the caller's tracker with `forward_to_child`, and one that settles a result into a caller's tracker itself calls `handle_reservoir_remaining_gas` with a caller that gave the share up; a caller that still holds the reservoir it forwarded ends with it twice. +- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. Only the instruction knows the reservoir as the frame-start hook left it before the input is built, and only the settlement can add the child's reservoir to what the caller kept. +- **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. +- **Default.** Every schedule forwards the whole reservoir, so the caller keeps none of it, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. + What a frame's tracker reads while its child runs differs: its reservoir is the part it kept, zero by default, where upstream's left the forwarded reservoir in it until the child returned; an inspector that reads the caller's gas at the `CALL` or `CREATE` instruction's `step_end` sees it. + Where measured with the pools' figures (above), the share and the generalised forward cost 8 instructions per `CALL` with one pool. + `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. + A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. ### The start charge -- **API.** The type `StartCharge` (`new`, `history`, `bytes`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`. +- **API.** The type `StartCharge` (`new(history, pools)`, `history`, `pools`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`, and `GasTracker::refill_start_charge`. `FrameStart::charge` (see Frame-start hook). `charged_start` on `CallInputs`, `CallOutcome` and `CreateOutcome` (fields) and on `CreateInputs` (`charged_start`, `set_charged_start`); `FrameResult::refundable_start_charge`. `revm_handler::execution::settle_first_frame`, the settlement of the first frame. -- **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and bytes of the pool. +- **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and an amount of each pool (`PoolAmounts`). The `frame_starting` hook charges the caller's tracker and declares the refundable part on the start it is handed (`start.charge`); the instruction copies it onto the frame's input when the hook admits the start; a start the hook refuses discards the charge with the start, and what the hook charged stands. The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. - The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_history` and `refill_bytes`, on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. + The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_start_charge` (`refill_history`, and `refill_pool` for each pool), on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. `last_frame_result` settles the first frame through `execution::settle_first_frame`, which is all of mainnet's settlement but the copy of the transaction's gas into the frame's result: the spend and the settlement of the frame, the EIP-2780 state-gas refund and the start-charge refund, each with its halt rule. A chain whose handler overrides `last_frame_result` calls it rather than copying the mainnet body, so the start-charge refund and any later step reach it too, and applies its own rules between it and the copy, such as the op-revm fork's pre-Regolith deposit rule. Upstream's own steps of the settlement (the spend, `handle_reservoir_remaining_gas` and the EIP-2780 refund) live in `crates/handler/src/execution/first_frame.rs`, not in `handler.rs`: a pick or a base-line merge that changes upstream's `last_frame_result` body lands there, and records the move as its conflict resolution. @@ -310,14 +338,16 @@ A format that encodes a struct by position, such as bincode, cannot read such an A precompile's answer and a start the handler refuses before any frame (call depth, balance) carry the input's charge, so they refund as a frame does. An outcome an inspector builds to answer a start carries no charge unless the inspector copies the input's (`CallOutcome::new` and `CreateOutcome::new` carry none), so the caller keeps the charge, as revm keeps its own upfront state charge on an outcome a tool builds; an outcome the inspector rewrites at `call_end` or `create_end` keeps the frame's charge, so a success rewritten into a failure is refunded. An answer a consumer builds itself, such as an interceptor's, is refunded by the same rule: it carries the charge the consumer puts on it, and none when built with `new`. -- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input copies the reservoir, and must give them back when the frame fails. The refund belongs where the fork refunds the upfront state charge. + A consumer that settles a result into a caller's tracker itself refunds the charge with `refill_start_charge` on the same condition, so a pool added to the charge reaches it. +- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input takes its share of the reservoir, and must give them back when the frame fails. It draws a start's records on the child's pools, so its hook declares history alone, but a creation's creator record is drawn from the caller's pools at the hook: when revm answers the creation before it bumps the nonce, the engine adds what the record drew to the answer's charge, so the creation's failure gives it back (`give_back_creator_record`). The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. - **Default.** The hook declares nothing, so the fields and the refund are zero. + The charge is four words, history and one per pool, on every input and outcome; its size is part of the outcomes' measured above (see Resource pools). `settle_first_frame` is inlined: where measured (callgrind, the fork's release profile), a transfer and a transaction of 64 calls run the same instruction count as with its steps written out in `last_frame_result`. A handler that overrides `last_frame_result` with a copy of mainnet's settlement instead of calling `settle_first_frame` compiles, but does not refund the first frame's start charge; that matters only to a consumer that declares one. - This entry is an exception to rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and carry fields upstream's do not (`charged_start`, and on `CallInputs` also `bytes_share` and `history_allowance`), so a literal written for upstream's fields does not compile until it names them. - A consumer that uses none of the figures names them at their defaults, no charge (`StartCharge::default()`), an unlimited share (`u64::MAX`) and no allowance (`0`), and keeps upstream's behaviour. - A consumer that answers a start with an outcome it builds itself sets the answer's charge as the Contract says and its pool as The byte pool says. + This entry is an exception to rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and carry fields upstream's do not (`charged_start`, and on `CallInputs` also `pool_shares` and `history_allowance`), so a literal written for upstream's fields does not compile until it names them. + A consumer that uses none of the figures names them at their defaults, no charge (`StartCharge::default()`), unlimited shares (`PoolAmounts::UNLIMITED`) and no allowance (`0`), and keeps upstream's behaviour. + A consumer that answers a start with an outcome it builds itself sets the answer's charge as the Contract says and its pools as Resource pools says. The outcomes also carry the state-gas refund's `charged_state_gas_address` (see State-gas price), which upstream's do not, so an outcome literal written for upstream's fields does not compile against the fork whatever this entry adds; `CallInputs` has upstream's fields apart from this entry's, so this entry is what breaks its literals. `CreateInputs` has private fields and is built with `CreateInputs::new`, so its new fields break no literal. From 69d42ed66452e124a17a6da82a3cddccc15bba26 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:32:28 +0800 Subject: [PATCH 039/110] fix(handler): the runtime out-of-gas stand-in takes the reservoir and the pools, so they settle back once Handler::runtime_oog_result built the stand-in first-frame result from the reservoir of the rebuilt transaction gas without taking it, so the settlement, which now adds the child's reservoir to what the caller kept, returned it twice. --- crates/handler/src/handler.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 28bf7ba755..c872e1a84a 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -319,11 +319,17 @@ pub trait Handler { // reservoir. *gas = self.tx_gas(evm, init_and_floor_gas); let tx_gas_limit = evm.ctx().tx().gas_limit(); - let reservoir = gas.reservoir(); + // The stand-in takes the whole reservoir and every pool out of the transaction's gas, as + // the first frame would (`create_init_frame`), so the settle adds them back once. + let shares = gas.forward_all_to_child(); let mut frame_result = match evm.ctx().tx().kind() { - TxKind::Call(_) => FrameResult::new_call_oog(tx_gas_limit, 0..0, reservoir), - TxKind::Create => FrameResult::new_create_oog(tx_gas_limit, reservoir), + TxKind::Call(_) => FrameResult::new_call_oog(tx_gas_limit, 0..0, shares.reservoir), + TxKind::Create => FrameResult::new_create_oog(tx_gas_limit, shares.reservoir), }; + frame_result + .gas_mut() + .tracker_mut() + .set_pools_remaining(shares.pools); self.last_frame_result(evm, &mut frame_result, gas)?; Ok(frame_result) } From 692f4116b2015d87e117c4b46e6cfa8a730d0e6b Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:32:39 +0800 Subject: [PATCH 040/110] fix(gas): a child's reservoir share is all but the caller's part, rounded down, as regular gas's forward takes it The reservoir share keeps Rex6's subtraction for the reservoir, remaining - remaining * 2 / 100 at 98, and the floor of 98/100 for the frame budgets. The reservoir share now takes the caller's (100 - percent) per cent away, rounded down; the pools keep their floor. The tracker-level test of the returned reservoir moves beside the forward. --- crates/context/interface/src/cfg/gas.rs | 28 -------- .../context/interface/src/cfg/gas/forward.rs | 35 +++++++++- .../context/interface/src/cfg/gas_params.rs | 66 +++++++++++++------ crates/handler/tests/reservoir_share.rs | 15 +++-- crates/inspector/tests/reservoir_share.rs | 4 +- 5 files changed, 88 insertions(+), 60 deletions(-) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 32a48a0685..b2b885eebe 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -839,34 +839,6 @@ mod tests { assert_eq!(gas.state_gas_spilled(), 0); assert_eq!(gas.state_gas_spent(), 400); } - - /// A caller that kept part of its reservoir when it forwarded a share gets the child's - /// reservoir added to what it kept, and the returned reservoir, not the kept part, unwinds - /// the caller's outstanding spill. With nothing kept the result is the child's reservoir, as - /// a settlement that replaced the caller's reservoir gave. - #[test] - fn returned_reservoir_joins_the_part_the_caller_kept() { - // Kept 20 of 1,000, the child returns 700 of its 980. - let mut kept = GasTracker::new(1_000, 1_000, 1_000); - kept.forward_reservoir(980); - kept.absorb_returned_reservoir(700); - assert_eq!((kept.reservoir(), kept.remaining()), (720, 1_000)); - - // A spill of 150 outstanding (a successful child's, merged before the absorb): the - // returned 100 unwinds 100 of it, and the 20 kept stays in the reservoir. - let mut spilled = GasTracker::new(1_000, 850, 20); - spilled.add_state_gas_spilled(150); - spilled.absorb_returned_reservoir(100); - assert_eq!(spilled.reservoir(), 20); - assert_eq!(spilled.remaining(), 950); - assert_eq!(spilled.state_gas_spilled(), 50); - - // Nothing kept: the child's reservoir, whatever the caller held before the forward. - let mut whole = GasTracker::new(1_000, 1_000, 1_000); - whole.forward_reservoir(1_000); - whole.absorb_returned_reservoir(300); - assert_eq!(whole.reservoir(), 300); - } } /// Gas cost for operations that consume zero gas. diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs index 4cf527a3fb..55d0995cae 100644 --- a/crates/context/interface/src/cfg/gas/forward.rs +++ b/crates/context/interface/src/cfg/gas/forward.rs @@ -131,13 +131,14 @@ mod tests { let shares = tracker.forward_to_child(¶ms); - // 98% of 999 is 979.02; 98% of 1,000 is 980; half of 500 is 250. - assert_eq!(shares.reservoir, 979); + // The reservoir's 999 less the caller's 2%, rounded down (19), is 980; 98% of 1,000 is + // 980; half of 500 is 250. + assert_eq!(shares.reservoir, 980); assert_eq!( PoolId::ALL.map(|pool| shares.pools.get(pool)), [980, 250, 0] ); - assert_eq!(tracker.reservoir(), 20); + assert_eq!(tracker.reservoir(), 19); assert_eq!( PoolId::ALL.map(|pool| tracker.pool_remaining(pool)), [20, 250, 100] @@ -166,6 +167,34 @@ mod tests { assert_eq!(tracker.pools_remaining(), PoolAmounts::ZERO); } + /// A caller that kept part of its reservoir when it forwarded a share gets the child's + /// reservoir added to what it kept, and the returned reservoir, not the kept part, unwinds + /// the caller's outstanding spill. With nothing kept the result is the child's reservoir, as + /// a settlement that replaced the caller's reservoir gave. + #[test] + fn test_a_returned_reservoir_joins_the_part_the_caller_kept() { + // Kept 20 of 1,000, the child returns 700 of its 980. + let mut kept = GasTracker::new(1_000, 1_000, 1_000); + kept.forward_reservoir(980); + kept.absorb_returned_reservoir(700); + assert_eq!((kept.reservoir(), kept.remaining()), (720, 1_000)); + + // A spill of 150 outstanding (a successful child's, merged before the absorb): the + // returned 100 unwinds 100 of it, and the 20 kept stays in the reservoir. + let mut spilled = GasTracker::new(1_000, 850, 20); + spilled.add_state_gas_spilled(150); + spilled.absorb_returned_reservoir(100); + assert_eq!(spilled.reservoir(), 20); + assert_eq!(spilled.remaining(), 950); + assert_eq!(spilled.state_gas_spilled(), 50); + + // Nothing kept: the child's reservoir, whatever the caller held before the forward. + let mut whole = GasTracker::new(1_000, 1_000, 1_000); + whole.forward_reservoir(1_000); + whole.absorb_returned_reservoir(300); + assert_eq!(whole.reservoir(), 300); + } + /// A forward above the reservoir saturates at an empty reservoir. #[test] fn test_a_reservoir_forward_saturates() { diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index fda49d41b4..6314e7fcc5 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -829,15 +829,21 @@ impl GasParams { percent_of(remaining, self.get(GasId::pool_forward_percent(pool))) } - /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: - /// [`reservoir_forward_percent`](GasId::reservoir_forward_percent) per cent of it, rounded - /// down. The caller keeps the rest while the child runs. + /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: all + /// but the caller's part, which is `100 - `[`reservoir_forward_percent`](GasId::reservoir_forward_percent) + /// per cent of the reservoir, rounded down, and which the caller keeps while the child runs. /// - /// A hundred or more, which every schedule here sets, forwards the whole reservoir, as - /// EIP-8037 does. + /// The child's share is taken as [`call_stipend_reduction`](Self::call_stipend_reduction) takes + /// regular gas, by subtracting the caller's part: at 98 it is `reservoir - reservoir * 2 / 100`, + /// so a reservoir of 99 forwards 98. A hundred or more, which every schedule here sets, + /// forwards the whole reservoir, as EIP-8037 does. #[inline] pub fn reservoir_forward_share(&self, reservoir: u64) -> u64 { - percent_of(reservoir, self.get(GasId::reservoir_forward_percent())) + let percent = self.get(GasId::reservoir_forward_percent()); + if percent >= 100 { + return reservoir; + } + reservoir - percent_of(reservoir, 100 - percent) } /// History gas a value call's child may spend before it charges its budget @@ -1686,9 +1692,10 @@ impl GasId { } /// The share of a caller's EIP-8037 reservoir a child frame receives when it starts, in per - /// cent of the reservoir, rounded down ([`GasParams::reservoir_forward_share`]). A hundred, - /// the whole reservoir as EIP-8037 forwards it, on every schedule defined here; a chain that - /// keeps part of the reservoir for the caller while the child runs lowers it. + /// cent of the reservoir: the caller keeps the rest, rounded down, and the child receives all + /// but that ([`GasParams::reservoir_forward_share`]). A hundred, the whole reservoir as + /// EIP-8037 forwards it, on every schedule defined here; a chain that keeps part of the + /// reservoir for the caller while the child runs lowers it. /// /// A fork id, allocated from the top of the table below /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). @@ -1867,17 +1874,35 @@ mod tests { PoolId::ALL.map(|pool| params.pool_forward_share(pool, amount)), ) }; + // A pool's share is its percentage rounded down; the reservoir's is what is left once the + // caller's 2% is taken, rounded down, as regular gas's forward takes its part: 98% of 99 + // is 97.02, so a pool forwards 97 and the reservoir 99 - 1 = 98. assert_eq!(share(0), (0, [0, 0, 0])); - assert_eq!(share(1), (0, [0, 0, 0])); + assert_eq!(share(1), (1, [0, 0, 0])); + assert_eq!(share(99), (98, [97, 49, 0])); assert_eq!(share(100), (98, [98, 50, 0])); - assert_eq!(share(149), (146, [146, 74, 0]), "rounded down"); + assert_eq!(share(149), (147, [146, 74, 0])); assert_eq!(share(1_000), (980, [980, 500, 0])); let max_98 = (u64::MAX as u128 * 98 / 100) as u64; + let max_less_2 = u64::MAX - (u64::MAX as u128 * 2 / 100) as u64; assert_eq!( share(u64::MAX), - (max_98, [max_98, u64::MAX / 2, 0]), + (max_less_2, [max_98, u64::MAX / 2, 0]), "no overflow" ); + for reservoir in (0..10_000).chain([u64::MAX - 1, u64::MAX]) { + assert_eq!( + params.reservoir_forward_share(reservoir), + (reservoir as u128 - reservoir as u128 * 2 / 100) as u64, + "the reservoir's share is `reservoir - reservoir * 2 / 100`" + ); + } + params.override_gas([(GasId::reservoir_forward_percent(), 0)]); + assert_eq!( + params.reservoir_forward_share(1_000), + 0, + "the caller keeps all" + ); params.override_gas([(GasId::reservoir_forward_percent(), 250)]); assert_eq!( @@ -1909,27 +1934,28 @@ mod tests { } } - /// REX's forward of regular gas to a child, `remaining - remaining * 2 / 100` rounded down, is - /// upstream's `call_stipend_reduction` with the quotient 50 in place of EIP-150's 64: the two - /// agree on every amount, so a chain that forwards 98/100 of its regular gas needs no fork - /// change, only the schedule entry. + /// A forward of 98/100 of the regular gas to a child, `remaining - remaining * 2 / 100` rounded + /// down, is upstream's `call_stipend_reduction` with the quotient 50 in place of EIP-150's 64: + /// the two agree on every amount, so a chain that forwards 98/100 of its regular gas needs no + /// fork change, only the schedule entry. #[test] fn test_a_call_stipend_reduction_of_50_forwards_98_per_cent() { let mut params = GasParams::new_spec(SpecId::OSAKA); params.override_gas([(GasId::call_stipend_reduction(), 50)]); - let rex = |remaining: u64| (remaining as u128 - remaining as u128 * 2 / 100) as u64; + let ninety_eight = + |remaining: u64| (remaining as u128 - remaining as u128 * 2 / 100) as u64; let amounts = (0..10_000) .chain([1_000_000, 16_777_216, 30_000_000, 1 << 40]) .chain([u64::MAX - 49, u64::MAX - 1, u64::MAX]); for remaining in amounts { assert_eq!( params.call_stipend_reduction(remaining), - rex(remaining), + ninety_eight(remaining), "{remaining}" ); } - // Worked examples: 98% of 1,000 is 980; of 1,049 is 1,028.02, kept as 1,029 by REX's - // rule, which takes 2% rounded down (20) away. + // Worked examples: 98% of 1,000 is 980; of 1,049 is 1,028.02, and the rule keeps 1,029: it + // takes 2% rounded down (20) away. assert_eq!(params.call_stipend_reduction(1_000), 980); assert_eq!(params.call_stipend_reduction(1_049), 1_029); assert_eq!(params.call_stipend_reduction(99), 98); diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index 235827ca50..fb1e671f40 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -95,7 +95,7 @@ const fn charge( /// its net state gas. type Returned = (InstructionResult, u64, i64); -fn returned(result: &FrameResult) -> Returned { +const fn returned(result: &FrameResult) -> Returned { let gas = result.gas(); ( result.instruction_result(), @@ -338,9 +338,9 @@ fn at_depth() -> Run { Run::new(ends(parent)) } -/// 98% of `reservoir`, rounded down. +/// The share at 98: `reservoir` less the caller's 2%, rounded down. const fn share(reservoir: u64) -> u64 { - reservoir * PERCENT / 100 + reservoir - reservoir * (100 - PERCENT) / 100 } /// Every start forwards 98% of its caller's reservoir, rounded down, and the caller keeps the @@ -359,9 +359,10 @@ fn test_the_reservoir_is_forwarded_by_its_share_and_settled_at_depth() { // OK returns 978,020, so PARENT holds 19,980 + 978,020 = 998,000 for each later start. let before_each = after_parent - CHARGED; assert_eq!(share(before_each), 978_040); - // NESTER charged 1,000 of its 978,040 before calling OK: 98% of 977,040 is 957,499.2. + // NESTER charged 1,000 of its 978,040 before calling OK: it keeps 2% of 977,040 rounded + // down, 19,540, where 98% rounded down would have forwarded 957,499. let nester_after = share(before_each) - CHARGED; - assert_eq!(share(nester_after), 957_499); + assert_eq!(share(nester_after), 957_500); assert_eq!( handler.starts, [ @@ -392,13 +393,13 @@ fn test_the_reservoir_is_forwarded_by_its_share_and_settled_at_depth() { share(before_each) - CHARGED, charged ), - // OK under NESTER: 957,499 less its charge. + // OK under NESTER: 957,500 less its charge. ( InstructionResult::Stop, share(nester_after) - CHARGED, charged ), - // NESTER kept 19,541 and got back 956,499: 976,040, two charges net. + // NESTER kept 19,540 and got back 956,500: 976,040, two charges net. (InstructionResult::Revert, 976_040, 2 * charged), ( InstructionResult::Stop, diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs index ffe01db019..a37d06472f 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_share.rs @@ -34,8 +34,8 @@ const RESERVOIR: u64 = 1_000_000; const SLOT: u64 = 97_920; /// What [`PARENT`] holds when it calls [`OK`]. const BEFORE_THE_CALL: u64 = RESERVOIR - SLOT; -/// 98% of it, rounded down: 884,038.4. -const SHARE: u64 = 884_038; +/// Its share at 98: all but the caller's 2%, rounded down (18,041.6 → 18,041). +const SHARE: u64 = 884_039; /// Writes a new slot, calls [`OK`] and stops. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); From f5b8169ea8554cb9b8b68c8ba5de6edc3dba7b4a Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:32:47 +0800 Subject: [PATCH 041/110] test: the reservoir share through a creation, a collision, a creation transaction and a runtime out-of-gas --- crates/handler/tests/reservoir_share.rs | 182 +++++++++++++++++++++++- 1 file changed, 177 insertions(+), 5 deletions(-) diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index fb1e671f40..f0dfeeb3c8 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -13,7 +13,8 @@ //! as it starts, and as it returns before its caller settles it. use bytecode::opcode::{ - CALL, DELEGATECALL, INVALID, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, SSTORE, STOP, + CALL, CREATE, DELEGATECALL, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH2, PUSH20, PUSH3, REVERT, + SSTORE, STOP, }; use context::{ result::{EVMError, ExecutionResult}, @@ -126,6 +127,10 @@ struct ShareHandler { returned: Vec<Returned>, /// The transaction's reservoir and net state gas after the first frame settled into it. settled: Option<(u64, i64)>, + /// The reservoir of the last gas `tx_gas` built. + tx_reservoir: core::cell::Cell<Option<u64>>, + /// The transaction's reservoir once the first frame's input was built. + after_first_input: Option<u64>, } impl ShareHandler { @@ -137,6 +142,8 @@ impl ShareHandler { starts: Vec::new(), returned: Vec::new(), settled: None, + tx_reservoir: core::cell::Cell::new(None), + after_first_input: None, } } } @@ -152,9 +159,20 @@ impl Handler for ShareHandler { gas.set_remaining(gas.remaining() - reservoir); gas.set_reservoir(reservoir); } + self.tx_reservoir.set(Some(gas.reservoir())); gas } + fn first_frame_input( + &mut self, + evm: &mut TestEvm, + gas: &mut GasTracker, + ) -> Result<Option<FrameInit>, TestError> { + let input = self.mainnet.first_frame_input(evm, gas)?; + self.after_first_input = Some(gas.reservoir()); + Ok(input) + } + /// The default loop, recording each frame's reservoir as it starts and its figures as it /// returns, and starting the frames below the transaction's past the call-stack limit if told /// to. @@ -234,6 +252,12 @@ struct Run { parent_balance: u64, /// `reservoir_forward_percent` in the schedule, if not the default. percent: Option<u64>, + /// The transaction, if not a call to [`PARENT`] with [`GAS_LIMIT`]. + tx: Option<TxEnv>, + /// The regular cap, if not [`RESERVOIR`] below [`GAS_LIMIT`]. + cap: Option<u64>, + /// An account with code at [`PARENT`]'s first created address, where a `CREATE` collides. + occupied: bool, } impl Run { @@ -242,6 +266,9 @@ impl Run { parent, parent_balance: 10, percent: None, + tx: None, + cap: None, + occupied: false, } } @@ -250,6 +277,25 @@ impl Run { self } + /// A transaction that creates a contract from `initcode`. + fn creation(initcode: Vec<u8>) -> Self { + let mut run = Self::new(Vec::new()); + run.tx = Some( + TxEnv::builder_for_bench() + .kind(TxKind::Create) + .data(Bytes::from(initcode)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(), + ); + run + } + + const fn occupied(mut self) -> Self { + self.occupied = true; + self + } + const fn penniless(mut self) -> Self { self.parent_balance = 0; self @@ -288,16 +334,25 @@ impl Run { .with_code(Bytecode::new_raw(Bytes::from(code))); db.insert_account_info(address, info); } + if self.occupied { + db.insert_account_info( + PARENT.create(1), + AccountInfo::default() + .with_nonce(1) + .with_code(Bytecode::new_raw(Bytes::from_static(&[STOP]))), + ); + } db } fn evm(&self) -> TestEvm { let percent = self.percent; + let cap = self.cap.unwrap_or(GAS_LIMIT - RESERVOIR); let ctx = Context::mainnet() .with_db(self.db()) .modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); - cfg.tx_gas_limit_cap = Some(GAS_LIMIT - RESERVOIR); + cfg.tx_gas_limit_cap = Some(cap); if let Some(percent) = percent { cfg.gas_params .override_gas([(GasId::reservoir_forward_percent(), percent)]); @@ -306,13 +361,13 @@ impl Run { let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(CHARGE, Instruction::new(charge), 0); let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(SPEC)); - evm.ctx.set_tx( + evm.ctx.set_tx(self.tx.clone().unwrap_or_else(|| { TxEnv::builder_for_bench() .kind(TxKind::Call(PARENT)) .gas_price(0) .gas_limit(GAS_LIMIT) - .build_fill(), - ); + .build_fill() + })); evm } @@ -670,3 +725,120 @@ fn test_the_schedule_forwards_the_whole_reservoir() { 100 ); } + +/// `CREATE` of the two bytes `CHARGE STOP`, endowed with nothing, dropping the address. +fn create_charging() -> Vec<u8> { + vec![ + PUSH2, CHARGE, STOP, PUSH0, MSTORE, PUSH1, 2, PUSH1, 30, PUSH0, CREATE, POP, + ] +} + +/// A creation's frame gets its share like a call's, after the creation instruction's own state +/// charge for the account it creates, and settles it back; a creation that lands on an occupied +/// address fails before any frame and hands the share back whole. +#[test] +fn test_a_creation_forwards_its_share_and_a_collision_hands_it_back() { + let account = Run::new(Vec::new()) + .evm() + .ctx + .cfg() + .gas_params() + .get(GasId::create_state_gas()); + let mut parent = vec![CHARGE]; + parent.extend(create_charging()); + let after_parent = RESERVOIR - CHARGED; + + let (result, handler) = Run::new(ends(parent.clone())).percent(PERCENT).run(); + assert!(result.is_success(), "{result:?}"); + let before = after_parent - account; + assert_eq!(handler.starts, [RESERVOIR, share(before)]); + assert_eq!( + handler.returned[0], + ( + InstructionResult::Return, + share(before) - CHARGED, + CHARGED as i64 + ), + "the creation's own charge is on its frame" + ); + assert_eq!( + handler.settled, + Some((before - CHARGED, (2 * CHARGED + account) as i64)) + ); + + let (result, handler) = Run::new(ends(parent)).percent(PERCENT).occupied().run(); + assert!(result.is_success(), "{result:?}"); + assert_eq!( + handler.starts, + [RESERVOIR, share(after_parent)], + "no charge for an occupied address" + ); + assert_eq!( + handler.returned[0], + (InstructionResult::CreateCollision, share(after_parent), 0) + ); + assert_eq!(handler.settled, Some((after_parent, CHARGED as i64))); +} + +/// A creation transaction's frame takes the whole reservoir the transaction has left, whatever +/// the schedule, and settles back into it. +#[test] +fn test_a_creation_transaction_takes_the_whole_reservoir() { + for percent in [None, Some(PERCENT)] { + let mut run = Run::creation(vec![CHARGE, STOP]); + run.percent = percent; + let (result, handler) = run.run(); + + assert!(result.is_success(), "{percent:?}: {result:?}"); + assert_eq!( + handler.after_first_input, + Some(0), + "{percent:?}: all of it taken" + ); + let first = handler.starts[0]; + assert!(first > 0, "{percent:?}"); + assert_eq!( + handler.settled.map(|(reservoir, _)| reservoir), + Some(first - CHARGED) + ); + } +} + +/// A transaction whose EIP-2780 runtime phase runs out of gas skips execution and is settled +/// from a stand-in for its first frame: all regular gas consumed and the reservoir returned once. +#[test] +fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { + const LIMIT: u64 = 130_000; + const CAP: u64 = 30_000; + for percent in [None, Some(PERCENT)] { + // A value transfer to an account that does not exist, whose new-account state gas the + // reservoir and the regular gas left together cannot pay. + let mut run = Run::new(Vec::new()); + run.percent = percent; + run.cap = Some(CAP); + run.tx = Some( + TxEnv::builder_for_bench() + .kind(TxKind::Call(address!( + "0x00000000000000000000000000000000000e3970" + ))) + .value(U256::from(1)) + .gas_price(0) + .gas_limit(LIMIT) + .build_fill(), + ); + let (result, handler) = run.run(); + + assert!( + matches!(result, ExecutionResult::Halt { .. }), + "{percent:?}: {result:?}" + ); + let reservoir = handler.tx_reservoir.get().expect("tx_gas ran"); + assert!(reservoir > 0, "{percent:?}"); + assert_eq!(handler.settled, Some((reservoir, 0)), "{percent:?}"); + assert_eq!( + result.gas().total_gas_spent(), + LIMIT - reservoir, + "{percent:?}: every regular gas spent, the reservoir returned" + ); + } +} From bf2ec779ef5f347313cbb6db3fa81c4c4d62375f Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:32:47 +0800 Subject: [PATCH 042/110] chore: comments and test docs name the pools and the added-back reservoir --- crates/context/interface/src/cfg/gas/pools.rs | 11 +++++------ crates/handler/src/frame.rs | 6 +++--- crates/handler/tests/code_deposit_admission.rs | 2 +- crates/handler/tests/resource_pools.rs | 6 +++--- crates/inspector/tests/resource_pools.rs | 3 ++- crates/interpreter/tests/instruction_hooks.rs | 2 +- crates/interpreter/tests/resource_pools.rs | 16 ++++++++-------- 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/crates/context/interface/src/cfg/gas/pools.rs b/crates/context/interface/src/cfg/gas/pools.rs index 38e121b4d6..1447554672 100644 --- a/crates/context/interface/src/cfg/gas/pools.rs +++ b/crates/context/interface/src/cfg/gas/pools.rs @@ -258,16 +258,15 @@ impl GasTracker { } /// Settles every pool of a returning child into this, its caller's, tracker: the child's nets - /// merge into this tracker's when `kept` (the child succeeded), and what the child left of - /// each pool is absorbed back whatever its end, as - /// [`absorb_returned_pool`](Self::absorb_returned_pool) says. A child that failed has already - /// rolled its draws back. + /// merge into this tracker's when the child `succeeded`, and what the child left of each pool + /// is absorbed back whatever its end, as [`absorb_returned_pool`](Self::absorb_returned_pool) + /// says. A child that failed has already rolled its draws back. #[inline] - pub const fn absorb_returned_pools(&mut self, child: &Self, kept: bool) { + pub const fn absorb_returned_pools(&mut self, child: &Self, succeeded: bool) { let mut index = 0; while index < PoolId::COUNT { let pool = PoolId::ALL[index]; - if kept { + if succeeded { self.add_pool_spent(pool, child.pools_spent[index]); } self.absorb_returned_pool(pool, child.pools_remaining[index]); diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 7632f6bd1b..c09ad65e7f 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -598,7 +598,7 @@ impl EthFrame<EthInterpreter> { } // Settle the child's gas and merge it into the parent (returns - // unused regular gas, adopts the reservoir, and propagates state + // unused regular gas, adds back the reservoir, and propagates state // gas / refunds on success). handle_reservoir_remaining_gas( ins_result, @@ -629,7 +629,7 @@ impl EthFrame<EthInterpreter> { let mut create_gas = *outcome.gas(); // Settle the child's gas and merge it into the parent (returns - // unused regular gas, adopts the reservoir, and propagates state + // unused regular gas, adds back the reservoir, and propagates state // gas / refunds on success). handle_reservoir_remaining_gas( instruction_result, @@ -649,7 +649,7 @@ impl EthFrame<EthInterpreter> { } // Refund the upfront state charge after the child's gas is settled - // (the settle overwrites the reservoir with the child's). + // (the settle adds the child's reservoir to what the parent kept). if let Some(charge) = refund_state_gas { self.interpreter.gas.refill_reservoir(charge); } diff --git a/crates/handler/tests/code_deposit_admission.rs b/crates/handler/tests/code_deposit_admission.rs index a4587bbdd6..3f4111650c 100644 --- a/crates/handler/tests/code_deposit_admission.rs +++ b/crates/handler/tests/code_deposit_admission.rs @@ -6,7 +6,7 @@ //! output, or fails fatally. Each case is compared with a twin: an admitting context against //! [`Context`] itself, and a refused deposit against the same creation whose init code reverts. //! Two tests call `return_create` directly: on a frame whose regular gas is partly withheld, and -//! on a frame with a byte pool the hook draws the deposit from. +//! on a frame with a pool the hook draws the deposit from. use bytecode::opcode::{ CREATE, MSTORE, MSTORE8, PUSH0, PUSH1, PUSH3, PUSH4, RETURN, RETURNDATASIZE, REVERT, SSTORE, diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs index 883db9e580..a8df801dc6 100644 --- a/crates/handler/tests/resource_pools.rs +++ b/crates/handler/tests/resource_pools.rs @@ -1,7 +1,7 @@ -//! The byte pool, the start charge and the history allowance, as the mainnet handler forwards +//! The resource pools, the start charge and the history allowance, as the mainnet handler forwards //! and settles them. //! -//! A consumer sets the transaction's pool on the gas `tx_gas` returns; every frame then starts +//! A consumer sets the transaction's pools on the gas `tx_gas` returns; every frame then starts //! with the share its caller's instruction forwarded, and `handle_reservoir_remaining_gas` settles //! what it left: its remaining pool when it succeeded, the whole share when it reverted or halted. //! A start charge a hook declared rides on the frame's input and is refunded whole when the frame @@ -1216,7 +1216,7 @@ fn test_a_start_refused_for_the_depth_gives_the_share_and_the_start_charge_back( } } -/// With `bytes_forward_percent` at 98, every start forwards 98% of its caller's pool, rounded +/// With [`FIRST`]'s `pool_forward_percent` at 98, every start forwards 98% of its caller's pool, rounded /// down, and the caller keeps the rest; what a child hands back adds to what its caller kept, so /// the transaction ends with the figures the whole-pool forward gives. #[test] diff --git a/crates/inspector/tests/resource_pools.rs b/crates/inspector/tests/resource_pools.rs index 916977b188..432f6ef97a 100644 --- a/crates/inspector/tests/resource_pools.rs +++ b/crates/inspector/tests/resource_pools.rs @@ -1,4 +1,5 @@ -//! The byte pool, the start charge and the history allowance on the plain and the inspected path. +//! The resource pools, the start charge and the history allowance on the plain and the inspected +//! path. //! //! `transact` runs the frames in the handler's loop and `inspect_tx` in the inspector's; both //! build frames with `make_call_frame` and `make_create_frame` and settle them with diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index 7934dec745..3ced75e033 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -837,7 +837,7 @@ fn input_gas(input: &FrameInput) -> (u64, u64) { /// Each frame-starting instruction hands its start to the hook once the forward is taken, and /// charges nothing after it: the instruction leaves the gas the hook was handed, apart from the -/// byte pool, whose share goes to the frame after the hook, and the frame's input carries the +/// reservoir and the pools, whose shares go to the frame after the hook, and the frame's input carries the /// forward, with a value call's stipend on top. #[test] fn test_a_start_reaches_the_hook_with_the_forward_taken() { diff --git a/crates/interpreter/tests/resource_pools.rs b/crates/interpreter/tests/resource_pools.rs index 27e62687ed..99e17289c5 100644 --- a/crates/interpreter/tests/resource_pools.rs +++ b/crates/interpreter/tests/resource_pools.rs @@ -1,12 +1,12 @@ -//! The byte pool, the start charge and the history allowance at the call and creation -//! instructions. +//! The resource pools, the reservoir share, the start charge and the history allowance at the call +//! and creation instructions. //! //! Once [`Host::frame_starting`] has answered, the instruction copies the start charge the hook -//! declared on the start onto the frame's input, takes the child's share of the caller's byte pool -//! out of the pool and puts it on the input too, and, for a value call, gives the input the -//! schedule's history allowance. Each test runs one frame on [`PoolHost`], whose start hook draws -//! bytes from the gas it is handed, declares a start charge, and admits or refuses the start as -//! the test tells it. +//! declared on the start onto the frame's input, takes the child's shares of the caller's +//! reservoir and pools out of them and puts them on the input too, and, for a value call, gives +//! the input the schedule's history allowance. Each test runs one frame on [`PoolHost`], whose +//! start hook draws from a pool of the gas it is handed, declares a start charge, and admits or +//! refuses the start as the test tells it. use bytecode::{opcode::*, Bytecode}; use context_interface::{ @@ -232,7 +232,7 @@ impl Host for PoolHost { } } -/// Runs `code` as [`CONTRACT`], called by [`CALLER`], with [`AMPLE`] gas and a byte pool of +/// Runs `code` as [`CONTRACT`], called by [`CALLER`], with [`AMPLE`] gas and [`FIRST`] at /// `pool`, if given, and returns what the frame asked for and its gas. fn run(code: &[u8], pool: Option<u64>, host: &mut PoolHost) -> (InterpreterAction, Gas) { run_on(code, host, |gas| { From 961915e384d2c3713f71bd693813b2d676f97f7f Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 10:32:47 +0800 Subject: [PATCH 043/110] docs: the reservoir share's rounding, the runtime out-of-gas stand-in and what a later pool changes, in MEGAETH-FORK.md --- MEGAETH-FORK.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index baf0124c0a..368be436ed 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -278,7 +278,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an Amounts are bounded as the tracker bounds gas amounts: every draw and refill is at most `i64::MAX`, and each net with its children's nets merged in stays within `±i64::MAX`, so it can be negated; a debug build asserts it where a net moves, and past it a release build saturates the net, so a rollback no longer restores the pool exactly. Each pool is a figure of its own: nothing the fork does to one moves another, and a consumer that draws several for one write draws them one by one, in the order its rules give. A consumer draws deployed code where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). - The transaction's frame gets every whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution (`forward_all_to_child`, from `create_init_frame`). + The transaction's frame gets every whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution (`forward_all_to_child`, from `create_init_frame` and from the stand-in `Handler::runtime_oog_result` builds when the EIP-2780 runtime phase runs out of gas). At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `pool_forward_share(pool, …)` of each of the caller's pools out of it and puts the shares on the frame's input as `pool_shares`: the child's pools when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). `pool_forward_share` is the pool's `pool_forward_percent` per cent of what the caller has left of it, rounded down; a hundred or more forwards the whole pool. A forward is not a draw. @@ -293,7 +293,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **Consumer.** mega-evm keeps per-frame budgets of what a transaction adds to the chain: the bytes it appends to the state and the history, the write records it makes and the state entries it creates, each forwarded to a child at 98/100 of what its caller has left, each given back by a failed frame and handed to its caller by a successful one, and each held to a per-transaction and a per-block limit. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry figures that move with a frame's gas. - **Removal.** When upstream carries equivalent per-frame budgets on its gas, or when mega-evm stops limiting these per frame. - **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. - Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. `PoolId::COUNT` is one constant: a later pool is a size change, not an API change. + Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's forward percentage the next free id and a name, and changes the tests that count them. The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 213 instructions more (+3.9%), each `CALL` about 264 more (+11.2% on a transaction of 64 calls), a top-level creation 275 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 278 more (+3.4%). @@ -305,11 +305,11 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **API.** `GasId::reservoir_forward_percent` (id 254) and `GasParams::reservoir_forward_share(reservoir)`. On `GasTracker`: `forward_reservoir(share)`, and `forward_to_child(&GasParams)` and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). - **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. - `reservoir_forward_share` is `reservoir_forward_percent` per cent of the reservoir, rounded down; a hundred or more forwards the whole reservoir, as EIP-8037 does. + `reservoir_forward_share` is the reservoir less the caller's part, `100 − reservoir_forward_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 98 the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool at 98 forwards 97 (its share is rounded down). A hundred or more forwards the whole reservoir, as EIP-8037 does. The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. - The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too. + The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too; so does the stand-in result `Handler::runtime_oog_result` builds for a transaction whose EIP-2780 runtime phase ran out of gas, which carries the whole reservoir and every pool and settles them back once. A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. A consumer that builds a child's input itself takes the child's shares from the caller's tracker with `forward_to_child`, and one that settles a result into a caller's tracker itself calls `handle_reservoir_remaining_gas` with a caller that gave the share up; a caller that still holds the reservoir it forwarded ends with it twice. @@ -320,6 +320,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an Where measured with the pools' figures (above), the share and the generalised forward cost 8 instructions per `CALL` with one pool. `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. + Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too. ### The start charge From c4b2bc516b85ebdb6e1412ce477e774c864ff247 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 11:11:45 +0800 Subject: [PATCH 044/110] test: a system call's frame takes every pool whole and settles them back --- crates/handler/tests/reservoir_share.rs | 34 +++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index f0dfeeb3c8..c9d19c3cfa 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -27,7 +27,7 @@ use context_interface::{ use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, PoolAmounts, PoolId, }; use primitives::{ address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, TxKind, U256, @@ -105,6 +105,20 @@ const fn returned(result: &FrameResult) -> Returned { ) } +fn pool_shares_of(input: &FrameInput) -> PoolAmounts { + match input { + FrameInput::Call(inputs) => inputs.pool_shares, + FrameInput::Create(inputs) => inputs.pool_shares(), + FrameInput::Empty => unreachable!(), + } +} + +/// The pools a system call's gas gets in [`ShareHandler::tx_gas`]. +const SYSTEM_POOLS: PoolAmounts = PoolAmounts::ZERO + .with(PoolId::new(0), 1_000) + .with(PoolId::new(1), 500) + .with(PoolId::new(2), 100); + fn reservoir_of(input: &FrameInput) -> u64 { match input { FrameInput::Call(inputs) => inputs.reservoir, @@ -131,6 +145,10 @@ struct ShareHandler { tx_reservoir: core::cell::Cell<Option<u64>>, /// The transaction's reservoir once the first frame's input was built. after_first_input: Option<u64>, + /// Every frame's pool shares as it started. + pool_starts: Vec<PoolAmounts>, + /// The transaction's pools after the first frame settled into them. + settled_pools: Option<PoolAmounts>, } impl ShareHandler { @@ -144,6 +162,8 @@ impl ShareHandler { settled: None, tx_reservoir: core::cell::Cell::new(None), after_first_input: None, + pool_starts: Vec::new(), + settled_pools: None, } } } @@ -158,6 +178,8 @@ impl Handler for ShareHandler { if let Some(reservoir) = self.system_reservoir { gas.set_remaining(gas.remaining() - reservoir); gas.set_reservoir(reservoir); + // And pools, as a consumer that limits a system call's figures sets them. + gas.set_pools_remaining(SYSTEM_POOLS); } self.tx_reservoir.set(Some(gas.reservoir())); gas @@ -183,6 +205,8 @@ impl Handler for ShareHandler { ) -> Result<FrameResult, TestError> { self.starts .push(reservoir_of(&first_frame_input.frame_input)); + self.pool_starts + .push(pool_shares_of(&first_frame_input.frame_input)); if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { self.returned.push(returned(&result)); return Ok(result); @@ -191,6 +215,7 @@ impl Handler for ShareHandler { let result = match evm.frame_run()? { ItemOrResult::Item(mut init) => { self.starts.push(reservoir_of(&init.frame_input)); + self.pool_starts.push(pool_shares_of(&init.frame_input)); if self.too_deep { init.depth = CALL_STACK_LIMIT as usize + 1; } @@ -217,6 +242,7 @@ impl Handler for ShareHandler { ) -> Result<(), TestError> { self.mainnet.last_frame_result(evm, frame_result, gas)?; self.settled = Some((gas.reservoir(), gas.state_gas_spent())); + self.settled_pools = Some(gas.pools_remaining()); Ok(()) } } @@ -678,7 +704,7 @@ fn test_an_answer_without_a_frame_hands_the_share_back() { } /// A system call's frame takes the whole reservoir its gas holds, a consumer's split of the -/// system call's gas, and its children their shares, as a transaction's do. +/// system call's gas, and every whole pool, and its children their shares, as a transaction's do. #[test] fn test_a_system_call_forwards_and_settles_its_reservoir() { for percent in [None, Some(PERCENT)] { @@ -710,6 +736,10 @@ fn test_a_system_call_forwards_and_settles_its_reservoir() { Some((RESERVOIR - CHARGED, CHARGED as i64)), "{percent:?}" ); + // The pools go the same way: the system call's frame takes them whole, the schedule + // forwards them whole, and they come back as they were, nothing drawn. + assert_eq!(handler.pool_starts, [SYSTEM_POOLS; 2], "{percent:?}"); + assert_eq!(handler.settled_pools, Some(SYSTEM_POOLS), "{percent:?}"); } } From 27e12c9105c6a05ee72930a582658747e403fa81 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 11:11:45 +0800 Subject: [PATCH 045/110] docs: the pools' cost at the final head in MEGAETH-FORK.md --- MEGAETH-FORK.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 368be436ed..d5ee3d602c 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -296,9 +296,9 @@ A format that encodes a struct by position, such as bincode, cannot read such an Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's forward percentage the next free id and a name, and changes the tests that count them. The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). - Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 213 instructions more (+3.9%), each `CALL` about 264 more (+11.2% on a transaction of 64 calls), a top-level creation 275 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 278 more (+3.4%). - Nearly all of it is the size: the same code with one pool, at the earlier sizes, costs 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. - Against the base without any of the fork's figures, a transfer costs 334 more (+6.2%) and each `CALL` about 404 more (+18.1% on a transaction of 64 calls). + Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 216 instructions more (+3.9%), each `CALL` about 260 more (+11.0% on a transaction of 64 calls), a top-level creation 276 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 281 more (+3.5%). + Nearly all of it is the size: the same code with one pool, at the earlier sizes, cost 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. + Against the base without any of the fork's figures, a transfer costs 337 more (+6.2%) and each `CALL` about 400 more (+18.0% on a transaction of 64 calls). ### The reservoir share From e9eabd0fa857410a2ed9fa7306e402380dc5e8e6 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:13:30 +0800 Subject: [PATCH 046/110] fix(gas): an answer drawn past its pool share fails closed, as a crossing held to the share A provider that draws on an answer without first starting its pools at the input's shares draws on the unlimited pools the answer was built with. adopt_pool_share then saturated the pool at zero and kept the net, so the caller got back more than it forwarded on success and on failure alike, with no crossing (raised in review of PR #76). A net above the share now empties that pool, caps the net at the share and sets the pool's crossing; every other pool, every crossing already set and the answer's result are left as they are. A net within the share, or below zero, is adopted as before. Tests: the tracker on every pool, at the share and past it, settled on success (and the caller's later rollback) and on failure; the handler with a provider that draws on every pool without seeding, within, at and past the share, succeeding and failing. --- MEGAETH-FORK.md | 1 + crates/context/interface/src/cfg/gas/pools.rs | 102 +++++++++++++++++- crates/handler/src/frame.rs | 5 +- crates/handler/tests/resource_pools.rs | 101 ++++++++++++++++- 4 files changed, 198 insertions(+), 11 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index d5ee3d602c..ba0b1d9bfe 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -287,6 +287,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an `rollback_state_gas` rolls every pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pools back with it. The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `pool_spent` of each pool is then the transaction's net draw. A precompile's answer adopts the shares as the pools it started with (`adopt_pool_shares`): each pool is the share less what its provider drew on it, so its pools and nets add up to the shares as a frame's do; a provider that draws on its answer starts the answer's pools at the input's `pool_shares` first, so a draw a share cannot pay fails. + A provider that drew more than a share anyway, on pools it did not start at the shares, fails closed on that pool: the adoption empties the pool, caps its net at the share and sets its crossing, so the caller gets back no more than it forwarded whether the answer succeeds or fails, and the consumer classifies the crossing as it classifies a refused draw. The answer's result is the provider's, so a successful answer can carry a crossing. An outcome an inspector builds to answer a start carries whatever pools its gas was built with, unlimited ones with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs them as they are. A consumer that answers a start itself, without a frame or a provider, sets the answer's pools to the shares it was given (`set_pools_remaining(inputs.pool_shares)`), and a consumer that builds a child's input itself takes the child's shares with `forward_to_child`. The pools are not reported on `ResultGas`. diff --git a/crates/context/interface/src/cfg/gas/pools.rs b/crates/context/interface/src/cfg/gas/pools.rs index 1447554672..bd427d7d3d 100644 --- a/crates/context/interface/src/cfg/gas/pools.rs +++ b/crates/context/interface/src/cfg/gas/pools.rs @@ -238,13 +238,25 @@ impl GasTracker { /// drawn so far, so that the pool and the net add up to `share`, as a frame's do. /// /// For a tracker built outside a frame, such as a precompile's answer, which may have drawn - /// before it learns the share its caller forwarded. A rollback then restores `share`. A net - /// above `share` leaves an empty pool. + /// before it learns the share its caller forwarded. A rollback then restores `share`. + /// + /// A net above `share` is a draw the share could not have paid, and fails closed: the pool is + /// emptied, the net is capped at `share` and the pool's crossing is set, as a draw the pool + /// refused sets it. The caller then gets back no more than it forwarded, whether the answer + /// succeeds or fails, and a consumer reads the crossing as it reads any. The answer's result + /// and every other pool are left as they are. #[inline] pub const fn adopt_pool_share(&mut self, pool: PoolId, share: u64) { let index = pool.index(); - self.pools_remaining[index] = - share.saturating_add_signed(self.pools_spent[index].saturating_neg()); + let spent = self.pools_spent[index]; + if spent > 0 && spent as u64 > share { + self.pools_remaining[index] = 0; + // `share < spent <= i64::MAX`, so the cast is exact. + self.pools_spent[index] = share as i64; + self.pool_crossings |= 1 << index; + return; + } + self.pools_remaining[index] = share.saturating_add_signed(spent.saturating_neg()); } /// [`adopt_pool_share`](Self::adopt_pool_share) for every pool. @@ -683,6 +695,88 @@ mod tests { } } + /// A draw of exactly the share adopts as any draw within it does: an empty pool, the net kept + /// and no crossing. + #[test] + fn test_an_answer_that_drew_its_whole_share_adopts_it_unchanged() { + for pool in PoolId::ALL { + let mut answer = GasTracker::new(500, 500, 0); + assert!(answer.record_pool(pool, 100)); + + answer.adopt_pool_share(pool, 100); + + assert_eq!( + ( + answer.pool_remaining(pool), + answer.pool_spent(pool), + answer.pool_crossing(pool) + ), + (0, 100, false), + "{pool:?}" + ); + } + } + + /// An answer whose provider drew more than the share fails closed on that pool: the pool is + /// empty, the net is the share and the crossing is set, so the caller gets back exactly what + /// it held, whether the answer succeeds (and a later rollback of the caller undoes the draw) + /// or fails. Every other pool, and every crossing already set, is left as it was. + #[test] + fn test_an_answer_that_drew_past_its_share_is_a_crossing_capped_at_the_share() { + for pool in PoolId::ALL { + for succeeded in [true, false] { + // The caller forwards 100 of its 1,000 and keeps 900; the provider drew 150 on + // an answer whose pools were unlimited, and failed a draw on another pool. + let mut caller = pools_1000(); + caller.forward_pool(pool, 100); + let other = PoolId::new((pool.index() + 1) % PoolId::COUNT); + let mut answer = GasTracker::new(500, 500, 0); + answer.set_pool_remaining(other, 0); + assert!(!answer.record_pool(other, 1)); + assert!(answer.record_pool(pool, 150)); + + answer.adopt_pool_share(pool, 100); + + assert_eq!( + ( + answer.pool_remaining(pool), + answer.pool_spent(pool), + answer.pool_crossing(pool) + ), + (0, 100, true), + "{pool:?}" + ); + assert!( + answer.pool_crossing(other), + "{pool:?}: the other crossing stays" + ); + assert_eq!(answer.pool_spent(other), 0, "{pool:?}"); + + if !succeeded { + answer.rollback_state_gas(); + assert_eq!( + answer.pool_remaining(pool), + 100, + "{pool:?}: the rollback restores the share, not the draw" + ); + } + caller.absorb_returned_pools(&answer, succeeded); + let settled = if succeeded { (900, 100) } else { (1_000, 0) }; + assert_eq!( + (caller.pool_remaining(pool), caller.pool_spent(pool)), + settled, + "{pool:?} succeeded: {succeeded}" + ); + caller.rollback_state_gas(); + assert_eq!( + caller.pool_remaining(pool), + 1_000, + "{pool:?} succeeded: {succeeded}: the caller's rollback gives back what it held" + ); + } + } + } + /// Every pool adopts its own share. #[test] fn test_adopted_shares_go_to_their_pools() { diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index c09ad65e7f..3bde883644 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -221,8 +221,9 @@ impl EthFrame<EthInterpreter> { if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { // The provider built the answer's gas from the inputs' regular gas and reservoir. The // answer takes the caller's shares as the pools it started with, less what the - // provider drew on them, and the allowance the input carries, so the caller's - // settlement gets the shares back from the answer as it would from a frame. + // provider drew on them (a draw past a share is held to it, with the pool's + // crossing), and the allowance the input carries, so the caller's settlement gets + // the shares back from the answer as it would from a frame. result.gas.tracker_mut().adopt_pool_shares(pool_shares); result.gas.set_history_allowance(history_allowance); let mut logs = Vec::new(); diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs index a8df801dc6..da38026faf 100644 --- a/crates/handler/tests/resource_pools.rs +++ b/crates/handler/tests/resource_pools.rs @@ -402,10 +402,13 @@ impl Host for DeclaringContext { /// [`EthPrecompiles`], whose answers the provider draws on when told to: it starts an answer's /// pool at the share the input carries and draws `draw` bytes from it, as a provider that appends -/// bytes for a call would. With nothing to draw it is [`EthPrecompiles`]. +/// bytes for a call would. Told not to `seed`, it draws `draw` from every pool of the answer as +/// [`EthPrecompiles`] built it, unlimited, without starting them at the shares. With nothing to +/// draw it is [`EthPrecompiles`]. struct DrawingPrecompiles { inner: EthPrecompiles, draw: u64, + seed: bool, } impl PrecompileProvider<TestContext> for DrawingPrecompiles { @@ -422,10 +425,16 @@ impl PrecompileProvider<TestContext> for DrawingPrecompiles { ) -> Result<Option<InterpreterResult>, String> { let mut answer = self.inner.run(context, inputs)?; if let Some(answer) = answer.as_mut().filter(|_| self.draw > 0) { - answer - .gas - .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); - assert!(answer.gas.record_pool(FIRST, self.draw)); + if self.seed { + answer + .gas + .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); + assert!(answer.gas.record_pool(FIRST, self.draw)); + } else { + for pool in PoolId::ALL { + assert!(answer.gas.record_pool(pool, self.draw)); + } + } } Ok(answer) } @@ -660,6 +669,8 @@ struct Run { deposit: Deposit, /// What the precompile provider draws on each answer. precompile_draw: u64, + /// Whether the provider starts an answer's pool at the share before it draws. + precompile_seeds: bool, /// [`FIRST`]'s `pool_forward_percent` in the schedule, if not the default. forward_percent: Option<u64>, /// Every pool's `pool_forward_percent` in the schedule, if not the default. @@ -677,6 +688,7 @@ impl Run { allowance: 0, deposit: Deposit::Untouched, precompile_draw: 0, + precompile_seeds: true, forward_percent: None, pool_percents: None, creates: false, @@ -705,6 +717,14 @@ impl Run { self } + /// The provider draws `draw` from every pool of each answer as built, without starting the + /// pools at the shares first. + const fn unseeded_precompile_draw(mut self, draw: u64) -> Self { + self.precompile_draw = draw; + self.precompile_seeds = false; + self + } + const fn deposit(mut self, deposit: Deposit) -> Self { self.deposit = deposit; self @@ -789,6 +809,7 @@ impl Run { let precompiles = DrawingPrecompiles { inner: EthPrecompiles::new(SPEC), draw: self.precompile_draw, + seed: self.precompile_seeds, }; let mut evm: TestEvm = Evm::new(ctx, instructions, precompiles); let (kind, data) = if self.creates { @@ -1161,6 +1182,76 @@ fn test_a_precompile_answer_keeps_what_its_provider_drew() { } } +/// A provider that draws on an answer without starting its pools at the shares draws on the +/// unlimited pools the answer was built with, so it can draw past a share. Within the share the +/// answer is adopted as any is; past it, each pool fails closed: the answer holds an empty pool, +/// a net of exactly the share and the pool's crossing, and the caller ends with exactly what it +/// held, whether the call succeeds or fails. The answer's result is the provider's. +#[test] +fn test_a_precompile_answer_that_drew_past_its_share_is_a_crossing_held_to_the_share() { + let succeeding = call(ECRECOVER, 0); + let failing = starved_call(ECRECOVER); + // Every pool of 1,000 forwards 10%, 100, and PARENT keeps 900. + for (name, parent, draw, returned, settled) in [ + ( + "within, succeeds", + succeeding.clone(), + 40, + Returned::ended(InstructionResult::Return, 60, 40), + (960, 40), + ), + ( + "the whole share, succeeds", + succeeding.clone(), + 100, + Returned::ended(InstructionResult::Return, 0, 100), + (900, 100), + ), + ( + "past it, succeeds", + succeeding, + 150, + Returned { + crossing: true, + ..Returned::ended(InstructionResult::Return, 0, 100) + }, + (900, 100), + ), + ( + "past it, fails", + failing, + 150, + Returned { + crossing: true, + ..Returned::ended(InstructionResult::PrecompileOOG, 0, 100) + }, + (1_000, 0), + ), + ] { + let run = Run::new(ends(parent)) + .pool_percents([10; PoolId::COUNT]) + .unseeded_precompile_draw(draw); + + let (result, handler) = run.with(PoolHandler::new(Some(POOL))); + + assert!(result.is_success(), "{name}: {result:?}"); + assert_eq!( + handler.pool_starts[1], + PoolAmounts::ZERO + .with(FIRST, 100) + .with(PoolId::new(1), 100) + .with(PoolId::new(2), 100), + "{name}" + ); + assert_eq!(handler.returned[0], returned, "{name}"); + assert_eq!( + handler.settled_pools, + Some([settled; PoolId::COUNT]), + "{name}: every pool" + ); + } +} + /// A precompile's answer to a value call carries the history allowance the call instruction gave /// the start, as a frame does, and an answer to a call without value carries none. #[test] From 6f76ad3c81644f9eea37ceef3452df8e045d630f Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:25:14 +0800 Subject: [PATCH 047/110] fix(gas): the share entries are the caller's kept percent, so a table without them forwards everything A gas schedule is a table, so serde(default) cannot reach an entry: a table built raw, or decoded from an encoding made upstream, by the fork's release or by an earlier revision of the shares, held zero in the new entries, and zero forwarded no reservoir and no pool. A child that could pay a state charge from the reservoir under a fresh schedule then ran out of gas under the decoded one, with nothing to warn the consumer. The entries now say what the caller keeps: reservoir_kept_percent (id 249) and pool_kept_percent(pool) (ids 252, 251, 250), zero by default as upstream's table has them. Zero forwards everything, a hundred or more nothing, so an intended zero forward stays expressible. The shares and their rounding are unchanged: the reservoir's is the reservoir less its kept part rounded down, a pool's the rest rounded down. Id 254 held a forward percentage of 100 in an earlier revision and is left unused, so a table encoded then does not read as a kept part. Tests: raw tables (all zeros, upstream's, the earlier revision's at 100 and 98), their JSON, and a CfgEnv given one by each of its three constructors or decoded from JSON; the existing share tests restated in kept parts with their figures unchanged. --- MEGAETH-FORK.md | 21 +- .../context/interface/src/cfg/gas/forward.rs | 8 +- .../context/interface/src/cfg/gas_params.rs | 233 +++++++++++------- crates/context/tests/schedule_shares.rs | 64 +++++ crates/handler/tests/reservoir_share.rs | 20 +- crates/handler/tests/resource_pools.rs | 11 +- crates/inspector/tests/reservoir_share.rs | 5 +- .../src/instructions/instruction_hooks.rs | 4 +- .../src/interpreter_action/call_inputs.rs | 4 +- .../src/interpreter_action/create_inputs.rs | 6 +- crates/interpreter/tests/resource_pools.rs | 10 +- 11 files changed, 262 insertions(+), 124 deletions(-) create mode 100644 crates/context/tests/schedule_shares.rs diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index ba0b1d9bfe..4b6ca71940 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -71,6 +71,10 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th A field a hook adds to a serialized type carries `serde(default)`, so in a format that carries field names, such as JSON, an encoding made before the field existed decodes with the default. A format that encodes a struct by position, such as bincode, cannot read such an encoding, as with upstream's own field additions: it reads the old fields in their places and then looks for the new ones, so a value persisted in such a format must not cross an upgrade of the fork that adds a field. +A gas schedule (`GasParams`) is a table of 256 entries, not named fields, so `serde(default)` cannot reach an entry: a table built raw (`GasParams::new`) or decoded from an encoding made before an entry existed holds zero there. +Every entry the fork adds is therefore zero by default, and zero is upstream's behaviour: such a table behaves as the default schedule does. +An id the fork once used for an entry with another default is left unused rather than given a new meaning, so a table encoded then does not read as a setting. + ### State-gas price - **API.** `Host::state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64>` and `Host::state_gas_charge(&mut self, charge: StateGasCharge) -> Option<u64>`. @@ -267,7 +271,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an - **API.** `PoolId` (`new(index)`, `index`, `COUNT` = 3, `ALL`) and `PoolAmounts` (an amount per pool: `ZERO`, `UNLIMITED`, `get`, `set`, `with`, `is_zero`), in `revm_context_interface::cfg::gas`, re-exported from `revm_interpreter`. On `GasTracker`, forwarded on `Gas`: `pool_remaining`, `set_pool_remaining`, `pool_spent`, `set_pool_spent`, `record_pool`, `refill_pool`, `pool_crossing`, `clear_pool_crossing`, `set_pool_crossing`, each taking the `PoolId`. On `GasTracker` alone, the fork's own plumbing: `pools_remaining`, `set_pools_remaining`, `add_pool_spent`, `forward_pool`, `absorb_returned_pool`, `absorb_returned_pools`, `adopt_pool_share`, `adopt_pool_shares`, and `forward_to_child` and `forward_all_to_child` with their `ChildShares` (see The reservoir share). - `GasId::pool_forward_percent(pool)` (ids 252, 251 and 250) and `GasParams::pool_forward_share(pool, remaining)`. + `GasId::pool_kept_percent(pool)` (ids 252, 251 and 250) and `GasParams::pool_forward_share(pool, remaining)`. `pool_shares` on `CallInputs` (a field) and `CreateInputs` (`pool_shares`, `set_pool_shares`). - **Contract.** A tracker carries `PoolId::COUNT` pools, budgets beside its gas whose meaning the consumer gives (bytes a frame may append, records it may write, entries it may create); the fork knows them by index only. For each pool, `pool_remaining` is what the frame may still draw and `pool_spent` its net draw, signed as `history_gas_spent` is. @@ -280,7 +284,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an A consumer draws deployed code where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). The transaction's frame gets every whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution (`forward_all_to_child`, from `create_init_frame` and from the stand-in `Handler::runtime_oog_result` builds when the EIP-2780 runtime phase runs out of gas). At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `pool_forward_share(pool, …)` of each of the caller's pools out of it and puts the shares on the frame's input as `pool_shares`: the child's pools when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). - `pool_forward_share` is the pool's `pool_forward_percent` per cent of what the caller has left of it, rounded down; a hundred or more forwards the whole pool. + `pool_forward_share` is `100 − pool_kept_percent` per cent of what the caller has left of the pool, rounded down, and the caller keeps the rest: zero kept forwards the whole pool, a hundred or more none. A forward is not a draw. The settlement is in `handle_reservoir_remaining_gas` (`absorb_returned_pools`) and follows the reservoir, not regular gas: a child that reverts or halts has its draws on every pool undone by `rollback_state_gas`, which gives each pool's net back to it, so what the caller absorbs of each pool is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame draws nothing; the caller kept what it did not forward. The child's nets merge into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. @@ -293,8 +297,9 @@ A format that encodes a struct by position, such as bincode, cannot read such an The pools are not reported on `ResultGas`. - **Consumer.** mega-evm keeps per-frame budgets of what a transaction adds to the chain: the bytes it appends to the state and the history, the write records it makes and the state entries it creates, each forwarded to a child at 98/100 of what its caller has left, each given back by a failed frame and handed to its caller by a successful one, and each held to a per-transaction and a per-block limit. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry figures that move with a frame's gas. - **Removal.** When upstream carries equivalent per-frame budgets on its gas, or when mega-evm stops limiting these per frame. -- **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. - Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's forward percentage the next free id and a name, and changes the tests that count them. +- **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule keeps none of a pool and so forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. + A table without the entries, built raw or decoded from an encoding that predates them, keeps none too (see Hooks). + Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's kept percentage the next free id and a name, and changes the tests that count them. The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 216 instructions more (+3.9%), each `CALL` about 260 more (+11.0% on a transaction of 64 calls), a top-level creation 276 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 281 more (+3.5%). @@ -303,10 +308,10 @@ A format that encodes a struct by position, such as bincode, cannot read such an ### The reservoir share -- **API.** `GasId::reservoir_forward_percent` (id 254) and `GasParams::reservoir_forward_share(reservoir)`. +- **API.** `GasId::reservoir_kept_percent` (id 249) and `GasParams::reservoir_forward_share(reservoir)`. On `GasTracker`: `forward_reservoir(share)`, and `forward_to_child(&GasParams)` and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). - **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. - `reservoir_forward_share` is the reservoir less the caller's part, `100 − reservoir_forward_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 98 the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool at 98 forwards 97 (its share is rounded down). A hundred or more forwards the whole reservoir, as EIP-8037 does. + `reservoir_forward_share` is the reservoir less the caller's part, `reservoir_kept_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 2 kept the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool keeping 2 forwards 97 (its share is rounded down). Zero kept forwards the whole reservoir, as EIP-8037 does; a hundred or more forwards none. The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. @@ -316,12 +321,14 @@ A format that encodes a struct by position, such as bincode, cannot read such an A consumer that builds a child's input itself takes the child's shares from the caller's tracker with `forward_to_child`, and one that settles a result into a caller's tracker itself calls `handle_reservoir_remaining_gas` with a caller that gave the share up; a caller that still holds the reservoir it forwarded ends with it twice. - **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. Only the instruction knows the reservoir as the frame-start hook left it before the input is built, and only the settlement can add the child's reservoir to what the caller kept. - **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. -- **Default.** Every schedule forwards the whole reservoir, so the caller keeps none of it, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. +- **Default.** Every schedule keeps none of the reservoir and so forwards it whole, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. + A table without the entry, built raw or decoded from an encoding that predates it, keeps none too (see Hooks). What a frame's tracker reads while its child runs differs: its reservoir is the part it kept, zero by default, where upstream's left the forwarded reservoir in it until the child returned; an inspector that reads the caller's gas at the `CALL` or `CREATE` instruction's `step_end` sees it. Where measured with the pools' figures (above), the share and the generalised forward cost 8 instructions per `CALL` with one pool. `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too. + The entries are kept parts, not forwarded ones, so that zero, which a table without them holds, forwards everything. Id 254 is left unused. A consumer names the entries by function, and a chain that forwards 98 per cent keeps 2. ### The start charge diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs index 55d0995cae..e6b11470f2 100644 --- a/crates/context/interface/src/cfg/gas/forward.rs +++ b/crates/context/interface/src/cfg/gas/forward.rs @@ -121,10 +121,10 @@ mod tests { fn test_each_share_is_the_schedules() { let mut params = GasParams::new_spec(SpecId::AMSTERDAM); params.override_gas([ - (GasId::reservoir_forward_percent(), 98), - (GasId::pool_forward_percent(PoolId::new(0)), 98), - (GasId::pool_forward_percent(PoolId::new(1)), 50), - (GasId::pool_forward_percent(PoolId::new(2)), 0), + (GasId::reservoir_kept_percent(), 2), + (GasId::pool_kept_percent(PoolId::new(0)), 2), + (GasId::pool_kept_percent(PoolId::new(1)), 50), + (GasId::pool_kept_percent(PoolId::new(2)), 100), ]); let mut tracker = caller(); assert!(tracker.record_state_cost(1)); diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index 6314e7fcc5..6521d5550d 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -232,12 +232,9 @@ impl GasParams { gas::NON_ZERO_BYTE_MULTIPLIER; table[GasId::tx_token_cost().as_usize()] = gas::STANDARD_TOKEN_COST; table[GasId::tx_base_stipend().as_usize()] = 21000; - // The fork's entries: a child frame receives the whole reservoir and every whole pool, - // and a value call's child no history allowance, on every spec. - table[GasId::reservoir_forward_percent().as_usize()] = 100; - for pool in PoolId::ALL { - table[GasId::pool_forward_percent(pool).as_usize()] = 100; - } + // The fork's entries are zero on every spec, as upstream's table has them: a caller keeps + // none of its reservoir and none of any pool while its child runs, and a value call's + // child has no history allowance. if spec.is_enabled_in(SpecId::HOMESTEAD) { table[GasId::tx_create_cost().as_usize()] = gas::CREATE; @@ -821,29 +818,36 @@ impl GasParams { } /// The share of a caller's `remaining` in `pool` a child frame receives when it starts: - /// [`pool_forward_percent`](GasId::pool_forward_percent) per cent of it, rounded down. + /// `100 - `[`pool_kept_percent`](GasId::pool_kept_percent) per cent of it, rounded down; the + /// caller keeps the rest while the child runs. /// - /// A hundred or more, which every schedule here sets, forwards the whole pool. + /// Zero kept, which every schedule here and every table without the entry has, forwards the + /// whole pool; a hundred or more forwards nothing. #[inline] pub fn pool_forward_share(&self, pool: PoolId, remaining: u64) -> u64 { - percent_of(remaining, self.get(GasId::pool_forward_percent(pool))) + let kept = self.get(GasId::pool_kept_percent(pool)); + if kept == 0 { + return remaining; + } + percent_of(remaining, 100u64.saturating_sub(kept)) } /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: all - /// but the caller's part, which is `100 - `[`reservoir_forward_percent`](GasId::reservoir_forward_percent) + /// but the caller's part, which is [`reservoir_kept_percent`](GasId::reservoir_kept_percent) /// per cent of the reservoir, rounded down, and which the caller keeps while the child runs. /// /// The child's share is taken as [`call_stipend_reduction`](Self::call_stipend_reduction) takes - /// regular gas, by subtracting the caller's part: at 98 it is `reservoir - reservoir * 2 / 100`, - /// so a reservoir of 99 forwards 98. A hundred or more, which every schedule here sets, - /// forwards the whole reservoir, as EIP-8037 does. + /// regular gas, by subtracting the caller's part: at 2 kept it is + /// `reservoir - reservoir * 2 / 100`, so a reservoir of 99 forwards 98. Zero kept, which every + /// schedule here and every table without the entry has, forwards the whole reservoir, as + /// EIP-8037 does; a hundred or more forwards nothing. #[inline] pub fn reservoir_forward_share(&self, reservoir: u64) -> u64 { - let percent = self.get(GasId::reservoir_forward_percent()); - if percent >= 100 { + let kept = self.get(GasId::reservoir_kept_percent()); + if kept == 0 { return reservoir; } - reservoir - percent_of(reservoir, 100 - percent) + reservoir - percent_of(reservoir, kept) } /// History gas a value call's child may spend before it charges its budget @@ -1315,11 +1319,11 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", - x if x == Self::reservoir_forward_percent().as_u8() => "reservoir_forward_percent", x if x == Self::call_history_allowance().as_u8() => "call_history_allowance", - x if x == Self::pool_forward_percent(PoolId::new(0)).as_u8() => "pool0_forward_percent", - x if x == Self::pool_forward_percent(PoolId::new(1)).as_u8() => "pool1_forward_percent", - x if x == Self::pool_forward_percent(PoolId::new(2)).as_u8() => "pool2_forward_percent", + x if x == Self::pool_kept_percent(PoolId::new(0)).as_u8() => "pool0_kept_percent", + x if x == Self::pool_kept_percent(PoolId::new(1)).as_u8() => "pool1_kept_percent", + x if x == Self::pool_kept_percent(PoolId::new(2)).as_u8() => "pool2_kept_percent", + x if x == Self::reservoir_kept_percent().as_u8() => "reservoir_kept_percent", _ => "unknown", } } @@ -1395,11 +1399,11 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), - "reservoir_forward_percent" => Some(Self::reservoir_forward_percent()), "call_history_allowance" => Some(Self::call_history_allowance()), - "pool0_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(0))), - "pool1_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(1))), - "pool2_forward_percent" => Some(Self::pool_forward_percent(PoolId::new(2))), + "pool0_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(0))), + "pool1_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(1))), + "pool2_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(2))), + "reservoir_kept_percent" => Some(Self::reservoir_kept_percent()), _ => None, } } @@ -1691,39 +1695,47 @@ impl GasId { Self::new(255) } - /// The share of a caller's EIP-8037 reservoir a child frame receives when it starts, in per - /// cent of the reservoir: the caller keeps the rest, rounded down, and the child receives all - /// but that ([`GasParams::reservoir_forward_share`]). A hundred, the whole reservoir as - /// EIP-8037 forwards it, on every schedule defined here; a chain that keeps part of the - /// reservoir for the caller while the child runs lowers it. - /// - /// A fork id, allocated from the top of the table below - /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). - pub const fn reservoir_forward_percent() -> GasId { - Self::new(254) - } - /// History gas a value call's child may spend before it charges its budget /// ([`GasTracker::history_allowance`](crate::cfg::gas::GasTracker::history_allowance)). The /// call instruction sets it on the child where it adds the call stipend. Zero on every /// schedule defined here. /// /// A fork id, allocated from the top of the table below - /// [`reservoir_forward_percent`](Self::reservoir_forward_percent). + /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). Id 254, between the two, is + /// left unused: an earlier revision of the fork put a forward percentage there, 100 by + /// default, which a table encoded then still holds and which no entry reads. pub const fn call_history_allowance() -> GasId { Self::new(253) } - /// The share of a caller's `pool` a child frame receives when it starts, in per cent of what - /// the caller has left of it, rounded down ([`GasParams::pool_forward_share`]). A hundred, - /// the whole pool, on every schedule defined here; a chain that keeps part of a pool for the - /// caller lowers it. + /// The part of a caller's `pool` the caller keeps while its child frame runs, in per cent of + /// what the caller has left of it: the child receives the rest, rounded down + /// ([`GasParams::pool_forward_share`]). + /// + /// Zero, the whole pool forwarded, on every schedule defined here and in every table without + /// the entry, such as upstream's or one encoded before the entry existed; a chain that keeps + /// part of a pool for the caller raises it, and a hundred forwards none. /// /// Fork ids, one per pool, allocated from the top of the table below /// [`call_history_allowance`](Self::call_history_allowance): pool `i` at `252 - i`. - pub const fn pool_forward_percent(pool: PoolId) -> GasId { + pub const fn pool_kept_percent(pool: PoolId) -> GasId { Self::new(252 - pool.index() as u8) } + + /// The part of a caller's EIP-8037 reservoir the caller keeps while its child frame runs, in + /// per cent of the reservoir, rounded down: the child receives all but that + /// ([`GasParams::reservoir_forward_share`]). + /// + /// Zero, the whole reservoir forwarded as EIP-8037 forwards it, on every schedule defined + /// here and in every table without the entry, such as upstream's or one encoded before the + /// entry existed; a chain that keeps part of the reservoir for the caller raises it, and a + /// hundred forwards none. + /// + /// A fork id, allocated from the top of the table below the pools' + /// ([`pool_kept_percent`](Self::pool_kept_percent)). + pub const fn reservoir_kept_percent() -> GasId { + Self::new(249) + } } /// `percent` per cent of `value`, rounded down; a hundred or more is the whole of it. @@ -1809,10 +1821,10 @@ mod tests { // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated // from the top of the table so upstream's next sequential id does not collide with them: - // `code_deposit_history_gas` at 255, `reservoir_forward_percent` at 254, - // `call_history_allowance` at 253 and the three pools' forward percents at 252, 251 and - // 250. Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain(250..=255).collect(); + // `code_deposit_history_gas` at 255, `call_history_allowance` at 253, the three pools' + // kept percents at 252, 251 and 250 and `reservoir_kept_percent` at 249; 254 is unused. + // Every one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain(249..=253).chain([255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), @@ -1822,9 +1834,10 @@ mod tests { ); } - /// Every schedule forwards every whole pool and the whole reservoir: the share is the amount - /// itself, `u64::MAX` included. A schedule that sets a percentage forwards that much, rounded - /// down, and one at or above a hundred forwards the whole amount. + /// Every schedule forwards every whole pool and the whole reservoir: each kept percent is + /// zero and the share is the amount itself, `u64::MAX` included. A schedule that keeps a + /// percentage forwards the rest, rounded down, and one that keeps a hundred or more forwards + /// nothing. #[test] fn test_forward_shares_default_to_the_whole_amount() { let amounts = [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX]; @@ -1836,18 +1849,14 @@ mod tests { SpecId::default(), ] { let params = GasParams::new_spec(spec); - assert_eq!( - params.get(GasId::reservoir_forward_percent()), - 100, - "{spec:?}" - ); + assert_eq!(params.get(GasId::reservoir_kept_percent()), 0, "{spec:?}"); for amount in amounts { assert_eq!(params.reservoir_forward_share(amount), amount, "{spec:?}"); } for pool in PoolId::ALL { assert_eq!( - params.get(GasId::pool_forward_percent(pool)), - 100, + params.get(GasId::pool_kept_percent(pool)), + 0, "{spec:?} {pool:?}" ); for amount in amounts { @@ -1860,13 +1869,13 @@ mod tests { } } - // Each entry is its own: the reservoir at 98, the pools at 98, 50 and 0. + // Each entry is its own: the reservoir keeps 2, the pools 2, 50 and 100. let mut params = GasParams::new_spec(SpecId::OSAKA); params.override_gas([ - (GasId::reservoir_forward_percent(), 98), - (GasId::pool_forward_percent(PoolId::new(0)), 98), - (GasId::pool_forward_percent(PoolId::new(1)), 50), - (GasId::pool_forward_percent(PoolId::new(2)), 0), + (GasId::reservoir_kept_percent(), 2), + (GasId::pool_kept_percent(PoolId::new(0)), 2), + (GasId::pool_kept_percent(PoolId::new(1)), 50), + (GasId::pool_kept_percent(PoolId::new(2)), 100), ]); let share = |amount| { ( @@ -1874,7 +1883,7 @@ mod tests { PoolId::ALL.map(|pool| params.pool_forward_share(pool, amount)), ) }; - // A pool's share is its percentage rounded down; the reservoir's is what is left once the + // A pool's share is the rest rounded down; the reservoir's is what is left once the // caller's 2% is taken, rounded down, as regular gas's forward takes its part: 98% of 99 // is 97.02, so a pool forwards 97 and the reservoir 99 - 1 = 98. assert_eq!(share(0), (0, [0, 0, 0])); @@ -1897,41 +1906,95 @@ mod tests { "the reservoir's share is `reservoir - reservoir * 2 / 100`" ); } - params.override_gas([(GasId::reservoir_forward_percent(), 0)]); - assert_eq!( - params.reservoir_forward_share(1_000), - 0, - "the caller keeps all" - ); - - params.override_gas([(GasId::reservoir_forward_percent(), 250)]); - assert_eq!( - params.reservoir_forward_share(1_000), - 1_000, - "capped at the whole reservoir" - ); + for (kept, share) in [(100, 0), (250, 0), (0, 1_000)] { + params.override_gas([ + (GasId::reservoir_kept_percent(), kept), + (GasId::pool_kept_percent(PoolId::new(1)), kept), + ]); + assert_eq!( + ( + params.reservoir_forward_share(1_000), + params.pool_forward_share(PoolId::new(1), 1_000) + ), + (share, share), + "kept {kept}" + ); + } for (id, name) in [ + (GasId::reservoir_kept_percent(), "reservoir_kept_percent"), ( - GasId::reservoir_forward_percent(), - "reservoir_forward_percent", - ), - ( - GasId::pool_forward_percent(PoolId::new(0)), - "pool0_forward_percent", + GasId::pool_kept_percent(PoolId::new(0)), + "pool0_kept_percent", ), ( - GasId::pool_forward_percent(PoolId::new(1)), - "pool1_forward_percent", + GasId::pool_kept_percent(PoolId::new(1)), + "pool1_kept_percent", ), ( - GasId::pool_forward_percent(PoolId::new(2)), - "pool2_forward_percent", + GasId::pool_kept_percent(PoolId::new(2)), + "pool2_kept_percent", ), ] { assert_eq!(GasId::from_name(name), Some(id)); assert_eq!(id.name(), name); } + assert_eq!(GasId::new(254).name(), "unknown", "254 is unused"); + } + + /// Tables that lack the fork's share entries, each as a consumer could hold one: all zeros; + /// upstream's table, which has no entry above id 49, as is a table of the fork's release before + /// the shares, whose one entry above it (id 255) is zero by default; and that table with the + /// forward percentage an earlier revision of the shares put at id 254, at its default of 100 + /// and at the 98 a consumer set. + fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 4] { + let mut upstream = *GasParams::new_spec(SpecId::AMSTERDAM).table(); + upstream[50..].fill(0); + let mut earlier_default = upstream; + earlier_default[254] = 100; + let mut earlier_98 = upstream; + earlier_98[254] = 98; + [ + ("all zeros", [0; 256]), + ("upstream's", upstream), + ("an earlier revision's, at its default", earlier_default), + ("an earlier revision's, at 98", earlier_98), + ] + } + + /// Whether `params` forwards the whole reservoir and every whole pool, as upstream does. + fn forwards_everything(params: &GasParams) -> bool { + [0, 1, 99, 1_000, u64::MAX].into_iter().all(|amount| { + params.reservoir_forward_share(amount) == amount + && PoolId::ALL + .into_iter() + .all(|pool| params.pool_forward_share(pool, amount) == amount) + }) + } + + /// A table built raw, without the fork's share entries, forwards the whole reservoir and every + /// whole pool, as upstream does, and never nothing. + #[test] + fn test_a_raw_table_without_the_share_entries_forwards_everything() { + for (name, table) in tables_without_the_share_entries() { + assert!( + forwards_everything(&GasParams::new(Arc::new(table))), + "{name}" + ); + } + } + + /// A schedule encoded without the fork's share entries decodes to one that forwards the whole + /// reservoir and every whole pool. + #[cfg(feature = "serde")] + #[test] + fn test_a_schedule_encoded_without_the_share_entries_forwards_everything() { + for (name, table) in tables_without_the_share_entries() { + let encoded = serde_json::json!({ "table": table.to_vec() }); + let params: GasParams = serde_json::from_value(encoded).expect(name); + assert_eq!(params.table(), &table, "{name}"); + assert!(forwards_everything(¶ms), "{name}"); + } } /// A forward of 98/100 of the regular gas to a child, `remaining - remaining * 2 / 100` rounded diff --git a/crates/context/tests/schedule_shares.rs b/crates/context/tests/schedule_shares.rs new file mode 100644 index 0000000000..bc820713e6 --- /dev/null +++ b/crates/context/tests/schedule_shares.rs @@ -0,0 +1,64 @@ +//! A configuration whose gas schedule lacks the fork's share entries forwards a child frame the +//! whole reservoir and every whole pool, as upstream does: the schedule a consumer builds raw and +//! hands to the configuration, and the one it decodes from a configuration encoded before the +//! entries existed. + +use context_interface::{ + cfg::{gas::PoolId, GasParams}, + Cfg, +}; +use primitives::hardfork::SpecId; +use revm_context::CfgEnv; +use std::sync::Arc; + +/// Upstream's Osaka schedule: the fork's table with nothing above id 49, upstream's last. +fn upstream_table() -> [u64; 256] { + let mut table = *GasParams::new_spec(SpecId::OSAKA).table(); + table[50..].fill(0); + table +} + +/// Whether `cfg`'s schedule forwards the whole reservoir and every whole pool. +fn forwards_everything(cfg: &CfgEnv) -> bool { + let params = cfg.gas_params(); + [0, 1, 99, 1_000, u64::MAX].into_iter().all(|amount| { + params.reservoir_forward_share(amount) == amount + && PoolId::ALL + .into_iter() + .all(|pool| params.pool_forward_share(pool, amount) == amount) + }) +} + +/// Each way to give a configuration a schedule other than the spec's default: at construction, +/// with the builder and with the setter. +#[test] +fn test_a_cfg_given_a_raw_schedule_forwards_everything() { + let raw = GasParams::new(Arc::new(upstream_table())); + + let built = CfgEnv::new_with_spec_and_gas_params(SpecId::OSAKA, raw.clone()); + let chained = CfgEnv::new_with_spec(SpecId::OSAKA).with_gas_params(raw.clone()); + let mut set = CfgEnv::new_with_spec(SpecId::OSAKA); + set.set_gas_params(raw); + + for (name, cfg) in [("built", built), ("chained", chained), ("set", set)] { + assert!(forwards_everything(&cfg), "{name}"); + } +} + +/// A configuration encoded with upstream's schedule, or with the forward percentage an earlier +/// revision of the shares put at id 254, decodes to one that forwards everything. +#[cfg(feature = "serde")] +#[test] +fn test_a_cfg_encoded_without_the_share_entries_forwards_everything() { + let mut earlier = upstream_table(); + earlier[254] = 100; + for (name, table) in [("upstream's", upstream_table()), ("earlier", earlier)] { + let mut encoded = serde_json::to_value(CfgEnv::new_with_spec(SpecId::OSAKA)).unwrap(); + encoded["gas_params"]["table"] = serde_json::json!(table.to_vec()); + + let cfg: CfgEnv = serde_json::from_value(encoded).expect(name); + + assert_eq!(cfg.gas_params().table(), &table, "{name}"); + assert!(forwards_everything(&cfg), "{name}"); + } +} diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index c9d19c3cfa..3517ff27f0 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -1,10 +1,11 @@ //! The share of its caller's EIP-8037 reservoir a child frame receives, as the mainnet handler //! forwards and settles it. //! -//! A frame start takes the schedule's `reservoir_forward_percent` of its caller's reservoir out of -//! the caller's tracker for the child, and the child's return adds what the child left to what the -//! caller kept. Every schedule forwards the whole reservoir, which is upstream's forward; these -//! tests set 98, a chain that keeps 2% of the reservoir for the caller, and compare with it. +//! A frame start takes all but the schedule's `reservoir_kept_percent` of its caller's reservoir +//! out of the caller's tracker for the child, and the child's return adds what the child left to +//! what the caller kept. Every schedule keeps none and forwards the whole reservoir, which is +//! upstream's forward; these tests forward 98, a chain that keeps 2% of the reservoir for the +//! caller, and compare with it. //! //! The transactions run on Amsterdam with a gas limit [`RESERVOIR`] above the regular cap, so they //! start with a reservoir. The frames charge state gas through an instruction of the test's own, @@ -276,7 +277,8 @@ fn ends(mut code: Vec<u8>) -> Vec<u8> { struct Run { parent: Vec<u8>, parent_balance: u64, - /// `reservoir_forward_percent` in the schedule, if not the default. + /// The per cent of the reservoir a child receives, if not the default: the schedule's + /// `reservoir_kept_percent` is the rest. percent: Option<u64>, /// The transaction, if not a call to [`PARENT`] with [`GAS_LIMIT`]. tx: Option<TxEnv>, @@ -381,7 +383,7 @@ impl Run { cfg.tx_gas_limit_cap = Some(cap); if let Some(percent) = percent { cfg.gas_params - .override_gas([(GasId::reservoir_forward_percent(), percent)]); + .override_gas([(GasId::reservoir_kept_percent(), 100 - percent)]); } }); let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); @@ -743,7 +745,7 @@ fn test_a_system_call_forwards_and_settles_its_reservoir() { } } -/// The schedule's entry is upstream's forward on every spec. +/// The schedule's entry is upstream's forward on every spec: the caller keeps none. #[test] fn test_the_schedule_forwards_the_whole_reservoir() { let evm = Run::new(ends(Vec::new())).evm(); @@ -751,8 +753,8 @@ fn test_the_schedule_forwards_the_whole_reservoir() { evm.ctx .cfg() .gas_params() - .get(GasId::reservoir_forward_percent()), - 100 + .get(GasId::reservoir_kept_percent()), + 0 ); } diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs index da38026faf..7e19220adb 100644 --- a/crates/handler/tests/resource_pools.rs +++ b/crates/handler/tests/resource_pools.rs @@ -671,9 +671,10 @@ struct Run { precompile_draw: u64, /// Whether the provider starts an answer's pool at the share before it draws. precompile_seeds: bool, - /// [`FIRST`]'s `pool_forward_percent` in the schedule, if not the default. + /// The per cent of [`FIRST`] a child receives, if not the default: the schedule's + /// `pool_kept_percent` is the rest. forward_percent: Option<u64>, - /// Every pool's `pool_forward_percent` in the schedule, if not the default. + /// The per cent of each pool a child receives, if not the default. pool_percents: Option<[u64; PoolId::COUNT]>, /// Whether the transaction creates a contract from `parent` instead of calling [`PARENT`]. creates: bool, @@ -789,12 +790,12 @@ impl Run { if let Some(percents) = pool_percents { for (pool, percent) in PoolId::ALL.into_iter().zip(percents) { cfg.gas_params - .override_gas([(GasId::pool_forward_percent(pool), percent)]); + .override_gas([(GasId::pool_kept_percent(pool), 100 - percent)]); } } if let Some(percent) = forward_percent { cfg.gas_params - .override_gas([(GasId::pool_forward_percent(FIRST), percent)]); + .override_gas([(GasId::pool_kept_percent(FIRST), 100 - percent)]); } }); let ctx = DeclaringContext { @@ -1307,7 +1308,7 @@ fn test_a_start_refused_for_the_depth_gives_the_share_and_the_start_charge_back( } } -/// With [`FIRST`]'s `pool_forward_percent` at 98, every start forwards 98% of its caller's pool, rounded +/// With [`FIRST`]'s `pool_kept_percent` at 2, every start forwards 98% of its caller's pool, rounded /// down, and the caller keeps the rest; what a child hands back adds to what its caller kept, so /// the transaction ends with the figures the whole-pool forward gives. #[test] diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs index a37d06472f..d69150c927 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_share.rs @@ -91,7 +91,8 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } /// [`PARENT`]'s reservoir as its frame returned, and the reservoir the call to [`OK`] was given, -/// with `percent` as the schedule's `reservoir_forward_percent`. +/// with `percent` per cent of a caller's reservoir forwarded: the schedule's +/// `reservoir_kept_percent` is the rest. fn run(answer: Answer, percent: Option<u64>) -> (u64, u64) { let mut db = Db::default(); db.insert_account_info( @@ -116,7 +117,7 @@ fn run(answer: Answer, percent: Option<u64>) -> (u64, u64) { cfg.tx_gas_limit_cap = Some(GAS_LIMIT - RESERVOIR); if let Some(percent) = percent { cfg.gas_params - .override_gas([(GasId::reservoir_forward_percent(), percent)]); + .override_gas([(GasId::reservoir_kept_percent(), 100 - percent)]); } }); let mut evm: Evm< diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 9c44f87775..7abb881f4a 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -93,8 +93,8 @@ pub(crate) fn running_account<H: Host + ?Sized>( Ok((account.balance, account.nonce)) } -/// Takes the child's shares of the caller's reservoir and pools out of `gas`, by the schedule's -/// `reservoir_forward_percent` and `pool_forward_percent`s, and returns them: what the child's +/// Takes the child's shares of the caller's reservoir and pools out of `gas`, all but the +/// schedule's `reservoir_kept_percent` and `pool_kept_percent`s, and returns them: what the child's /// tracker starts with ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). /// Called once the frame-start hook has answered, so the shares are of the reservoir and the pools /// as the hook left them. diff --git a/crates/interpreter/src/interpreter_action/call_inputs.rs b/crates/interpreter/src/interpreter_action/call_inputs.rs index deee076431..bac1a3c263 100644 --- a/crates/interpreter/src/interpreter_action/call_inputs.rs +++ b/crates/interpreter/src/interpreter_action/call_inputs.rs @@ -186,8 +186,8 @@ pub struct CallInputs { #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, /// The share of each of the caller's pools the call receives: its pools when it starts. - /// Taken out of the caller's pools by the call instruction, by the schedule's - /// `pool_forward_percent` of each, and given back with what the call left of them when it + /// Taken out of the caller's pools by the call instruction, all but the schedule's + /// `pool_kept_percent` of each, and given back with what the call left of them when it /// returns. /// /// In a format that carries field names, such as JSON, encodings made before this field existed diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index 1e6c09dc72..f15ee5f0e9 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -42,9 +42,9 @@ pub struct CreateInputs { #[cfg_attr(feature = "serde", serde(default))] charged_start: StartCharge, /// The share of each of the caller's pools the creation receives: its pools when it starts. - /// Taken out of the caller's pools by the creation instruction, by the schedule's - /// `pool_forward_percent` of each, and given back with what the creation left of them when - /// it returns. + /// Taken out of the caller's pools by the creation instruction, all but the schedule's + /// `pool_kept_percent` of each, and given back with what the creation left of them when it + /// returns. /// /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as every pool unlimited. diff --git a/crates/interpreter/tests/resource_pools.rs b/crates/interpreter/tests/resource_pools.rs index 99e17289c5..25afd62d7a 100644 --- a/crates/interpreter/tests/resource_pools.rs +++ b/crates/interpreter/tests/resource_pools.rs @@ -79,7 +79,7 @@ impl PoolHost { /// call's child an allowance. fn on_a_chains_schedule(mut self) -> Self { self.params.override_gas([ - (GasId::pool_forward_percent(FIRST), PERCENT), + (GasId::pool_kept_percent(FIRST), 100 - PERCENT), (GasId::call_history_allowance(), ALLOWANCE), ]); self @@ -551,10 +551,10 @@ fn test_every_start_forwards_the_reservoir_and_each_pool_by_its_own_share() { let mut host = PoolHost::new(SpecId::OSAKA); host.params.override_gas([ - (GasId::reservoir_forward_percent(), 98), - (GasId::pool_forward_percent(PoolId::new(0)), 98), - (GasId::pool_forward_percent(PoolId::new(1)), 50), - (GasId::pool_forward_percent(PoolId::new(2)), 0), + (GasId::reservoir_kept_percent(), 2), + (GasId::pool_kept_percent(PoolId::new(0)), 2), + (GasId::pool_kept_percent(PoolId::new(1)), 50), + (GasId::pool_kept_percent(PoolId::new(2)), 100), ]); let (action, gas) = run_on(&code, &mut host, with_pools); let (reservoir, pools) = shares(&started(action)); From 0d4b5f69f13ffe9324a1a4a9eb9d966a58bb673f Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:33:44 +0800 Subject: [PATCH 048/110] fix(handler): a debug build refuses a first frame settled into gas that still holds what the frame was given The settlement adds what a frame returns to what its caller holds, where upstream's replaced the caller's reservoir. Code that hands a frame the caller's reservoir or a pool without taking it compiles, and counts it twice: a runner that seeds the transaction's gas from the frame's own reservoir before last_frame_result, or a first frame built from the transaction's gas without taking it. settle_first_frame now debug-asserts on entry that the transaction's gas holds no reservoir and no limited pool; an unlimited pool is exempt, since what comes back saturates at it. Frames below the transaction's get no assertion: a caller may legitimately hold a kept part, or an excess it was given back after capping a child's share, beside the share. No code in a release build. MEGAETH-FORK.md names the class by its shapes, with what a consumer does instead (forward_to_child, forward_all_to_child, or taking a share it computed), in place of the instance list. Handler::last_frame_result's doc no longer says the reservoir is adopted from the frame. --- MEGAETH-FORK.md | 12 +++++- crates/handler/src/execution/first_frame.rs | 20 ++++++++- crates/handler/src/handler.rs | 4 +- crates/handler/tests/reservoir_share.rs | 46 +++++++++++++++++++++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 4b6ca71940..7316c2aa7e 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -318,7 +318,15 @@ An id the fork once used for an entry with another default is left unused rather The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too; so does the stand-in result `Handler::runtime_oog_result` builds for a transaction whose EIP-2780 runtime phase ran out of gas, which carries the whole reservoir and every pool and settles them back once. A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. - A consumer that builds a child's input itself takes the child's shares from the caller's tracker with `forward_to_child`, and one that settles a result into a caller's tracker itself calls `handle_reservoir_remaining_gas` with a caller that gave the share up; a caller that still holds the reservoir it forwarded ends with it twice. + **The settlement adds.** `handle_reservoir_remaining_gas` (with the `GasTracker::absorb_returned_reservoir` and `absorb_returned_pools` it calls) and `execution::settle_first_frame` add what a frame returns to what its caller holds, so the caller must no longer hold what it handed the frame. + Code that hands a frame the caller's reservoir or a pool without taking it from the caller compiles, and the caller ends with it twice. The shapes: + - a child's input built by hand from the caller's `reservoir()` or `pools_remaining()`, while the caller keeps them; + - the transaction's frame, or a stand-in result for it, built from the transaction's gas without taking from it, in an override of `Handler::first_frame_input` or `Handler::runtime_oog_result` or in a runner of its own; + - a runner that settles the transaction's frame into gas it seeds from the frame's own figures (`GasTracker::new(limit, frame.remaining(), frame.reservoir())`) and then calls `last_frame_result` or `settle_first_frame`. + + A consumer takes what it hands over: `forward_to_child` takes the schedule's shares, as the instructions do; `forward_all_to_child` takes everything, as the transaction's frame does; `forward_reservoir` and `forward_pool` take a share the consumer computed. + A consumer that lowers a child's share after the forward and gives the excess back to the caller keeps the sum, and is right; so is code that settles with arithmetic of its own that replaces the caller's reservoir and calls none of these functions. + A debug build asserts on entry to `settle_first_frame` that the transaction's gas holds no reservoir and no limited pool; an unlimited pool is exempt, since what comes back saturates at it. A frame below the transaction's has no such check: its caller may hold a kept part, or an excess given back, beside the share, and only the code that built the input knows which. - **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. Only the instruction knows the reservoir as the frame-start hook left it before the input is built, and only the settlement can add the child's reservoir to what the caller kept. - **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. - **Default.** Every schedule keeps none of the reservoir and so forwards it whole, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. @@ -327,7 +335,7 @@ An id the fork once used for an entry with another default is left unused rather Where measured with the pools' figures (above), the share and the generalised forward cost 8 instructions per `CALL` with one pool. `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. - Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too. + Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too (see The settlement adds). The entries are kept parts, not forwarded ones, so that zero, which a table without them holds, forwards everything. Id 254 is left unused. A consumer names the entries by function, and a chain that forwards 98 per cent keeps 2. ### The start charge diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index f06eed0705..1805860655 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -5,7 +5,7 @@ use crate::{frame::handle_reservoir_remaining_gas, FrameResult}; use context::result::FromStringError; use context_interface::{context::take_error, ContextTr, Database}; -use interpreter::GasTracker; +use interpreter::{GasTracker, PoolId}; use std::string::ToString; /// Settles the transaction's frame, the first frame, into the transaction-level `gas`, every step @@ -25,6 +25,11 @@ use std::string::ToString; /// ([`FrameResult::refundable_start_charge`]) is refunded whole when the frame failed; after a /// halt the regular gas the refund credited is consumed. /// +/// `gas` holds no reservoir and no limited pool on entry: the first frame took them whole +/// ([`GasTracker::forward_all_to_child`]), and the settlement adds back what the frame left, so +/// gas that still held what the frame was given would count it twice. A debug build asserts it. +/// An unlimited pool is exempt, since what comes back saturates at it. +/// /// A chain whose handler overrides `last_frame_result` calls this rather than copying the mainnet /// body, so a step the fork adds here reaches its handler too. It applies its own rules to `gas` /// after this returns and then copies `gas` into the frame's result, as op-revm's handler does @@ -49,6 +54,19 @@ where { let instruction_result = frame_result.instruction_result(); + debug_assert!( + gas.reservoir() == 0, + "the transaction's gas still holds the reservoir its frame was given; the settlement \ + would count it twice (take it with `GasTracker::forward_all_to_child`)" + ); + debug_assert!( + PoolId::ALL + .into_iter() + .all(|pool| matches!(gas.pool_remaining(pool), 0 | u64::MAX)), + "the transaction's gas still holds a pool its frame was given; the settlement would \ + count it twice (take it with `GasTracker::forward_all_to_child`)" + ); + // All regular gas was forwarded to the first frame: consume it on the // transaction-level gas; the settle below returns the frame's unused // part. diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index c872e1a84a..3ed0085572 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -499,8 +499,8 @@ pub trait Handler { /// ([`handle_reservoir_remaining_gas`]): a failing frame rolls its /// state-gas charges back in LIFO order and drops its refund counter, an /// exceptional halt additionally consumes its regular gas; unused regular - /// gas then returns to the transaction-level gas and the reservoir is - /// adopted from the frame. The EIP-2780 refundable first-frame charge is + /// gas then returns to the transaction-level gas and the reservoir the + /// frame left is added back to it. The EIP-2780 refundable first-frame charge is /// refunded from the outcome's `charged_*` flags, mirroring /// `EthFrame::return_result`. /// diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index 3517ff27f0..fceab0158f 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -874,3 +874,49 @@ fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { ); } } + +/// The transaction's frame took the whole reservoir and every whole pool, and its settlement adds +/// back what it left. A runner that settles the frame into gas that still holds what the frame was +/// given, because it built the frame without taking it or seeded the gas from the frame's own +/// figures, would count it twice; a debug build refuses the settlement. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "the transaction's gas still holds the reservoir its frame was given")] +fn test_a_first_frame_settled_into_gas_that_kept_the_reservoir_panics_in_a_debug_build() { + let mut evm = Run::new(ends(Vec::new())).evm(); + let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, RESERVOIR); + let mut gas = GasTracker::new(GAS_LIMIT, 0, RESERVOIR); + + let _ = Mainnet::default().last_frame_result(&mut evm, &mut result, &mut gas); +} + +/// The same for a pool the transaction's gas still holds. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "the transaction's gas still holds a pool its frame was given")] +fn test_a_first_frame_settled_into_gas_that_kept_a_pool_panics_in_a_debug_build() { + let mut evm = Run::new(ends(Vec::new())).evm(); + let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); + let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); + gas.set_pools_remaining(PoolAmounts::ZERO); + gas.set_pool_remaining(PoolId::new(2), 1_000); + + let _ = Mainnet::default().last_frame_result(&mut evm, &mut result, &mut gas); +} + +/// An unlimited pool the transaction's gas still holds cannot be counted twice, since what comes +/// back saturates at it: a runner that builds the gas with `GasTracker::new` and draws no pool, +/// with no reservoir, settles as before. +#[test] +fn test_a_first_frame_settled_into_gas_with_unlimited_pools_and_no_reservoir_settles() { + let mut evm = Run::new(ends(Vec::new())).evm(); + let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); + let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); + + Mainnet::default() + .last_frame_result(&mut evm, &mut result, &mut gas) + .expect("the frame settles"); + + assert_eq!(gas.pools_remaining(), PoolAmounts::UNLIMITED); + assert_eq!(gas.reservoir(), 0); +} From 7236a7517d58cbc02546e9e2edaa026402e038ca Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:39:11 +0800 Subject: [PATCH 049/110] test(handler): a refill beside a kept reservoir and a child's spill credits regular gas first, as EIP-8037 orders it With a share below the whole reservoir, a caller can hold its kept part beside the spill of a child that spent past its share, which a whole forward cannot produce. A refill in that caller then keeps EIP-8037's order, regular gas up to the outstanding spill first and the reservoir after, so a charge it paid from its kept reservoir comes back as regular gas. The semantics are unchanged. The test pins the figures at 98 per cent and, for contrast, at the whole forward, where the refill undoes the caller's own spill; the sum is conserved and the caller's rollback restores what it started with. MEGAETH-FORK.md states the order as the rule, with the example. --- MEGAETH-FORK.md | 4 +++ crates/handler/src/frame.rs | 65 +++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 7316c2aa7e..0f6bb90ad4 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -315,6 +315,10 @@ An id the fork once used for an entry with another default is left unused rather The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. + A caller that keeps part of its reservoir can therefore hold it beside an outstanding spill: a child that succeeded after spending past its share spilled onto its regular gas, and the spill merges into the caller's. A whole forward cannot produce this, since the caller then keeps none. + A refill in such a caller (an EIP-8037 restoration, `refill_history`, the refund of an upfront or a start charge) keeps EIP-8037's order: regular gas up to the outstanding spill first, the reservoir after, whichever of the two paid the charge the refill undoes. So a charge the caller paid from its kept reservoir comes back as regular gas while a child's spill is outstanding. + For example, a caller with a reservoir of 1,000 that keeps 2 per cent keeps 20 and forwards 980; a child that charges 1,000 spills 20; the caller then charges 10 from its reservoir (reservoir 10, spill 20) and refills 10, which leaves its reservoir at 10, its spill at 10 and its regular gas 10 higher. + The sum of the two is conserved, a rollback still restores the reservoir the frame started with, and the reimbursement and `gas_used` read the sum, so no final figure moves; `GAS` in the caller reads the credited regular gas. The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too; so does the stand-in result `Handler::runtime_oog_result` builds for a transaction whose EIP-2780 runtime phase ran out of gas, which carries the whole reservoir and every pool and settles them back once. A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 3bde883644..78930ff438 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -1137,4 +1137,69 @@ mod tests { assert_eq!(a.remaining(), 10_000); assert_eq!(a.state_gas_spent(), 0); } + + /// A caller that kept part of its reservoir holds it beside the spill of a child that spent + /// past its share, which a whole forward cannot produce. A refill in the caller then keeps + /// EIP-8037's order, regular gas up to the outstanding spill first and the reservoir after, + /// whichever paid the charge it undoes: a charge the caller paid from its kept reservoir comes + /// back as regular gas. The sum of the two is conserved, and a rollback restores the reservoir + /// the caller started with. With the whole reservoir forwarded, the caller's charge spills + /// too, and its refill returns where the charge was taken. + #[test] + fn test_a_refill_beside_a_kept_reservoir_and_a_childs_spill_credits_regular_gas_first() { + // (reservoir, remaining, spilled, state gas spent) of a tracker. + let figures = |gas: &GasTracker| { + ( + gas.reservoir(), + gas.remaining(), + gas.state_gas_spilled(), + gas.state_gas_spent(), + ) + }; + for (forwarded, after_child, after_charge, after_refill) in [ + // 98%: B keeps 20 and C spills 20; B's charge comes from its reservoir, the refill + // goes to its regular gas. + ( + 980, + (20, 9_980, 20, 1_000), + (10, 9_980, 20, 1_010), + (10, 9_990, 10, 1_000), + ), + // The whole reservoir: B keeps none and C spills 0; B's charge spills, and the refill + // undoes that spill. + ( + 1_000, + (0, 10_000, 0, 1_000), + (0, 9_990, 10, 1_010), + (0, 10_000, 0, 1_000), + ), + ] { + // B holds 1,000 of reservoir and forwards 5,000 of regular gas; C charges 1,000. + let mut b = GasTracker::new(10_000, 10_000, 1_000); + assert!(b.record_regular_cost(5_000)); + b.forward_reservoir(forwarded); + let mut c = GasTracker::new(5_000, 5_000, forwarded); + assert!(c.record_state_cost(1_000)); + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); + assert_eq!(figures(&b), after_child, "{forwarded}: after C"); + + // B writes a slot, 10 of state gas, and puts it back, a refill of 10. + assert!(b.record_state_cost(10)); + assert_eq!(figures(&b), after_charge, "{forwarded}: after B's charge"); + b.refill_reservoir(10); + assert_eq!(figures(&b), after_refill, "{forwarded}: after B's refill"); + assert_eq!( + b.reservoir() + b.remaining(), + 10_000, + "{forwarded}: the sum is conserved" + ); + + b.rollback_state_gas(); + assert_eq!( + (b.reservoir(), b.remaining()), + (1_000, 10_000), + "{forwarded}: B's rollback restores what it started with" + ); + } + } } From 107cf3fb38a4e8ac28fd5c0fe29afa5e2b01b722 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:41:41 +0800 Subject: [PATCH 050/110] test: an inspector's creation answer and a creation's runtime out-of-gas settle the reservoir and the pools once An inspector's answer to a creation settles through the same arm as an answer to a call; the test now pins it as built (the caller keeps its kept part and the creation's charge), with the shares and the input's charges (the caller gets back what it held before the start) and run, at the whole forward and at 98. The runtime out-of-gas stand-in was pinned for a call with unlimited pools only; a creation transaction on finite pools now settles both back once, and the test fails against a stand-in that copies the transaction's figures without taking them. --- crates/handler/tests/reservoir_share.rs | 47 ++++++++++++ crates/inspector/tests/reservoir_share.rs | 90 ++++++++++++++++++++--- 2 files changed, 125 insertions(+), 12 deletions(-) diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index fceab0158f..8bd19e18a3 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -138,6 +138,8 @@ struct ShareHandler { /// A reservoir to give the transaction's gas, as a consumer that splits a system call's gas /// does; mainnet gives a system call none. system_reservoir: Option<u64>, + /// Pools to give the transaction's gas, as a consumer that limits its figures does. + tx_pools: Option<PoolAmounts>, starts: Vec<u64>, returned: Vec<Returned>, /// The transaction's reservoir and net state gas after the first frame settled into it. @@ -158,6 +160,7 @@ impl ShareHandler { mainnet: Mainnet::default(), too_deep: false, system_reservoir: None, + tx_pools: None, starts: Vec::new(), returned: Vec::new(), settled: None, @@ -182,6 +185,9 @@ impl Handler for ShareHandler { // And pools, as a consumer that limits a system call's figures sets them. gas.set_pools_remaining(SYSTEM_POOLS); } + if let Some(pools) = self.tx_pools { + gas.set_pools_remaining(pools); + } self.tx_reservoir.set(Some(gas.reservoir())); gas } @@ -875,6 +881,47 @@ fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { } } +/// The same for a creation transaction, whose runtime phase charges the account it would create, +/// on a transaction's gas a consumer gave finite pools: the stand-in takes the whole reservoir +/// and every pool, and both settle back once. +#[test] +fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the_pools_once() { + const LIMIT: u64 = 160_000; + const CAP: u64 = 60_000; + for percent in [None, Some(PERCENT)] { + // A creation whose account's state gas the reservoir and the regular gas left together + // cannot pay. + let mut run = Run::new(Vec::new()); + run.percent = percent; + run.cap = Some(CAP); + run.tx = Some( + TxEnv::builder_for_bench() + .kind(TxKind::Create) + .gas_price(0) + .gas_limit(LIMIT) + .build_fill(), + ); + let mut handler = ShareHandler::new(); + handler.tx_pools = Some(SYSTEM_POOLS); + + let (result, handler) = run.with(handler); + + assert!( + matches!(result, ExecutionResult::Halt { .. }), + "{percent:?}: {result:?}" + ); + let reservoir = handler.tx_reservoir.get().expect("tx_gas ran"); + assert!(reservoir > 0, "{percent:?}"); + assert_eq!(handler.settled, Some((reservoir, 0)), "{percent:?}"); + assert_eq!(handler.settled_pools, Some(SYSTEM_POOLS), "{percent:?}"); + assert_eq!( + result.gas().total_gas_spent(), + LIMIT - reservoir, + "{percent:?}: every regular gas spent, the reservoir returned" + ); + } +} + /// The transaction's frame took the whole reservoir and every whole pool, and its settlement adds /// back what it left. A runner that settles the frame into gas that still holds what the frame was /// given, because it built the frame without taking it or seeded the gas from the frame's own diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs index d69150c927..aa6de171f1 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_share.rs @@ -7,6 +7,10 @@ //! the caller is left with none, as upstream's settlement, which put the answer's reservoir in //! place of the caller's, leaves it; with 98% forwarded, the caller is left with the 2% it kept. //! An answer that carries the input's reservoir gives the caller back what it forwarded. +//! +//! A creation's answer settles through the same arm as a call's: the caller also paid the +//! creation's upfront state charge before the forward, which an answer that copies the input's +//! charge gives back and one built with `CreateOutcome::new` does not. use context::{context_interface::cfg::GasId, Context, Evm, TxEnv}; use database::{CacheDB, EmptyDB, BENCH_CALLER}; @@ -14,12 +18,13 @@ use handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, MainContext, MainnetContext, }; use interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult, + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, + InstructionResult, InterpreterResult, }; use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{InspectEvm, Inspector}; use state::{ - bytecode::opcode::{CALL, POP, PUSH0, PUSH1, PUSH20, PUSH3, SSTORE, STOP}, + bytecode::opcode::{CALL, CREATE, POP, PUSH0, PUSH1, PUSH20, PUSH3, SSTORE, STOP}, AccountInfo, Bytecode, }; @@ -37,7 +42,15 @@ const BEFORE_THE_CALL: u64 = RESERVOIR - SLOT; /// Its share at 98: all but the caller's 2%, rounded down (18,041.6 → 18,041). const SHARE: u64 = 884_039; -/// Writes a new slot, calls [`OK`] and stops. +/// The state charge a creation's start pays for its account on Amsterdam's schedule, before the +/// forward. +const ACCOUNT: u64 = 183_600; +/// What [`PARENT`] holds when it creates, once the creation's charge is paid. +const BEFORE_THE_CREATION: u64 = BEFORE_THE_CALL - ACCOUNT; +/// Its share at 98: all but the caller's 2%, rounded down (14,369.6 → 14,369). +const CREATION_SHARE: u64 = 704_111; + +/// Writes a new slot, calls [`OK`] (or creates a contract with empty init code) and stops. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Stops, when it runs. const OK: Address = address!("0x0000000000000000000000000000000000000c00"); @@ -53,8 +66,8 @@ enum Answer { WithTheShares, } -/// Answers the call to [`OK`] as told, and records the reservoir the call was given and -/// [`PARENT`]'s reservoir as its frame returned, before the transaction settled it. +/// Answers the call to [`OK`], or the creation, as told, and records the reservoir the start was +/// given and [`PARENT`]'s reservoir as its frame returned, before the transaction settled it. struct Answering { answer: Answer, given: Option<u64>, @@ -83,6 +96,30 @@ impl Inspector<Ctx, EthInterpreter> for Answering { )) } + fn create(&mut self, _: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { + self.given = Some(inputs.reservoir()); + let gas = match self.answer { + Answer::Runs => return None, + Answer::AsBuilt => Gas::new(inputs.gas_limit()), + Answer::WithTheShares => { + let mut gas = + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares()); + gas + } + }; + let mut outcome = CreateOutcome::new( + InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), + None, + ); + if let Answer::WithTheShares = self.answer { + outcome.charged_create_state_gas = inputs.charged_create_state_gas(); + outcome.charged_state_gas_address = inputs.charged_state_gas_address(); + outcome.charged_start = inputs.charged_start(); + } + Some(outcome) + } + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { if inputs.target_address == PARENT { self.parent_returned = Some(outcome.result.gas.reservoir()); @@ -91,9 +128,9 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } /// [`PARENT`]'s reservoir as its frame returned, and the reservoir the call to [`OK`] was given, -/// with `percent` per cent of a caller's reservoir forwarded: the schedule's -/// `reservoir_kept_percent` is the rest. -fn run(answer: Answer, percent: Option<u64>) -> (u64, u64) { +/// or the creation if [`PARENT`] `creates`, with `percent` per cent of a caller's reservoir +/// forwarded: the schedule's `reservoir_kept_percent` is the rest. +fn run(answer: Answer, percent: Option<u64>, creates: bool) -> (u64, u64) { let mut db = Db::default(); db.insert_account_info( BENCH_CALLER, @@ -102,8 +139,14 @@ fn run(answer: Answer, percent: Option<u64>) -> (u64, u64) { let mut parent = vec![ PUSH1, 1, PUSH0, SSTORE, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20, ]; - parent.extend_from_slice(OK.as_slice()); - parent.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP, STOP]); + if creates { + // `CREATE(0, 0, 0)` in place of the call's last five pushes and the call. + parent.truncate(4); + parent.extend_from_slice(&[PUSH0, PUSH0, PUSH0, CREATE, POP, STOP]); + } else { + parent.extend_from_slice(OK.as_slice()); + parent.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP, STOP]); + } for (address, code) in [(PARENT, parent), (OK, vec![STOP])] { db.insert_account_info( address, @@ -159,14 +202,37 @@ fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), ] { assert_eq!( - run(answer, None), + run(answer, None, false), (whole, BEFORE_THE_CALL), "{answer:?}, the whole reservoir forwarded" ); assert_eq!( - run(answer, Some(98)), + run(answer, Some(98), false), (kept_98, SHARE), "{answer:?}, 98% forwarded" ); } } + +/// A creation's answer settles as a call's: as built, the caller keeps its kept part and the +/// creation's charge; with the shares and the input's charges, the caller gets back what it held +/// before the creation's start. +#[test] +fn test_an_answer_the_inspector_builds_for_a_creation_settles_its_reservoir_as_built() { + for (answer, whole, kept_98) in [ + (Answer::Runs, BEFORE_THE_CREATION, BEFORE_THE_CREATION), + (Answer::AsBuilt, 0, BEFORE_THE_CREATION - CREATION_SHARE), + (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), + ] { + assert_eq!( + run(answer, None, true), + (whole, BEFORE_THE_CREATION), + "{answer:?}, the whole reservoir forwarded" + ); + assert_eq!( + run(answer, Some(98), true), + (kept_98, CREATION_SHARE), + "{answer:?}, 98% forwarded" + ); + } +} From c47708032d720344fc381b3838d9caaa67ac3ff3 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:42:22 +0800 Subject: [PATCH 051/110] docs: the two share roundings are fixed by the fork, not by the schedule, in MEGAETH-FORK.md The reservoir's share takes the caller's part away as regular gas's forward does, and a pool's share is rounded down; no entry chooses either. --- MEGAETH-FORK.md | 1 + 1 file changed, 1 insertion(+) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 0f6bb90ad4..c967e9581a 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -312,6 +312,7 @@ An id the fork once used for an entry with another default is left unused rather On `GasTracker`: `forward_reservoir(share)`, and `forward_to_child(&GasParams)` and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). - **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. `reservoir_forward_share` is the reservoir less the caller's part, `reservoir_kept_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 2 kept the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool keeping 2 forwards 97 (its share is rounded down). Zero kept forwards the whole reservoir, as EIP-8037 does; a hundred or more forwards none. + The two roundings are the fork's, not the schedule's: the reservoir's share takes the caller's part away as regular gas's forward does, and a pool's share is rounded down. A chain that needs the floor for the reservoir, or the subtraction for a pool, has no entry for it. The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. From ab74a51825125fe9c1fc5f71aded46e207e6f6ef Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 12:48:00 +0800 Subject: [PATCH 052/110] docs: the pools' cost at the head with the review fixes, and the adoption's check, in MEGAETH-FORK.md Measured against 34f30eb7 with the same drivers (callgrind, aarch64, two rounds, equal to the instruction): a transfer -1, each CALL -1.9, a top-level creation -3, a nested CREATE -7.75, a SELFDESTRUCT transaction +4 and a precompile answer +11, the fail-closed adoption's check of each pool. The figures against the byte pool and against the base move by those amounts. --- MEGAETH-FORK.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index c967e9581a..5d0ebd1754 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -302,9 +302,10 @@ An id the fork once used for an entry with another default is left unused rather Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's kept percentage the next free id and a name, and changes the tests that count them. The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). - Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 216 instructions more (+3.9%), each `CALL` about 260 more (+11.0% on a transaction of 64 calls), a top-level creation 276 more (+1.5%), a nested `CREATE` 339 more (+2.1%) and a `SELFDESTRUCT` transaction 281 more (+3.5%). + Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 215 instructions more (+3.9%), each `CALL` about 258 more (+10.9% on a transaction of 64 calls), a top-level creation 273 more (+1.5%), a nested `CREATE` 331 more (+2.1%) and a `SELFDESTRUCT` transaction 285 more (+3.5%). Nearly all of it is the size: the same code with one pool, at the earlier sizes, cost 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. - Against the base without any of the fork's figures, a transfer costs 337 more (+6.2%) and each `CALL` about 400 more (+18.0% on a transaction of 64 calls). + Against the base without any of the fork's figures, a transfer costs 336 more (+6.2%) and each `CALL` about 398 more (+17.9% on a transaction of 64 calls). + A precompile's answer runs 11 instructions more than with an adoption that does not check each pool's net against its share (see Contract); a transfer, a call, a creation and a `SELFDESTRUCT` run no more for it. ### The reservoir share From 3b5f9ed98209a6d80ff98c1e984a108124fc3a28 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 13:10:35 +0800 Subject: [PATCH 053/110] fix(gas): the pools' kept entries move below the reservoir's, so a later pool takes a free id and every earlier table forwards everything At 252 - i, a fourth pool's entry landed on 249, the reservoir's, and a table encoded by the previous revision of the shares, with 100 at 250 to 252, read as every pool kept whole and forwarded nothing. The pools' entries are now at 248 - i (248, 247, 246), ids 250 to 252 are left unused beside 254, and a later pool takes 245. Also: new_spec carries no comment where the fork's entries were set, since they are zero as upstream's table has them; the two share functions say why they test zero first; the CfgEnv test covers with_spec_and_gas_params and decodes every earlier form, the 98 at 254 and the later revision's pools included. --- MEGAETH-FORK.md | 6 +-- .../context/interface/src/cfg/gas_params.rs | 47 +++++++++++-------- crates/context/tests/schedule_shares.rs | 40 +++++++++++++--- 3 files changed, 63 insertions(+), 30 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 5d0ebd1754..260d3b3573 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -271,7 +271,7 @@ An id the fork once used for an entry with another default is left unused rather - **API.** `PoolId` (`new(index)`, `index`, `COUNT` = 3, `ALL`) and `PoolAmounts` (an amount per pool: `ZERO`, `UNLIMITED`, `get`, `set`, `with`, `is_zero`), in `revm_context_interface::cfg::gas`, re-exported from `revm_interpreter`. On `GasTracker`, forwarded on `Gas`: `pool_remaining`, `set_pool_remaining`, `pool_spent`, `set_pool_spent`, `record_pool`, `refill_pool`, `pool_crossing`, `clear_pool_crossing`, `set_pool_crossing`, each taking the `PoolId`. On `GasTracker` alone, the fork's own plumbing: `pools_remaining`, `set_pools_remaining`, `add_pool_spent`, `forward_pool`, `absorb_returned_pool`, `absorb_returned_pools`, `adopt_pool_share`, `adopt_pool_shares`, and `forward_to_child` and `forward_all_to_child` with their `ChildShares` (see The reservoir share). - `GasId::pool_kept_percent(pool)` (ids 252, 251 and 250) and `GasParams::pool_forward_share(pool, remaining)`. + `GasId::pool_kept_percent(pool)` (ids 248, 247 and 246) and `GasParams::pool_forward_share(pool, remaining)`. `pool_shares` on `CallInputs` (a field) and `CreateInputs` (`pool_shares`, `set_pool_shares`). - **Contract.** A tracker carries `PoolId::COUNT` pools, budgets beside its gas whose meaning the consumer gives (bytes a frame may append, records it may write, entries it may create); the fork knows them by index only. For each pool, `pool_remaining` is what the frame may still draw and `pool_spent` its net draw, signed as `history_gas_spent` is. @@ -299,7 +299,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream carries equivalent per-frame budgets on its gas, or when mega-evm stops limiting these per frame. - **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule keeps none of a pool and so forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. A table without the entries, built raw or decoded from an encoding that predates them, keeps none too (see Hooks). - Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's kept percentage the next free id and a name, and changes the tests that count them. + Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's kept percentage the next id below the pools' (245) and a name, and changes the tests that count them. The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 215 instructions more (+3.9%), each `CALL` about 258 more (+10.9% on a transaction of 64 calls), a top-level creation 273 more (+1.5%), a nested `CREATE` 331 more (+2.1%) and a `SELFDESTRUCT` transaction 285 more (+3.5%). @@ -342,7 +342,7 @@ An id the fork once used for an entry with another default is left unused rather `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too (see The settlement adds). - The entries are kept parts, not forwarded ones, so that zero, which a table without them holds, forwards everything. Id 254 is left unused. A consumer names the entries by function, and a chain that forwards 98 per cent keeps 2. + The entries are kept parts, not forwarded ones, so that zero, which a table without them holds, forwards everything. Ids 254 and 250 to 252 are left unused. A consumer names the entries by function, and a chain that forwards 98 per cent keeps 2. ### The start charge diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index 6521d5550d..7587726dce 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -232,9 +232,6 @@ impl GasParams { gas::NON_ZERO_BYTE_MULTIPLIER; table[GasId::tx_token_cost().as_usize()] = gas::STANDARD_TOKEN_COST; table[GasId::tx_base_stipend().as_usize()] = 21000; - // The fork's entries are zero on every spec, as upstream's table has them: a caller keeps - // none of its reservoir and none of any pool while its child runs, and a value call's - // child has no history allowance. if spec.is_enabled_in(SpecId::HOMESTEAD) { table[GasId::tx_create_cost().as_usize()] = gas::CREATE; @@ -826,6 +823,7 @@ impl GasParams { #[inline] pub fn pool_forward_share(&self, pool: PoolId, remaining: u64) -> u64 { let kept = self.get(GasId::pool_kept_percent(pool)); + // The default, the whole pool, without the arithmetic. if kept == 0 { return remaining; } @@ -844,6 +842,7 @@ impl GasParams { #[inline] pub fn reservoir_forward_share(&self, reservoir: u64) -> u64 { let kept = self.get(GasId::reservoir_kept_percent()); + // The default, the whole reservoir, without the arithmetic. if kept == 0 { return reservoir; } @@ -1701,9 +1700,8 @@ impl GasId { /// schedule defined here. /// /// A fork id, allocated from the top of the table below - /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). Id 254, between the two, is - /// left unused: an earlier revision of the fork put a forward percentage there, 100 by - /// default, which a table encoded then still holds and which no entry reads. + /// [`code_deposit_history_gas`](Self::code_deposit_history_gas); id 254, between the two, is + /// left unused (see [`reservoir_kept_percent`](Self::reservoir_kept_percent)). pub const fn call_history_allowance() -> GasId { Self::new(253) } @@ -1716,10 +1714,11 @@ impl GasId { /// the entry, such as upstream's or one encoded before the entry existed; a chain that keeps /// part of a pool for the caller raises it, and a hundred forwards none. /// - /// Fork ids, one per pool, allocated from the top of the table below - /// [`call_history_allowance`](Self::call_history_allowance): pool `i` at `252 - i`. + /// Fork ids, one per pool, allocated downward below + /// [`reservoir_kept_percent`](Self::reservoir_kept_percent): pool `i` at `248 - i`, so a later + /// pool takes the next id below them. pub const fn pool_kept_percent(pool: PoolId) -> GasId { - Self::new(252 - pool.index() as u8) + Self::new(248 - pool.index() as u8) } /// The part of a caller's EIP-8037 reservoir the caller keeps while its child frame runs, in @@ -1731,8 +1730,10 @@ impl GasId { /// entry existed; a chain that keeps part of the reservoir for the caller raises it, and a /// hundred forwards none. /// - /// A fork id, allocated from the top of the table below the pools' - /// ([`pool_kept_percent`](Self::pool_kept_percent)). + /// A fork id, allocated from the top of the table below + /// [`call_history_allowance`](Self::call_history_allowance). Ids 254 and 250 to 252 are left + /// unused: earlier revisions of the fork put forward percentages there, 100 by default, which + /// a table encoded then still holds and which no entry reads. pub const fn reservoir_kept_percent() -> GasId { Self::new(249) } @@ -1821,10 +1822,10 @@ mod tests { // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated // from the top of the table so upstream's next sequential id does not collide with them: - // `code_deposit_history_gas` at 255, `call_history_allowance` at 253, the three pools' - // kept percents at 252, 251 and 250 and `reservoir_kept_percent` at 249; 254 is unused. - // Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain(249..=253).chain([255]).collect(); + // `code_deposit_history_gas` at 255, `call_history_allowance` at 253, + // `reservoir_kept_percent` at 249 and the three pools' kept percents at 248, 247 and 246; + // 254 and 250 to 252 are unused. Every one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain(246..=249).chain([253, 255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), @@ -1939,26 +1940,32 @@ mod tests { assert_eq!(GasId::from_name(name), Some(id)); assert_eq!(id.name(), name); } - assert_eq!(GasId::new(254).name(), "unknown", "254 is unused"); + for unused in [250, 251, 252, 254] { + assert_eq!(GasId::new(unused).name(), "unknown", "{unused} is unused"); + } } /// Tables that lack the fork's share entries, each as a consumer could hold one: all zeros; /// upstream's table, which has no entry above id 49, as is a table of the fork's release before - /// the shares, whose one entry above it (id 255) is zero by default; and that table with the - /// forward percentage an earlier revision of the shares put at id 254, at its default of 100 - /// and at the 98 a consumer set. - fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 4] { + /// the shares, whose one entry above it (id 255) is zero by default; that table with the + /// forward percentage an earlier revision put at id 254, at its default of 100 and at the 98 a + /// consumer set; and with the forward percentages a later one put at ids 254 and 250 to 252, + /// at their default of 100. + fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 5] { let mut upstream = *GasParams::new_spec(SpecId::AMSTERDAM).table(); upstream[50..].fill(0); let mut earlier_default = upstream; earlier_default[254] = 100; let mut earlier_98 = upstream; earlier_98[254] = 98; + let mut later_default = earlier_default; + later_default[250..=252].fill(100); [ ("all zeros", [0; 256]), ("upstream's", upstream), ("an earlier revision's, at its default", earlier_default), ("an earlier revision's, at 98", earlier_98), + ("a later revision's, at its defaults", later_default), ] } diff --git a/crates/context/tests/schedule_shares.rs b/crates/context/tests/schedule_shares.rs index bc820713e6..b24b31f0fb 100644 --- a/crates/context/tests/schedule_shares.rs +++ b/crates/context/tests/schedule_shares.rs @@ -18,6 +18,27 @@ fn upstream_table() -> [u64; 256] { table } +/// Schedules without the share entries, as a configuration could have been encoded: upstream's; +/// with the forward percentage an earlier revision of the fork put at id 254, at its default of +/// 100 and at the 98 a consumer set; and with those a later revision put at ids 254 and 250 to +/// 252, at their default of 100. +#[cfg(feature = "serde")] +fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 4] { + let upstream = upstream_table(); + let mut earlier = upstream; + earlier[254] = 100; + let mut earlier_98 = upstream; + earlier_98[254] = 98; + let mut later = earlier; + later[250..=252].fill(100); + [ + ("upstream's", upstream), + ("an earlier revision's", earlier), + ("an earlier revision's, at 98", earlier_98), + ("a later revision's", later), + ] +} + /// Whether `cfg`'s schedule forwards the whole reservoir and every whole pool. fn forwards_everything(cfg: &CfgEnv) -> bool { let params = cfg.gas_params(); @@ -30,29 +51,34 @@ fn forwards_everything(cfg: &CfgEnv) -> bool { } /// Each way to give a configuration a schedule other than the spec's default: at construction, -/// with the builder and with the setter. +/// with the two builders and with the setter. #[test] fn test_a_cfg_given_a_raw_schedule_forwards_everything() { let raw = GasParams::new(Arc::new(upstream_table())); let built = CfgEnv::new_with_spec_and_gas_params(SpecId::OSAKA, raw.clone()); let chained = CfgEnv::new_with_spec(SpecId::OSAKA).with_gas_params(raw.clone()); + let respecced = + CfgEnv::new_with_spec(SpecId::PRAGUE).with_spec_and_gas_params(SpecId::OSAKA, raw.clone()); let mut set = CfgEnv::new_with_spec(SpecId::OSAKA); set.set_gas_params(raw); - for (name, cfg) in [("built", built), ("chained", chained), ("set", set)] { + for (name, cfg) in [ + ("built", built), + ("chained", chained), + ("respecced", respecced), + ("set", set), + ] { assert!(forwards_everything(&cfg), "{name}"); } } -/// A configuration encoded with upstream's schedule, or with the forward percentage an earlier -/// revision of the shares put at id 254, decodes to one that forwards everything. +/// A configuration encoded with a schedule without the share entries decodes to one that forwards +/// everything. #[cfg(feature = "serde")] #[test] fn test_a_cfg_encoded_without_the_share_entries_forwards_everything() { - let mut earlier = upstream_table(); - earlier[254] = 100; - for (name, table) in [("upstream's", upstream_table()), ("earlier", earlier)] { + for (name, table) in tables_without_the_share_entries() { let mut encoded = serde_json::to_value(CfgEnv::new_with_spec(SpecId::OSAKA)).unwrap(); encoded["gas_params"]["table"] = serde_json::json!(table.to_vec()); From 074163757a0fcb86a43486704af3a67cba14c818 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 13:10:35 +0800 Subject: [PATCH 054/110] test: the inspector's answers share one gas builder and name their start, and the limited pools are named for what they are The creation answer's test took a bare flag and rebuilt PARENT's code by truncating the call's (its comment counted the bytes wrong); it now builds the slot write and then the start it is given. The answers' gas is built once for a call and a creation. The finite pools a consumer gives the transaction's gas serve the system call and the creation's runtime out-of-gas alike, and are named LIMITED_POOLS. --- crates/handler/tests/reservoir_share.rs | 15 ++-- crates/inspector/tests/reservoir_share.rs | 89 ++++++++++++----------- 2 files changed, 56 insertions(+), 48 deletions(-) diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index 8bd19e18a3..70f1a5d88f 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -114,8 +114,9 @@ fn pool_shares_of(input: &FrameInput) -> PoolAmounts { } } -/// The pools a system call's gas gets in [`ShareHandler::tx_gas`]. -const SYSTEM_POOLS: PoolAmounts = PoolAmounts::ZERO +/// Finite pools a consumer gives the transaction's gas: a system call's in +/// [`ShareHandler::tx_gas`], or any transaction's with [`ShareHandler::tx_pools`]. +const LIMITED_POOLS: PoolAmounts = PoolAmounts::ZERO .with(PoolId::new(0), 1_000) .with(PoolId::new(1), 500) .with(PoolId::new(2), 100); @@ -183,7 +184,7 @@ impl Handler for ShareHandler { gas.set_remaining(gas.remaining() - reservoir); gas.set_reservoir(reservoir); // And pools, as a consumer that limits a system call's figures sets them. - gas.set_pools_remaining(SYSTEM_POOLS); + gas.set_pools_remaining(LIMITED_POOLS); } if let Some(pools) = self.tx_pools { gas.set_pools_remaining(pools); @@ -746,8 +747,8 @@ fn test_a_system_call_forwards_and_settles_its_reservoir() { ); // The pools go the same way: the system call's frame takes them whole, the schedule // forwards them whole, and they come back as they were, nothing drawn. - assert_eq!(handler.pool_starts, [SYSTEM_POOLS; 2], "{percent:?}"); - assert_eq!(handler.settled_pools, Some(SYSTEM_POOLS), "{percent:?}"); + assert_eq!(handler.pool_starts, [LIMITED_POOLS; 2], "{percent:?}"); + assert_eq!(handler.settled_pools, Some(LIMITED_POOLS), "{percent:?}"); } } @@ -902,7 +903,7 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the .build_fill(), ); let mut handler = ShareHandler::new(); - handler.tx_pools = Some(SYSTEM_POOLS); + handler.tx_pools = Some(LIMITED_POOLS); let (result, handler) = run.with(handler); @@ -913,7 +914,7 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the let reservoir = handler.tx_reservoir.get().expect("tx_gas ran"); assert!(reservoir > 0, "{percent:?}"); assert_eq!(handler.settled, Some((reservoir, 0)), "{percent:?}"); - assert_eq!(handler.settled_pools, Some(SYSTEM_POOLS), "{percent:?}"); + assert_eq!(handler.settled_pools, Some(LIMITED_POOLS), "{percent:?}"); assert_eq!( result.gas().total_gas_spent(), LIMIT - reservoir, diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs index aa6de171f1..f5ffe0eb98 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_share.rs @@ -19,7 +19,7 @@ use handler::{ }; use interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, InterpreterResult, + InstructionResult, InterpreterResult, PoolAmounts, }; use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{InspectEvm, Inspector}; @@ -55,6 +55,15 @@ const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Stops, when it runs. const OK: Address = address!("0x0000000000000000000000000000000000000c00"); +/// What [`PARENT`] starts after writing its slot. +#[derive(Clone, Copy, Debug)] +enum Start { + /// A call to [`OK`]. + Call, + /// A creation with empty init code. + Create, +} + /// What the inspector does with the call to [`OK`]. #[derive(Clone, Copy, Debug)] enum Answer { @@ -74,22 +83,29 @@ struct Answering { parent_returned: Option<u64>, } +impl Answering { + /// The gas of the answer to a start of `gas_limit` given `reservoir` and `pools`, or `None` + /// to let the start run. + const fn gas(&mut self, gas_limit: u64, reservoir: u64, pools: PoolAmounts) -> Option<Gas> { + self.given = Some(reservoir); + match self.answer { + Answer::Runs => None, + Answer::AsBuilt => Some(Gas::new(gas_limit)), + Answer::WithTheShares => { + let mut gas = Gas::new_with_regular_gas_and_reservoir(gas_limit, reservoir); + gas.tracker_mut().set_pools_remaining(pools); + Some(gas) + } + } + } +} + impl Inspector<Ctx, EthInterpreter> for Answering { fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { if inputs.target_address != OK { return None; } - self.given = Some(inputs.reservoir); - let gas = match self.answer { - Answer::Runs => return None, - Answer::AsBuilt => Gas::new(inputs.gas_limit), - Answer::WithTheShares => { - let mut gas = - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); - gas.tracker_mut().set_pools_remaining(inputs.pool_shares); - gas - } - }; + let gas = self.gas(inputs.gas_limit, inputs.reservoir, inputs.pool_shares)?; Some(CallOutcome::new( InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), inputs.return_memory_offset.clone(), @@ -97,17 +113,7 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } fn create(&mut self, _: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { - self.given = Some(inputs.reservoir()); - let gas = match self.answer { - Answer::Runs => return None, - Answer::AsBuilt => Gas::new(inputs.gas_limit()), - Answer::WithTheShares => { - let mut gas = - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()); - gas.tracker_mut().set_pools_remaining(inputs.pool_shares()); - gas - } - }; + let gas = self.gas(inputs.gas_limit(), inputs.reservoir(), inputs.pool_shares())?; let mut outcome = CreateOutcome::new( InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), None, @@ -127,26 +133,27 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } } -/// [`PARENT`]'s reservoir as its frame returned, and the reservoir the call to [`OK`] was given, -/// or the creation if [`PARENT`] `creates`, with `percent` per cent of a caller's reservoir -/// forwarded: the schedule's `reservoir_kept_percent` is the rest. -fn run(answer: Answer, percent: Option<u64>, creates: bool) -> (u64, u64) { +/// [`PARENT`]'s reservoir as its frame returned, and the reservoir its `start` was given, with +/// `percent` per cent of a caller's reservoir forwarded: the schedule's `reservoir_kept_percent` +/// is the rest. +fn run(answer: Answer, percent: Option<u64>, start: Start) -> (u64, u64) { let mut db = Db::default(); db.insert_account_info( BENCH_CALLER, AccountInfo::from_balance(U256::from(10u128.pow(21))), ); - let mut parent = vec![ - PUSH1, 1, PUSH0, SSTORE, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20, - ]; - if creates { - // `CREATE(0, 0, 0)` in place of the call's last five pushes and the call. - parent.truncate(4); - parent.extend_from_slice(&[PUSH0, PUSH0, PUSH0, CREATE, POP, STOP]); - } else { - parent.extend_from_slice(OK.as_slice()); - parent.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP, STOP]); + let mut parent = vec![PUSH1, 1, PUSH0, SSTORE]; + match start { + // `CALL(100_000, OK, 0, 0, 0, 0, 0)`. + Start::Call => { + parent.extend_from_slice(&[PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]); + parent.extend_from_slice(OK.as_slice()); + parent.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL]); + } + // `CREATE(0, 0, 0)`. + Start::Create => parent.extend_from_slice(&[PUSH0, PUSH0, PUSH0, CREATE]), } + parent.extend_from_slice(&[POP, STOP]); for (address, code) in [(PARENT, parent), (OK, vec![STOP])] { db.insert_account_info( address, @@ -202,12 +209,12 @@ fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), ] { assert_eq!( - run(answer, None, false), + run(answer, None, Start::Call), (whole, BEFORE_THE_CALL), "{answer:?}, the whole reservoir forwarded" ); assert_eq!( - run(answer, Some(98), false), + run(answer, Some(98), Start::Call), (kept_98, SHARE), "{answer:?}, 98% forwarded" ); @@ -225,12 +232,12 @@ fn test_an_answer_the_inspector_builds_for_a_creation_settles_its_reservoir_as_b (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), ] { assert_eq!( - run(answer, None, true), + run(answer, None, Start::Create), (whole, BEFORE_THE_CREATION), "{answer:?}, the whole reservoir forwarded" ); assert_eq!( - run(answer, Some(98), true), + run(answer, Some(98), Start::Create), (kept_98, CREATION_SHARE), "{answer:?}, 98% forwarded" ); From 83aea8cf808228abaac90c14e5d3fff80d4b041e Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 15:31:22 +0800 Subject: [PATCH 055/110] docs: the check's measured cost, and that only the pools' adoption fails closed, in MEGAETH-FORK.md --- MEGAETH-FORK.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 260d3b3573..e14bc1f119 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -305,7 +305,7 @@ An id the fork once used for an entry with another default is left unused rather Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 215 instructions more (+3.9%), each `CALL` about 258 more (+10.9% on a transaction of 64 calls), a top-level creation 273 more (+1.5%), a nested `CREATE` 331 more (+2.1%) and a `SELFDESTRUCT` transaction 285 more (+3.5%). Nearly all of it is the size: the same code with one pool, at the earlier sizes, cost 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. Against the base without any of the fork's figures, a transfer costs 336 more (+6.2%) and each `CALL` about 398 more (+17.9% on a transaction of 64 calls). - A precompile's answer runs 11 instructions more than with an adoption that does not check each pool's net against its share (see Contract); a transfer, a call, a creation and a `SELFDESTRUCT` run no more for it. + A precompile's answer runs 11 instructions more than with an adoption that does not check each pool's net against its share (see Contract); measured against the head before the check, a transfer runs 1 instruction less, each `CALL` 1.9 less, a top-level creation 3 less and a nested `CREATE` 7.75 less, and a `SELFDESTRUCT` transaction 4 more, from code layout, not from the check. ### The reservoir share @@ -322,7 +322,7 @@ An id the fork once used for an entry with another default is left unused rather For example, a caller with a reservoir of 1,000 that keeps 2 per cent keeps 20 and forwards 980; a child that charges 1,000 spills 20; the caller then charges 10 from its reservoir (reservoir 10, spill 20) and refills 10, which leaves its reservoir at 10, its spill at 10 and its regular gas 10 higher. The sum of the two is conserved, a rollback still restores the reservoir the frame started with, and the reimbursement and `gas_used` read the sum, so no final figure moves; `GAS` in the caller reads the credited regular gas. The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too; so does the stand-in result `Handler::runtime_oog_result` builds for a transaction whose EIP-2780 runtime phase ran out of gas, which carries the whole reservoir and every pool and settles them back once. - A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. + A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir (the standard providers do, and a provider must); the fork does not check an answer's reservoir, state-gas net or spill against what the input forwarded, and takes the provider's answer as the provider reports it, as upstream does, so only the pools are adopted fail-closed; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. **The settlement adds.** `handle_reservoir_remaining_gas` (with the `GasTracker::absorb_returned_reservoir` and `absorb_returned_pools` it calls) and `execution::settle_first_frame` add what a frame returns to what its caller holds, so the caller must no longer hold what it handed the frame. Code that hands a frame the caller's reservoir or a pool without taking it from the caller compiles, and the caller ends with it twice. The shapes: From 41c09815ab75dbe8be1ad5941319cabfcf8b0d96 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 16:42:55 +0800 Subject: [PATCH 056/110] feat(interpreter): a frame's run returns an action set before it, before any instruction and any inspector step Interpreter::run_plain and inspect_instructions check for a pending action before their first step: a consumer that sets a frame's next action with LoopControl::set_action at the frame's start, or once a child returned into it, gets that action back as the run's result, with no instruction executed and no Inspector::step or step_end for that run. revm itself never sets an action before a run, so its results and callbacks are unchanged. --- crates/inspector/src/handler.rs | 7 + crates/inspector/tests/loop_hooks.rs | 473 +++++++++++++++++++++ crates/interpreter/src/interpreter.rs | 7 + crates/interpreter/tests/pending_action.rs | 83 ++++ 4 files changed, 570 insertions(+) create mode 100644 crates/inspector/tests/loop_hooks.rs create mode 100644 crates/interpreter/tests/pending_action.rs diff --git a/crates/inspector/src/handler.rs b/crates/inspector/src/handler.rs index 71337c388f..8297d850f1 100644 --- a/crates/inspector/src/handler.rs +++ b/crates/inspector/src/handler.rs @@ -247,6 +247,9 @@ pub fn frame_end<CTX, INTR: InterpreterTypes>( /// This function is used to inspect the Interpreter loop. /// It will call [`Inspector::step`] and [`Inspector::step_end`] after each instruction. /// And [`Inspector::log`],[`Inspector::selfdestruct`] for each log and selfdestruct instruction. +/// +/// An action set before the run ([`LoopControl::set_action`]) is returned before any +/// instruction runs and before any [`Inspector::step`], as [`Interpreter::run_plain`] returns it. pub fn inspect_instructions<CTX, IT>( context: &mut CTX, interpreter: &mut Interpreter<IT>, @@ -258,6 +261,10 @@ where CTX: ContextTr<Journal: JournalExt> + Host, IT: InterpreterTypes, { + if interpreter.bytecode.is_end() { + cold_path(); + return interpreter.take_next_action(); + } let mut instruction_journal_i = None; loop { inspector.step(interpreter, context); diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs new file mode 100644 index 0000000000..7800339d22 --- /dev/null +++ b/crates/inspector/tests/loop_hooks.rs @@ -0,0 +1,473 @@ +//! The two points the handler loops give a consumer's EVM, on the plain and the inspected path. +//! +//! A pending action: a consumer sets a frame's next action on its interpreter before the frame +//! runs, at its start or when a child returned into it, and the frame's run returns that action +//! before any instruction runs, without an inspector `step`. +//! +//! The consumer here wraps revm's EVM and changes nothing else: [`PARENT`] calls [`CHILD`], then +//! marks a slot of its own, and returns the call's status and return data; [`CHILD`] marks a slot +//! of its own and halts. A slot left unmarked is an instruction that did not run. + +use context::{ + result::{EVMError, ExecutionResult, Output}, + Context, ContextSetters, ContextTr, Evm, FrameStack, JournalTr, TxEnv, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + evm::{ContextDbError, FrameInitResult}, + instructions::EthInstructions, + EthFrame, EthPrecompiles, EvmTr, FrameInitOrResult, FrameResult, Handler, ItemOrResult, + MainBuilder, MainContext, MainnetContext, MainnetHandler, +}; +use interpreter::{ + interpreter::{EthInterpreter, ExtBytecode}, + interpreter_action::FrameInit, + interpreter_types::{Jumps, LoopControl}, + CallInputs, CallOutcome, FrameInput, InputsImpl, InstructionResult, Interpreter, + InterpreterAction, SharedMemory, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{inspect_instructions, Inspector, InspectorEvmTr, InspectorHandler}; +use state::{ + bytecode::opcode::{ + ADD, CALL, INVALID, MSTORE, PUSH0, PUSH1, PUSH20, PUSH3, RETURN, RETURNDATACOPY, + RETURNDATASIZE, SSTORE, + }, + AccountInfo, Bytecode, +}; +use std::convert::Infallible; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; +type Inner = Evm<Ctx, Recorder, EthInstructions<EthInterpreter, Ctx>, EthPrecompiles, EthFrame>; +type Error = EVMError<Infallible>; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 1_000_000; + +/// Calls [`CHILD`] with [`CHILD_GAS`], marks its slot 0, and returns the call's status as a word +/// followed by the call's return data. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Marks its slot 0 and halts on `INVALID`. +const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); +/// The gas [`PARENT`] forwards to [`CHILD`], whose halt spends it: 0x0186a0. +const CHILD_GAS: [u8; 3] = [0x01, 0x86, 0xa0]; + +/// The output of the action the consumer sets on [`CHILD`] at its start. +const AT_START: &[u8] = b"set at its start"; +/// The output of the action the consumer sets on [`PARENT`] when [`CHILD`] returns into it. +const ON_RESUME: &[u8] = b"set on its resume"; + +/// Where the consumer sets an action before a frame runs. +#[derive(Clone, Copy, Debug, Default)] +struct Plan { + /// A return carrying [`AT_START`] on [`CHILD`]'s frame, once revm built it. + at_start: bool, + /// A return carrying [`ON_RESUME`] on [`PARENT`]'s frame, once [`CHILD`]'s result is in it. + on_resume: bool, +} + +/// What the inspector saw, one line per callback, by the account the frame runs as. +#[derive(Debug, Default)] +struct Recorder { + events: Vec<String>, +} + +const fn name(address: Address) -> &'static str { + match address { + PARENT => "PARENT", + CHILD => "CHILD", + _ => "other", + } +} + +fn target(input: &FrameInput) -> &'static str { + match input { + FrameInput::Call(inputs) => name(inputs.target_address), + _ => "other", + } +} + +impl Inspector<Ctx> for Recorder { + fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + let account = name(interp.input.target_address); + self.events.push(format!("initialize_interp {account}")); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + let (account, pc) = (name(interp.input.target_address), interp.bytecode.pc()); + self.events.push(format!("step {account} {pc}")); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + let (account, pc) = (name(interp.input.target_address), interp.bytecode.pc()); + self.events.push(format!("step_end {account} {pc}")); + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + let (result, output) = (outcome.result.result, &outcome.result.output); + let account = name(inputs.target_address); + self.events + .push(format!("call_end {account} {result:?} {output}")); + } + + fn frame_end(&mut self, _: &mut Ctx, input: &FrameInput, result: &mut FrameResult) { + let (account, result) = (target(input), result.instruction_result()); + self.events.push(format!("frame_end {account} {result:?}")); + } +} + +/// revm's EVM, with a consumer's actions set as [`Plan`] says. +struct Consumer { + evm: Inner, + plan: Plan, +} + +impl EvmTr for Consumer { + type Context = Ctx; + type Instructions = EthInstructions<EthInterpreter, Ctx>; + type Precompiles = EthPrecompiles; + type Frame = EthFrame; + + fn all( + &self, + ) -> ( + &Self::Context, + &Self::Instructions, + &Self::Precompiles, + &FrameStack<Self::Frame>, + ) { + self.evm.all() + } + + fn all_mut( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack<Self::Frame>, + ) { + self.evm.all_mut() + } + + fn frame_init( + &mut self, + frame_input: FrameInit, + ) -> Result<FrameInitResult<'_, EthFrame>, ContextDbError<Ctx>> { + let child = target(&frame_input.frame_input) == "CHILD"; + let mut started = self.evm.frame_init(frame_input)?; + if let ItemOrResult::Item(frame) = &mut started { + if child && self.plan.at_start { + let gas = frame.interpreter.gas; + frame + .interpreter + .bytecode + .set_action(InterpreterAction::new_return( + InstructionResult::Return, + Bytes::from_static(AT_START), + gas, + )); + } + } + Ok(started) + } + + fn frame_run(&mut self) -> Result<FrameInitOrResult<EthFrame>, ContextDbError<Ctx>> { + self.evm.frame_run() + } + + fn frame_return_result( + &mut self, + result: FrameResult, + ) -> Result<Option<FrameResult>, ContextDbError<Ctx>> { + let returned = self.evm.frame_return_result(result)?; + if returned.is_none() && self.plan.on_resume { + let caller = self.evm.frame_stack.get(); + let gas = caller.interpreter.gas; + caller + .interpreter + .bytecode + .set_action(InterpreterAction::new_return( + InstructionResult::Return, + Bytes::from_static(ON_RESUME), + gas, + )); + } + Ok(returned) + } +} + +impl InspectorEvmTr for Consumer { + type Inspector = Recorder; + + fn all_inspector( + &self, + ) -> ( + &Self::Context, + &Self::Instructions, + &Self::Precompiles, + &FrameStack<Self::Frame>, + &Self::Inspector, + ) { + self.evm.all_inspector() + } + + fn all_mut_inspector( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack<Self::Frame>, + &mut Self::Inspector, + ) { + self.evm.all_mut_inspector() + } +} + +/// [`PARENT`]'s code. +fn parent_code() -> Bytecode { + let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + code.extend_from_slice(CHILD.as_slice()); + code.push(PUSH3); + code.extend_from_slice(&CHILD_GAS); + code.extend_from_slice(&[ + CALL, + // Mark slot 0: the frame resumed. + PUSH1, + 1, + PUSH0, + SSTORE, + // The status at 0, the return data after it. + PUSH0, + MSTORE, + RETURNDATASIZE, + PUSH0, + PUSH1, + 32, + RETURNDATACOPY, + RETURNDATASIZE, + PUSH1, + 32, + ADD, + PUSH0, + RETURN, + ]); + Bytecode::new_raw(code.into()) +} + +/// [`CHILD`]'s code. +fn child_code() -> Bytecode { + Bytecode::new_raw(Bytes::from_static(&[PUSH1, 1, PUSH0, SSTORE, INVALID])) +} + +/// What one transaction to [`PARENT`] did. +#[derive(Debug)] +struct Run { + result: ExecutionResult, + /// The inspector's lines; empty on the plain path. + events: Vec<String>, + /// Whether [`PARENT`]'s and [`CHILD`]'s slot 0 hold the mark. + marked: (bool, bool), +} + +impl Run { + fn output(&self) -> &Bytes { + match &self.result { + ExecutionResult::Success { + output: Output::Call(output), + .. + } => output, + other => panic!("the transaction returns, got {other:?}"), + } + } + + /// The lines of `account`'s steps. + fn steps(&self, account: &str) -> Vec<&str> { + let prefix = format!("step {account} "); + self.events + .iter() + .map(String::as_str) + .filter(|line| line.starts_with(&prefix)) + .collect() + } +} + +/// Runs a transaction to [`PARENT`] through the mainnet handler on the consumer's EVM, inspected +/// or not. +fn run(plan: Plan, inspected: bool) -> Run { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + for (address, code) in [(PARENT, parent_code()), (CHILD, child_code())] { + db.insert_account_info( + address, + AccountInfo::new(U256::ZERO, 1, code.hash_slow(), code), + ); + } + let ctx = Context::mainnet() + .with_db(db) + .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(SPEC)); + let mut consumer = Consumer { + evm: ctx.build_mainnet_with_inspector(Recorder::default()), + plan, + }; + consumer.evm.ctx.set_tx( + TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(), + ); + + let mut handler = MainnetHandler::<Consumer, Error, EthFrame>::default(); + let result = if inspected { + handler.inspect_run(&mut consumer) + } else { + handler.run(&mut consumer) + } + .expect("the transaction runs"); + + let state = consumer.evm.ctx.journal_mut().finalize(); + let mark = |address: Address| { + state + .get(&address) + .and_then(|account| account.storage.get(&U256::ZERO)) + .is_some_and(|slot| slot.present_value == U256::from(1)) + }; + Run { + result, + events: core::mem::take(&mut consumer.evm.inspector.events), + marked: (mark(PARENT), mark(CHILD)), + } +} + +/// The 32-byte status word of a call, followed by its return data. +fn status_and(success: bool, data: &[u8]) -> Bytes { + let mut output = U256::from(success as u8).to_be_bytes_vec(); + output.extend_from_slice(data); + output.into() +} + +/// Without a plan the consumer is revm: the frames run as their code says. +#[test] +fn test_without_a_pending_action_every_frame_runs() { + for inspected in [false, true] { + let run = run(Plan::default(), inspected); + + assert_eq!(run.output(), &status_and(false, &[]), "{inspected}"); + assert_eq!( + run.marked, + (true, false), + "the halt took the child's mark back" + ); + if inspected { + assert_eq!(run.steps("CHILD").len(), 4, "PUSH1 PUSH0 SSTORE INVALID"); + } + } +} + +/// An interpreter whose next action is set before it runs returns that action: no instruction +/// runs and the inspector sees no `step` or `step_end`. +#[test] +fn test_inspect_instructions_returns_a_pending_action_without_a_step() { + let mut ctx: Ctx = Context::mainnet().with_db(Db::default()); + let mut interpreter = Interpreter::<EthInterpreter>::new( + SharedMemory::new(), + ExtBytecode::new(child_code()), + InputsImpl::default(), + false, + SPEC, + GAS_LIMIT, + ); + let action = InterpreterAction::new_return( + InstructionResult::Return, + Bytes::from_static(AT_START), + interpreter.gas, + ); + interpreter.bytecode.set_action(action.clone()); + let instructions = EthInstructions::<EthInterpreter, Ctx>::new_mainnet_with_spec(SPEC); + let mut recorder = Recorder::default(); + + let returned = inspect_instructions( + &mut ctx, + &mut interpreter, + &mut recorder, + instructions.instruction_table(), + instructions.gas_table(), + ); + + assert_eq!(returned, action); + assert_eq!(recorder.events, Vec::<String>::new()); + assert_eq!(interpreter.bytecode.pc(), 0, "no instruction ran"); + assert_eq!( + interpreter.gas.remaining(), + GAS_LIMIT, + "no instruction charged" + ); +} + +/// An action the consumer sets on a frame revm built is the frame's result: its code does not +/// run, on either path, and the inspector sees the frame start and end with no step between. +#[test] +fn test_an_action_set_at_a_frames_start_is_its_result() { + let plan = Plan { + at_start: true, + ..Plan::default() + }; + for inspected in [false, true] { + let run = run(plan, inspected); + + assert_eq!(run.output(), &status_and(true, AT_START), "{inspected}"); + assert_eq!(run.marked, (true, false), "the child ran no instruction"); + if inspected { + let seen: Vec<&str> = run + .events + .iter() + .map(String::as_str) + .filter(|line| line.contains("CHILD")) + .collect(); + let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_START)); + assert_eq!( + seen, + ["initialize_interp CHILD", &end, "frame_end CHILD Return"] + ); + } + } +} + +/// An action the consumer sets on a caller once its child's result is in it is the caller's +/// result: the rest of its code does not run, and the inspector sees no step of it after the +/// child's end. +#[test] +fn test_an_action_set_on_a_frames_resume_is_its_result() { + let plan = Plan { + on_resume: true, + ..Plan::default() + }; + for inspected in [false, true] { + let run = run(plan, inspected); + + assert_eq!(run.output(), &Bytes::from_static(ON_RESUME), "{inspected}"); + assert_eq!( + run.marked, + (false, false), + "the parent ran nothing after the call" + ); + if inspected { + let child_end = run + .events + .iter() + .position(|line| line == "frame_end CHILD InvalidFEOpcode") + .expect("the child ends"); + let end = format!("call_end PARENT Return {}", Bytes::from_static(ON_RESUME)); + assert_eq!( + &run.events[child_end + 1..], + [end.as_str(), "frame_end PARENT Return"] + ); + } + } +} diff --git a/crates/interpreter/src/interpreter.rs b/crates/interpreter/src/interpreter.rs index 370593d38a..9ed5931406 100644 --- a/crates/interpreter/src/interpreter.rs +++ b/crates/interpreter/src/interpreter.rs @@ -323,6 +323,9 @@ impl<IW: InterpreterTypes> Interpreter<IW> { } /// Executes the interpreter until it returns or stops. + /// + /// An action set before the run ([`LoopControl::set_action`]) is returned before any + /// instruction runs. #[inline] pub fn run_plain<H: Host + ?Sized>( &mut self, @@ -330,6 +333,10 @@ impl<IW: InterpreterTypes> Interpreter<IW> { gas_table: &GasTable, host: &mut H, ) -> InterpreterAction { + if self.bytecode.is_end() { + cold_path(); + return self.take_next_action(); + } let e = loop { if let Err(e) = self.step(instruction_table, gas_table, host) { cold_path(); diff --git a/crates/interpreter/tests/pending_action.rs b/crates/interpreter/tests/pending_action.rs new file mode 100644 index 0000000000..65847a7ddb --- /dev/null +++ b/crates/interpreter/tests/pending_action.rs @@ -0,0 +1,83 @@ +//! An action set on an interpreter before it runs is what the run returns, before any +//! instruction. +//! +//! A consumer sets a frame's next action between the frame's start and its run (or after a child +//! returned into it) with `LoopControl::set_action`. The plain run returns that action as it was +//! set: no instruction runs, so the frame's gas, program counter and stack are as the consumer +//! left them, and the interpreter is ready to run again. + +use bytecode::{opcode::*, Bytecode}; +use primitives::{hardfork::SpecId, Bytes}; +use revm_interpreter::{ + host::DummyHost, + instruction_table, + instructions::gas_table_spec, + interpreter::{EthInterpreter, ExtBytecode}, + interpreter_types::{Jumps, LoopControl}, + InputsImpl, InstructionResult, Interpreter, InterpreterAction, SharedMemory, +}; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 10_000; + +/// Code that would push twice and stop: every instruction it runs moves the program counter, the +/// stack and the gas. +const CODE: &[u8] = &[PUSH0, PUSH0, STOP]; + +/// An interpreter on [`CODE`] with a revert set as its next action, and that action. +fn pending() -> (Interpreter<EthInterpreter>, InterpreterAction) { + let mut interpreter = Interpreter::<EthInterpreter>::new( + SharedMemory::new(), + ExtBytecode::new(Bytecode::new_raw(Bytes::from_static(CODE))), + InputsImpl::default(), + false, + SPEC, + GAS_LIMIT, + ); + let action = InterpreterAction::new_return( + InstructionResult::Revert, + Bytes::from_static(b"set before the run"), + interpreter.gas, + ); + interpreter.bytecode.set_action(action.clone()); + (interpreter, action) +} + +/// Asserts that `interpreter` ran no instruction and is ready to run again. +fn assert_ran_nothing(interpreter: &Interpreter<EthInterpreter>) { + assert_eq!( + interpreter.bytecode.pc(), + 0, + "no instruction moved the counter" + ); + assert_eq!(interpreter.stack.len(), 0, "no instruction pushed"); + assert_eq!( + interpreter.gas.remaining(), + GAS_LIMIT, + "no instruction charged" + ); + assert!(interpreter.bytecode.is_not_end(), "the action was taken"); +} + +#[test] +fn test_run_plain_returns_a_pending_action_before_any_instruction() { + let (mut interpreter, action) = pending(); + let table = instruction_table::<EthInterpreter, DummyHost>(); + + let returned = interpreter.run_plain(&table, &gas_table_spec(SPEC), &mut DummyHost::new(SPEC)); + + assert_eq!(returned, action); + assert_ran_nothing(&interpreter); +} + +#[test] +fn test_run_plain_as_output_returns_a_pending_action_before_any_instruction() { + let (mut interpreter, action) = pending(); + let table = instruction_table::<EthInterpreter, DummyHost>(); + + let returned = + interpreter.run_plain_as_output(&table, &gas_table_spec(SPEC), &mut DummyHost::new(SPEC)); + + assert_eq!(returned, action); + assert_ran_nothing(&interpreter); +} From a52e78c6835c3113caa7937726b1eb9850f809a5 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 16:53:19 +0800 Subject: [PATCH 057/110] feat(handler): a frame's run result reaches the EVM once, before the inspector's frame_end and its caller EvmTr::frame_run_result, a provided method whose default does nothing, receives the result of the frame on top of the stack as it leaves the frame's own run: Handler::run_exec_loop calls it when frame_run returns a result, and InspectorEvmTr::inspect_frame_run calls it after process_next_action and before the inspector's call_end, create_end and frame_end. What it leaves in the result is what the inspector and the caller see. A result given without a run (a refused start, a precompile's or an inspector's answer), which frame_init returns, does not reach it. The plain call is in the handler's loop rather than in Evm::frame_run so that it dispatches to the outermost EVM type: a wrapper that delegates frame_run to revm's Evm would otherwise reach Evm's no-op. The inspected run now marks the frame finished before the hook instead of after frame_end, so the hook sees the frame as the plain loop shows it; no inspector callback can observe the flag. --- crates/handler/src/evm.rs | 25 ++++ crates/handler/src/handler.rs | 5 +- crates/inspector/src/traits.rs | 12 +- crates/inspector/tests/loop_hooks.rs | 209 +++++++++++++++++++++++++-- 4 files changed, 232 insertions(+), 19 deletions(-) diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index a62b2e15c9..6e97aceb5c 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -117,6 +117,31 @@ pub trait EvmTr { &mut self, ) -> Result<FrameInitOrResult<Self::Frame>, ContextDbError<Self::Context>>; + /// Receives the result of the frame on top of the stack as it leaves the frame's own run, + /// before anything else sees it. What it leaves in `result` is what the inspector and the + /// caller see. + /// + /// The handler loops call it once for each frame that ran and returns, after the frame's + /// last action was processed and the frame marked finished, while the frame is still on top of + /// the stack: `Handler::run_exec_loop` when [`frame_run`](EvmTr::frame_run) returns a result, + /// and the inspected run (`InspectorEvmTr::inspect_frame_run`) before the inspector's + /// `call_end`, `create_end` and `frame_end`. On both paths it runs before + /// [`frame_return_result`](EvmTr::frame_return_result). + /// + /// A result given without a run does not reach it: [`frame_init`](EvmTr::frame_init) + /// returns those (a start the handler refuses, a precompile's answer, an inspector's answer), + /// so `frame_init`, or the inspector, has them first. + /// + /// The default does nothing. + #[inline] + fn frame_run_result( + &mut self, + result: &mut <Self::Frame as FrameTr>::FrameResult, + ) -> Result<(), ContextDbError<Self::Context>> { + let _ = result; + Ok(()) + } + /// Returns the result of the frame to the caller. Frame is popped from the frame stack. /// Consumes the frame result or returns it if there is more frames to run. fn frame_return_result( diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 3ed0085572..d965c7aaed 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -564,7 +564,10 @@ pub trait Handler { ItemOrResult::Result(result) => result, } } - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index e72b827855..bc3b29a5d3 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -144,7 +144,8 @@ pub trait InspectorEvmTr: /// Run the frame from the top of the stack. Returns the frame init or result. /// - /// If frame has returned result it would mark it as finished. + /// If frame has returned result it would mark it as finished, and hand it to + /// [`EvmTr::frame_run_result`] before the inspector's `frame_end`. #[inline] fn inspect_frame_run( &mut self, @@ -152,7 +153,11 @@ pub trait InspectorEvmTr: let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); let Some(frame) = frame.eth_frame() else { - return self.frame_run(); + let mut result = self.frame_run()?; + if let ItemOrResult::Result(frame_result) = &mut result { + self.frame_run_result(frame_result)?; + } + return Ok(result); }; let next_action = inspect_instructions( @@ -165,11 +170,12 @@ pub trait InspectorEvmTr: let mut result = frame.process_next_action(ctx, next_action); if let Ok(ItemOrResult::Result(frame_result)) = &mut result { + frame.set_finished(true); + self.frame_run_result(frame_result)?; let (ctx, inspector, frame) = self.ctx_inspector_frame(); // TODO When all_mut fn is added we can fetch inspector at the top of the function.s if let Some(frame) = frame.eth_frame() { frame_end(ctx, inspector, &frame.input, frame_result); - frame.set_finished(true); } }; result diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 7800339d22..fa1c19d85b 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -4,9 +4,15 @@ //! runs, at its start or when a child returned into it, and the frame's run returns that action //! before any instruction runs, without an inspector `step`. //! +//! A frame's run result: the result of a frame that ran reaches the consumer's +//! [`EvmTr::frame_run_result`] once, as it leaves the frame's run, before the inspector's +//! `call_end` and `frame_end` and before its caller; what the consumer leaves in it is what they +//! see. A result given without a run (a precompile's, an inspector's answer) does not reach it. +//! //! The consumer here wraps revm's EVM and changes nothing else: [`PARENT`] calls [`CHILD`], then //! marks a slot of its own, and returns the call's status and return data; [`CHILD`] marks a slot -//! of its own and halts. A slot left unmarked is an instruction that did not run. +//! of its own and halts. A slot left unmarked is an instruction that did not run. The consumer's +//! hook writes its line into the inspector's, so one list orders both. use context::{ result::{EVMError, ExecutionResult, Output}, @@ -23,8 +29,8 @@ use interpreter::{ interpreter::{EthInterpreter, ExtBytecode}, interpreter_action::FrameInit, interpreter_types::{Jumps, LoopControl}, - CallInputs, CallOutcome, FrameInput, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, SharedMemory, + CallInputs, CallOutcome, FrameInput, Gas, InputsImpl, InstructionResult, Interpreter, + InterpreterAction, InterpreterResult, SharedMemory, }; use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{inspect_instructions, Inspector, InspectorEvmTr, InspectorHandler}; @@ -45,38 +51,60 @@ type Error = EVMError<Infallible>; const SPEC: SpecId = SpecId::OSAKA; const GAS_LIMIT: u64 = 1_000_000; -/// Calls [`CHILD`] with [`CHILD_GAS`], marks its slot 0, and returns the call's status as a word -/// followed by the call's return data. +/// Calls [`CHILD`] (or the [`Callee`] a test names) with [`CHILD_GAS`], marks its slot 0, and +/// returns the call's status as a word followed by the call's return data. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Marks its slot 0 and halts on `INVALID`. const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); /// The gas [`PARENT`] forwards to [`CHILD`], whose halt spends it: 0x0186a0. const CHILD_GAS: [u8; 3] = [0x01, 0x86, 0xa0]; +/// The identity precompile, which revm answers without running a frame. +const IDENTITY: Address = address!("0x0000000000000000000000000000000000000004"); /// The output of the action the consumer sets on [`CHILD`] at its start. const AT_START: &[u8] = b"set at its start"; /// The output of the action the consumer sets on [`PARENT`] when [`CHILD`] returns into it. const ON_RESUME: &[u8] = b"set on its resume"; +/// The output of the revert the consumer's hook makes of [`CHILD`]'s halt. +const REWRITTEN: &[u8] = b"rewritten as it leaves its run"; +/// The output of the revert the inspector answers the call to [`CHILD`] with. +const ANSWERED: &[u8] = b"answered by the inspector"; -/// Where the consumer sets an action before a frame runs. +/// What the consumer does at the loops' points. #[derive(Clone, Copy, Debug, Default)] struct Plan { /// A return carrying [`AT_START`] on [`CHILD`]'s frame, once revm built it. at_start: bool, /// A return carrying [`ON_RESUME`] on [`PARENT`]'s frame, once [`CHILD`]'s result is in it. on_resume: bool, + /// [`CHILD`]'s halt made a revert carrying [`REWRITTEN`] as it leaves its run. + rewrite: bool, +} + +/// What [`PARENT`] calls, and whether the call runs. +#[derive(Clone, Copy, Debug)] +enum Callee { + /// [`CHILD`], which runs. + Child, + /// [`IDENTITY`], which revm answers. + Precompile, + /// [`CHILD`], which the inspector answers with a revert carrying [`ANSWERED`]. + Answered, } /// What the inspector saw, one line per callback, by the account the frame runs as. #[derive(Debug, Default)] struct Recorder { events: Vec<String>, + /// Answers the call to [`CHILD`]. + answer: bool, } const fn name(address: Address) -> &'static str { match address { PARENT => "PARENT", CHILD => "CHILD", + IDENTITY => "IDENTITY", _ => "other", } } @@ -104,6 +132,21 @@ impl Inspector<Ctx> for Recorder { self.events.push(format!("step_end {account} {pc}")); } + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + if !self.answer || inputs.target_address != CHILD { + return None; + } + let result = InterpreterResult::new( + InstructionResult::Revert, + Bytes::from_static(ANSWERED), + Gas::new(inputs.gas_limit), + ); + Some(CallOutcome::new( + result, + inputs.return_memory_offset.clone(), + )) + } + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { let (result, output) = (outcome.result.result, &outcome.result.output); let account = name(inputs.target_address); @@ -196,6 +239,24 @@ impl EvmTr for Consumer { } Ok(returned) } + + /// Writes the result it got into the inspector's lines, and rewrites [`CHILD`]'s halt as + /// [`Plan::rewrite`] says. + fn frame_run_result(&mut self, result: &mut FrameResult) -> Result<(), ContextDbError<Ctx>> { + let frame = self.evm.frame_stack.get(); + assert!(frame.is_finished(), "the frame on top is the one that ran"); + let (account, got) = (target(&frame.input), result.instruction_result()); + self.evm + .inspector + .events + .push(format!("hook {account} {got:?}")); + if self.plan.rewrite && got == InstructionResult::InvalidFEOpcode { + let result = result.interpreter_result_mut(); + result.result = InstructionResult::Revert; + result.output = Bytes::from_static(REWRITTEN); + } + Ok(()) + } } impl InspectorEvmTr for Consumer { @@ -226,10 +287,10 @@ impl InspectorEvmTr for Consumer { } } -/// [`PARENT`]'s code. -fn parent_code() -> Bytecode { +/// [`PARENT`]'s code, calling `callee`. +fn parent_code(callee: Address) -> Bytecode { let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; - code.extend_from_slice(CHILD.as_slice()); + code.extend_from_slice(callee.as_slice()); code.push(PUSH3); code.extend_from_slice(&CHILD_GAS); code.extend_from_slice(&[ @@ -292,17 +353,45 @@ impl Run { .filter(|line| line.starts_with(&prefix)) .collect() } + + /// The consumer's hook lines. + fn hooks(&self) -> Vec<&str> { + self.lines(|line| line.starts_with("hook ")) + } + + /// Every line but the steps: the frames' starts and ends, and the hook's. + fn ends(&self) -> Vec<&str> { + self.lines(|line| !line.starts_with("step")) + } + + fn lines(&self, keep: impl Fn(&str) -> bool) -> Vec<&str> { + self.events + .iter() + .map(String::as_str) + .filter(|line| keep(line)) + .collect() + } } -/// Runs a transaction to [`PARENT`] through the mainnet handler on the consumer's EVM, inspected -/// or not. +/// Runs a transaction to [`PARENT`], calling [`CHILD`], through the mainnet handler on the +/// consumer's EVM, inspected or not. fn run(plan: Plan, inspected: bool) -> Run { + run_calling(Callee::Child, plan, inspected) +} + +/// [`run`], with [`PARENT`] calling `callee`. +fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { + let (address, answer) = match callee { + Callee::Child => (CHILD, false), + Callee::Precompile => (IDENTITY, false), + Callee::Answered => (CHILD, true), + }; let mut db = Db::default(); db.insert_account_info( BENCH_CALLER, AccountInfo::from_balance(U256::from(10u128.pow(21))), ); - for (address, code) in [(PARENT, parent_code()), (CHILD, child_code())] { + for (address, code) in [(PARENT, parent_code(address)), (CHILD, child_code())] { db.insert_account_info( address, AccountInfo::new(U256::ZERO, 1, code.hash_slow(), code), @@ -312,7 +401,10 @@ fn run(plan: Plan, inspected: bool) -> Run { .with_db(db) .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(SPEC)); let mut consumer = Consumer { - evm: ctx.build_mainnet_with_inspector(Recorder::default()), + evm: ctx.build_mainnet_with_inspector(Recorder { + answer, + ..Recorder::default() + }), plan, }; consumer.evm.ctx.set_tx( @@ -423,6 +515,7 @@ fn test_an_action_set_at_a_frames_start_is_its_result() { assert_eq!(run.output(), &status_and(true, AT_START), "{inspected}"); assert_eq!(run.marked, (true, false), "the child ran no instruction"); + assert_eq!(run.hooks(), ["hook CHILD Return", "hook PARENT Return"]); if inspected { let seen: Vec<&str> = run .events @@ -433,7 +526,12 @@ fn test_an_action_set_at_a_frames_start_is_its_result() { let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_START)); assert_eq!( seen, - ["initialize_interp CHILD", &end, "frame_end CHILD Return"] + [ + "initialize_interp CHILD", + "hook CHILD Return", + &end, + "frame_end CHILD Return" + ] ); } } @@ -466,8 +564,89 @@ fn test_an_action_set_on_a_frames_resume_is_its_result() { let end = format!("call_end PARENT Return {}", Bytes::from_static(ON_RESUME)); assert_eq!( &run.events[child_end + 1..], - [end.as_str(), "frame_end PARENT Return"] + ["hook PARENT Return", &end, "frame_end PARENT Return"] ); } } } + +/// The result of each frame that ran reaches the consumer once, as it leaves the frame's run, on +/// both paths; on the inspected path, before the inspector's `call_end` and `frame_end`. +#[test] +fn test_a_frames_run_result_reaches_the_consumer_once_before_the_inspector() { + for inspected in [false, true] { + let run = run(Plan::default(), inspected); + + assert_eq!( + run.hooks(), + ["hook CHILD InvalidFEOpcode", "hook PARENT Return"], + "{inspected}" + ); + if inspected { + let parent_end = format!("call_end PARENT Return {}", status_and(false, &[])); + assert_eq!( + run.ends(), + [ + "initialize_interp PARENT", + "initialize_interp CHILD", + "hook CHILD InvalidFEOpcode", + "call_end CHILD InvalidFEOpcode 0x", + "frame_end CHILD InvalidFEOpcode", + "hook PARENT Return", + &parent_end, + "frame_end PARENT Return", + ] + ); + } + } +} + +/// What the consumer leaves in a frame's result is what the inspector and the caller see: the +/// child's halt, made a revert with output, reaches the inspector's ends and the caller's status +/// and return data as that revert. +#[test] +fn test_the_consumers_rewrite_is_what_the_inspector_and_the_caller_see() { + let plan = Plan { + rewrite: true, + ..Plan::default() + }; + for inspected in [false, true] { + let run = run(plan, inspected); + + assert_eq!(run.output(), &status_and(false, REWRITTEN), "{inspected}"); + assert_eq!( + run.marked, + (true, false), + "the revert took the child's mark back" + ); + if inspected { + let child_end = format!("call_end CHILD Revert {}", Bytes::from_static(REWRITTEN)); + let seen = run.ends(); + let from = seen + .iter() + .position(|line| *line == "hook CHILD InvalidFEOpcode") + .expect("the hook saw the halt"); + assert_eq!( + seen[from + 1..from + 3], + [&child_end, "frame_end CHILD Revert"] + ); + } + } +} + +/// A result given without a run does not reach the consumer: neither a precompile's answer, which +/// revm gives at the frame's start, nor an inspector's. +#[test] +fn test_a_result_given_without_a_run_does_not_reach_the_consumer() { + for inspected in [false, true] { + let run = run_calling(Callee::Precompile, Plan::default(), inspected); + + assert_eq!(run.output(), &status_and(true, &[]), "{inspected}"); + assert_eq!(run.hooks(), ["hook PARENT Return"], "{inspected}"); + } + + let run = run_calling(Callee::Answered, Plan::default(), true); + + assert_eq!(run.output(), &status_and(false, ANSWERED)); + assert_eq!(run.hooks(), ["hook PARENT Return"]); +} From 89e796d017104f88ba639ba4c3e3939f9c884bfc Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 16:53:20 +0800 Subject: [PATCH 058/110] test(inspector): revm's own EVM gives the callbacks, results and state recorded before the loop hooks A recording inspector's lines for a transaction whose frames return, revert, self-destruct, create and are answered by a precompile, and the result and state on the plain and the inspected path, compared with the lines recorded on the loops without the pending-action check and the frame-run-result hook. --- crates/inspector/tests/loop_callbacks.rs | 431 +++++++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 crates/inspector/tests/loop_callbacks.rs diff --git a/crates/inspector/tests/loop_callbacks.rs b/crates/inspector/tests/loop_callbacks.rs new file mode 100644 index 0000000000..e928906af2 --- /dev/null +++ b/crates/inspector/tests/loop_callbacks.rs @@ -0,0 +1,431 @@ +//! What revm's own EVM, which uses neither loop hook, gives an inspector and a caller: every +//! callback with what it is handed, and the transaction's result on the plain and the inspected +//! path. [`EXPECTED`] was recorded on the loops before they had the hooks (a pending action +//! returned before the first step; a frame's run result handed to the EVM before `frame_end`), so +//! the hooks' defaults change nothing a consumer that does not use them sees. +//! +//! [`PARENT`] calls a child that writes, logs and reverts, a precompile, and a contract that +//! self-destructs; creates a contract; logs; and returns. Each frame ends a different way. + +use context::{result::ExecutionResult, Context, TxEnv}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ExecuteEvm, FrameResult, MainBuilder, MainContext, MainnetContext, MainnetEvm}; +use interpreter::{ + interpreter_types::Jumps, CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, + Interpreter, +}; +use primitives::{address, hardfork::SpecId, Address, Log, TxKind, U256}; +use revm_inspector::{InspectEvm, Inspector}; +use state::{ + bytecode::opcode::{ + OpCode, CALL, CREATE, INVALID, LOG0, LOG1, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, + RETURN, REVERT, SELFDESTRUCT, SSTORE, + }, + AccountInfo, Bytecode, EvmState, +}; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 1_000_000; + +/// Calls [`CHILD`], [`IDENTITY`] and [`DESTRUCT`], creates a contract, logs and returns. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Writes its slot 0, logs, and reverts with no output. +const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); +/// Self-destructs to the transaction's caller. +const DESTRUCT: Address = address!("0x00000000000000000000000000000000000c0de2"); +/// The identity precompile. +const IDENTITY: Address = address!("0x0000000000000000000000000000000000000004"); +/// The gas [`PARENT`] forwards to each call: 0x0186a0. +const CALL_GAS: [u8; 3] = [0x01, 0x86, 0xa0]; +/// The creation's init code, which returns one `INVALID` byte as the contract's code. +const INIT_CODE: [u8; 9] = [PUSH1, INVALID, PUSH0, MSTORE, PUSH1, 1, PUSH1, 31, RETURN]; + +/// Every callback, one line each, with what it is handed. +#[derive(Debug, Default)] +struct Recorder { + events: Vec<String>, +} + +fn name(address: Address) -> String { + match address { + PARENT => "PARENT".into(), + CHILD => "CHILD".into(), + DESTRUCT => "DESTRUCT".into(), + IDENTITY => "IDENTITY".into(), + BENCH_CALLER => "CALLER".into(), + other => other.to_string(), + } +} + +fn frame(input: &FrameInput) -> String { + match input { + FrameInput::Call(inputs) => format!("call {}", name(inputs.target_address)), + FrameInput::Create(inputs) => format!("create by {}", name(inputs.caller())), + FrameInput::Empty => "empty".into(), + } +} + +fn ended(result: &FrameResult) -> String { + let (interpreter_result, gas) = (result.interpreter_result(), result.gas()); + format!( + "{:?} {} remaining={} refunded={} reservoir={}", + interpreter_result.result, + interpreter_result.output, + gas.remaining(), + gas.refunded(), + gas.reservoir() + ) +} + +fn at(interp: &Interpreter) -> String { + let pc = interp.bytecode.pc(); + let opcode = OpCode::new(interp.bytecode.opcode()).map_or("?", OpCode::as_str); + format!( + "{} {pc} {opcode} gas={} stack={}", + name(interp.input.target_address), + interp.gas.remaining(), + interp.stack.len() + ) +} + +impl Inspector<Ctx> for Recorder { + fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + self.events + .push(format!("initialize_interp {}", at(interp))); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + self.events.push(format!("step {}", at(interp))); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + self.events.push(format!("step_end {}", at(interp))); + } + + fn log(&mut self, _: &mut Ctx, log: Log) { + self.events.push(format!("log {log:?}")); + } + + fn log_full(&mut self, interp: &mut Interpreter, _: &mut Ctx, log: Log) { + self.events.push(format!("log_full {} {log:?}", at(interp))); + } + + fn frame_start(&mut self, _: &mut Ctx, input: &mut FrameInput) -> Option<FrameResult> { + self.events.push(format!("frame_start {}", frame(input))); + None + } + + fn frame_end(&mut self, _: &mut Ctx, input: &FrameInput, result: &mut FrameResult) { + let line = format!("frame_end {} {}", frame(input), ended(result)); + self.events.push(line); + } + + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + let (target, gas) = (name(inputs.target_address), inputs.gas_limit); + self.events.push(format!("call {target} gas={gas}")); + None + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + let result = ended(&FrameResult::Call(outcome.clone())); + let target = name(inputs.target_address); + self.events.push(format!("call_end {target} {result}")); + } + + fn create(&mut self, _: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { + let (caller, gas) = (name(inputs.caller()), inputs.gas_limit()); + self.events.push(format!("create by {caller} gas={gas}")); + None + } + + fn create_end(&mut self, _: &mut Ctx, _: &CreateInputs, outcome: &mut CreateOutcome) { + let address = outcome.address.map(name); + let result = ended(&FrameResult::Create(outcome.clone())); + self.events.push(format!("create_end {address:?} {result}")); + } + + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + let (contract, target) = (name(contract), name(target)); + self.events + .push(format!("selfdestruct {contract} to {target} value={value}")); + } +} + +/// Appends a call to `target` with [`CALL_GAS`] and no input, whose status it pops. +fn call(code: &mut Vec<u8>, target: Address) { + code.extend_from_slice(&[PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]); + code.extend_from_slice(target.as_slice()); + code.push(PUSH3); + code.extend_from_slice(&CALL_GAS); + code.extend_from_slice(&[CALL, POP]); +} + +fn parent_code() -> Bytecode { + let mut code = Vec::new(); + call(&mut code, CHILD); + call(&mut code, IDENTITY); + call(&mut code, DESTRUCT); + // The init code at the end of the first word, then CREATE(0, 32 - len, len). + code.push(PUSH1 + INIT_CODE.len() as u8 - 1); + code.extend_from_slice(&INIT_CODE); + code.extend_from_slice(&[PUSH0, MSTORE]); + code.extend_from_slice(&[ + PUSH1, + INIT_CODE.len() as u8, + PUSH1, + 32 - INIT_CODE.len() as u8, + PUSH0, + CREATE, + POP, + ]); + code.extend_from_slice(&[PUSH1, 7, PUSH0, PUSH0, LOG1]); + code.extend_from_slice(&[PUSH1, 32, PUSH0, RETURN]); + Bytecode::new_raw(code.into()) +} + +fn child_code() -> Bytecode { + Bytecode::new_raw( + vec![ + PUSH1, 1, PUSH0, SSTORE, PUSH0, PUSH0, LOG0, PUSH0, PUSH0, REVERT, + ] + .into(), + ) +} + +fn destruct_code() -> Bytecode { + let mut code = vec![PUSH20]; + code.extend_from_slice(BENCH_CALLER.as_slice()); + code.push(SELFDESTRUCT); + Bytecode::new_raw(code.into()) +} + +fn evm() -> MainnetEvm<Ctx, Recorder> { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + for (address, code, balance) in [ + (PARENT, parent_code(), 0), + (CHILD, child_code(), 0), + (DESTRUCT, destruct_code(), 5), + ] { + let info = AccountInfo::new(U256::from(balance), 1, code.hash_slow(), code); + db.insert_account_info(address, info); + } + Context::mainnet() + .with_db(db) + .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(SPEC)) + .build_mainnet_with_inspector(Recorder::default()) +} + +fn tx() -> TxEnv { + TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill() +} + +/// The result, and the state the transaction left, one line per account. +fn summary(result: &ExecutionResult, state: EvmState) -> Vec<String> { + let mut lines = vec![format!("result {result:?}")]; + let mut accounts: Vec<_> = state.into_iter().collect(); + accounts.sort_by_key(|(address, _)| *address); + for (address, account) in accounts { + let mut slots: Vec<_> = account + .storage + .iter() + .map(|(slot, value)| (*slot, value.present_value)) + .collect(); + slots.sort(); + lines.push(format!( + "account {} balance={} nonce={} code={} slots={slots:?}", + name(address), + account.info.balance, + account.info.nonce, + account.info.code_hash + )); + } + lines +} + +/// The inspector's lines, then the result and state lines, as recorded on the loops without the +/// hooks. +const EXPECTED: &[&str] = &[ + "frame_start call PARENT", + "call PARENT gas=979000", + "initialize_interp PARENT 0 PUSH0 gas=979000 stack=0", + "step PARENT 0 PUSH0 gas=979000 stack=0", + "step_end PARENT 1 PUSH0 gas=978998 stack=1", + "step PARENT 1 PUSH0 gas=978998 stack=1", + "step_end PARENT 2 PUSH0 gas=978996 stack=2", + "step PARENT 2 PUSH0 gas=978996 stack=2", + "step_end PARENT 3 PUSH0 gas=978994 stack=3", + "step PARENT 3 PUSH0 gas=978994 stack=3", + "step_end PARENT 4 PUSH0 gas=978992 stack=4", + "step PARENT 4 PUSH0 gas=978992 stack=4", + "step_end PARENT 5 PUSH20 gas=978990 stack=5", + "step PARENT 5 PUSH20 gas=978990 stack=5", + "step_end PARENT 26 PUSH3 gas=978987 stack=6", + "step PARENT 26 PUSH3 gas=978987 stack=6", + "step_end PARENT 30 CALL gas=978984 stack=7", + "step PARENT 30 CALL gas=978984 stack=7", + "step_end PARENT 31 POP gas=876384 stack=0", + "frame_start call CHILD", + "call CHILD gas=100000", + "initialize_interp CHILD 0 PUSH1 gas=100000 stack=0", + "step CHILD 0 PUSH1 gas=100000 stack=0", + "step_end CHILD 2 PUSH0 gas=99997 stack=1", + "step CHILD 2 PUSH0 gas=99997 stack=1", + "step_end CHILD 3 SSTORE gas=99995 stack=2", + "step CHILD 3 SSTORE gas=99995 stack=2", + "step_end CHILD 4 PUSH0 gas=77895 stack=0", + "step CHILD 4 PUSH0 gas=77895 stack=0", + "step_end CHILD 5 PUSH0 gas=77893 stack=1", + "step CHILD 5 PUSH0 gas=77893 stack=1", + "step_end CHILD 6 LOG0 gas=77891 stack=2", + "step CHILD 6 LOG0 gas=77891 stack=2", + "log_full CHILD 7 PUSH0 gas=77516 stack=0 Log { address: 0x00000000000000000000000000000000000c0de1, data: LogData { topics: [], data: 0x } }", + "step_end CHILD 7 PUSH0 gas=77516 stack=0", + "step CHILD 7 PUSH0 gas=77516 stack=0", + "step_end CHILD 8 PUSH0 gas=77514 stack=1", + "step CHILD 8 PUSH0 gas=77514 stack=1", + "step_end CHILD 9 REVERT gas=77512 stack=2", + "step CHILD 9 REVERT gas=77512 stack=2", + "step_end CHILD 10 STOP gas=77512 stack=0", + "call_end CHILD Revert 0x remaining=77512 refunded=0 reservoir=0", + "frame_end call CHILD Revert 0x remaining=77512 refunded=0 reservoir=0", + "step PARENT 31 POP gas=953896 stack=1", + "step_end PARENT 32 PUSH0 gas=953894 stack=0", + "step PARENT 32 PUSH0 gas=953894 stack=0", + "step_end PARENT 33 PUSH0 gas=953892 stack=1", + "step PARENT 33 PUSH0 gas=953892 stack=1", + "step_end PARENT 34 PUSH0 gas=953890 stack=2", + "step PARENT 34 PUSH0 gas=953890 stack=2", + "step_end PARENT 35 PUSH0 gas=953888 stack=3", + "step PARENT 35 PUSH0 gas=953888 stack=3", + "step_end PARENT 36 PUSH0 gas=953886 stack=4", + "step PARENT 36 PUSH0 gas=953886 stack=4", + "step_end PARENT 37 PUSH20 gas=953884 stack=5", + "step PARENT 37 PUSH20 gas=953884 stack=5", + "step_end PARENT 58 PUSH3 gas=953881 stack=6", + "step PARENT 58 PUSH3 gas=953881 stack=6", + "step_end PARENT 62 CALL gas=953878 stack=7", + "step PARENT 62 CALL gas=953878 stack=7", + "step_end PARENT 63 POP gas=853778 stack=0", + "frame_start call IDENTITY", + "call IDENTITY gas=100000", + "call_end IDENTITY Return 0x remaining=99985 refunded=0 reservoir=0", + "frame_end call IDENTITY Return 0x remaining=99985 refunded=0 reservoir=0", + "step PARENT 63 POP gas=953763 stack=1", + "step_end PARENT 64 PUSH0 gas=953761 stack=0", + "step PARENT 64 PUSH0 gas=953761 stack=0", + "step_end PARENT 65 PUSH0 gas=953759 stack=1", + "step PARENT 65 PUSH0 gas=953759 stack=1", + "step_end PARENT 66 PUSH0 gas=953757 stack=2", + "step PARENT 66 PUSH0 gas=953757 stack=2", + "step_end PARENT 67 PUSH0 gas=953755 stack=3", + "step PARENT 67 PUSH0 gas=953755 stack=3", + "step_end PARENT 68 PUSH0 gas=953753 stack=4", + "step PARENT 68 PUSH0 gas=953753 stack=4", + "step_end PARENT 69 PUSH20 gas=953751 stack=5", + "step PARENT 69 PUSH20 gas=953751 stack=5", + "step_end PARENT 90 PUSH3 gas=953748 stack=6", + "step PARENT 90 PUSH3 gas=953748 stack=6", + "step_end PARENT 94 CALL gas=953745 stack=7", + "step PARENT 94 CALL gas=953745 stack=7", + "step_end PARENT 95 POP gas=851145 stack=0", + "frame_start call DESTRUCT", + "call DESTRUCT gas=100000", + "initialize_interp DESTRUCT 0 PUSH20 gas=100000 stack=0", + "step DESTRUCT 0 PUSH20 gas=100000 stack=0", + "step_end DESTRUCT 21 SELFDESTRUCT gas=99997 stack=1", + "step DESTRUCT 21 SELFDESTRUCT gas=99997 stack=1", + "step_end DESTRUCT 22 STOP gas=94997 stack=0", + "selfdestruct DESTRUCT to CALLER value=5", + "call_end DESTRUCT SelfDestruct 0x remaining=94997 refunded=0 reservoir=0", + "frame_end call DESTRUCT SelfDestruct 0x remaining=94997 refunded=0 reservoir=0", + "step PARENT 95 POP gas=946142 stack=1", + "step_end PARENT 96 PUSH9 gas=946140 stack=0", + "step PARENT 96 PUSH9 gas=946140 stack=0", + "step_end PARENT 106 PUSH0 gas=946137 stack=1", + "step PARENT 106 PUSH0 gas=946137 stack=1", + "step_end PARENT 107 MSTORE gas=946135 stack=2", + "step PARENT 107 MSTORE gas=946135 stack=2", + "step_end PARENT 108 PUSH1 gas=946129 stack=0", + "step PARENT 108 PUSH1 gas=946129 stack=0", + "step_end PARENT 110 PUSH1 gas=946126 stack=1", + "step PARENT 110 PUSH1 gas=946126 stack=1", + "step_end PARENT 112 PUSH0 gas=946123 stack=2", + "step PARENT 112 PUSH0 gas=946123 stack=2", + "step_end PARENT 113 CREATE gas=946121 stack=3", + "step PARENT 113 CREATE gas=946121 stack=3", + "step_end PARENT 114 POP gas=14283 stack=0", + "frame_start create by PARENT", + "create by PARENT gas=899836", + "initialize_interp 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=899836 stack=0", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=899836 stack=0", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=899833 stack=1", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=899833 stack=1", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=899831 stack=2", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=899831 stack=2", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=899825 stack=0", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=899825 stack=0", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=899822 stack=1", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=899822 stack=1", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=899819 stack=2", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=899819 stack=2", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 9 STOP gas=899819 stack=0", + "create_end Some(\"0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18\") Return 0xfe remaining=899619 refunded=0 reservoir=0", + "frame_end create by PARENT Return 0xfe remaining=899619 refunded=0 reservoir=0", + "step PARENT 114 POP gas=913902 stack=1", + "step_end PARENT 115 PUSH1 gas=913900 stack=0", + "step PARENT 115 PUSH1 gas=913900 stack=0", + "step_end PARENT 117 PUSH0 gas=913897 stack=1", + "step PARENT 117 PUSH0 gas=913897 stack=1", + "step_end PARENT 118 PUSH0 gas=913895 stack=2", + "step PARENT 118 PUSH0 gas=913895 stack=2", + "step_end PARENT 119 LOG1 gas=913893 stack=3", + "step PARENT 119 LOG1 gas=913893 stack=3", + "log_full PARENT 120 PUSH1 gas=913143 stack=0 Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }", + "step_end PARENT 120 PUSH1 gas=913143 stack=0", + "step PARENT 120 PUSH1 gas=913143 stack=0", + "step_end PARENT 122 PUSH0 gas=913140 stack=1", + "step PARENT 122 PUSH0 gas=913140 stack=1", + "step_end PARENT 123 RETURN gas=913138 stack=2", + "step PARENT 123 RETURN gas=913138 stack=2", + "step_end PARENT 124 STOP gas=913138 stack=0", + "call_end PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=913138 refunded=0 reservoir=0", + "frame_end call PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=913138 refunded=0 reservoir=0", + "result Success { reason: Return, gas: ResultGas { total_gas_spent: 86862, state_gas_spent: 0, refunded: 0, floor_gas: 21000 }, logs: [Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }], output: Call(0x000000000000000000000000000000000000000000000060fe5f526001601ff3) }", + "account 0x0000000000000000000000000000000000000000 balance=0 nonce=0 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", + "account IDENTITY balance=0 nonce=0 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", + "account PARENT balance=0 nonce=2 code=0xdbf003432a6e20a1c2e13f77f0130cb233125ef7784a3402e451f5fab5fb380d slots=[]", + "account CHILD balance=0 nonce=1 code=0x67fda313dc72b1739f04ae407f6386f7db6466b9ee221a1c91ca0e0dbf9f648a slots=[(0, 0)]", + "account DESTRUCT balance=0 nonce=1 code=0x7ff285cf123c2738db918e966277ec00263c11d3942a177731207a462269db36 slots=[]", + "account 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 balance=0 nonce=1 code=0xbcc90f2d6dada5b18e155c17a1c0a55920aae94f39857d39d0d8ed07ae8f228b slots=[]", + "account CALLER balance=1000000000000000000005 nonce=1 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", +]; + +/// The inspector's callbacks, and the result and state of both paths, are as recorded. +#[test] +fn test_an_evm_without_the_loop_hooks_gives_the_recorded_callbacks_and_results() { + let mut inspected = evm(); + let result = inspected + .inspect_one_tx(tx()) + .expect("the transaction runs"); + let state = inspected.finalize(); + let mut seen = core::mem::take(&mut inspected.inspector.events); + seen.extend(summary(&result, state)); + + let mut plain = evm(); + let result = plain.transact_one(tx()).expect("the transaction runs"); + let plain = summary(&result, plain.finalize()); + + assert_eq!(seen[seen.len() - plain.len()..], plain, "the plain path"); + assert_eq!(seen, EXPECTED); +} From e3beab452a4e457f9f4d44674789ef63d5599294 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 16:59:15 +0800 Subject: [PATCH 059/110] docs: a pending action at a frame's run and a frame's run result, as hooks, in MEGAETH-FORK.md --- MEGAETH-FORK.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index e14bc1f119..b97e782178 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -387,6 +387,36 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. - **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. +### A pending action at a frame's run + +- **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction. +- **Contract.** An action set on a frame's interpreter before the frame runs is what the run returns, before any instruction runs. That is an action set once `frame_init` built the frame, or once `frame_return_result` put a child's result into its caller. + The plain and the inspected run return it alike: no instruction executes, so the frame's gas, stack, memory and program counter are as they were when it was set, and the inspected run calls neither `Inspector::step` nor `step_end` for that run. + The handler then processes it as any instruction's action (`process_next_action`): a `NewFrame` starts a child, a `Return` ends the frame on its result, as an instruction's return would. + A run that starts with no action set runs as upstream's: the inspector's `step` comes before each instruction, and an action the inspector sets in `step` ends the run after that `step`, as upstream's does. + An action an inspector sets in `initialize_interp` is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it. + One action at a time: `set_action` asserts in a debug build that none is pending, so a consumer sets an action only on a frame that has none, and an inspector's `initialize_interp` or `step` must not set one on a frame that has one. +- **Consumer.** mega-evm makes some of a frame's actions outside an instruction: the creation and the answer of a system contract's call, and the stop of a frame that a child left over a limit when it returns. They come back through the frame's run, so the loop starts the next frame or ends the frame, and an inspector sees the frame end. + Without the check, the plain run executes the frame's code before it returns the action, so mega-evm overrides `frame_run`, and the inspected run shows an inspector a `step` of an instruction that never runs. +- **Removal.** When upstream's runs check for a pending action before their first instruction, or when mega-evm makes no action outside an instruction. +- **Default.** revm sets no action before a run, so the check finds none and every run is upstream's, callbacks included, for a consumer and an inspector that set none. + Where measured (callgrind, the fork's release profile), the check costs about three instructions per frame run on the plain path: 6.03 per `CALL` (+0.23% on a transaction of 64 calls) and 6.12 per nested `CREATE`, which each run two frames (the child, and the caller's resume); 2 or 3 for a transaction whose one frame runs code; nothing for a transfer to an account without code or a precompile's answer, which run no frame. The inspected run was not measured. + +### A frame's run result + +- **API.** `EvmTr::frame_run_result(&mut self, result: &mut FrameResult) -> Result<(), ContextDbError<_>>`, a provided method. +- **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame marked finished and still on top of the stack. + On the plain path `Handler::run_exec_loop` calls it when `frame_run` returns a result. On the inspected path `InspectorEvmTr::inspect_frame_run` calls it before the inspector's `call_end` or `create_end` and its `frame_end`, and also for a frame without an `EthFrame`, whose run calls no inspector. On both, it runs before `frame_return_result`. + What it leaves in `result` is what everything after it sees: the inspector's end callbacks, `frame_return_result` and so the caller, and `last_frame_result` for the transaction's frame. An error it returns ends the transaction as an error of `frame_run` would. It leaves the frame stack as it found it. + A frame that returns a pending action (see A pending action at a frame's run) ran, and its result reaches it. + A result given without a run does not reach it: `frame_init` returns those (a start the handler refuses, a precompile's answer, an inspector's answer from `frame_start`, `call` or `create`, and an answer of a consumer's own `frame_init`). The consumer's `frame_init` has them first, and an inspector's answer is the inspector's. + The calls are in the loops, not in `Evm::frame_run`, so an EVM type that wraps revm's `Evm` and delegates `frame_run` to it gets its own `frame_run_result` called. A handler that overrides `run_exec_loop`, or an EVM type that overrides `inspect_frame_run`, calls it at the same point itself. +- **Consumer.** mega-evm decides how a frame that crossed its compute limit ends: its out-of-gas becomes a revert carrying the limit's output, with its gas put back. That has to happen once, before an inspector sees the frame end, on both paths. The plain path could do it in `frame_return_result`, but the inspected run calls `frame_end` before that, so a tracer would see the out-of-gas the caller never gets. +- **Removal.** When upstream has an equivalent point between a frame's last action and the inspector's end of it, or when mega-evm rewrites no frame's end. +- **Default.** Does nothing, so every result and every callback is upstream's. + Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under A pending action at a frame's run are that check's. The inspected path was not measured. + The inspected run marks a frame finished before the hook, where upstream's marked it after `frame_end`, so the hook sees the frame as the plain loop leaves it; no inspector callback is handed the frame, so none can tell. + ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. From f38073e994ef16614bd6137df6e0983a427ff9a3 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 17:17:56 +0800 Subject: [PATCH 060/110] test: a creation set at a frame's start runs before the frame, the recorded callbacks include a halt, and the handler tests' loops call the run-result hook A consumer that sets a creation on a frame revm built, taking its gas and shares from the frame, and an answer once the creation returned, gets the creation run and the answer as the frame's result, with no instruction of the frame's own and no step of it, on both paths. The recording of revm's own callbacks gains a frame that halts. The handler tests that copy the default loop to observe it call EvmTr::frame_run_result where the loop does. --- crates/handler/tests/failed_charge.rs | 5 +- crates/handler/tests/history_gas.rs | 5 +- crates/handler/tests/reservoir_share.rs | 5 +- crates/handler/tests/resource_pools.rs | 5 +- crates/handler/tests/withheld_gas.rs | 5 +- crates/inspector/tests/loop_callbacks.rs | 195 ++++++++++++++--------- crates/inspector/tests/loop_hooks.rs | 173 +++++++++++++++----- 7 files changed, 269 insertions(+), 124 deletions(-) diff --git a/crates/handler/tests/failed_charge.rs b/crates/handler/tests/failed_charge.rs index 93b77d946b..40df8f48d0 100644 --- a/crates/handler/tests/failed_charge.rs +++ b/crates/handler/tests/failed_charge.rs @@ -92,7 +92,10 @@ impl Handler for Observer { ItemOrResult::Item(_) => continue, ItemOrResult::Result(result) => result, }, - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; record(&result); if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/handler/tests/history_gas.rs b/crates/handler/tests/history_gas.rs index af45f91b10..0db5493e0d 100644 --- a/crates/handler/tests/history_gas.rs +++ b/crates/handler/tests/history_gas.rs @@ -248,7 +248,10 @@ impl Handler for Observer { ItemOrResult::Item(_) => continue, ItemOrResult::Result(result) => result, }, - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; self.record(&result); if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index 70f1a5d88f..5b3e70aed3 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -232,7 +232,10 @@ impl Handler for ShareHandler { ItemOrResult::Result(result) => result, } } - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; self.returned.push(returned(&result)); if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs index 7e19220adb..887b436d0c 100644 --- a/crates/handler/tests/resource_pools.rs +++ b/crates/handler/tests/resource_pools.rs @@ -576,7 +576,10 @@ impl Handler for PoolHandler { ItemOrResult::Result(result) => result, } } - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; self.returned.push(Returned::of(&result)); if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/handler/tests/withheld_gas.rs b/crates/handler/tests/withheld_gas.rs index 6b6a3a7f85..131a31adc0 100644 --- a/crates/handler/tests/withheld_gas.rs +++ b/crates/handler/tests/withheld_gas.rs @@ -143,7 +143,10 @@ impl Handler for Observer { ItemOrResult::Item(_) => continue, ItemOrResult::Result(result) => result, }, - ItemOrResult::Result(result) => result, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } }; record(&result); if let Some(result) = evm.frame_return_result(result)? { diff --git a/crates/inspector/tests/loop_callbacks.rs b/crates/inspector/tests/loop_callbacks.rs index e928906af2..66f3277eac 100644 --- a/crates/inspector/tests/loop_callbacks.rs +++ b/crates/inspector/tests/loop_callbacks.rs @@ -4,8 +4,10 @@ //! returned before the first step; a frame's run result handed to the EVM before `frame_end`), so //! the hooks' defaults change nothing a consumer that does not use them sees. //! -//! [`PARENT`] calls a child that writes, logs and reverts, a precompile, and a contract that -//! self-destructs; creates a contract; logs; and returns. Each frame ends a different way. +//! [`PARENT`] calls a child that writes, logs and reverts, one that halts, a precompile, and a +//! contract that self-destructs; creates a contract; logs; and returns. Each frame ends a +//! different way. A change that moves gas or callbacks, such as an upstream pick, moves these +//! lines too: they are then recorded again on the loops of the change's base. use context::{result::ExecutionResult, Context, TxEnv}; use database::{CacheDB, EmptyDB, BENCH_CALLER}; @@ -30,10 +32,13 @@ type Ctx = MainnetContext<Db>; const SPEC: SpecId = SpecId::OSAKA; const GAS_LIMIT: u64 = 1_000_000; -/// Calls [`CHILD`], [`IDENTITY`] and [`DESTRUCT`], creates a contract, logs and returns. +/// Calls [`CHILD`], [`HALTS`], [`IDENTITY`] and [`DESTRUCT`], creates a contract, logs and +/// returns. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Writes its slot 0, logs, and reverts with no output. const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); +/// Halts on `INVALID`. +const HALTS: Address = address!("0x00000000000000000000000000000000000c0de3"); /// Self-destructs to the transaction's caller. const DESTRUCT: Address = address!("0x00000000000000000000000000000000000c0de2"); /// The identity precompile. @@ -49,10 +54,12 @@ struct Recorder { events: Vec<String>, } +/// The name the lines give `address`. fn name(address: Address) -> String { match address { PARENT => "PARENT".into(), CHILD => "CHILD".into(), + HALTS => "HALTS".into(), DESTRUCT => "DESTRUCT".into(), IDENTITY => "IDENTITY".into(), BENCH_CALLER => "CALLER".into(), @@ -60,6 +67,7 @@ fn name(address: Address) -> String { } } +/// The frame `input` starts. fn frame(input: &FrameInput) -> String { match input { FrameInput::Call(inputs) => format!("call {}", name(inputs.target_address)), @@ -68,6 +76,7 @@ fn frame(input: &FrameInput) -> String { } } +/// How a frame ended: its result, output and gas. fn ended(result: &FrameResult) -> String { let (interpreter_result, gas) = (result.interpreter_result(), result.gas()); format!( @@ -80,6 +89,7 @@ fn ended(result: &FrameResult) -> String { ) } +/// Where `interp` is: its account, program counter, opcode, gas and stack depth. fn at(interp: &Interpreter) -> String { let pc = interp.bytecode.pc(); let opcode = OpCode::new(interp.bytecode.opcode()).map_or("?", OpCode::as_str); @@ -163,9 +173,11 @@ fn call(code: &mut Vec<u8>, target: Address) { code.extend_from_slice(&[CALL, POP]); } +/// [`PARENT`]'s code. fn parent_code() -> Bytecode { let mut code = Vec::new(); call(&mut code, CHILD); + call(&mut code, HALTS); call(&mut code, IDENTITY); call(&mut code, DESTRUCT); // The init code at the end of the first word, then CREATE(0, 32 - len, len). @@ -186,6 +198,7 @@ fn parent_code() -> Bytecode { Bytecode::new_raw(code.into()) } +/// [`CHILD`]'s code. fn child_code() -> Bytecode { Bytecode::new_raw( vec![ @@ -195,6 +208,7 @@ fn child_code() -> Bytecode { ) } +/// [`DESTRUCT`]'s code. fn destruct_code() -> Bytecode { let mut code = vec![PUSH20]; code.extend_from_slice(BENCH_CALLER.as_slice()); @@ -202,6 +216,7 @@ fn destruct_code() -> Bytecode { Bytecode::new_raw(code.into()) } +/// revm's mainnet EVM, with the accounts and a [`Recorder`]. fn evm() -> MainnetEvm<Ctx, Recorder> { let mut db = Db::default(); db.insert_account_info( @@ -211,6 +226,7 @@ fn evm() -> MainnetEvm<Ctx, Recorder> { for (address, code, balance) in [ (PARENT, parent_code(), 0), (CHILD, child_code(), 0), + (HALTS, Bytecode::new_raw(vec![PUSH0, INVALID].into()), 0), (DESTRUCT, destruct_code(), 5), ] { let info = AccountInfo::new(U256::from(balance), 1, code.hash_slow(), code); @@ -222,6 +238,7 @@ fn evm() -> MainnetEvm<Ctx, Recorder> { .build_mainnet_with_inspector(Recorder::default()) } +/// The transaction to [`PARENT`]. fn tx() -> TxEnv { TxEnv::builder_for_bench() .kind(TxKind::Call(PARENT)) @@ -316,29 +333,56 @@ const EXPECTED: &[&str] = &[ "step PARENT 58 PUSH3 gas=953881 stack=6", "step_end PARENT 62 CALL gas=953878 stack=7", "step PARENT 62 CALL gas=953878 stack=7", - "step_end PARENT 63 POP gas=853778 stack=0", + "step_end PARENT 63 POP gas=851278 stack=0", + "frame_start call HALTS", + "call HALTS gas=100000", + "initialize_interp HALTS 0 PUSH0 gas=100000 stack=0", + "step HALTS 0 PUSH0 gas=100000 stack=0", + "step_end HALTS 1 INVALID gas=99998 stack=1", + "step HALTS 1 INVALID gas=99998 stack=1", + "step_end HALTS 2 STOP gas=99998 stack=1", + "call_end HALTS InvalidFEOpcode 0x remaining=99998 refunded=0 reservoir=0", + "frame_end call HALTS InvalidFEOpcode 0x remaining=99998 refunded=0 reservoir=0", + "step PARENT 63 POP gas=851278 stack=1", + "step_end PARENT 64 PUSH0 gas=851276 stack=0", + "step PARENT 64 PUSH0 gas=851276 stack=0", + "step_end PARENT 65 PUSH0 gas=851274 stack=1", + "step PARENT 65 PUSH0 gas=851274 stack=1", + "step_end PARENT 66 PUSH0 gas=851272 stack=2", + "step PARENT 66 PUSH0 gas=851272 stack=2", + "step_end PARENT 67 PUSH0 gas=851270 stack=3", + "step PARENT 67 PUSH0 gas=851270 stack=3", + "step_end PARENT 68 PUSH0 gas=851268 stack=4", + "step PARENT 68 PUSH0 gas=851268 stack=4", + "step_end PARENT 69 PUSH20 gas=851266 stack=5", + "step PARENT 69 PUSH20 gas=851266 stack=5", + "step_end PARENT 90 PUSH3 gas=851263 stack=6", + "step PARENT 90 PUSH3 gas=851263 stack=6", + "step_end PARENT 94 CALL gas=851260 stack=7", + "step PARENT 94 CALL gas=851260 stack=7", + "step_end PARENT 95 POP gas=751160 stack=0", "frame_start call IDENTITY", "call IDENTITY gas=100000", "call_end IDENTITY Return 0x remaining=99985 refunded=0 reservoir=0", "frame_end call IDENTITY Return 0x remaining=99985 refunded=0 reservoir=0", - "step PARENT 63 POP gas=953763 stack=1", - "step_end PARENT 64 PUSH0 gas=953761 stack=0", - "step PARENT 64 PUSH0 gas=953761 stack=0", - "step_end PARENT 65 PUSH0 gas=953759 stack=1", - "step PARENT 65 PUSH0 gas=953759 stack=1", - "step_end PARENT 66 PUSH0 gas=953757 stack=2", - "step PARENT 66 PUSH0 gas=953757 stack=2", - "step_end PARENT 67 PUSH0 gas=953755 stack=3", - "step PARENT 67 PUSH0 gas=953755 stack=3", - "step_end PARENT 68 PUSH0 gas=953753 stack=4", - "step PARENT 68 PUSH0 gas=953753 stack=4", - "step_end PARENT 69 PUSH20 gas=953751 stack=5", - "step PARENT 69 PUSH20 gas=953751 stack=5", - "step_end PARENT 90 PUSH3 gas=953748 stack=6", - "step PARENT 90 PUSH3 gas=953748 stack=6", - "step_end PARENT 94 CALL gas=953745 stack=7", - "step PARENT 94 CALL gas=953745 stack=7", - "step_end PARENT 95 POP gas=851145 stack=0", + "step PARENT 95 POP gas=851145 stack=1", + "step_end PARENT 96 PUSH0 gas=851143 stack=0", + "step PARENT 96 PUSH0 gas=851143 stack=0", + "step_end PARENT 97 PUSH0 gas=851141 stack=1", + "step PARENT 97 PUSH0 gas=851141 stack=1", + "step_end PARENT 98 PUSH0 gas=851139 stack=2", + "step PARENT 98 PUSH0 gas=851139 stack=2", + "step_end PARENT 99 PUSH0 gas=851137 stack=3", + "step PARENT 99 PUSH0 gas=851137 stack=3", + "step_end PARENT 100 PUSH0 gas=851135 stack=4", + "step PARENT 100 PUSH0 gas=851135 stack=4", + "step_end PARENT 101 PUSH20 gas=851133 stack=5", + "step PARENT 101 PUSH20 gas=851133 stack=5", + "step_end PARENT 122 PUSH3 gas=851130 stack=6", + "step PARENT 122 PUSH3 gas=851130 stack=6", + "step_end PARENT 126 CALL gas=851127 stack=7", + "step PARENT 126 CALL gas=851127 stack=7", + "step_end PARENT 127 POP gas=748527 stack=0", "frame_start call DESTRUCT", "call DESTRUCT gas=100000", "initialize_interp DESTRUCT 0 PUSH20 gas=100000 stack=0", @@ -349,64 +393,65 @@ const EXPECTED: &[&str] = &[ "selfdestruct DESTRUCT to CALLER value=5", "call_end DESTRUCT SelfDestruct 0x remaining=94997 refunded=0 reservoir=0", "frame_end call DESTRUCT SelfDestruct 0x remaining=94997 refunded=0 reservoir=0", - "step PARENT 95 POP gas=946142 stack=1", - "step_end PARENT 96 PUSH9 gas=946140 stack=0", - "step PARENT 96 PUSH9 gas=946140 stack=0", - "step_end PARENT 106 PUSH0 gas=946137 stack=1", - "step PARENT 106 PUSH0 gas=946137 stack=1", - "step_end PARENT 107 MSTORE gas=946135 stack=2", - "step PARENT 107 MSTORE gas=946135 stack=2", - "step_end PARENT 108 PUSH1 gas=946129 stack=0", - "step PARENT 108 PUSH1 gas=946129 stack=0", - "step_end PARENT 110 PUSH1 gas=946126 stack=1", - "step PARENT 110 PUSH1 gas=946126 stack=1", - "step_end PARENT 112 PUSH0 gas=946123 stack=2", - "step PARENT 112 PUSH0 gas=946123 stack=2", - "step_end PARENT 113 CREATE gas=946121 stack=3", - "step PARENT 113 CREATE gas=946121 stack=3", - "step_end PARENT 114 POP gas=14283 stack=0", + "step PARENT 127 POP gas=843524 stack=1", + "step_end PARENT 128 PUSH9 gas=843522 stack=0", + "step PARENT 128 PUSH9 gas=843522 stack=0", + "step_end PARENT 138 PUSH0 gas=843519 stack=1", + "step PARENT 138 PUSH0 gas=843519 stack=1", + "step_end PARENT 139 MSTORE gas=843517 stack=2", + "step PARENT 139 MSTORE gas=843517 stack=2", + "step_end PARENT 140 PUSH1 gas=843511 stack=0", + "step PARENT 140 PUSH1 gas=843511 stack=0", + "step_end PARENT 142 PUSH1 gas=843508 stack=1", + "step PARENT 142 PUSH1 gas=843508 stack=1", + "step_end PARENT 144 PUSH0 gas=843505 stack=2", + "step PARENT 144 PUSH0 gas=843505 stack=2", + "step_end PARENT 145 CREATE gas=843503 stack=3", + "step PARENT 145 CREATE gas=843503 stack=3", + "step_end PARENT 146 POP gas=12679 stack=0", "frame_start create by PARENT", - "create by PARENT gas=899836", - "initialize_interp 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=899836 stack=0", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=899836 stack=0", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=899833 stack=1", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=899833 stack=1", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=899831 stack=2", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=899831 stack=2", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=899825 stack=0", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=899825 stack=0", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=899822 stack=1", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=899822 stack=1", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=899819 stack=2", - "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=899819 stack=2", - "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 9 STOP gas=899819 stack=0", - "create_end Some(\"0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18\") Return 0xfe remaining=899619 refunded=0 reservoir=0", - "frame_end create by PARENT Return 0xfe remaining=899619 refunded=0 reservoir=0", - "step PARENT 114 POP gas=913902 stack=1", - "step_end PARENT 115 PUSH1 gas=913900 stack=0", - "step PARENT 115 PUSH1 gas=913900 stack=0", - "step_end PARENT 117 PUSH0 gas=913897 stack=1", - "step PARENT 117 PUSH0 gas=913897 stack=1", - "step_end PARENT 118 PUSH0 gas=913895 stack=2", - "step PARENT 118 PUSH0 gas=913895 stack=2", - "step_end PARENT 119 LOG1 gas=913893 stack=3", - "step PARENT 119 LOG1 gas=913893 stack=3", - "log_full PARENT 120 PUSH1 gas=913143 stack=0 Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }", - "step_end PARENT 120 PUSH1 gas=913143 stack=0", - "step PARENT 120 PUSH1 gas=913143 stack=0", - "step_end PARENT 122 PUSH0 gas=913140 stack=1", - "step PARENT 122 PUSH0 gas=913140 stack=1", - "step_end PARENT 123 RETURN gas=913138 stack=2", - "step PARENT 123 RETURN gas=913138 stack=2", - "step_end PARENT 124 STOP gas=913138 stack=0", - "call_end PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=913138 refunded=0 reservoir=0", - "frame_end call PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=913138 refunded=0 reservoir=0", - "result Success { reason: Return, gas: ResultGas { total_gas_spent: 86862, state_gas_spent: 0, refunded: 0, floor_gas: 21000 }, logs: [Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }], output: Call(0x000000000000000000000000000000000000000000000060fe5f526001601ff3) }", + "create by PARENT gas=798822", + "initialize_interp 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=798822 stack=0", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 0 PUSH1 gas=798822 stack=0", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=798819 stack=1", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 2 PUSH0 gas=798819 stack=1", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=798817 stack=2", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 3 MSTORE gas=798817 stack=2", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=798811 stack=0", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 4 PUSH1 gas=798811 stack=0", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=798808 stack=1", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 6 PUSH1 gas=798808 stack=1", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=798805 stack=2", + "step 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 8 RETURN gas=798805 stack=2", + "step_end 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 9 STOP gas=798805 stack=0", + "create_end Some(\"0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18\") Return 0xfe remaining=798605 refunded=0 reservoir=0", + "frame_end create by PARENT Return 0xfe remaining=798605 refunded=0 reservoir=0", + "step PARENT 146 POP gas=811284 stack=1", + "step_end PARENT 147 PUSH1 gas=811282 stack=0", + "step PARENT 147 PUSH1 gas=811282 stack=0", + "step_end PARENT 149 PUSH0 gas=811279 stack=1", + "step PARENT 149 PUSH0 gas=811279 stack=1", + "step_end PARENT 150 PUSH0 gas=811277 stack=2", + "step PARENT 150 PUSH0 gas=811277 stack=2", + "step_end PARENT 151 LOG1 gas=811275 stack=3", + "step PARENT 151 LOG1 gas=811275 stack=3", + "log_full PARENT 152 PUSH1 gas=810525 stack=0 Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }", + "step_end PARENT 152 PUSH1 gas=810525 stack=0", + "step PARENT 152 PUSH1 gas=810525 stack=0", + "step_end PARENT 154 PUSH0 gas=810522 stack=1", + "step PARENT 154 PUSH0 gas=810522 stack=1", + "step_end PARENT 155 RETURN gas=810520 stack=2", + "step PARENT 155 RETURN gas=810520 stack=2", + "step_end PARENT 156 STOP gas=810520 stack=0", + "call_end PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=810520 refunded=0 reservoir=0", + "frame_end call PARENT Return 0x000000000000000000000000000000000000000000000060fe5f526001601ff3 remaining=810520 refunded=0 reservoir=0", + "result Success { reason: Return, gas: ResultGas { total_gas_spent: 189480, state_gas_spent: 0, refunded: 0, floor_gas: 21000 }, logs: [Log { address: 0x00000000000000000000000000000000000c0de0, data: LogData { topics: [0x0000000000000000000000000000000000000000000000000000000000000007], data: 0x } }], output: Call(0x000000000000000000000000000000000000000000000060fe5f526001601ff3) }", "account 0x0000000000000000000000000000000000000000 balance=0 nonce=0 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", "account IDENTITY balance=0 nonce=0 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", - "account PARENT balance=0 nonce=2 code=0xdbf003432a6e20a1c2e13f77f0130cb233125ef7784a3402e451f5fab5fb380d slots=[]", + "account PARENT balance=0 nonce=2 code=0x768dfcacf8bd182319a6177b16b326be856c90ddb3e3ece4f54c6884fd242918 slots=[]", "account CHILD balance=0 nonce=1 code=0x67fda313dc72b1739f04ae407f6386f7db6466b9ee221a1c91ca0e0dbf9f648a slots=[(0, 0)]", "account DESTRUCT balance=0 nonce=1 code=0x7ff285cf123c2738db918e966277ec00263c11d3942a177731207a462269db36 slots=[]", + "account HALTS balance=0 nonce=1 code=0xf8e33f1c6e1a51f3b5f0cf6136a5ffe74392bd9bcca9d6a96614fe629ef3cf6d slots=[]", "account 0xed591dC4375A9E8c959dA1AAa3712ac1063fCC18 balance=0 nonce=1 code=0xbcc90f2d6dada5b18e155c17a1c0a55920aae94f39857d39d0d8ed07ae8f228b slots=[]", "account CALLER balance=1000000000000000000005 nonce=1 code=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 slots=[]", ]; diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index fa1c19d85b..889c9234f0 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -2,7 +2,8 @@ //! //! A pending action: a consumer sets a frame's next action on its interpreter before the frame //! runs, at its start or when a child returned into it, and the frame's run returns that action -//! before any instruction runs, without an inspector `step`. +//! before any instruction runs, without an inspector `step`. A return ends the frame; a new frame +//! starts a child, and the frame resumes on its result. //! //! A frame's run result: the result of a frame that ran reaches the consumer's //! [`EvmTr::frame_run_result`] once, as it leaves the frame's run, before the inspector's @@ -16,7 +17,7 @@ use context::{ result::{EVMError, ExecutionResult, Output}, - Context, ContextSetters, ContextTr, Evm, FrameStack, JournalTr, TxEnv, + Cfg, Context, ContextSetters, ContextTr, Evm, FrameStack, JournalTr, TxEnv, }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ @@ -29,8 +30,8 @@ use interpreter::{ interpreter::{EthInterpreter, ExtBytecode}, interpreter_action::FrameInit, interpreter_types::{Jumps, LoopControl}, - CallInputs, CallOutcome, FrameInput, Gas, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, InterpreterResult, SharedMemory, + CallInputs, CallOutcome, CreateInputs, CreateScheme, FrameInput, Gas, InputsImpl, + InstructionResult, Interpreter, InterpreterAction, InterpreterResult, SharedMemory, }; use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{inspect_instructions, Inspector, InspectorEvmTr, InspectorHandler}; @@ -60,11 +61,16 @@ const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); const CHILD_GAS: [u8; 3] = [0x01, 0x86, 0xa0]; /// The identity precompile, which revm answers without running a frame. const IDENTITY: Address = address!("0x0000000000000000000000000000000000000004"); +/// The gas the consumer takes from [`CHILD`] for the creation it starts there. +const CREATION_GAS: u64 = 50_000; /// The output of the action the consumer sets on [`CHILD`] at its start. const AT_START: &[u8] = b"set at its start"; /// The output of the action the consumer sets on [`PARENT`] when [`CHILD`] returns into it. const ON_RESUME: &[u8] = b"set on its resume"; +/// The output of the action the consumer sets on [`CHILD`] when the creation it started there +/// returns into it. +const AFTER_ITS_CHILD: &[u8] = b"set once its child returned"; /// The output of the revert the consumer's hook makes of [`CHILD`]'s halt. const REWRITTEN: &[u8] = b"rewritten as it leaves its run"; /// The output of the revert the inspector answers the call to [`CHILD`] with. @@ -73,14 +79,24 @@ const ANSWERED: &[u8] = b"answered by the inspector"; /// What the consumer does at the loops' points. #[derive(Clone, Copy, Debug, Default)] struct Plan { - /// A return carrying [`AT_START`] on [`CHILD`]'s frame, once revm built it. - at_start: bool, + /// What the consumer sets on [`CHILD`]'s frame, once revm built it. + at_start: Option<AtStart>, /// A return carrying [`ON_RESUME`] on [`PARENT`]'s frame, once [`CHILD`]'s result is in it. on_resume: bool, /// [`CHILD`]'s halt made a revert carrying [`REWRITTEN`] as it leaves its run. rewrite: bool, } +/// The action the consumer sets on [`CHILD`]'s frame before it runs. +#[derive(Clone, Copy, Debug)] +enum AtStart { + /// A return carrying [`AT_START`]. + Return, + /// A creation with no init code on [`CREATION_GAS`] and the shares of the frame's reservoir + /// and pools; once it returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. + Create, +} + /// What [`PARENT`] calls, and whether the call runs. #[derive(Clone, Copy, Debug)] enum Callee { @@ -112,10 +128,24 @@ const fn name(address: Address) -> &'static str { fn target(input: &FrameInput) -> &'static str { match input { FrameInput::Call(inputs) => name(inputs.target_address), - _ => "other", + FrameInput::Create(_) => "CREATION", + FrameInput::Empty => "other", } } +fn is_call_to(input: &FrameInput, address: Address) -> bool { + matches!(input, FrameInput::Call(inputs) if inputs.target_address == address) +} + +/// A return of `frame` carrying `output`, on the gas it holds. +const fn returning(frame: &EthFrame, output: &'static [u8]) -> InterpreterAction { + InterpreterAction::new_return( + InstructionResult::Return, + Bytes::from_static(output), + frame.interpreter.gas, + ) +} + impl Inspector<Ctx> for Recorder { fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut Ctx) { let account = name(interp.input.target_address); @@ -198,20 +228,35 @@ impl EvmTr for Consumer { &mut self, frame_input: FrameInit, ) -> Result<FrameInitResult<'_, EthFrame>, ContextDbError<Ctx>> { - let child = target(&frame_input.frame_input) == "CHILD"; + let at_start = self + .plan + .at_start + .filter(|_| is_call_to(&frame_input.frame_input, CHILD)); + let params = self.evm.ctx.cfg().gas_params().clone(); let mut started = self.evm.frame_init(frame_input)?; - if let ItemOrResult::Item(frame) = &mut started { - if child && self.plan.at_start { - let gas = frame.interpreter.gas; - frame - .interpreter - .bytecode - .set_action(InterpreterAction::new_return( - InstructionResult::Return, - Bytes::from_static(AT_START), - gas, - )); - } + if let (Some(at_start), ItemOrResult::Item(frame)) = (at_start, &mut started) { + let action = match at_start { + AtStart::Return => returning(frame, AT_START), + AtStart::Create => { + let gas = &mut frame.interpreter.gas; + assert!( + gas.record_regular_cost(CREATION_GAS), + "the frame pays the creation" + ); + let shares = gas.tracker_mut().forward_to_child(¶ms); + let mut inputs = CreateInputs::new( + CHILD, + CreateScheme::Create, + U256::ZERO, + Bytes::new(), + CREATION_GAS, + shares.reservoir, + ); + inputs.set_pool_shares(shares.pools); + InterpreterAction::NewFrame(FrameInput::Create(Box::new(inputs))) + } + }; + frame.interpreter.bytecode.set_action(action); } Ok(started) } @@ -225,19 +270,21 @@ impl EvmTr for Consumer { result: FrameResult, ) -> Result<Option<FrameResult>, ContextDbError<Ctx>> { let returned = self.evm.frame_return_result(result)?; - if returned.is_none() && self.plan.on_resume { - let caller = self.evm.frame_stack.get(); - let gas = caller.interpreter.gas; - caller - .interpreter - .bytecode - .set_action(InterpreterAction::new_return( - InstructionResult::Return, - Bytes::from_static(ON_RESUME), - gas, - )); + if returned.is_some() { + return Ok(returned); } - Ok(returned) + let caller = self.evm.frame_stack.get(); + let created = matches!(self.plan.at_start, Some(AtStart::Create)); + let output = if is_call_to(&caller.input, CHILD) && created { + AFTER_ITS_CHILD + } else if is_call_to(&caller.input, PARENT) && self.plan.on_resume { + ON_RESUME + } else { + return Ok(None); + }; + let action = returning(caller, output); + caller.interpreter.bytecode.set_action(action); + Ok(None) } /// Writes the result it got into the inspector's lines, and rewrites [`CHILD`]'s halt as @@ -347,11 +394,7 @@ impl Run { /// The lines of `account`'s steps. fn steps(&self, account: &str) -> Vec<&str> { let prefix = format!("step {account} "); - self.events - .iter() - .map(String::as_str) - .filter(|line| line.starts_with(&prefix)) - .collect() + self.lines(|line| line.starts_with(&prefix)) } /// The consumer's hook lines. @@ -364,6 +407,7 @@ impl Run { self.lines(|line| !line.starts_with("step")) } + /// The lines `keep` keeps, in order. fn lines(&self, keep: impl Fn(&str) -> bool) -> Vec<&str> { self.events .iter() @@ -507,7 +551,7 @@ fn test_inspect_instructions_returns_a_pending_action_without_a_step() { #[test] fn test_an_action_set_at_a_frames_start_is_its_result() { let plan = Plan { - at_start: true, + at_start: Some(AtStart::Return), ..Plan::default() }; for inspected in [false, true] { @@ -517,12 +561,7 @@ fn test_an_action_set_at_a_frames_start_is_its_result() { assert_eq!(run.marked, (true, false), "the child ran no instruction"); assert_eq!(run.hooks(), ["hook CHILD Return", "hook PARENT Return"]); if inspected { - let seen: Vec<&str> = run - .events - .iter() - .map(String::as_str) - .filter(|line| line.contains("CHILD")) - .collect(); + let seen = run.lines(|line| line.contains("CHILD")); let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_START)); assert_eq!( seen, @@ -570,6 +609,52 @@ fn test_an_action_set_on_a_frames_resume_is_its_result() { } } +/// A child the consumer starts from a frame's start runs before the frame does, and the frame +/// returns the action the consumer sets once the child's result is in it: the frame runs no +/// instruction of its own, on either path, and the inspector sees no step of it. +#[test] +fn test_a_child_started_at_a_frames_start_runs_before_the_frame() { + let plan = Plan { + at_start: Some(AtStart::Create), + ..Plan::default() + }; + for inspected in [false, true] { + let run = run(plan, inspected); + + assert_eq!( + run.output(), + &status_and(true, AFTER_ITS_CHILD), + "{inspected}" + ); + assert_eq!(run.marked, (true, false), "the child ran no instruction"); + assert_eq!( + run.hooks(), + [ + "hook CREATION Return", + "hook CHILD Return", + "hook PARENT Return" + ], + "{inspected}" + ); + if inspected { + assert_eq!(run.steps("CHILD"), Vec::<&str>::new()); + let created = run + .events + .iter() + .position(|line| line == "frame_end CREATION Return"); + let child_ends = run + .events + .iter() + .position(|line| line == "frame_end CHILD Return"); + assert!( + created < child_ends, + "the creation ends first: {:?}", + run.events + ); + } + } +} + /// The result of each frame that ran reaches the consumer once, as it leaves the frame's run, on /// both paths; on the inspected path, before the inspector's `call_end` and `frame_end`. #[test] From 28124451a060847e64909903cd8a84ffa4eaa624 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 17:17:56 +0800 Subject: [PATCH 061/110] docs: where the run-result hook is reached for a wrapping EVM, why it is on EvmTr, and an inspector's action in initialize_interp as a baseline change --- MEGAETH-FORK.md | 20 +++++++++++++------- crates/handler/src/evm.rs | 9 +++++++-- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index b97e782178..39e7363755 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -387,7 +387,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. - **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. -### A pending action at a frame's run +### The pending action - **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction. - **Contract.** An action set on a frame's interpreter before the frame runs is what the run returns, before any instruction runs. That is an action set once `frame_init` built the frame, or once `frame_return_result` put a child's result into its caller. @@ -402,31 +402,37 @@ An id the fork once used for an entry with another default is left unused rather - **Default.** revm sets no action before a run, so the check finds none and every run is upstream's, callbacks included, for a consumer and an inspector that set none. Where measured (callgrind, the fork's release profile), the check costs about three instructions per frame run on the plain path: 6.03 per `CALL` (+0.23% on a transaction of 64 calls) and 6.12 per nested `CREATE`, which each run two frames (the child, and the caller's resume); 2 or 3 for a transaction whose one frame runs code; nothing for a transfer to an account without code or a precompile's answer, which run no frame. The inspected run was not measured. -### A frame's run result +### Frame-run result hook -- **API.** `EvmTr::frame_run_result(&mut self, result: &mut FrameResult) -> Result<(), ContextDbError<_>>`, a provided method. +- **API.** `EvmTr::frame_run_result(&mut self, result: &mut <Self::Frame as FrameTr>::FrameResult) -> Result<(), ContextDbError<Self::Context>>`, whose default does nothing. - **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame marked finished and still on top of the stack. On the plain path `Handler::run_exec_loop` calls it when `frame_run` returns a result. On the inspected path `InspectorEvmTr::inspect_frame_run` calls it before the inspector's `call_end` or `create_end` and its `frame_end`, and also for a frame without an `EthFrame`, whose run calls no inspector. On both, it runs before `frame_return_result`. What it leaves in `result` is what everything after it sees: the inspector's end callbacks, `frame_return_result` and so the caller, and `last_frame_result` for the transaction's frame. An error it returns ends the transaction as an error of `frame_run` would. It leaves the frame stack as it found it. - A frame that returns a pending action (see A pending action at a frame's run) ran, and its result reaches it. + A frame that returns a pending action (see The pending action) ran, and its result reaches it. A result given without a run does not reach it: `frame_init` returns those (a start the handler refuses, a precompile's answer, an inspector's answer from `frame_start`, `call` or `create`, and an answer of a consumer's own `frame_init`). The consumer's `frame_init` has them first, and an inspector's answer is the inspector's. - The calls are in the loops, not in `Evm::frame_run`, so an EVM type that wraps revm's `Evm` and delegates `frame_run` to it gets its own `frame_run_result` called. A handler that overrides `run_exec_loop`, or an EVM type that overrides `inspect_frame_run`, calls it at the same point itself. + It is on `EvmTr` because both calls reach it there: the inspected run is a provided method of `InspectorEvmTr`, which extends `EvmTr`, and has the EVM but not the handler. + The plain call is in the handler's loop, not in `Evm::frame_run`, and the inspected call is in the provided `inspect_frame_run`. So an EVM type that wraps revm's `Evm`, delegates `frame_run` to it and keeps the provided `inspect_frame_run` has its own `frame_run_result` called on both paths. + An override of `run_exec_loop` or of `inspect_frame_run` calls it at the same point itself. An `inspect_frame_run` that delegates to an inner EVM's reaches the inner EVM's `frame_run_result`, not its own, and runs the inner EVM's `frame_end` before the outer type sees the result. - **Consumer.** mega-evm decides how a frame that crossed its compute limit ends: its out-of-gas becomes a revert carrying the limit's output, with its gas put back. That has to happen once, before an inspector sees the frame end, on both paths. The plain path could do it in `frame_return_result`, but the inspected run calls `frame_end` before that, so a tracer would see the out-of-gas the caller never gets. - **Removal.** When upstream has an equivalent point between a frame's last action and the inspector's end of it, or when mega-evm rewrites no frame's end. - **Default.** Does nothing, so every result and every callback is upstream's. - Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under A pending action at a frame's run are that check's. The inspected path was not measured. + Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured. The inspected run marks a frame finished before the hook, where upstream's marked it after `frame_end`, so the hook sees the frame as the plain loop leaves it; no inspector callback is handed the frame, so none can tell. ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. A pick that changes what the journal records lands with a switch back to the base line (see revm 40.0.3's journal semantics). -One pick changes what the top-level entry points do with the journal, and has no switch: +One pick changes what the top-level entry points do with the journal, and has no switch. +One hook changes what an inspector that sets an action itself sees, and has no switch either: - **The journal is finalized on an error.** `ExecuteCommitEvm::transact_commit`, `ExecuteEvm::replay`, `InspectEvm::inspect_tx` and `inspect`, `InspectCommitEvm::inspect_tx_commit` and `inspect_commit`, and the four `inspect_system_call` variants clear the journal when execution returns an error. revm 40.0.3 left it holding the failed transaction's warm set and touched accounts, which leaked into the next transaction run on the same EVM. Upstream #3780, carried verbatim with the EIP-8037 / EIP-2780 gas core. There is no switch: a consumer that must keep the journal after an error uses the entry points that do not finalize (`transact_one`, `inspect_one_tx`, `system_call_one`) and finalizes itself. +- **An action an inspector sets in `initialize_interp` is returned without a `step`.** The inspected run returns an action pending when it starts before its first `Inspector::step` (see The pending action), so an inspector that halts a frame, or sets its next action, in `initialize_interp` sees no `step` of that frame's run. + revm 40.0.3 called `step` once first, at the frame's first instruction, and then returned the action without running it. + Results do not change: the run returns the same action, and no instruction runs on either. ## Tracking upstream diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index 6e97aceb5c..4dd434d95b 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -124,10 +124,15 @@ pub trait EvmTr { /// The handler loops call it once for each frame that ran and returns, after the frame's /// last action was processed and the frame marked finished, while the frame is still on top of /// the stack: `Handler::run_exec_loop` when [`frame_run`](EvmTr::frame_run) returns a result, - /// and the inspected run (`InspectorEvmTr::inspect_frame_run`) before the inspector's - /// `call_end`, `create_end` and `frame_end`. On both paths it runs before + /// and the provided inspected run (`InspectorEvmTr::inspect_frame_run`) before the + /// inspector's `call_end`, `create_end` and `frame_end`. On both paths it runs before /// [`frame_return_result`](EvmTr::frame_return_result). /// + /// The calls are on the EVM the loops run, so an EVM type that delegates `frame_run` to an + /// inner EVM still has its own method called. An override of `run_exec_loop` or of + /// `inspect_frame_run` calls it at the same point itself; one that delegates + /// `inspect_frame_run` to an inner EVM reaches the inner EVM's method instead. + /// /// A result given without a run does not reach it: [`frame_init`](EvmTr::frame_init) /// returns those (a start the handler refuses, a precompile's answer, an inspector's answer), /// so `frame_init`, or the inspector, has them first. From d033fea3bc2789784c86fec1508985a02532473e Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 19:20:52 +0800 Subject: [PATCH 062/110] fix(inspector): a frame whose action is set when it is built is not handed to initialize_interp A consumer's frame_init may set a new frame's next action, which the frame's first run returns before any instruction. inspect_frame_init then handed that frame to Inspector::initialize_interp, where an inspector that halted it tripped set_action's "action already set" assertion in a debug build and, in a release build, replaced the consumer's action with its halt. inspect_frame_init now hands a new frame to initialize_interp only if its interpreter has no action pending. revm never builds a frame with one, so every upstream frame still reaches initialize_interp and the callbacks are unchanged. A frame whose action is a return shows the inspector its start and end only, as a precompile's answer does; one whose action starts a child and that resumes with no action set runs its code with a step before each instruction. --- crates/inspector/src/inspector.rs | 3 + crates/inspector/src/traits.rs | 12 +++- crates/inspector/tests/loop_hooks.rs | 99 +++++++++++++++++++++++----- 3 files changed, 95 insertions(+), 19 deletions(-) diff --git a/crates/inspector/src/inspector.rs b/crates/inspector/src/inspector.rs index 26840c49e9..97c2f239e1 100644 --- a/crates/inspector/src/inspector.rs +++ b/crates/inspector/src/inspector.rs @@ -20,6 +20,9 @@ pub trait Inspector<CTX, INTR: InterpreterTypes = EthInterpreter, FI = FrameInpu /// Called before the interpreter is initialized. /// /// If `interp.bytecode.set_action` is set the execution of the interpreter is skipped. + /// + /// Not called for a frame whose next action the EVM set when it built the frame: the frame's + /// first run returns that action before any instruction. #[inline] fn initialize_interp(&mut self, interp: &mut Interpreter<INTR>, context: &mut CTX) { let _ = interp; diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index bc3b29a5d3..69663e4ad6 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -5,8 +5,8 @@ use handler::{ EthFrame, EvmTr, FrameInitOrResult, FrameResult, ItemOrResult, }; use interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallOutcome, FrameInput, - InterpreterTypes, + interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, + CallOutcome, FrameInput, InterpreterTypes, }; use crate::{ @@ -95,6 +95,10 @@ pub trait InspectorEvmTr: } /// Initializes the frame for the given frame input. Frame is pushed to the frame stack. + /// + /// A new frame is handed to [`Inspector::initialize_interp`] unless its next action is + /// already set ([`EvmTr::frame_init`] set it): its first run returns that action before any + /// instruction, and the inspector may not replace it. #[inline] fn inspect_frame_init( &mut self, @@ -137,7 +141,9 @@ pub trait InspectorEvmTr: } if let Some(frame) = frame.eth_frame() { let interp = &mut frame.interpreter; - inspector.initialize_interp(interp, ctx); + if interp.bytecode.is_not_end() { + inspector.initialize_interp(interp, ctx); + } }; Ok(ItemOrResult::Item(frame)) } diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 889c9234f0..3121b00378 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -3,7 +3,8 @@ //! A pending action: a consumer sets a frame's next action on its interpreter before the frame //! runs, at its start or when a child returned into it, and the frame's run returns that action //! before any instruction runs, without an inspector `step`. A return ends the frame; a new frame -//! starts a child, and the frame resumes on its result. +//! starts a child, and the frame resumes on its result. A frame whose action is set at its start +//! is not handed to the inspector's `initialize_interp`, so the inspector cannot replace it. //! //! A frame's run result: the result of a frame that ran reaches the consumer's //! [`EvmTr::frame_run_result`] once, as it leaves the frame's run, before the inspector's @@ -95,6 +96,9 @@ enum AtStart { /// A creation with no init code on [`CREATION_GAS`] and the shares of the frame's reservoir /// and pools; once it returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. Create, + /// The creation of [`AtStart::Create`]; once it returned into [`CHILD`], nothing, so + /// [`CHILD`] runs its code. + CreateThenRun, } /// What [`PARENT`] calls, and whether the call runs. @@ -106,6 +110,8 @@ enum Callee { Precompile, /// [`CHILD`], which the inspector answers with a revert carrying [`ANSWERED`]. Answered, + /// [`CHILD`], which the inspector halts out of gas in `initialize_interp`. + HaltedAtInit, } /// What the inspector saw, one line per callback, by the account the frame runs as. @@ -114,6 +120,8 @@ struct Recorder { events: Vec<String>, /// Answers the call to [`CHILD`]. answer: bool, + /// Halts [`CHILD`]'s frame out of gas in `initialize_interp`. + halt_at_init: bool, } const fn name(address: Address) -> &'static str { @@ -150,6 +158,9 @@ impl Inspector<Ctx> for Recorder { fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut Ctx) { let account = name(interp.input.target_address); self.events.push(format!("initialize_interp {account}")); + if self.halt_at_init && interp.input.target_address == CHILD { + interp.halt(InstructionResult::OutOfGas); + } } fn step(&mut self, interp: &mut Interpreter, _: &mut Ctx) { @@ -237,7 +248,7 @@ impl EvmTr for Consumer { if let (Some(at_start), ItemOrResult::Item(frame)) = (at_start, &mut started) { let action = match at_start { AtStart::Return => returning(frame, AT_START), - AtStart::Create => { + AtStart::Create | AtStart::CreateThenRun => { let gas = &mut frame.interpreter.gas; assert!( gas.record_regular_cost(CREATION_GAS), @@ -425,10 +436,11 @@ fn run(plan: Plan, inspected: bool) -> Run { /// [`run`], with [`PARENT`] calling `callee`. fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { - let (address, answer) = match callee { - Callee::Child => (CHILD, false), - Callee::Precompile => (IDENTITY, false), - Callee::Answered => (CHILD, true), + let (address, answer, halt_at_init) = match callee { + Callee::Child => (CHILD, false, false), + Callee::Precompile => (IDENTITY, false, false), + Callee::Answered => (CHILD, true, false), + Callee::HaltedAtInit => (CHILD, false, true), }; let mut db = Db::default(); db.insert_account_info( @@ -447,6 +459,7 @@ fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { let mut consumer = Consumer { evm: ctx.build_mainnet_with_inspector(Recorder { answer, + halt_at_init, ..Recorder::default() }), plan, @@ -547,7 +560,8 @@ fn test_inspect_instructions_returns_a_pending_action_without_a_step() { } /// An action the consumer sets on a frame revm built is the frame's result: its code does not -/// run, on either path, and the inspector sees the frame start and end with no step between. +/// run, on either path, and the inspector sees the frame start and end with nothing between, no +/// `initialize_interp` and no step. #[test] fn test_an_action_set_at_a_frames_start_is_its_result() { let plan = Plan { @@ -563,19 +577,30 @@ fn test_an_action_set_at_a_frames_start_is_its_result() { if inspected { let seen = run.lines(|line| line.contains("CHILD")); let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_START)); - assert_eq!( - seen, - [ - "initialize_interp CHILD", - "hook CHILD Return", - &end, - "frame_end CHILD Return" - ] - ); + assert_eq!(seen, ["hook CHILD Return", &end, "frame_end CHILD Return"]); } } } +/// A frame whose action the consumer set at its start is not handed to `initialize_interp`, so an +/// inspector that halts the frame there does not replace the consumer's action: the consumer's +/// action is the frame's result. +#[test] +fn test_an_inspector_cannot_halt_a_frame_whose_action_is_set_at_its_start() { + let plan = Plan { + at_start: Some(AtStart::Return), + ..Plan::default() + }; + let run = run_calling(Callee::HaltedAtInit, plan, true); + + assert_eq!(run.output(), &status_and(true, AT_START)); + let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_START)); + assert_eq!( + run.lines(|line| line.contains("CHILD")), + ["hook CHILD Return", &end, "frame_end CHILD Return"] + ); +} + /// An action the consumer sets on a caller once its child's result is in it is the caller's /// result: the rest of its code does not run, and the inspector sees no step of it after the /// child's end. @@ -655,6 +680,48 @@ fn test_a_child_started_at_a_frames_start_runs_before_the_frame() { } } +/// A frame that resumes with no action set, from a child the consumer started at its start, runs +/// its code then, on either path; the inspector sees a step before each instruction, though the +/// frame was not handed to `initialize_interp`. +#[test] +fn test_a_frame_resumed_from_a_child_started_at_its_start_runs_its_code() { + let plan = Plan { + at_start: Some(AtStart::CreateThenRun), + ..Plan::default() + }; + for inspected in [false, true] { + let run = run(plan, inspected); + + assert_eq!(run.output(), &status_and(false, &[]), "{inspected}"); + assert_eq!( + run.hooks(), + [ + "hook CREATION Return", + "hook CHILD InvalidFEOpcode", + "hook PARENT Return" + ], + "{inspected}" + ); + if inspected { + let steps = [ + "step CHILD 0", + "step CHILD 2", + "step CHILD 3", + "step CHILD 4", + ]; + assert_eq!(run.steps("CHILD"), steps, "PUSH1 PUSH0 SSTORE INVALID"); + assert_eq!( + run.lines(|line| line.contains("CHILD") && !line.starts_with("step")), + [ + "hook CHILD InvalidFEOpcode", + "call_end CHILD InvalidFEOpcode 0x", + "frame_end CHILD InvalidFEOpcode" + ] + ); + } + } +} + /// The result of each frame that ran reaches the consumer once, as it leaves the frame's run, on /// both paths; on the inspected path, before the inspector's `call_end` and `frame_end`. #[test] From 9f4a4625f97d610c68de5c83ae36c7d78a2f5a81 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 19:21:01 +0800 Subject: [PATCH 063/110] test(inspector): an inspector's halt in initialize_interp ends a frame without a step Pins the documented baseline change: an inspector that halts an ordinary frame in initialize_interp gets no step of it (upstream's run calls step once first). The halt is the frame's result, and the transaction's result is the one the frame's own halt gives. --- crates/inspector/tests/loop_hooks.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 3121b00378..b63eafe221 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -601,6 +601,27 @@ fn test_an_inspector_cannot_halt_a_frame_whose_action_is_set_at_its_start() { ); } +/// An inspector that halts a frame in `initialize_interp` ends it before its first instruction +/// and before any `step` (upstream's run calls `step` once first): the halt is the frame's result, +/// and its caller gets a failed call and none of its gas back, the transaction's result when the +/// frame's own `INVALID` halts it. +#[test] +fn test_an_inspectors_halt_in_initialize_interp_ends_the_frame_without_a_step() { + let halted = run_calling(Callee::HaltedAtInit, Plan::default(), true); + + assert_eq!(halted.output(), &status_and(false, &[])); + assert_eq!(halted.result, run(Plan::default(), true).result); + assert_eq!( + halted.lines(|line| line.contains("CHILD")), + [ + "initialize_interp CHILD", + "hook CHILD OutOfGas", + "call_end CHILD OutOfGas 0x", + "frame_end CHILD OutOfGas" + ] + ); +} + /// An action the consumer sets on a caller once its child's result is in it is the caller's /// result: the rest of its code does not run, and the inspector sees no step of it after the /// child's end. From 897b90d9b4dbbdd9488fc5e1897909da4479c402 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 19:21:01 +0800 Subject: [PATCH 064/110] test(inspector): the run-result hook's rewrite of the transaction's frame is the transaction's result Sends the transaction to the frame whose halt the hook makes a revert with output: on both paths the transaction ends as that revert and gets back the gas the frame left, so last_frame_result settles what the hook left rather than the frame's own halt. --- crates/inspector/tests/loop_hooks.rs | 59 ++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index b63eafe221..2ca1bd060a 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -13,8 +13,9 @@ //! //! The consumer here wraps revm's EVM and changes nothing else: [`PARENT`] calls [`CHILD`], then //! marks a slot of its own, and returns the call's status and return data; [`CHILD`] marks a slot -//! of its own and halts. A slot left unmarked is an instruction that did not run. The consumer's -//! hook writes its line into the inspector's, so one list orders both. +//! of its own and halts. A transaction goes to [`PARENT`] unless a test sends it to [`CHILD`]. A +//! slot left unmarked is an instruction that did not run. The consumer's hook writes its line into +//! the inspector's, so one list orders both. use context::{ result::{EVMError, ExecutionResult, Output}, @@ -381,7 +382,7 @@ fn child_code() -> Bytecode { Bytecode::new_raw(Bytes::from_static(&[PUSH1, 1, PUSH0, SSTORE, INVALID])) } -/// What one transaction to [`PARENT`] did. +/// What one transaction did. #[derive(Debug)] struct Run { result: ExecutionResult, @@ -436,6 +437,11 @@ fn run(plan: Plan, inspected: bool) -> Run { /// [`run`], with [`PARENT`] calling `callee`. fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { + run_to(PARENT, callee, plan, inspected) +} + +/// [`run_calling`], with the transaction sent to `to`. +fn run_to(to: Address, callee: Callee, plan: Plan, inspected: bool) -> Run { let (address, answer, halt_at_init) = match callee { Callee::Child => (CHILD, false, false), Callee::Precompile => (IDENTITY, false, false), @@ -466,7 +472,7 @@ fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { }; consumer.evm.ctx.set_tx( TxEnv::builder_for_bench() - .kind(TxKind::Call(PARENT)) + .kind(TxKind::Call(to)) .gas_price(0) .gas_limit(GAS_LIMIT) .build_fill(), @@ -807,6 +813,51 @@ fn test_the_consumers_rewrite_is_what_the_inspector_and_the_caller_see() { } } +/// What the consumer leaves in the transaction's own frame's result is the transaction's result: a +/// transaction to [`CHILD`], whose halt the consumer makes a revert with output, ends as that +/// revert on both paths, and gets back the gas the frame left, as a revert does and a halt does +/// not. +#[test] +fn test_the_consumers_rewrite_of_the_transactions_frame_is_the_transactions_result() { + let plan = Plan { + rewrite: true, + ..Plan::default() + }; + for inspected in [false, true] { + let halted = run_to(CHILD, Callee::Child, Plan::default(), inspected); + let rewritten = run_to(CHILD, Callee::Child, plan, inspected); + + assert_eq!( + halted.result.tx_gas_used(), + GAS_LIMIT, + "a halt spends it all" + ); + let ExecutionResult::Revert { output, .. } = &rewritten.result else { + panic!("the transaction reverts, got {:?}", rewritten.result); + }; + assert_eq!(output, &Bytes::from_static(REWRITTEN), "{inspected}"); + // 21,000 for the transaction, then PUSH1 3, PUSH0 2 and SSTORE's cold zero-to-one 22,100. + assert_eq!(rewritten.result.tx_gas_used(), 43_105, "{inspected}"); + assert_eq!( + rewritten.marked, + (false, false), + "the halt took the mark back" + ); + if inspected { + let end = format!("call_end CHILD Revert {}", Bytes::from_static(REWRITTEN)); + assert_eq!( + rewritten.ends(), + [ + "initialize_interp CHILD", + "hook CHILD InvalidFEOpcode", + &end, + "frame_end CHILD Revert" + ] + ); + } + } +} + /// A result given without a run does not reach the consumer: neither a precompile's answer, which /// revm gives at the frame's start, nor an inspector's. #[test] From ff7c3ed02dab16a529b7ac3e52d80cc3b61a59d3 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 19:21:01 +0800 Subject: [PATCH 065/110] docs: a frame whose action is set when it is built is not handed to initialize_interp, in MEGAETH-FORK.md Replaces the rule that an inspector's initialize_interp or step must not set an action on a frame that has one: step never sees such a frame, and the fork now keeps initialize_interp from seeing one. Records what a frame that resumes from a child it started that way gives an inspector, and why mega-evm needs the rule. --- MEGAETH-FORK.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 39e7363755..5dec4befe6 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -389,18 +389,21 @@ An id the fork once used for an entry with another default is left unused rather ### The pending action -- **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction. +- **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction, and which `InspectorEvmTr::inspect_frame_init` reads before it hands a new frame to `Inspector::initialize_interp`. - **Contract.** An action set on a frame's interpreter before the frame runs is what the run returns, before any instruction runs. That is an action set once `frame_init` built the frame, or once `frame_return_result` put a child's result into its caller. The plain and the inspected run return it alike: no instruction executes, so the frame's gas, stack, memory and program counter are as they were when it was set, and the inspected run calls neither `Inspector::step` nor `step_end` for that run. The handler then processes it as any instruction's action (`process_next_action`): a `NewFrame` starts a child, a `Return` ends the frame on its result, as an instruction's return would. A run that starts with no action set runs as upstream's: the inspector's `step` comes before each instruction, and an action the inspector sets in `step` ends the run after that `step`, as upstream's does. - An action an inspector sets in `initialize_interp` is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it. - One action at a time: `set_action` asserts in a debug build that none is pending, so a consumer sets an action only on a frame that has none, and an inspector's `initialize_interp` or `step` must not set one on a frame that has one. + A frame whose action is set when it is built is not handed to `initialize_interp`, and runs no `step` before that action: the action `frame_init` set is the frame's, which no inspector can replace, and the inspector sees the frame's start and end, as it sees a precompile's answer. + If that action starts a child and the frame resumes with no action set, the frame runs its code with a `step` before each instruction, never having been handed to `initialize_interp`. + An action an inspector sets in `initialize_interp` on any other frame is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it. + One action at a time: `set_action` asserts in a debug build that none is pending, so a consumer sets an action only on a frame that has none. - **Consumer.** mega-evm makes some of a frame's actions outside an instruction: the creation and the answer of a system contract's call, and the stop of a frame that a child left over a limit when it returns. They come back through the frame's run, so the loop starts the next frame or ends the frame, and an inspector sees the frame end. Without the check, the plain run executes the frame's code before it returns the action, so mega-evm overrides `frame_run`, and the inspected run shows an inspector a `step` of an instruction that never runs. -- **Removal.** When upstream's runs check for a pending action before their first instruction, or when mega-evm makes no action outside an instruction. -- **Default.** revm sets no action before a run, so the check finds none and every run is upstream's, callbacks included, for a consumer and an inspector that set none. - Where measured (callgrind, the fork's release profile), the check costs about three instructions per frame run on the plain path: 6.03 per `CALL` (+0.23% on a transaction of 64 calls) and 6.12 per nested `CREATE`, which each run two frames (the child, and the caller's resume); 2 or 3 for a transaction whose one frame runs code; nothing for a transfer to an account without code or a precompile's answer, which run no frame. The inspected run was not measured. + Without the `initialize_interp` rule, an inspector that halts the frame of a system contract's call there trips `set_action`'s assertion in a debug build, and in a release build replaces the creation mega-evm set with its halt. +- **Removal.** When upstream's runs check for a pending action before their first instruction and its inspected frame start does not hand a frame with one to `initialize_interp`, or when mega-evm makes no action outside an instruction. +- **Default.** revm sets no action before a run, so the check finds none, every frame revm builds is handed to `initialize_interp`, and every run is upstream's, callbacks included, for a consumer and an inspector that set none. + Where measured (callgrind, the fork's release profile), the check costs about three instructions per frame run on the plain path: 6.03 per `CALL` (+0.23% on a transaction of 64 calls) and 6.12 per nested `CREATE`, which each run two frames (the child, and the caller's resume); 2 or 3 for a transaction whose one frame runs code; nothing for a transfer to an account without code or a precompile's answer, which run no frame. The inspected path, which also reads the action once per new frame before `initialize_interp`, was not measured. ### Frame-run result hook From 6aee52370ef372d68c1d0069a7052ac67202b1c7 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 22:02:35 +0800 Subject: [PATCH 066/110] fix(inspector): the inspected run marks a frame finished after the inspector's end callbacks, as upstream's does The run marked a frame finished before it looked the frame up again for call_end and frame_end, so a frame type whose InspectorFrame::eth_frame gives no finished frame lost both end callbacks, and an inspector's rewrite there. The run-result hook still comes first; it does not rely on the finished mark, which revm's plain frame_run sets before the plain loop calls the hook. Tested with such a frame type through a whole inspected transaction. --- MEGAETH-FORK.md | 5 +- crates/handler/src/evm.rs | 12 +- crates/inspector/src/traits.rs | 6 +- crates/inspector/tests/custom_frame.rs | 337 +++++++++++++++++++++++++ crates/inspector/tests/loop_hooks.rs | 5 +- 5 files changed, 353 insertions(+), 12 deletions(-) create mode 100644 crates/inspector/tests/custom_frame.rs diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 5dec4befe6..ac8d55f063 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -408,7 +408,8 @@ An id the fork once used for an entry with another default is left unused rather ### Frame-run result hook - **API.** `EvmTr::frame_run_result(&mut self, result: &mut <Self::Frame as FrameTr>::FrameResult) -> Result<(), ContextDbError<Self::Context>>`, whose default does nothing. -- **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame marked finished and still on top of the stack. +- **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame still on top of the stack. + Whether the frame is marked finished differs by path, so the hook does not rely on it: revm's `frame_run` marks it before the plain loop calls the hook, and the inspected run marks it after the inspector's end callbacks, as upstream's does. On the plain path `Handler::run_exec_loop` calls it when `frame_run` returns a result. On the inspected path `InspectorEvmTr::inspect_frame_run` calls it before the inspector's `call_end` or `create_end` and its `frame_end`, and also for a frame without an `EthFrame`, whose run calls no inspector. On both, it runs before `frame_return_result`. What it leaves in `result` is what everything after it sees: the inspector's end callbacks, `frame_return_result` and so the caller, and `last_frame_result` for the transaction's frame. An error it returns ends the transaction as an error of `frame_run` would. It leaves the frame stack as it found it. A frame that returns a pending action (see The pending action) ran, and its result reaches it. @@ -420,7 +421,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream has an equivalent point between a frame's last action and the inspector's end of it, or when mega-evm rewrites no frame's end. - **Default.** Does nothing, so every result and every callback is upstream's. Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured. - The inspected run marks a frame finished before the hook, where upstream's marked it after `frame_end`, so the hook sees the frame as the plain loop leaves it; no inspector callback is handed the frame, so none can tell. + The inspected run looks the frame up for the inspector's end callbacks (`InspectorFrame::eth_frame`) and marks it finished in upstream's order, so a frame type whose accessor gives the inspector no finished frame still has its `call_end` and `frame_end`. ## Baseline behaviour the fork changes diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index 4dd434d95b..ad085ee0fa 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -122,12 +122,16 @@ pub trait EvmTr { /// caller see. /// /// The handler loops call it once for each frame that ran and returns, after the frame's - /// last action was processed and the frame marked finished, while the frame is still on top of - /// the stack: `Handler::run_exec_loop` when [`frame_run`](EvmTr::frame_run) returns a result, - /// and the provided inspected run (`InspectorEvmTr::inspect_frame_run`) before the - /// inspector's `call_end`, `create_end` and `frame_end`. On both paths it runs before + /// last action was processed, while the frame is still on top of the stack: + /// `Handler::run_exec_loop` when [`frame_run`](EvmTr::frame_run) returns a result, and the + /// provided inspected run (`InspectorEvmTr::inspect_frame_run`) before the inspector's + /// `call_end`, `create_end` and `frame_end`. On both paths it runs before /// [`frame_return_result`](EvmTr::frame_return_result). /// + /// Whether the frame is marked finished differs by path: `frame_run` marks it before the plain + /// loop calls this, and the inspected run marks it after the inspector's end callbacks, as + /// upstream's does. An implementation does not rely on the mark. + /// /// The calls are on the EVM the loops run, so an EVM type that delegates `frame_run` to an /// inner EVM still has its own method called. An override of `run_exec_loop` or of /// `inspect_frame_run` calls it at the same point itself; one that delegates diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index 69663e4ad6..26632a4614 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -150,8 +150,8 @@ pub trait InspectorEvmTr: /// Run the frame from the top of the stack. Returns the frame init or result. /// - /// If frame has returned result it would mark it as finished, and hand it to - /// [`EvmTr::frame_run_result`] before the inspector's `frame_end`. + /// If frame has returned result it would hand it to [`EvmTr::frame_run_result`], then to the + /// inspector's `frame_end`, and mark the frame as finished. #[inline] fn inspect_frame_run( &mut self, @@ -176,12 +176,12 @@ pub trait InspectorEvmTr: let mut result = frame.process_next_action(ctx, next_action); if let Ok(ItemOrResult::Result(frame_result)) = &mut result { - frame.set_finished(true); self.frame_run_result(frame_result)?; let (ctx, inspector, frame) = self.ctx_inspector_frame(); // TODO When all_mut fn is added we can fetch inspector at the top of the function.s if let Some(frame) = frame.eth_frame() { frame_end(ctx, inspector, &frame.input, frame_result); + frame.set_finished(true); } }; result diff --git a/crates/inspector/tests/custom_frame.rs b/crates/inspector/tests/custom_frame.rs new file mode 100644 index 0000000000..91c60767ad --- /dev/null +++ b/crates/inspector/tests/custom_frame.rs @@ -0,0 +1,337 @@ +//! The inspected run of a consumer's own frame type, which wraps revm's [`EthFrame`] and gives the +//! inspector that frame ([`InspectorFrame::eth_frame`]) only while it has not finished. Nothing +//! asks the accessor to ignore the frame's state, so the run looks the frame up for the inspector's +//! end callbacks before it marks the frame finished, as upstream's does: the inspector sees each +//! frame's `call_end` and `frame_end`. +//! +//! [`PARENT`] calls [`CHILD`], and both stop. The consumer sets no action and keeps +//! [`EvmTr::frame_run_result`]'s default; its EVM runs its frames as revm's own does. + +use context::{ + result::{EVMError, ExecutionResult, HaltReason}, + Context, ContextSetters, Evm, FrameStack, TxEnv, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + evm::{ContextDbError, FrameInitResult, FrameTr}, + instructions::{EthInstructions, InstructionProvider}, + EthFrame, EthPrecompiles, EvmTr, FrameInitOrResult, FrameResult, Handler, ItemOrResult, + MainContext, MainnetContext, +}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, CallOutcome, FrameInput, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{Inspector, InspectorEvmTr, InspectorFrame, InspectorHandler}; +use state::{ + bytecode::opcode::{CALL, GAS, PUSH0, PUSH20, STOP}, + AccountInfo, Bytecode, +}; +use std::convert::Infallible; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; +type Instructions = EthInstructions<EthInterpreter, Ctx>; +type Inner = Evm<Ctx, Recorder, Instructions, EthPrecompiles, Frame>; +type Error = EVMError<Infallible>; + +const SPEC: SpecId = SpecId::OSAKA; +const GAS_LIMIT: u64 = 1_000_000; + +/// Calls [`CHILD`] with all its gas, and stops. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Stops. +const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); + +/// revm's frame, which the inspector is given only while it has not finished. +#[derive(Debug, Default)] +struct Frame(EthFrame); + +impl FrameTr for Frame { + type FrameInit = FrameInit; + type FrameResult = FrameResult; +} + +impl InspectorFrame for Frame { + type IT = EthInterpreter; + + fn eth_frame(&mut self) -> Option<&mut EthFrame> { + if self.0.is_finished() { + None + } else { + Some(&mut self.0) + } + } +} + +/// The frames' starts and ends, one line per callback, by the account the frame runs as. +#[derive(Debug, Default)] +struct Recorder { + events: Vec<String>, +} + +const fn name(address: Address) -> &'static str { + match address { + PARENT => "PARENT", + CHILD => "CHILD", + _ => "other", + } +} + +impl Inspector<Ctx> for Recorder { + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + let account = name(inputs.target_address); + self.events.push(format!("call {account}")); + None + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + let (account, result) = (name(inputs.target_address), outcome.result.result); + self.events.push(format!("call_end {account} {result:?}")); + } + + fn frame_end(&mut self, _: &mut Ctx, input: &FrameInput, result: &mut FrameResult) { + let account = match input { + FrameInput::Call(inputs) => name(inputs.target_address), + _ => "other", + }; + let result = result.instruction_result(); + self.events.push(format!("frame_end {account} {result:?}")); + } +} + +/// revm's EVM on [`Frame`]: its frame start, run and return are revm's own, on the [`EthFrame`] +/// inside. +struct Consumer(Inner); + +impl EvmTr for Consumer { + type Context = Ctx; + type Instructions = Instructions; + type Precompiles = EthPrecompiles; + type Frame = Frame; + + fn all(&self) -> (&Ctx, &Instructions, &EthPrecompiles, &FrameStack<Frame>) { + let evm = &self.0; + ( + &evm.ctx, + &evm.instruction, + &evm.precompiles, + &evm.frame_stack, + ) + } + + fn all_mut( + &mut self, + ) -> ( + &mut Ctx, + &mut Instructions, + &mut EthPrecompiles, + &mut FrameStack<Frame>, + ) { + let evm = &mut self.0; + ( + &mut evm.ctx, + &mut evm.instruction, + &mut evm.precompiles, + &mut evm.frame_stack, + ) + } + + fn frame_init( + &mut self, + frame_input: FrameInit, + ) -> Result<FrameInitResult<'_, Frame>, ContextDbError<Ctx>> { + let Evm { + ctx, + precompiles, + frame_stack, + .. + } = &mut self.0; + let is_first_init = frame_stack.index().is_none(); + let mut slot = if is_first_init { + frame_stack.start_init() + } else { + frame_stack.get_next() + }; + let frame = &mut slot.get(Frame::default).0; + let out = context::OutFrame::new_init(frame); + if let ItemOrResult::Result(result) = + EthFrame::init_with_context(out, ctx, precompiles, frame_input)? + { + return Ok(ItemOrResult::Result(result)); + } + let token = slot.consume(); + // SAFETY: the token is the slot's this stack just gave, which `slot.get` initialized. + unsafe { + if is_first_init { + frame_stack.end_init(token); + } else { + frame_stack.push(token); + } + } + Ok(ItemOrResult::Item(frame_stack.get())) + } + + fn frame_run(&mut self) -> Result<FrameInitOrResult<Frame>, ContextDbError<Ctx>> { + let Evm { + ctx, + instruction, + frame_stack, + .. + } = &mut self.0; + let frame = &mut frame_stack.get().0; + let action = frame.interpreter.run_plain( + instruction.instruction_table(), + instruction.gas_table(), + ctx, + ); + let result = frame.process_next_action(ctx, action); + if let Ok(ItemOrResult::Result(_)) = &result { + frame.set_finished(true); + } + result + } + + fn frame_return_result( + &mut self, + result: FrameResult, + ) -> Result<Option<FrameResult>, ContextDbError<Ctx>> { + let Evm { + ctx, frame_stack, .. + } = &mut self.0; + if frame_stack.get().0.is_finished() { + frame_stack.pop(); + } + if frame_stack.index().is_none() { + return Ok(Some(result)); + } + frame_stack + .get() + .0 + .return_result::<_, ContextDbError<Ctx>>(ctx, result)?; + Ok(None) + } +} + +impl InspectorEvmTr for Consumer { + type Inspector = Recorder; + + fn all_inspector( + &self, + ) -> ( + &Ctx, + &Instructions, + &EthPrecompiles, + &FrameStack<Frame>, + &Recorder, + ) { + let evm = &self.0; + ( + &evm.ctx, + &evm.instruction, + &evm.precompiles, + &evm.frame_stack, + &evm.inspector, + ) + } + + fn all_mut_inspector( + &mut self, + ) -> ( + &mut Ctx, + &mut Instructions, + &mut EthPrecompiles, + &mut FrameStack<Frame>, + &mut Recorder, + ) { + let evm = &mut self.0; + ( + &mut evm.ctx, + &mut evm.instruction, + &mut evm.precompiles, + &mut evm.frame_stack, + &mut evm.inspector, + ) + } +} + +/// The mainnet handler, on [`Consumer`]. +struct Mainnet; + +impl Handler for Mainnet { + type Evm = Consumer; + type Error = Error; + type HaltReason = HaltReason; +} + +impl InspectorHandler for Mainnet { + type IT = EthInterpreter; +} + +/// A [`Consumer`] holding [`PARENT`] and [`CHILD`], with a transaction to [`PARENT`]. +fn consumer() -> Consumer { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut parent = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + parent.extend_from_slice(CHILD.as_slice()); + parent.extend_from_slice(&[GAS, CALL, STOP]); + let codes = [ + (PARENT, parent.into()), + (CHILD, Bytes::from_static(&[STOP])), + ]; + for (address, code) in codes { + let code = Bytecode::new_raw(code); + db.insert_account_info( + address, + AccountInfo::new(U256::ZERO, 1, code.hash_slow(), code), + ); + } + let mut ctx = Context::mainnet() + .with_db(db) + .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(SPEC)); + ctx.set_tx( + TxEnv::builder_for_bench() + .kind(TxKind::Call(PARENT)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(), + ); + Consumer(Evm { + ctx, + inspector: Recorder::default(), + instruction: Instructions::new_mainnet_with_spec(SPEC), + precompiles: EthPrecompiles::new(SPEC), + frame_stack: FrameStack::new(), + }) +} + +/// The inspector sees each frame's end, though the frame's accessor gives it no finished frame, +/// and the transaction's result is the plain run's. +#[test] +fn test_a_frame_hidden_once_finished_gets_its_end_callbacks() { + let mut inspected = consumer(); + let result = Mainnet + .inspect_run(&mut inspected) + .expect("the transaction runs"); + + assert_eq!( + inspected.0.inspector.events, + [ + "call PARENT", + "call CHILD", + "call_end CHILD Stop", + "frame_end CHILD Stop", + "call_end PARENT Stop", + "frame_end PARENT Stop", + ] + ); + assert!( + matches!(result, ExecutionResult::Success { .. }), + "{result:?}" + ); + let plain = Mainnet.run(&mut consumer()).expect("the transaction runs"); + assert_eq!(result, plain); +} diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 2ca1bd060a..204b928a5a 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -299,11 +299,10 @@ impl EvmTr for Consumer { Ok(None) } - /// Writes the result it got into the inspector's lines, and rewrites [`CHILD`]'s halt as - /// [`Plan::rewrite`] says. + /// Writes the result it got into the inspector's lines, by the frame on top of the stack, and + /// rewrites [`CHILD`]'s halt as [`Plan::rewrite`] says. fn frame_run_result(&mut self, result: &mut FrameResult) -> Result<(), ContextDbError<Ctx>> { let frame = self.evm.frame_stack.get(); - assert!(frame.is_finished(), "the frame on top is the one that ran"); let (account, got) = (target(&frame.input), result.instruction_result()); self.evm .inspector From d352b717873040aa59d231452bb5ffa4811aff8e Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 22:02:41 +0800 Subject: [PATCH 067/110] test(inspector): an inspector's action in initialize_interp is returned without the step that would edit it Pins the documented baseline change where it changes a result: an inspector sets a return in initialize_interp and edits a pending return in its step. The frame returns what initialize_interp set; upstream's run calls that step first and returns the edit. The initialize_interp doc says a step of that run never sees the action. --- crates/inspector/src/inspector.rs | 2 ++ crates/inspector/tests/loop_hooks.rs | 52 +++++++++++++++++++++++++--- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/inspector/src/inspector.rs b/crates/inspector/src/inspector.rs index 97c2f239e1..affc763c0a 100644 --- a/crates/inspector/src/inspector.rs +++ b/crates/inspector/src/inspector.rs @@ -20,6 +20,8 @@ pub trait Inspector<CTX, INTR: InterpreterTypes = EthInterpreter, FI = FrameInpu /// Called before the interpreter is initialized. /// /// If `interp.bytecode.set_action` is set the execution of the interpreter is skipped. + /// The frame's run returns that action before its first [`Inspector::step`], so no `step` of + /// that run sees or edits it. /// /// Not called for a frame whose next action the EVM set when it built the frame: the frame's /// first run returns that action before any instruction. diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 204b928a5a..84853f3255 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -77,6 +77,10 @@ const AFTER_ITS_CHILD: &[u8] = b"set once its child returned"; const REWRITTEN: &[u8] = b"rewritten as it leaves its run"; /// The output of the revert the inspector answers the call to [`CHILD`] with. const ANSWERED: &[u8] = b"answered by the inspector"; +/// The output of the return the inspector sets on [`CHILD`]'s frame in `initialize_interp`. +const AT_INIT: &[u8] = b"set in initialize_interp"; +/// The output the inspector's `step` writes into a return pending on the frame it steps. +const IN_STEP: &[u8] = b"edited in step"; /// What the consumer does at the loops' points. #[derive(Clone, Copy, Debug, Default)] @@ -113,6 +117,9 @@ enum Callee { Answered, /// [`CHILD`], which the inspector halts out of gas in `initialize_interp`. HaltedAtInit, + /// [`CHILD`], which the inspector returns with [`AT_INIT`] in `initialize_interp`, and whose + /// pending return its `step` edits to carry [`IN_STEP`]. + ReturnedAtInit, } /// What the inspector saw, one line per callback, by the account the frame runs as. @@ -123,6 +130,9 @@ struct Recorder { answer: bool, /// Halts [`CHILD`]'s frame out of gas in `initialize_interp`. halt_at_init: bool, + /// Returns [`CHILD`]'s frame with [`AT_INIT`] in `initialize_interp`, and edits a return + /// pending on a frame it steps to carry [`IN_STEP`]. + return_at_init: bool, } const fn name(address: Address) -> &'static str { @@ -162,11 +172,19 @@ impl Inspector<Ctx> for Recorder { if self.halt_at_init && interp.input.target_address == CHILD { interp.halt(InstructionResult::OutOfGas); } + if self.return_at_init && interp.input.target_address == CHILD { + interp.return_with_output(Bytes::from_static(AT_INIT)); + } } fn step(&mut self, interp: &mut Interpreter, _: &mut Ctx) { let (account, pc) = (name(interp.input.target_address), interp.bytecode.pc()); self.events.push(format!("step {account} {pc}")); + if let (true, Some(InterpreterAction::Return(result))) = + (self.return_at_init, interp.bytecode.action()) + { + result.output = Bytes::from_static(IN_STEP); + } } fn step_end(&mut self, interp: &mut Interpreter, _: &mut Ctx) { @@ -441,11 +459,12 @@ fn run_calling(callee: Callee, plan: Plan, inspected: bool) -> Run { /// [`run_calling`], with the transaction sent to `to`. fn run_to(to: Address, callee: Callee, plan: Plan, inspected: bool) -> Run { - let (address, answer, halt_at_init) = match callee { - Callee::Child => (CHILD, false, false), - Callee::Precompile => (IDENTITY, false, false), - Callee::Answered => (CHILD, true, false), - Callee::HaltedAtInit => (CHILD, false, true), + let (address, answer, halt_at_init, return_at_init) = match callee { + Callee::Child => (CHILD, false, false, false), + Callee::Precompile => (IDENTITY, false, false, false), + Callee::Answered => (CHILD, true, false, false), + Callee::HaltedAtInit => (CHILD, false, true, false), + Callee::ReturnedAtInit => (CHILD, false, false, true), }; let mut db = Db::default(); db.insert_account_info( @@ -465,6 +484,7 @@ fn run_to(to: Address, callee: Callee, plan: Plan, inspected: bool) -> Run { evm: ctx.build_mainnet_with_inspector(Recorder { answer, halt_at_init, + return_at_init, ..Recorder::default() }), plan, @@ -627,6 +647,28 @@ fn test_an_inspectors_halt_in_initialize_interp_ends_the_frame_without_a_step() ); } +/// An action an inspector sets in `initialize_interp` is returned before the frame's first `step` +/// (upstream's run calls that `step` first), so whatever that `step` would do is not done: here +/// the `step` edits the pending return, and the frame returns what `initialize_interp` set, where +/// upstream's returns the edit. +#[test] +fn test_an_inspectors_action_in_initialize_interp_is_returned_without_the_step_that_edits_it() { + let run = run_calling(Callee::ReturnedAtInit, Plan::default(), true); + + assert_eq!(run.output(), &status_and(true, AT_INIT)); + assert_eq!(run.marked, (true, false), "the child runs no instruction"); + let end = format!("call_end CHILD Return {}", Bytes::from_static(AT_INIT)); + assert_eq!( + run.lines(|line| line.contains("CHILD")), + [ + "initialize_interp CHILD", + "hook CHILD Return", + &end, + "frame_end CHILD Return" + ] + ); +} + /// An action the consumer sets on a caller once its child's result is in it is the caller's /// result: the rest of its code does not run, and the inspector sees no step of it after the /// child's end. From 47d075888973521453ac048ded450a39fbaf4da1 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 22:02:41 +0800 Subject: [PATCH 068/110] docs: the initialize_interp baseline change can change an inspector's result, in MEGAETH-FORK.md Only an inspector that sets an action before a frame runs is affected: it loses that run's first step and whatever the step would have done. A step that only observes leaves the result as it was; a step that edits the pending action or changes the context or state does not. --- MEGAETH-FORK.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index ac8d55f063..7b838438df 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -396,7 +396,7 @@ An id the fork once used for an entry with another default is left unused rather A run that starts with no action set runs as upstream's: the inspector's `step` comes before each instruction, and an action the inspector sets in `step` ends the run after that `step`, as upstream's does. A frame whose action is set when it is built is not handed to `initialize_interp`, and runs no `step` before that action: the action `frame_init` set is the frame's, which no inspector can replace, and the inspector sees the frame's start and end, as it sees a precompile's answer. If that action starts a child and the frame resumes with no action set, the frame runs its code with a `step` before each instruction, never having been handed to `initialize_interp`. - An action an inspector sets in `initialize_interp` on any other frame is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it. + An action an inspector sets in `initialize_interp` on any other frame is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it, and returns the action as that `step` left it (see Baseline behaviour the fork changes). One action at a time: `set_action` asserts in a debug build that none is pending, so a consumer sets an action only on a frame that has none. - **Consumer.** mega-evm makes some of a frame's actions outside an instruction: the creation and the answer of a system contract's call, and the stop of a frame that a child left over a limit when it returns. They come back through the frame's run, so the loop starts the next frame or ends the frame, and an inspector sees the frame end. Without the check, the plain run executes the frame's code before it returns the action, so mega-evm overrides `frame_run`, and the inspected run shows an inspector a `step` of an instruction that never runs. @@ -428,15 +428,18 @@ An id the fork once used for an entry with another default is left unused rather Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. A pick that changes what the journal records lands with a switch back to the base line (see revm 40.0.3's journal semantics). One pick changes what the top-level entry points do with the journal, and has no switch. -One hook changes what an inspector that sets an action itself sees, and has no switch either: +One hook changes what an inspector that sets an action before a frame runs sees and gets, and has no switch either: - **The journal is finalized on an error.** `ExecuteCommitEvm::transact_commit`, `ExecuteEvm::replay`, `InspectEvm::inspect_tx` and `inspect`, `InspectCommitEvm::inspect_tx_commit` and `inspect_commit`, and the four `inspect_system_call` variants clear the journal when execution returns an error. revm 40.0.3 left it holding the failed transaction's warm set and touched accounts, which leaked into the next transaction run on the same EVM. Upstream #3780, carried verbatim with the EIP-8037 / EIP-2780 gas core. There is no switch: a consumer that must keep the journal after an error uses the entry points that do not finalize (`transact_one`, `inspect_one_tx`, `system_call_one`) and finalizes itself. -- **An action an inspector sets in `initialize_interp` is returned without a `step`.** The inspected run returns an action pending when it starts before its first `Inspector::step` (see The pending action), so an inspector that halts a frame, or sets its next action, in `initialize_interp` sees no `step` of that frame's run. - revm 40.0.3 called `step` once first, at the frame's first instruction, and then returned the action without running it. - Results do not change: the run returns the same action, and no instruction runs on either. +- **An action an inspector sets in `initialize_interp` is returned without a `step`.** The inspected run returns an action pending when it starts before its first `Inspector::step` (see The pending action). + Only an inspector that sets an action before a frame runs, by halting the frame or setting its next action in `initialize_interp`, is affected: it loses that run's first `step`, and with it whatever that `step` would have done. + revm 40.0.3 called `step` once first, at the frame's first instruction, and then returned the action as that `step` left it, without running the instruction. + An inspector whose `step` only observes sees one `step` fewer and gets the same result, since no instruction runs on either. + An inspector whose `step` edits the pending action (`LoopControl::action`), or changes the context or the state, gets a different result: the frame returns the action `initialize_interp` set, and the `step`'s changes are not made. + An inspector that sets no action before a frame runs sees every `step` and gets every result revm 40.0.3 gives it. ## Tracking upstream From b83996f0901300ad69ad473fd3393aa86305a8c3 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 22:12:16 +0800 Subject: [PATCH 069/110] docs: where a frame is marked finished around the run-result hook, by path and frame type The inspected run marks a frame with an EthFrame after the inspector's end callbacks, and a frame without one is marked by its own frame_run, before the hook; the docs said the former for every frame. The baseline entry names the pending-action check as what changes an inspector's initialize_interp action, drops a sentence that was false where a consumer sets a frame's action, and the Default bullet no longer repeats the Contract's order. --- MEGAETH-FORK.md | 6 ++---- crates/handler/src/evm.rs | 6 +++--- crates/inspector/src/traits.rs | 3 ++- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 7b838438df..f48e8d44a6 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -409,7 +409,7 @@ An id the fork once used for an entry with another default is left unused rather - **API.** `EvmTr::frame_run_result(&mut self, result: &mut <Self::Frame as FrameTr>::FrameResult) -> Result<(), ContextDbError<Self::Context>>`, whose default does nothing. - **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame still on top of the stack. - Whether the frame is marked finished differs by path, so the hook does not rely on it: revm's `frame_run` marks it before the plain loop calls the hook, and the inspected run marks it after the inspector's end callbacks, as upstream's does. + Whether the frame is marked finished differs by path and frame type, so the hook does not rely on it: revm's `frame_run` marks it before the plain loop calls the hook, the inspected run marks a frame with an `EthFrame` after the inspector's end callbacks, as upstream's does, and a frame without one is marked by its own `frame_run`, before the hook. On the plain path `Handler::run_exec_loop` calls it when `frame_run` returns a result. On the inspected path `InspectorEvmTr::inspect_frame_run` calls it before the inspector's `call_end` or `create_end` and its `frame_end`, and also for a frame without an `EthFrame`, whose run calls no inspector. On both, it runs before `frame_return_result`. What it leaves in `result` is what everything after it sees: the inspector's end callbacks, `frame_return_result` and so the caller, and `last_frame_result` for the transaction's frame. An error it returns ends the transaction as an error of `frame_run` would. It leaves the frame stack as it found it. A frame that returns a pending action (see The pending action) ran, and its result reaches it. @@ -421,14 +421,13 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream has an equivalent point between a frame's last action and the inspector's end of it, or when mega-evm rewrites no frame's end. - **Default.** Does nothing, so every result and every callback is upstream's. Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured. - The inspected run looks the frame up for the inspector's end callbacks (`InspectorFrame::eth_frame`) and marks it finished in upstream's order, so a frame type whose accessor gives the inspector no finished frame still has its `call_end` and `frame_end`. ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. A pick that changes what the journal records lands with a switch back to the base line (see revm 40.0.3's journal semantics). One pick changes what the top-level entry points do with the journal, and has no switch. -One hook changes what an inspector that sets an action before a frame runs sees and gets, and has no switch either: +The pending-action check changes what an inspector that sets an action before a frame runs sees and gets, and has no switch either: - **The journal is finalized on an error.** `ExecuteCommitEvm::transact_commit`, `ExecuteEvm::replay`, `InspectEvm::inspect_tx` and `inspect`, `InspectCommitEvm::inspect_tx_commit` and `inspect_commit`, and the four `inspect_system_call` variants clear the journal when execution returns an error. revm 40.0.3 left it holding the failed transaction's warm set and touched accounts, which leaked into the next transaction run on the same EVM. @@ -439,7 +438,6 @@ One hook changes what an inspector that sets an action before a frame runs sees revm 40.0.3 called `step` once first, at the frame's first instruction, and then returned the action as that `step` left it, without running the instruction. An inspector whose `step` only observes sees one `step` fewer and gets the same result, since no instruction runs on either. An inspector whose `step` edits the pending action (`LoopControl::action`), or changes the context or the state, gets a different result: the frame returns the action `initialize_interp` set, and the `step`'s changes are not made. - An inspector that sets no action before a frame runs sees every `step` and gets every result revm 40.0.3 gives it. ## Tracking upstream diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index ad085ee0fa..7728f9c3a6 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -128,9 +128,9 @@ pub trait EvmTr { /// `call_end`, `create_end` and `frame_end`. On both paths it runs before /// [`frame_return_result`](EvmTr::frame_return_result). /// - /// Whether the frame is marked finished differs by path: `frame_run` marks it before the plain - /// loop calls this, and the inspected run marks it after the inspector's end callbacks, as - /// upstream's does. An implementation does not rely on the mark. + /// Whether the frame is marked finished differs by path and frame type, so an implementation + /// does not rely on the mark: `frame_run` marks it before the plain loop calls this, and the + /// inspected run marks a frame with an `EthFrame` after the inspector's end callbacks. /// /// The calls are on the EVM the loops run, so an EVM type that delegates `frame_run` to an /// inner EVM still has its own method called. An override of `run_exec_loop` or of diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index 26632a4614..59425b4d5f 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -151,7 +151,8 @@ pub trait InspectorEvmTr: /// Run the frame from the top of the stack. Returns the frame init or result. /// /// If frame has returned result it would hand it to [`EvmTr::frame_run_result`], then to the - /// inspector's `frame_end`, and mark the frame as finished. + /// inspector's `frame_end`, and mark the frame as finished. A frame without an `EthFrame` is + /// run by [`EvmTr::frame_run`], and its result handed to [`EvmTr::frame_run_result`] only. #[inline] fn inspect_frame_run( &mut self, From 2fc8edf33b2ffddb195cebc17be9adabfd95417c Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 22 Oct 2026 22:12:16 +0800 Subject: [PATCH 070/110] test(inspector): name the frame type that hides once finished, and match the loop-hook tests' idiom The custom frame type is HiddenOnceFinished; the EVM wrapping it holds revm's EVM in a named field, as the loop-hook tests' consumer does; the step that edits a pending return nests its condition as the callbacks around it do. No behaviour changes. --- crates/inspector/tests/custom_frame.rs | 75 +++++++++++++++----------- crates/inspector/tests/loop_hooks.rs | 8 +-- 2 files changed, 47 insertions(+), 36 deletions(-) diff --git a/crates/inspector/tests/custom_frame.rs b/crates/inspector/tests/custom_frame.rs index 91c60767ad..4c939ae523 100644 --- a/crates/inspector/tests/custom_frame.rs +++ b/crates/inspector/tests/custom_frame.rs @@ -9,7 +9,7 @@ use context::{ result::{EVMError, ExecutionResult, HaltReason}, - Context, ContextSetters, Evm, FrameStack, TxEnv, + Context, ContextSetters, Evm, FrameStack, OutFrame, TxEnv, }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ @@ -32,7 +32,7 @@ use std::convert::Infallible; type Db = CacheDB<EmptyDB>; type Ctx = MainnetContext<Db>; type Instructions = EthInstructions<EthInterpreter, Ctx>; -type Inner = Evm<Ctx, Recorder, Instructions, EthPrecompiles, Frame>; +type Inner = Evm<Ctx, Recorder, Instructions, EthPrecompiles, HiddenOnceFinished>; type Error = EVMError<Infallible>; const SPEC: SpecId = SpecId::OSAKA; @@ -45,14 +45,14 @@ const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); /// revm's frame, which the inspector is given only while it has not finished. #[derive(Debug, Default)] -struct Frame(EthFrame); +struct HiddenOnceFinished(EthFrame); -impl FrameTr for Frame { +impl FrameTr for HiddenOnceFinished { type FrameInit = FrameInit; type FrameResult = FrameResult; } -impl InspectorFrame for Frame { +impl InspectorFrame for HiddenOnceFinished { type IT = EthInterpreter; fn eth_frame(&mut self) -> Option<&mut EthFrame> { @@ -100,18 +100,27 @@ impl Inspector<Ctx> for Recorder { } } -/// revm's EVM on [`Frame`]: its frame start, run and return are revm's own, on the [`EthFrame`] -/// inside. -struct Consumer(Inner); +/// revm's EVM on [`HiddenOnceFinished`]: its frame start, run and return are revm's own, on the +/// [`EthFrame`] inside. +struct Consumer { + evm: Inner, +} impl EvmTr for Consumer { type Context = Ctx; type Instructions = Instructions; type Precompiles = EthPrecompiles; - type Frame = Frame; + type Frame = HiddenOnceFinished; - fn all(&self) -> (&Ctx, &Instructions, &EthPrecompiles, &FrameStack<Frame>) { - let evm = &self.0; + fn all( + &self, + ) -> ( + &Ctx, + &Instructions, + &EthPrecompiles, + &FrameStack<HiddenOnceFinished>, + ) { + let evm = &self.evm; ( &evm.ctx, &evm.instruction, @@ -126,9 +135,9 @@ impl EvmTr for Consumer { &mut Ctx, &mut Instructions, &mut EthPrecompiles, - &mut FrameStack<Frame>, + &mut FrameStack<HiddenOnceFinished>, ) { - let evm = &mut self.0; + let evm = &mut self.evm; ( &mut evm.ctx, &mut evm.instruction, @@ -140,21 +149,21 @@ impl EvmTr for Consumer { fn frame_init( &mut self, frame_input: FrameInit, - ) -> Result<FrameInitResult<'_, Frame>, ContextDbError<Ctx>> { + ) -> Result<FrameInitResult<'_, HiddenOnceFinished>, ContextDbError<Ctx>> { let Evm { ctx, precompiles, frame_stack, .. - } = &mut self.0; + } = &mut self.evm; let is_first_init = frame_stack.index().is_none(); let mut slot = if is_first_init { frame_stack.start_init() } else { frame_stack.get_next() }; - let frame = &mut slot.get(Frame::default).0; - let out = context::OutFrame::new_init(frame); + let frame = &mut slot.get(HiddenOnceFinished::default).0; + let out = OutFrame::new_init(frame); if let ItemOrResult::Result(result) = EthFrame::init_with_context(out, ctx, precompiles, frame_input)? { @@ -172,13 +181,13 @@ impl EvmTr for Consumer { Ok(ItemOrResult::Item(frame_stack.get())) } - fn frame_run(&mut self) -> Result<FrameInitOrResult<Frame>, ContextDbError<Ctx>> { + fn frame_run(&mut self) -> Result<FrameInitOrResult<HiddenOnceFinished>, ContextDbError<Ctx>> { let Evm { ctx, instruction, frame_stack, .. - } = &mut self.0; + } = &mut self.evm; let frame = &mut frame_stack.get().0; let action = frame.interpreter.run_plain( instruction.instruction_table(), @@ -198,7 +207,7 @@ impl EvmTr for Consumer { ) -> Result<Option<FrameResult>, ContextDbError<Ctx>> { let Evm { ctx, frame_stack, .. - } = &mut self.0; + } = &mut self.evm; if frame_stack.get().0.is_finished() { frame_stack.pop(); } @@ -222,10 +231,10 @@ impl InspectorEvmTr for Consumer { &Ctx, &Instructions, &EthPrecompiles, - &FrameStack<Frame>, + &FrameStack<HiddenOnceFinished>, &Recorder, ) { - let evm = &self.0; + let evm = &self.evm; ( &evm.ctx, &evm.instruction, @@ -241,10 +250,10 @@ impl InspectorEvmTr for Consumer { &mut Ctx, &mut Instructions, &mut EthPrecompiles, - &mut FrameStack<Frame>, + &mut FrameStack<HiddenOnceFinished>, &mut Recorder, ) { - let evm = &mut self.0; + let evm = &mut self.evm; ( &mut evm.ctx, &mut evm.instruction, @@ -299,13 +308,15 @@ fn consumer() -> Consumer { .gas_limit(GAS_LIMIT) .build_fill(), ); - Consumer(Evm { - ctx, - inspector: Recorder::default(), - instruction: Instructions::new_mainnet_with_spec(SPEC), - precompiles: EthPrecompiles::new(SPEC), - frame_stack: FrameStack::new(), - }) + Consumer { + evm: Evm { + ctx, + inspector: Recorder::default(), + instruction: Instructions::new_mainnet_with_spec(SPEC), + precompiles: EthPrecompiles::new(SPEC), + frame_stack: FrameStack::new(), + }, + } } /// The inspector sees each frame's end, though the frame's accessor gives it no finished frame, @@ -318,7 +329,7 @@ fn test_a_frame_hidden_once_finished_gets_its_end_callbacks() { .expect("the transaction runs"); assert_eq!( - inspected.0.inspector.events, + inspected.evm.inspector.events, [ "call PARENT", "call CHILD", diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 84853f3255..77ef133dc7 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -180,10 +180,10 @@ impl Inspector<Ctx> for Recorder { fn step(&mut self, interp: &mut Interpreter, _: &mut Ctx) { let (account, pc) = (name(interp.input.target_address), interp.bytecode.pc()); self.events.push(format!("step {account} {pc}")); - if let (true, Some(InterpreterAction::Return(result))) = - (self.return_at_init, interp.bytecode.action()) - { - result.output = Bytes::from_static(IN_STEP); + if self.return_at_init { + if let Some(InterpreterAction::Return(result)) = interp.bytecode.action() { + result.output = Bytes::from_static(IN_STEP); + } } } From bd2ad8d0f4459ddd0d251a1b85f607c1b80981b8 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:06:55 +0800 Subject: [PATCH 071/110] feat(state): lend an account's original info by reference `Account::original_info` returns a copy of the original info, and the copy moves the code's reference count up and down. `original_info_ref` returns the same info by reference: the stored original, or a default info built once for an account whose original was never set. Additive; nothing in the workspace calls it. --- MEGAETH-FORK.md | 10 ++++- crates/state/src/lib.rs | 1 + crates/state/src/original_info.rs | 66 +++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 crates/state/src/original_info.rs diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index f48e8d44a6..100b362651 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -63,7 +63,7 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T ## Hooks -This section lists every hook and switch the fork carries. +This section lists every hook, switch and accessor the fork carries. Each entry names the API a consumer uses and what the fork guarantees about it. A hook's default keeps upstream's behaviour: a consumer that does not use it sees the same results. Each entry's **Consumer** says who needs it and why it cannot be done outside the fork, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it. @@ -422,6 +422,14 @@ An id the fork once used for an entry with another default is left unused rather - **Default.** Does nothing, so every result and every callback is upstream's. Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured. +### The original account info by reference + +- **API.** `revm_state::Account::original_info_ref(&self) -> &AccountInfo`. +- **Contract.** It returns what `Account::original_info` returns, by reference, cloning nothing: the info the account holds as its original, or the default info for an account whose original was never set. +- **Consumer.** mega-evm tells whether a transaction changed an account by comparing the account's info with its original, for every frame start, value transfer and destruction it counts. `original_info` returns a copy, and copying the info's code moves the code's reference count up and down; the original is a private field, so only the crate can lend it. +- **Removal.** When upstream has an equivalent accessor, or when mega-evm stops comparing an account with its original. +- **Default.** Nothing in this workspace calls it, so every result is upstream's. The default info it lends an account without an original is built on the first such read and kept for the process. + ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. diff --git a/crates/state/src/lib.rs b/crates/state/src/lib.rs index 57d3fb8557..7b96d294f7 100644 --- a/crates/state/src/lib.rs +++ b/crates/state/src/lib.rs @@ -7,6 +7,7 @@ extern crate alloc as std; mod account_info; pub mod bal; +mod original_info; mod types; pub use bytecode; diff --git a/crates/state/src/original_info.rs b/crates/state/src/original_info.rs new file mode 100644 index 0000000000..7f02e752de --- /dev/null +++ b/crates/state/src/original_info.rs @@ -0,0 +1,66 @@ +//! The account's original info, read by reference. + +use crate::{Account, AccountInfo}; +use primitives::OnceLock; + +impl Account { + /// Returns a reference to the original account info: the info + /// [`original_info`](Self::original_info) returns, without cloning it. + /// + /// An account whose original info was never set reads the default info, as it does through + /// `original_info`. + #[inline] + pub fn original_info_ref(&self) -> &AccountInfo { + match self.original_info.as_deref() { + Some(info) => info, + None => default_info(), + } + } +} + +/// The default account info, built once and shared. +fn default_info() -> &'static AccountInfo { + static DEFAULT: OnceLock<AccountInfo> = OnceLock::new(); + DEFAULT.get_or_init(AccountInfo::default) +} + +#[cfg(test)] +mod tests { + use crate::{Account, AccountInfo, TransactionId}; + use bytecode::Bytecode; + use primitives::{Bytes, U256}; + + fn info(balance: u64, nonce: u64) -> AccountInfo { + AccountInfo::from_balance(U256::from(balance)) + .with_code(Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00]))) + .with_nonce(nonce) + } + + /// An account whose original info was never set reads the default info, code included, + /// whatever its info is now. + #[test] + fn test_an_unset_original_reads_the_default_info() { + let mut account = Account::new_not_existing(TransactionId::ZERO); + account.info = info(5, 1); + let original = account.original_info_ref(); + assert_eq!(*original, account.original_info()); + assert!(original.is_default()); + } + + /// A set original is read where the account holds it, not from a copy, and follows every + /// change made through `original_info_mut`. + #[test] + fn test_a_set_original_is_read_in_place() { + let mut account = Account::from(info(5, 1)); + account.info = info(7, 2); + assert_eq!(*account.original_info_ref(), info(5, 1)); + assert!(core::ptr::eq( + account.original_info_ref(), + account.original_info.as_deref().unwrap() + )); + + account.original_info_mut().nonce = 9; + assert_eq!(account.original_info_ref().nonce, 9); + assert_eq!(*account.original_info_ref(), account.original_info()); + } +} From a42714c18e8640c3d52ecf7df7a3212001d5c9b9 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:06:58 +0800 Subject: [PATCH 072/110] docs: a creation's pool forward is counted under Resource pools, in MEGAETH-FORK.md --- MEGAETH-FORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 100b362651..c9de2cd060 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -258,7 +258,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. - For `CREATE` and `CREATE2` the hook's only cost is the start's address; the byte pool's forward is counted under The byte pool. + For `CREATE` and `CREATE2` the hook's only cost is the start's address; the pools' forward is counted under Resource pools. With EIP-8037 off, the default spec's path, the address costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per creation. The instruction computes the address and a `CREATE2`'s init-code hash, and the handler reuses them, so a creation the handler builds or fails computes the same hashes as upstream's. A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. From 78276b43f2450a5502bbf99ec9798b5fe3c49d44 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 10:07:31 +0800 Subject: [PATCH 073/110] test(state): compare every field of the original info lent by reference The parity assertion goes through AccountInfo's PartialEq, which ignores the account id and cached code, and the tests never used created or destroyed accounts. Compare balance, nonce, code hash, code and account id explicitly, across never-loaded, stored, created, self-destructed, rebaselined and mutated originals. --- crates/state/src/original_info.rs | 89 +++++++++++++++++++++++++++---- 1 file changed, 78 insertions(+), 11 deletions(-) diff --git a/crates/state/src/original_info.rs b/crates/state/src/original_info.rs index 7f02e752de..131ca2a114 100644 --- a/crates/state/src/original_info.rs +++ b/crates/state/src/original_info.rs @@ -26,7 +26,7 @@ fn default_info() -> &'static AccountInfo { #[cfg(test)] mod tests { - use crate::{Account, AccountInfo, TransactionId}; + use crate::{Account, AccountId, AccountInfo, TransactionId}; use bytecode::Bytecode; use primitives::{Bytes, U256}; @@ -36,31 +36,98 @@ mod tests { .with_nonce(nonce) } - /// An account whose original info was never set reads the default info, code included, - /// whatever its info is now. + /// [`info`] with an account id, which `AccountInfo`'s `PartialEq` ignores. + fn info_with_id(balance: u64, nonce: u64, id: usize) -> AccountInfo { + let mut info = info(balance, nonce); + info.account_id = AccountId::new(id); + info + } + + /// Asserts the reference is the info `original_info` returns, field by field: `AccountInfo`'s + /// `PartialEq` ignores the account id and the cached code. + #[track_caller] + fn assert_parity(account: &Account) { + let by_ref = account.original_info_ref(); + let cloned = account.original_info(); + assert_eq!(by_ref.balance, cloned.balance); + assert_eq!(by_ref.nonce, cloned.nonce); + assert_eq!(by_ref.code_hash, cloned.code_hash); + assert_eq!(by_ref.code, cloned.code); + assert_eq!(by_ref.account_id, cloned.account_id); + } + + /// An account whose original info was never set reads the default info, code and account id + /// included, whatever its info and status are now. #[test] fn test_an_unset_original_reads_the_default_info() { let mut account = Account::new_not_existing(TransactionId::ZERO); - account.info = info(5, 1); + account.info = info_with_id(5, 1, 3); + assert_parity(&account); let original = account.original_info_ref(); - assert_eq!(*original, account.original_info()); assert!(original.is_default()); + assert_eq!(*original, AccountInfo::default()); + assert_eq!(original.code, Some(Bytecode::default())); + assert_eq!(original.account_id, None); + + account.mark_created(); + assert_parity(&account); + assert!(account.original_info_ref().is_default()); + assert_eq!(account.original_info_ref().account_id, None); + + account.mark_selfdestruct(); + assert_parity(&account); + assert!(account.original_info_ref().is_default()); + + account.unmark_created(); + assert_parity(&account); + assert!(account.original_info_ref().is_default()); + assert_eq!(account.original_info_ref().account_id, None); } - /// A set original is read where the account holds it, not from a copy, and follows every - /// change made through `original_info_mut`. + /// A set original is read where the account holds it, not from a copy, whatever the account's + /// status, and follows every change made through `original_info_mut` and + /// `set_current_info_as_original`. #[test] fn test_a_set_original_is_read_in_place() { - let mut account = Account::from(info(5, 1)); - account.info = info(7, 2); - assert_eq!(*account.original_info_ref(), info(5, 1)); + let mut account = Account::from(info_with_id(5, 1, 7)); + account.info = info_with_id(7, 2, 8); + assert_parity(&account); + assert_eq!(account.original_info_ref().balance, U256::from(5)); + assert_eq!(account.original_info_ref().nonce, 1); + assert_eq!(account.original_info_ref().account_id, AccountId::new(7)); assert!(core::ptr::eq( account.original_info_ref(), account.original_info.as_deref().unwrap() )); + account.mark_created(); + assert_parity(&account); + assert_eq!(account.original_info_ref().nonce, 1); + assert_eq!(account.original_info_ref().account_id, AccountId::new(7)); + + account.mark_selfdestruct(); + assert_parity(&account); + assert_eq!(account.original_info_ref().nonce, 1); + + account.unmark_created(); + assert_parity(&account); + assert_eq!(account.original_info_ref().balance, U256::from(5)); + assert_eq!(account.original_info_ref().account_id, AccountId::new(7)); + account.original_info_mut().nonce = 9; + account.original_info_mut().account_id = AccountId::new(11); + assert_parity(&account); assert_eq!(account.original_info_ref().nonce, 9); - assert_eq!(*account.original_info_ref(), account.original_info()); + assert_eq!(account.original_info_ref().account_id, AccountId::new(11)); + + account.set_current_info_as_original(); + assert_parity(&account); + assert_eq!(account.original_info_ref().balance, U256::from(7)); + assert_eq!(account.original_info_ref().nonce, 2); + assert_eq!(account.original_info_ref().account_id, AccountId::new(8)); + assert!(core::ptr::eq( + account.original_info_ref(), + account.original_info.as_deref().unwrap() + )); } } From b5fbc10713a1a5c4a7da26dc45f4c1d7f7599685 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:35:15 +0800 Subject: [PATCH 074/110] docs: rule 2 names the MegaETH accounting the fork carries, and rule 1 the reservoir exception Rule 2 said the fork adds hooks and data and implements no MegaETH semantics, but the fork carries MegaETH accounting inside revm's forwarding and settlement: withheld gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge and its refund, and the history allowance. The rule now names that set, bounds it, and states what an addition to it has to argue, keeping a design decision in mega-evm. Rule 1 now states the exception that no compiler or semver check finds: the reservoir settlement adds what a frame returns to what its caller kept, and the forward takes the reservoir out of the caller, where upstream's copy and replace. It names who that affects. REVIEW.md's checklist item and the mega:hook label follow the rule. --- MEGAETH-FORK.md | 34 +++++++++++++++++++++++++++++----- REVIEW.md | 3 ++- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index c9de2cd060..04d56a1960 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -8,7 +8,7 @@ Crate names stay `revm-*`; consumers switch to the fork through a `[patch.crates revm does not expose the hooks MegaETH needs (multi-dimensional gas, gas preserved on halt, read-only journal access). Without them, `mega-evm` had to wrap every opcode and copy upstream functions. -The fork adds those hooks as a thin layer; all MegaETH logic stays in `mega-evm`. +The fork adds those hooks, and the MegaETH accounting that has to move with a frame's gas inside revm's forwarding and settlement, a set rule 2 names and bounds; every other MegaETH rule stays in `mega-evm`. ## Baseline @@ -36,9 +36,33 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T `reth`, `alloy-evm` and `revm-inspectors` are compiled against this fork unmodified; `op-revm` is forked separately at [megaeth-labs/op-revm](https://github.com/megaeth-labs/op-revm) and ported there. The `Semver` workflow checks every pull request against its base; a deviation passes only with the `api:exception` label, and the pull request body lists every deviating item with the consumers it was checked against. Each consumer's own CI builds against the tagged fork. -2. **Thin layer.** - The fork adds hooks and data; it does not implement MegaETH semantics. - If a change needs a design decision, it belongs in `mega-evm`. + The fork carries accepted exceptions, and each entry under Hooks names its own. + One of them changes what upstream functions do without changing a signature, so neither the compiler nor the `Semver` workflow finds it: the reservoir settlement adds. + `handle_reservoir_remaining_gas` and `GasTracker::absorb_returned_reservoir` add the reservoir a frame returns to what its caller kept, where upstream's replace the caller's reservoir with it, and the forward takes the reservoir out of the caller where upstream's left it there (see The reservoir share). + A consumer that starts and settles frames only through revm's instructions and handler, on a schedule that keeps none of the reservoir, gets upstream's results, since the caller then holds nothing when the child returns. + It affects three kinds of consumer: + - code that hands a frame a reservoir or a pool without taking it from the caller, such as a child's input or a first-frame result built by hand, an override of `Handler::first_frame_input` or `Handler::runtime_oog_result`, or a runner that settles its own first frame: it compiles and counts the reservoir twice (see The settlement adds); + - an inspector that reads a caller's gas while its child runs, at a `CALL` or `CREATE` instruction's `step_end`: it sees the part the caller kept, zero by default, where upstream's showed the forwarded reservoir; + - a consumer whose schedule keeps part of the reservoir (`GasId::reservoir_kept_percent`), whose results differ from upstream's by design. +2. **Hooks and data, and a bounded set of MegaETH accounting.** + The fork adds hooks and data. + It also carries a named, bounded set of MegaETH accounting inside revm's forwarding and settlement, each item because it has to move with a frame's gas at a point only revm reaches: + - withheld regular gas and its crossing record, which every regular charge reads; + - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`; + - the resource pools, per-frame budgets forwarded to a child, given back by a failed one and settled with the reservoir; + - the reservoir kept share, and the additive settlement it needs (rule 1); + - the start charge, and its refund when the frame fails; + - the history allowance. + + Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing. + Nothing else that implements MegaETH semantics enters the fork. + An addition to the set needs all of these, argued in its pull request: + - no hook that sees only the state revm exposes at that point can make the same decision, because the figure is read or written inside a charge, or has to be ordered with revm's own settlement; the pull request says why the consumer cannot keep it beside revm's gas; + - it is mechanism, not policy: every amount, share, price and limit comes from the consumer, through the gas schedule or a hook, and a detail the fork has to fix itself, such as a rounding, is named in its entry; + - zero, unlimited or none as its default leaves every result upstream's, and its entry states what a consumer that sets nothing pays for it, in bytes on the frame results and in instructions; + - its entry names the condition under which the fork drops it. + + A design decision still belongs in `mega-evm`: the fork carries the figures and moves them with the gas, and `mega-evm` decides what they are and what happens when one runs out. 3. **Cargo versions stay fixed between base-line moves.** The `[patch.crates-io]` mechanism only applies when the patched version satisfies the consumer's requirement, and pre-release suffixes do not satisfy `^40.0.3`. Releases are identified by git tags only. @@ -477,7 +501,7 @@ Every pull request carries exactly one `mega:` label and one `api:` label; the ` | Label | Meaning | |---|---| | `mega:cherry-pick` | Upstream commits brought into the fork unchanged apart from recorded conflicts | -| `mega:hook` | A hook or data field added in the thin layer | +| `mega:hook` | A hook, data field or switch, or an item of rule 2's MegaETH accounting | | `mega:vendor` | A vendored crate (`crates/op-revm`) added or updated | | `mega:ci` | Workflows, `scripts/mega`, the fork documents | | `mega:rebase` | The base line moves to a new upstream tag | diff --git a/REVIEW.md b/REVIEW.md index 2fa8bb24fe..3040e48305 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -9,8 +9,9 @@ It is read by the automated reviewer as well as by people. 1. **Superset.** The public API of every published crate stays a superset of the crates.io baseline recorded in `scripts/mega/crates.txt`. The `Semver` workflow checks API changes against the pull request base; reviewers check baseline compatibility and the documented exceptions. A PR that must break the superset carries the `api:exception` label and lists in its body every deviating item with the consumers it was checked against (`reth`, `alloy-evm`, `revm-inspectors`, the `op-revm` fork). -2. **Thin layer.** The fork adds hooks and data, never MegaETH semantics. +2. **Hooks and data, and rule 2's set.** The fork adds hooks and data, and no MegaETH semantics beyond the bounded set of accounting `MEGAETH-FORK.md` rule 2 names. If a change makes a design decision (a price, a limit, a policy), ask for it to move to `mega-evm` and for the fork to expose only the hook it needs. + A change that adds to rule 2's set must argue every condition rule 2 lists, the first above all: why a hook on the state revm exposes cannot make the same decision. 3. **`no_std`.** No unguarded `std::`, no new dependency that enables `std` by default, no allocation in a path that did not allocate before. The CI checks both riscv targets; the reviewer checks the intent. 4. **One topic per PR, conventional prefix on every fork-authored commit.** Fork-authored commits and PR titles start with `feat`, `fix`, `chore`, `docs`, `ci` or `test` and say what changed; cherry-picked commits keep upstream's subject (`MEGAETH-FORK.md` rule 4); `git log --oneline <base>..main` (`<base>` from `scripts/mega/base.txt`) is the fork's changelog and must stay readable. From 2b487861ae0845b9e05020a96a4e7b2bbbb837d9 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:35:22 +0800 Subject: [PATCH 075/110] docs: what the fork carries, by class, as the plan for the next base-line move The fork's footprint mixes upstream picks that a newer base already contains, generic hooks worth proposing upstream, switches kept for one consumer, and MegaETH accounting, and the next base-line move treats each differently. The new section sizes each class and says what happens to it at the move: the picks go away once the base contains them, the hooks are proposed in a form upstream can take, the switches stay until their removal conditions, and the accounting is re-applied or replaced if a later design keeps it in mega-evm with the same results. --- MEGAETH-FORK.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 04d56a1960..ee27ef31af 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -85,9 +85,23 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T A tag is the only identity a fork release has (rule 3), and the release workflow tags only commits whose `ci success` is green. Consumer tag pinning is not enforced mechanically; each consumer's `Cargo.lock` records the commit it built against. +## What the fork carries + +`git diff <base>..main` is the fork's footprint on upstream (rule 4). +It falls into five classes, and the next base-line move (see Tracking upstream) treats each one differently. +The sizes are the lines of `crates/`, without tests, that `git blame <base>..main` attributes to each class's commits. + +| Class | What | Size | At the next base-line move | +|---|---|---|---| +| Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `EthFrame::return_result`, `create_init_frame`, `last_frame_result`), so that accounting is re-applied to the new base's versions of it. | +| Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | +| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action and the frame-run-result hook | about 1,750 lines | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | +| Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, revm 40.0.3's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; revm 40.0.3's journal semantics are not proposed. | +| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge, the history allowance | about 2,150 lines, of which the pools, the kept share, the start charge and the allowance are about 1,450 | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. The items that ride on the frame results (the pools, the start charge, the allowance) are the first candidates, since every consumer pays their size. | + ## Hooks -This section lists every hook, switch and accessor the fork carries. +This section lists every hook, switch and accessor the fork carries, and each item of rule 2's MegaETH accounting. Each entry names the API a consumer uses and what the fork guarantees about it. A hook's default keeps upstream's behaviour: a consumer that does not use it sees the same results. Each entry's **Consumer** says who needs it and why it cannot be done outside the fork, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it. From b747c755634fa983317e7a023e45ca9672b884b4 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:35:27 +0800 Subject: [PATCH 076/110] docs: once a consumer spec is sealed, a result-changing pick lands behind a switch or is not taken Tracking upstream took every fix that changes an execution result, applied verbatim. Once the consumer spec that runs on the fork is sealed, such a pick would change a frozen spec's results. The rule now puts it behind a switch that keeps the sealed result, on the pattern of legacy_journal_semantics (default upstream's, turned on by the consumer per sealed spec), or leaves it untaken; a pick that no sealed spec can reach needs no switch, and the consumer's outcome check settles which case a pick is. The verbatim rule records the switch as the pick's conflict resolution, and the baseline section and the reviewer's checklist point to the rule. --- MEGAETH-FORK.md | 11 +++++++++++ REVIEW.md | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index ee27ef31af..e479bf6242 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -471,6 +471,7 @@ An id the fork once used for an entry with another default is left unused rather ## Baseline behaviour the fork changes Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes. +Once a consumer spec that runs on the fork is sealed, a pick that changes a result it can reach lands behind a switch that keeps the sealed result, or is not taken (see Tracking upstream). A pick that changes what the journal records lands with a switch back to the base line (see revm 40.0.3's journal semantics). One pick changes what the top-level entry points do with the journal, and has no switch. The pending-action check changes what an inspector that sets an action before a frame runs sees and gets, and has no switch either: @@ -490,6 +491,7 @@ The pending-action check changes what an inspector that sets an action before a The fork keeps its crate versions at the revm version the MegaETH node pins, today `40.0.3`; a newer upstream tag would bump every crate's major, so the fork takes single upstream commits until the node moves. Taken: changes to the EIP-8037 / EIP-2780 gas core whatever their prefix; fixes that change execution results (gas, state, logs, halt reasons, precompile output, bytecode analysis, serialized formats); correctness and safety fixes relevant to the consumers, including undefined behaviour, missing out-of-gas checks, panics, and dependency or build failures; performance improvements to execution, precompiles and the database; each with the test-fixture bump that comes with it. +A change that moves an execution result is taken this way only until the consumer spec that runs on the fork is sealed; after that it follows the sealed-spec rule below, whatever its kind. Not taken: tooling-only changes, feature-gated additions the consumers do not use, and change/revert pairs, after checking that no taken commit depends on them. Picks are batched by crate or subsystem, one pull request per batch, so one reviewer can read a whole batch. The fork has no benchmark gate: a performance pick must leave execution results unchanged under the crate tests and the EEST run, and cite upstream's benchmark numbers in the pull request body. @@ -497,7 +499,16 @@ A pick that touches a precompile is tested under mutually exclusive feature sets A pick that breaks the public API needs `api:exception`, the deviating items listed in the pull request body, and a check of every consumer that uses them. An upstream change that upstream later reverted but the fork still needs lands as a fork-owned opt-in switch (`mega:hook`) whose default keeps upstream's behaviour. A picked upstream fix that changes journal semantics lands with an opt-in switch back to the base line's behaviour when a consumer reproduces the base line exactly; the switch defaults to the picked behaviour, the consumer that needs the base line sets it, and nothing else reads it. `CfgEnv::legacy_journal_semantics` (the cold-slot re-baseline and the `CodeChange` revert of revm 40.0.3) is the first. + +**Sealed specs.** Once a consumer spec that runs on the fork is sealed, the fork must not move that spec's results. +A pick that changes an execution result the sealed spec can reach then lands behind a switch, or is not taken. +The switch follows the `legacy_journal_semantics` pattern: it keeps the result the spec was sealed with, its default is the picked behaviour, which is upstream's, and the consumer turns it on for each sealed spec, so a later spec can take the fix by leaving it off. +A pick that cannot be put behind such a switch is not taken while a sealed spec runs on the fork, and its sweep records why. +A pick that changes only results no sealed spec reaches, such as a fix to a feature the sealed specs leave off, lands without a switch, and its pull request says why no sealed spec reaches it. +Whether a pick moves a sealed spec's results is settled by the consumer's outcome check on that spec, run against the pick, and the pull request records the result. + Every pick is applied verbatim: `git show -U0 <commit> | git patch-id --verbatim` gives the same id for the pick and its upstream commit unless the pick's message records a conflict resolution; the pull request body, which becomes the squash message, lists each pick's `(cherry picked from commit <sha>)` line and its conflicts. +A pick that lands behind a switch keeps the verbatim pick as its own branch commit, followed by the switch in a commit of its own, and the squash message records the switch as the pick's conflict resolution. For every upstream tag, a maintainer sweeps `<last swept tag>..<tag>` across the whole repository, fixtures, manifests and lockfile included, and records each commit as taken, candidate (with an owner and a disposition) or excluded (with the reason), with both tag SHAs, in the issue titled `Sweep <tag>` that the nightly workflow opens when the tag appears. The pull request that carries the picks links that issue; a sweep that takes nothing is closed with its classification in the issue. diff --git a/REVIEW.md b/REVIEW.md index 3040e48305..6cfd9e6cf2 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -21,7 +21,7 @@ It is read by the automated reviewer as well as by people. | Label | Look for | |---|---| -| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream <sha> — <title>`) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep <tag>` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along | +| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream <sha> — <title>`) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep <tag>` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along; once a consumer spec is sealed, a pick that moves a result that spec reaches carries the switch that keeps it, or is not taken (`MEGAETH-FORK.md`, Tracking upstream) | | `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)`, so that in a format that carries field names (JSON) payloads that predate it decode with the default; a positional format (bincode) cannot read them whatever the attribute, as `MEGAETH-FORK.md` (Hooks) says | | `mega:vendor` | The vendored crate keeps its upstream version number and a note of the upstream commit it was taken from; its own tests run in CI | | `mega:ci` | Workflows pin action SHAs; nothing requires a secret the repository does not have; the local equivalent of every job is documented | From 596f79db3c453e13d2621ac26999f3a3b64ea34a Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:41:51 +0800 Subject: [PATCH 077/110] docs: the state-gas price entry records its upstream signature change and the one charge that differs The entry listed Eip7702AuthFacts but not that the authorization phase's pre_execution::apply_auth_list_eip2780, a function picked with the gas core, takes the context and that list instead of upstream's journal, iterator and two prices. Rule 1 now states it in the form of the reservoir exception: the base line has no such function, a consumer that runs the phase through apply_eip7702_auth_list is unaffected, and a direct caller written for upstream's signature no longer compiles. The entry's Default said every charge and refund is upstream's. With EIP-2780 on, the first frame's creation is checked and charged at the address it deploys at, from the caller's account nonce, where upstream's uses the transaction's nonce; with the nonce check off and the two nonces different, as for an OP deposit, whether the creation pays create_state_gas and which address the phase warms can differ. The Default now says so. --- MEGAETH-FORK.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index e479bf6242..15bbb4a797 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -44,6 +44,12 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T - code that hands a frame a reservoir or a pool without taking it from the caller, such as a child's input or a first-frame result built by hand, an override of `Handler::first_frame_input` or `Handler::runtime_oog_result`, or a runner that settles its own first frame: it compiles and counts the reservoir twice (see The settlement adds); - an inspector that reads a caller's gas while its child runs, at a `CALL` or `CREATE` instruction's `step_end`: it sees the part the caller kept, zero by default, where upstream's showed the forwarded reservoir; - a consumer whose schedule keeps part of the reservoir (`GasId::reservoir_kept_percent`), whose results differ from upstream's by design. + + Another changes the signature of an upstream function the fork picked with the EIP-8037 / EIP-2780 gas core: `pre_execution::apply_auth_list_eip2780`. + The fork's takes the context, the authorization list as `&[Eip7702AuthFacts]` and whether EIP-8037 is on, where upstream's takes the journal, an iterator of authorizations and the two state-gas prices, so that every authorization's charge is priced through `Host::state_gas_price` (see State-gas price). + The base line has no such function, so the change breaks no code written for it. + A consumer that runs the authorization phase through `pre_execution::apply_eip7702_auth_list` or `Handler::apply_eip7702_auth_list`, whose signatures are upstream's, is unaffected. + It affects code that calls `apply_auth_list_eip2780` itself, written for upstream's signature: it does not compile against the fork until it passes the context and the list `Eip7702AuthFacts::collect` builds. 2. **Hooks and data, and a bounded set of MegaETH accounting.** The fork adds hooks and data. It also carries a named, bounded set of MegaETH accounting inside revm's forwarding and settlement, each item because it has to move with a frame's gas at a point only revm reaches: @@ -118,13 +124,17 @@ An id the fork once used for an entry with another default is left unused rather - **API.** `Host::state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64>` and `Host::state_gas_charge(&mut self, charge: StateGasCharge) -> Option<u64>`. The value types `StateGasSite` (`account`, `slot`) and `StateGasCharge` (`one`, `units`, `total`) in `revm_context_interface::cfg`. For the refund: `charged_state_gas_address` on `CreateInputs`, `CallOutcome` and `CreateOutcome`, and `FrameResult::refundable_state_gas_charge`. - `pre_execution::Eip7702AuthFacts`, the authorization list lifted out of the transaction so the authorization phase can hand the whole context to the hook. + `pre_execution::Eip7702AuthFacts`, the authorization list lifted out of the transaction so the authorization phase can hand the whole context to the hook, and the signature of `pre_execution::apply_auth_list_eip2780`, which takes the context and that list in place of upstream's journal, authorization iterator and two state-gas prices (an exception to rule 1). - **Contract.** Every EIP-8037 state-gas charge and every refund of one is priced through `state_gas_price`, so a charge and the refund that undoes it agree by construction. `site` names the account the charge lands on, and the storage slot for a slot-scoped charge; a creation is priced at the address it deploys at, the first frame's included. `None` reports a failed lookup: the implementation records the cause in the context error, and the charge site turns it into a fatal external error. - **Consumer.** mega-evm prices state gas by the storage bucket of the account or slot a charge lands on. Only the charge site knows the site, and the price must be the same at the charge and at its refund. - **Removal.** When upstream prices state gas through an equivalent hook, or when mega-evm prices every state-gas charge from the flat schedule. -- **Default.** Reads the flat schedule (`gas_params().get(id)`) and never fails, so every charge and refund is upstream's. +- **Default.** Reads the flat schedule (`gas_params().get(id)`) and never fails, so every price is upstream's, and so is every charge and refund but one. + With EIP-2780 on, the first frame's creation is checked and charged at the address it deploys at, which the caller's account nonce gives, where upstream's derives the address from the transaction's nonce. + The two agree while the nonce check is on. + With the nonce check off and a transaction nonce that differs from the caller's account nonce, as for an OP deposit, upstream's checks, charges and warms an address the transaction does not deploy at, and the fork's the address it deploys at. + There, whether the creation pays `create_state_gas` can differ from upstream's, and so can the gas of a later access to the other address, which upstream's leaves warm and the fork's leaves cold. The refund carries one address more in the frame inputs and outcomes, and under EIP-2780 an EIP-7702 transaction's authorization list is buffered before the authorization phase, one 88-byte entry per authorization that can apply. ### History gas From 4d8e06345c9e1cec32baa63a214adc8bd332c8f8 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:57:33 +0800 Subject: [PATCH 078/110] docs: rule 2 no longer claims necessity for accounting a consumer can keep, a sealed-spec pick needs an argument and tests, and the start charge entry matches the engine Rule 2 now says the fork carries a bounded set today and keeps the stricter test for additions; the exclusive-access sentences are removed. A pick without a switch needs a code-based argument that no sealed spec reaches the changed behaviour, plus regression tests; the outcome check is supporting evidence. The start charge Consumer paragraph describes the history-only hook charge and the creator record counted after the creation returns. The branch name and version tuple leave the new text, and the frame-start entry points at Resource pools. --- MEGAETH-FORK.md | 20 +++++++++++--------- REVIEW.md | 2 +- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 15bbb4a797..1732d1770d 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -52,7 +52,7 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T It affects code that calls `apply_auth_list_eip2780` itself, written for upstream's signature: it does not compile against the fork until it passes the context and the list `Eip7702AuthFacts::collect` builds. 2. **Hooks and data, and a bounded set of MegaETH accounting.** The fork adds hooks and data. - It also carries a named, bounded set of MegaETH accounting inside revm's forwarding and settlement, each item because it has to move with a frame's gas at a point only revm reaches: + It also carries, today, a named, bounded set of MegaETH accounting inside revm's forwarding and settlement; the set is what the fork carries now, and the test for an addition (below) is stricter: - withheld regular gas and its crossing record, which every regular charge reads; - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`; - the resource pools, per-frame budgets forwarded to a child, given back by a failed one and settled with the reservoir; @@ -60,6 +60,7 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T - the start charge, and its refund when the frame fails; - the history allowance. + Some of these a consumer could keep beside revm's gas through the hooks, at a cost in code and in the gas figures it has to restore; the next base-line move may take them out (see What the fork carries). Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing. Nothing else that implements MegaETH semantics enters the fork. An addition to the set needs all of these, argued in its pull request: @@ -93,16 +94,16 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T ## What the fork carries -`git diff <base>..main` is the fork's footprint on upstream (rule 4). +`git diff <base>..<fork head>` is the fork's footprint on upstream (rule 4). It falls into five classes, and the next base-line move (see Tracking upstream) treats each one differently. -The sizes are the lines of `crates/`, without tests, that `git blame <base>..main` attributes to each class's commits. +The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fork head>` attributes to each class's commits. | Class | What | Size | At the next base-line move | |---|---|---|---| | Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `EthFrame::return_result`, `create_init_frame`, `last_frame_result`), so that accounting is re-applied to the new base's versions of it. | | Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | | Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action and the frame-run-result hook | about 1,750 lines | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | -| Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, revm 40.0.3's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; revm 40.0.3's journal semantics are not proposed. | +| Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. | | MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge, the history allowance | about 2,150 lines, of which the pools, the kept share, the start charge and the allowance are about 1,450 | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. The items that ride on the frame results (the pools, the start charge, the allowance) are the first candidates, since every consumer pays their size. | ## Hooks @@ -306,7 +307,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. - For `CREATE` and `CREATE2` the hook's only cost is the start's address; the pools' forward is counted under Resource pools. + For `CREATE` and `CREATE2` the hook's only cost is the start's address; the resource pools' forward is counted under Resource pools. With EIP-8037 off, the default spec's path, the address costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per creation. The instruction computes the address and a `CREATE2`'s init-code hash, and the handler reuses them, so a creation the handler builds or fails computes the same hashes as upstream's. A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. @@ -381,7 +382,7 @@ An id the fork once used for an entry with another default is left unused rather A consumer takes what it hands over: `forward_to_child` takes the schedule's shares, as the instructions do; `forward_all_to_child` takes everything, as the transaction's frame does; `forward_reservoir` and `forward_pool` take a share the consumer computed. A consumer that lowers a child's share after the forward and gives the excess back to the caller keeps the sum, and is right; so is code that settles with arithmetic of its own that replaces the caller's reservoir and calls none of these functions. A debug build asserts on entry to `settle_first_frame` that the transaction's gas holds no reservoir and no limited pool; an unlimited pool is exempt, since what comes back saturates at it. A frame below the transaction's has no such check: its caller may hold a kept part, or an excess given back, beside the share, and only the code that built the input knows which. -- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. Only the instruction knows the reservoir as the frame-start hook left it before the input is built, and only the settlement can add the child's reservoir to what the caller kept. +- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. The kept part is taken from the reservoir as the frame-start hook left it, before the input is built, and added back to the caller's reservoir when the child's reservoir is settled. - **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. - **Default.** Every schedule keeps none of the reservoir and so forwards it whole, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. A table without the entry, built raw or decoded from an encoding that predates it, keeps none too (see Hooks). @@ -410,7 +411,7 @@ An id the fork once used for an entry with another default is left unused rather An outcome an inspector builds to answer a start carries no charge unless the inspector copies the input's (`CallOutcome::new` and `CreateOutcome::new` carry none), so the caller keeps the charge, as revm keeps its own upfront state charge on an outcome a tool builds; an outcome the inspector rewrites at `call_end` or `create_end` keeps the frame's charge, so a success rewritten into a failure is refunded. An answer a consumer builds itself, such as an interceptor's, is refunded by the same rule: it carries the charge the consumer puts on it, and none when built with `new`. A consumer that settles a result into a caller's tracker itself refunds the charge with `refill_start_charge` on the same condition, so a pool added to the charge reaches it. -- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input takes its share of the reservoir, and must give them back when the frame fails. It draws a start's records on the child's pools, so its hook declares history alone, but a creation's creator record is drawn from the caller's pools at the hook: when revm answers the creation before it bumps the nonce, the engine adds what the record drew to the answer's charge, so the creation's failure gives it back (`give_back_creator_record`). The refund belongs where the fork refunds the upfront state charge. +- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input takes its share of the reservoir, and must give them back when the frame fails. Its hook charges history only and declares `StartCharge::new(charge, PoolAmounts::ZERO)`: the records a start draws on the child's pools are counted in the child, and a creation's creator record is counted on the creator's pools after the creation returns, once the engine sees the creator's nonce was bumped, whether the creation succeeded or not, so no pool amount rides on the charge. The refund belongs where the fork refunds the upfront state charge. - **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. - **Default.** The hook declares nothing, so the fields and the refund are zero. The charge is four words, history and one per pool, on every input and outcome; its size is part of the outcomes' measured above (see Resource pools). @@ -431,7 +432,7 @@ An id the fork once used for an entry with another default is left unused rather Only a consumer draws it: `draw_history_allowance(cost)` takes `min(cost, allowance)` and returns the part of `cost` the allowance did not cover, which the consumer charges as history. A precompile's answer is given the input's allowance after its provider ran, so the allowance it carries back is the input's, whatever the provider drew. The allowance is the frame's alone: it is not returned, merged or rolled back. -- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. Only the call instruction knows which starts get the stipend. +- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. The call instruction decides which starts get the stipend, and the start carries that decision. - **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. - **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. @@ -515,7 +516,8 @@ A pick that changes an execution result the sealed spec can reach then lands beh The switch follows the `legacy_journal_semantics` pattern: it keeps the result the spec was sealed with, its default is the picked behaviour, which is upstream's, and the consumer turns it on for each sealed spec, so a later spec can take the fix by leaving it off. A pick that cannot be put behind such a switch is not taken while a sealed spec runs on the fork, and its sweep records why. A pick that changes only results no sealed spec reaches, such as a fix to a feature the sealed specs leave off, lands without a switch, and its pull request says why no sealed spec reaches it. -Whether a pick moves a sealed spec's results is settled by the consumer's outcome check on that spec, run against the pick, and the pull request records the result. +A pick lands without a switch only with both of these in its pull request: a code-based argument that names the behaviour the pick changes and shows that no sealed spec reaches it, and targeted regression tests for that behaviour. +The consumer's outcome check on each sealed spec, run against the pick, is supporting evidence and is recorded too; a fixture corpus shows only the cases it reaches, so passing it does not define the pick as safe. Every pick is applied verbatim: `git show -U0 <commit> | git patch-id --verbatim` gives the same id for the pick and its upstream commit unless the pick's message records a conflict resolution; the pull request body, which becomes the squash message, lists each pick's `(cherry picked from commit <sha>)` line and its conflicts. A pick that lands behind a switch keeps the verbatim pick as its own branch commit, followed by the switch in a commit of its own, and the squash message records the switch as the pick's conflict resolution. diff --git a/REVIEW.md b/REVIEW.md index 6cfd9e6cf2..9ba1400776 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -21,7 +21,7 @@ It is read by the automated reviewer as well as by people. | Label | Look for | |---|---| -| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream <sha> — <title>`) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep <tag>` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along; once a consumer spec is sealed, a pick that moves a result that spec reaches carries the switch that keeps it, or is not taken (`MEGAETH-FORK.md`, Tracking upstream) | +| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream <sha> — <title>`) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep <tag>` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along; once a consumer spec is sealed, a pick that moves a result that spec reaches carries the switch that keeps it, or is not taken, and a pick without a switch carries a code-based argument that no sealed spec reaches the changed behaviour, with targeted regression tests (the consumer's outcome check is supporting evidence) (`MEGAETH-FORK.md`, Tracking upstream) | | `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)`, so that in a format that carries field names (JSON) payloads that predate it decode with the default; a positional format (bincode) cannot read them whatever the attribute, as `MEGAETH-FORK.md` (Hooks) says | | `mega:vendor` | The vendored crate keeps its upstream version number and a note of the upstream commit it was taken from; its own tests run in CI | | `mega:ci` | Workflows pin action SHAs; nothing requires a secret the repository does not have; the local equivalent of every job is documented | From 74f4f9a55ff0615c883da685017c0d0e9a0c50a1 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 22:57:37 +0800 Subject: [PATCH 079/110] docs: the overview no longer says the carried accounting has to move with a frame's gas --- MEGAETH-FORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 1732d1770d..cfb810dff8 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -8,7 +8,7 @@ Crate names stay `revm-*`; consumers switch to the fork through a `[patch.crates revm does not expose the hooks MegaETH needs (multi-dimensional gas, gas preserved on halt, read-only journal access). Without them, `mega-evm` had to wrap every opcode and copy upstream functions. -The fork adds those hooks, and the MegaETH accounting that has to move with a frame's gas inside revm's forwarding and settlement, a set rule 2 names and bounds; every other MegaETH rule stays in `mega-evm`. +The fork adds those hooks, and the MegaETH accounting it carries today inside revm's forwarding and settlement, a set rule 2 names and bounds; every other MegaETH rule stays in `mega-evm`. ## Baseline From b418c58ccb70dfbe163f5e1319cb3993843340fc Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 23 Oct 2026 23:00:13 +0800 Subject: [PATCH 080/110] docs: the allowance entry says what the hook sees of a start, not that only the instruction can decide --- MEGAETH-FORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index cfb810dff8..8704df1410 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -432,7 +432,7 @@ An id the fork once used for an entry with another default is left unused rather Only a consumer draws it: `draw_history_allowance(cost)` takes `min(cost, allowance)` and returns the part of `cost` the allowance did not cover, which the consumer charges as history. A precompile's answer is given the input's allowance after its provider ran, so the allowance it carries back is the input's, whatever the provider drew. The allowance is the frame's alone: it is not returned, merged or rolled back. -- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. The call instruction decides which starts get the stipend, and the start carries that decision. +- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. The call instruction decides which starts get the stipend; a start's `kind` and `value` are public on `FrameStart`. - **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. - **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. From b370b53852507dfedd342e062e96dba896cb30df Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 10:13:03 +0800 Subject: [PATCH 081/110] docs: the reservoir consumer entry says the kept part stays in the caller, and the hooks introduction no longer claims every entry cannot be done outside the fork The instruction takes only the forwarded share and settlement adds the child's returned reservoir to what the caller kept, so the old sentence contradicted the contract and rule 1. Rule 2 now allows some accounting beside revm's gas, so the introduction describes the Consumer entry as who uses it and why the fork carries it. --- MEGAETH-FORK.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 8704df1410..bca0691604 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -111,7 +111,7 @@ The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fo This section lists every hook, switch and accessor the fork carries, and each item of rule 2's MegaETH accounting. Each entry names the API a consumer uses and what the fork guarantees about it. A hook's default keeps upstream's behaviour: a consumer that does not use it sees the same results. -Each entry's **Consumer** says who needs it and why it cannot be done outside the fork, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it. +Each entry's **Consumer** says who uses it and why the fork carries it, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it. A field a hook adds to a serialized type carries `serde(default)`, so in a format that carries field names, such as JSON, an encoding made before the field existed decodes with the default. A format that encodes a struct by position, such as bincode, cannot read such an encoding, as with upstream's own field additions: it reads the old fields in their places and then looks for the new ones, so a value persisted in such a format must not cross an upgrade of the fork that adds a field. @@ -382,7 +382,7 @@ An id the fork once used for an entry with another default is left unused rather A consumer takes what it hands over: `forward_to_child` takes the schedule's shares, as the instructions do; `forward_all_to_child` takes everything, as the transaction's frame does; `forward_reservoir` and `forward_pool` take a share the consumer computed. A consumer that lowers a child's share after the forward and gives the excess back to the caller keeps the sum, and is right; so is code that settles with arithmetic of its own that replaces the caller's reservoir and calls none of these functions. A debug build asserts on entry to `settle_first_frame` that the transaction's gas holds no reservoir and no limited pool; an unlimited pool is exempt, since what comes back saturates at it. A frame below the transaction's has no such check: its caller may hold a kept part, or an excess given back, beside the share, and only the code that built the input knows which. -- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. The kept part is taken from the reservoir as the frame-start hook left it, before the input is built, and added back to the caller's reservoir when the child's reservoir is settled. +- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. The instruction takes the forwarded share from the reservoir as the frame-start hook left it, so the kept part stays in the caller's tracker while the child runs, and the child's returned reservoir is added to it at settlement, after it has unwound the caller's outstanding spill. - **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. - **Default.** Every schedule keeps none of the reservoir and so forwards it whole, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. A table without the entry, built raw or decoded from an encoding that predates it, keeps none too (see Hooks). From f9cb0b7adebfc1cd58e08dda58e7268daf6b1eb3 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 11:48:20 +0800 Subject: [PATCH 082/110] feat(context): a start lifecycle record in the frame stack, its hooks with no-op defaults, and a debug mirror The frame stack keeps the open start of the transaction and of each frame on it, with checked u32 identities. Every step that would break the pairing is refused with a StartLifecycleError (Exhausted, Stale, NotOpen, NoParent, Unsettled). Host gains frame_split, frame_settle and frame_lifecycle_end, each a no-op by default. The context's local context keeps a lifecycle mirror in debug builds only: a stack driven by the hooks that checks (identity, depth) on every event and resets at the transaction's start. Nothing calls the record yet. --- crates/context/interface/src/host.rs | 42 ++ .../context/interface/src/host/lifecycle.rs | 83 +++ crates/context/interface/src/lib.rs | 5 +- crates/context/interface/src/local.rs | 28 +- .../context/interface/src/local/lifecycle.rs | 522 ++++++++++++++++++ crates/context/interface/src/local/mirror.rs | 228 ++++++++ crates/context/src/context.rs | 27 + crates/context/src/local.rs | 14 + 8 files changed, 947 insertions(+), 2 deletions(-) create mode 100644 crates/context/interface/src/host/lifecycle.rs create mode 100644 crates/context/interface/src/local/lifecycle.rs create mode 100644 crates/context/interface/src/local/mirror.rs diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 175d4e6b87..517ffb78c8 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -1,8 +1,10 @@ //! Host interface for external blockchain state access. mod instruction_hooks; +mod lifecycle; pub use instruction_hooks::{CompletedWrite, FrameStart, FrameStartKind, WriteVerdict}; +pub use lifecycle::{FrameSettle, FrameSplit, LifecycleEnd, SettleStatus}; use crate::{ cfg::{gas::GasTracker, GasId, GasParams, StateGasCharge, StateGasSite}, @@ -143,6 +145,46 @@ pub trait Host { true } + /* Start lifecycle */ + + /// Called when revm opens a start ([`FrameSplit`]): it consumed a frame's init and + /// initialises the frame next. A frame's `NewFrame` action opens a child start under the + /// frame's own; the transaction's frame, or the stand-in for one that never runs, opens the + /// transaction's start, the first of its lifecycle. + /// + /// Every start opened is closed once by [`frame_settle`](Self::frame_settle), innermost first, + /// unless the lifecycle is discarded ([`frame_lifecycle_end`](Self::frame_lifecycle_end)). A + /// start revm never opened, such as a `NewFrame` an inspector dropped, is never settled. + /// + /// The default touches nothing. + #[inline] + fn frame_split(&mut self, split: &FrameSplit) { + let _ = split; + } + + /// Called when revm settles the start `settle.id` into its caller's `gas`: after revm's own + /// settlement of the frame's result, and, for the transaction's frame, before revm's halt rule + /// consumes the regular gas left on a halt. + /// + /// The hook may debit and credit `gas`, which goes on as the hook left it. + /// + /// The default touches nothing. + #[inline] + fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { + let _ = (settle, gas); + } + + /// Called once when a transaction's lifecycle ends: [`LifecycleEnd::Settled`] at the + /// successful boundary, every start settled, or [`LifecycleEnd::Discarded`] at the fatal one, + /// the starts still open discarded. Not called for a transaction that failed before its start + /// opened. + /// + /// The default touches nothing. + #[inline] + fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { + let _ = end; + } + /* Database */ /// Block hash, calls `ContextTr::journal_mut().db().block_hash(number)` diff --git a/crates/context/interface/src/host/lifecycle.rs b/crates/context/interface/src/host/lifecycle.rs new file mode 100644 index 0000000000..fa48076718 --- /dev/null +++ b/crates/context/interface/src/host/lifecycle.rs @@ -0,0 +1,83 @@ +//! The start lifecycle revm keeps for a transaction, as the [`Host`](super::Host) hooks see it. +//! +//! A start opens where revm consumes a frame's init, just before it initialises the frame +//! ([`Host::frame_split`](super::Host::frame_split)), and closes where revm settles the frame's +//! result into its caller ([`Host::frame_settle`](super::Host::frame_settle)). The transaction's +//! lifecycle ends at one of two boundaries ([`Host::frame_lifecycle_end`](super::Host::frame_lifecycle_end)): +//! the successful one, where every start opened has settled, or the fatal one, where the starts +//! still open are discarded. +//! +//! revm owns the pairing. It allocates each start's identity, keeps the open starts in its frame +//! stack ([`FrameStack`](crate::FrameStack)), which no inspector is handed, and settles each +//! start it opened once, innermost first. The values here are built by that record only. + +/// What became of a start revm settles into its caller, read from the frame's result. +/// +/// Exhaustive on purpose: a new variant is a breaking change, so that every consumer handles every +/// kind of settlement. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SettleStatus { + /// The frame succeeded. + Ok, + /// The frame reverted. + Revert, + /// The frame halted. + Halt, +} + +/// How a transaction's lifecycle ended. +/// +/// Exhaustive on purpose: a new variant is a breaking change, so that every consumer handles every +/// end. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LifecycleEnd { + /// The successful boundary: every start opened in the transaction settled. + Settled, + /// The fatal boundary: an error ended the transaction, and the starts still open are + /// discarded unsettled. + Discarded, +} + +/// A start revm opened: the frame it makes is the next one revm initialises. +/// +/// Built by revm's record only, so a later field is not a breaking change. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct FrameSplit { + /// The start's identity: a sequence number revm allocated in this transaction, from 1, and + /// never reused in it. + pub id: u32, + /// The identity of the start the calling frame runs for, `None` for the transaction's own + /// frame. + pub parent: Option<u32>, + /// The depth of the frame the start makes, from the frame's init: 0 for the transaction's + /// frame. + pub depth: usize, +} + +/// A start revm settled into its caller: the caller's gas has absorbed the frame's result. +/// +/// Built by revm's record only, so a later field is not a breaking change. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct FrameSettle { + /// The identity revm allocated for the start when it opened ([`FrameSplit::id`]). + pub id: u32, + /// The depth of the frame the start made. + pub depth: usize, + /// What became of the frame. + pub status: SettleStatus, + /// For a creation, whether it took an address; `None` for a call. + pub created: Option<bool>, + /// An inspector answered the start: its `frame_start`, `call` or `create` returned the + /// result, so no frame ran. + pub inspector_answer: bool, + /// An inspector's end callbacks (`frame_end`, `call_end`, `create_end`) replaced the result's + /// gas tracker with one revm did not mark for this start. + pub gas_replaced: bool, + /// An inspector's end callbacks replaced the result's outcome with one revm did not mark for + /// this start, such as one a constructor built around the same result. + pub outcome_rebuilt: bool, + /// The reservoir the caller's gas held just before revm settled the result into it. + pub held_reservoir: u64, +} diff --git a/crates/context/interface/src/lib.rs b/crates/context/interface/src/lib.rs index 7452846d66..2df6af9591 100644 --- a/crates/context/interface/src/lib.rs +++ b/crates/context/interface/src/lib.rs @@ -25,5 +25,8 @@ pub use database_interface::{erased_error::ErasedError, DBErrorMarker, Database} pub use either; pub use host::{DummyHost, Host}; pub use journaled_state::JournalTr; -pub use local::{FrameStack, FrameToken, LocalContextTr, OutFrame}; +pub use local::{ + FrameStack, FrameToken, LifecycleEvent, LifecycleMirror, LocalContextTr, OutFrame, + PendingStart, StartLifecycleError, +}; pub use transaction::{Transaction, TransactionType}; diff --git a/crates/context/interface/src/local.rs b/crates/context/interface/src/local.rs index a231888358..93438be113 100644 --- a/crates/context/interface/src/local.rs +++ b/crates/context/interface/src/local.rs @@ -5,11 +5,22 @@ use core::{ }; use std::{rc::Rc, string::String, vec::Vec}; +mod lifecycle; +mod mirror; + +pub use lifecycle::{PendingStart, StartLifecycleError}; +pub use mirror::{LifecycleEvent, LifecycleMirror}; + /// Non-empty, item-pooling Vec. +/// +/// It also keeps the transaction's start lifecycle: the open start of the transaction and of each +/// frame on the stack, which pairs every settlement with the start it closes +/// ([`open_start`](Self::open_start), [`close_start`](Self::close_start)). #[derive(Debug, Clone)] pub struct FrameStack<T> { stack: Vec<T>, index: Option<usize>, + lifecycle: lifecycle::StartLifecycle, } impl<T> Default for FrameStack<T> { @@ -26,6 +37,7 @@ impl<T> FrameStack<T> { Self { stack: Vec::with_capacity(8), index: None, + lifecycle: Default::default(), } } @@ -37,7 +49,11 @@ impl<T> FrameStack<T> { { let mut stack = Vec::with_capacity(len); stack.resize_with(len, T::default); - Self { stack, index: None } + Self { + stack, + index: None, + lifecycle: Default::default(), + } } /// Initializes the stack with a single item. @@ -224,6 +240,16 @@ pub trait LocalContextTr { /// Clear the local context. fn clear(&mut self); + /// The lifecycle mirror this local context keeps, if any: a debug check that the context's + /// lifecycle hooks feed ([`LifecycleMirror`]). revm's own local context keeps one in debug + /// builds only. + /// + /// The default keeps none. + #[inline] + fn lifecycle_mirror(&mut self) -> Option<&mut LifecycleMirror> { + None + } + /// Set the error message for a precompile error, if any. /// /// This is used to bubble up precompile error messages when the diff --git a/crates/context/interface/src/local/lifecycle.rs b/crates/context/interface/src/local/lifecycle.rs new file mode 100644 index 0000000000..c561eb7ca8 --- /dev/null +++ b/crates/context/interface/src/local/lifecycle.rs @@ -0,0 +1,522 @@ +//! The start lifecycle revm keeps in its [`FrameStack`]: the open start of the transaction and +//! of each frame on the stack, with the sequence their identities come from. +//! +//! The record decides nothing a consumer computes: it pairs every settlement with the start it +//! closes, and refuses every step that would break the pairing ([`StartLifecycleError`]). + +use super::FrameStack; +use crate::host::{FrameSettle, FrameSplit, LifecycleEnd, SettleStatus}; +use std::vec::Vec; + +/// A start revm opened and has not settled, with what an inspector did to it so far. +/// +/// Its identity is the record's: it can be read, not changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct PendingStart { + id: u32, + inspector_answer: bool, + gas_replaced: bool, + outcome_rebuilt: bool, +} + +impl PendingStart { + /// The start's identity ([`FrameSplit::id`]). + #[inline] + pub const fn id(&self) -> u32 { + self.id + } + + /// Whether an inspector answered the start ([`FrameSettle::inspector_answer`]). + #[inline] + pub const fn inspector_answer(&self) -> bool { + self.inspector_answer + } + + /// Whether an inspector's end callbacks replaced the result's gas + /// ([`FrameSettle::gas_replaced`]). + #[inline] + pub const fn gas_replaced(&self) -> bool { + self.gas_replaced + } + + /// Whether an inspector's end callbacks rebuilt the result's outcome + /// ([`FrameSettle::outcome_rebuilt`]). + #[inline] + pub const fn outcome_rebuilt(&self) -> bool { + self.outcome_rebuilt + } + + /// Records that an inspector answered the start. + #[inline] + pub const fn set_inspector_answer(&mut self) { + self.inspector_answer = true; + } + + /// Records that an inspector's end callbacks replaced the result's gas. + #[inline] + pub const fn set_gas_replaced(&mut self) { + self.gas_replaced = true; + } + + /// Records that an inspector's end callbacks rebuilt the result's outcome. + #[inline] + pub const fn set_outcome_rebuilt(&mut self) { + self.outcome_rebuilt = true; + } +} + +/// Why the start lifecycle refused a step. Each is a fatal error of the transaction: the step +/// would have paired a settlement with the wrong start, or with none. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum StartLifecycleError { + /// The transaction's sequence of identities is exhausted: it has opened `u32::MAX` starts. + Exhausted, + /// A start opened where one is still open: a settlement or a boundary was missed, such as an + /// error dropped without the cleanup that discards the lifecycle. + Stale, + /// A settlement found no open start: the start was never opened, or already settled. + NotOpen, + /// A child start opened under a frame that has no start of its own: a runner drove the + /// transaction's frame without opening the transaction's start first. + NoParent, + /// The successful boundary found a start still open: a settlement was missed. + Unsettled, +} + +impl core::fmt::Display for StartLifecycleError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(match self { + Self::Exhausted => "start lifecycle: the transaction's identities are exhausted", + Self::Stale => "start lifecycle: a start opened where one is still open", + Self::NotOpen => "start lifecycle: a settlement found no open start", + Self::NoParent => { + "start lifecycle: a child start opened under a frame with no start (open the \ + transaction's start first)" + } + Self::Unsettled => "start lifecycle: the transaction ended with a start open", + }) + } +} + +impl core::error::Error for StartLifecycleError {} + +/// The record: the transaction's start and the open start of each frame on the stack, the child +/// it is making. +#[derive(Clone, Debug, Default)] +pub(super) struct StartLifecycle { + /// The last identity allocated in the transaction, 0 before the first. + next: u32, + /// Whether a lifecycle is under way: its first start opened, and it has not ended. + active: bool, + /// The transaction's start. + root: Option<PendingStart>, + /// The open start of the frame at each stack index. + children: Vec<Option<PendingStart>>, +} + +impl StartLifecycle { + /// The slot the next start opens in, and the next settlement closes: the transaction's on an + /// empty stack, else that of the frame on top, at `index`. + #[inline] + fn slot(&mut self, index: Option<usize>) -> Option<&mut Option<PendingStart>> { + match index { + None => Some(&mut self.root), + Some(i) => self.children.get_mut(i), + } + } + + #[inline] + fn any_open(&self) -> bool { + self.root.is_some() || self.children.iter().any(Option::is_some) + } + + #[inline] + fn reset(&mut self) { + self.next = 0; + self.active = false; + self.root = None; + self.children.clear(); + } +} + +impl<T> FrameStack<T> { + /// Opens the start of the frame the next init makes, at `depth`: the child of the frame on + /// top of the stack, or the transaction's start when the stack is empty. Returns the split to + /// hand to [`Host::frame_split`](crate::Host::frame_split). + /// + /// A frame has at most one open start, and so has the transaction. A failed open changes + /// nothing. + /// + /// # Errors + /// + /// [`StartLifecycleError::Exhausted`] once the transaction opened `u32::MAX` starts, + /// [`StartLifecycleError::Stale`] when the slot already holds an open start, and + /// [`StartLifecycleError::NoParent`] when the frame on top has no start of its own. + #[inline] + pub fn open_start(&mut self, depth: usize) -> Result<FrameSplit, StartLifecycleError> { + let record = &mut self.lifecycle; + let id = record + .next + .checked_add(1) + .ok_or(StartLifecycleError::Exhausted)?; + let parent = match self.index { + None => None, + Some(i) => { + let parent = match i { + 0 => record.root, + _ => record.children.get(i - 1).copied().flatten(), + }; + let Some(parent) = parent else { + return Err(StartLifecycleError::NoParent); + }; + if record.children.len() <= i { + record.children.resize(i + 1, None); + } + Some(parent.id) + } + }; + let slot = record + .slot(self.index) + .expect("the slot of the frame on top exists"); + if slot.is_some() { + return Err(StartLifecycleError::Stale); + } + *slot = Some(PendingStart { + id, + ..Default::default() + }); + record.next = id; + record.active = true; + Ok(FrameSplit { id, parent, depth }) + } + + /// Closes the start the next settlement closes ([`pending_start`](Self::pending_start)), that + /// of a frame at `depth` which settled with `status`, into a caller whose gas held + /// `held_reservoir` just before. Returns the settlement to hand to + /// [`Host::frame_settle`](crate::Host::frame_settle), with what the start's record says an + /// inspector did to it. + /// + /// # Errors + /// + /// [`StartLifecycleError::NotOpen`] when no start is open there. + #[inline] + pub fn close_start( + &mut self, + depth: usize, + status: SettleStatus, + created: Option<bool>, + held_reservoir: u64, + ) -> Result<FrameSettle, StartLifecycleError> { + let start = self + .lifecycle + .slot(self.index) + .and_then(Option::take) + .ok_or(StartLifecycleError::NotOpen)?; + Ok(FrameSettle { + id: start.id, + depth, + status, + created, + inspector_answer: start.inspector_answer, + gas_replaced: start.gas_replaced, + outcome_rebuilt: start.outcome_rebuilt, + held_reservoir, + }) + } + + /// The start the next settlement closes: the open start of the frame on top of the stack, the + /// child it is making, or the transaction's start when the stack is empty. + #[inline] + pub fn pending_start(&mut self) -> Option<&mut PendingStart> { + self.lifecycle.slot(self.index).and_then(Option::as_mut) + } + + /// The start the frame on top of the stack runs for: the open start of the frame below it, or + /// the transaction's start for the frame at the bottom. + #[inline] + pub fn running_start(&mut self) -> Option<&mut PendingStart> { + match self.index? { + 0 => self.lifecycle.root.as_mut(), + i => self + .lifecycle + .children + .get_mut(i - 1) + .and_then(Option::as_mut), + } + } + + /// Whether a transaction's lifecycle is under way: its first start opened, and neither + /// boundary ended it. + #[inline] + pub const fn lifecycle_active(&self) -> bool { + self.lifecycle.active + } + + /// Whether every start opened in the transaction has settled. + #[inline] + pub fn lifecycle_settled(&self) -> bool { + !self.lifecycle.any_open() + } + + /// The successful boundary: ends the lifecycle and resets the record for the next + /// transaction. Returns the end to hand to + /// [`Host::frame_lifecycle_end`](crate::Host::frame_lifecycle_end), + /// [`LifecycleEnd::Settled`], or `None` when no lifecycle was under way. + /// + /// # Errors + /// + /// [`StartLifecycleError::Unsettled`] when a start is still open. The record is left as it + /// is, for [`discard_lifecycle`](Self::discard_lifecycle). + #[inline] + pub fn settle_lifecycle(&mut self) -> Result<Option<LifecycleEnd>, StartLifecycleError> { + if self.lifecycle.any_open() { + return Err(StartLifecycleError::Unsettled); + } + let end = self.lifecycle.active.then_some(LifecycleEnd::Settled); + self.lifecycle.reset(); + Ok(end) + } + + /// The fatal boundary: discards the starts still open, ends the lifecycle and resets the + /// record for the next transaction. Returns the end to hand to + /// [`Host::frame_lifecycle_end`](crate::Host::frame_lifecycle_end), + /// [`LifecycleEnd::Discarded`], or `None` when no lifecycle was under way, so a second discard + /// owes nothing. + /// + /// It resets the lifecycle only: the frame stack's index is [`clear`](Self::clear)'s. + #[inline] + #[must_use = "a lifecycle that was under way owes the consumer its end"] + pub fn discard_lifecycle(&mut self) -> Option<LifecycleEnd> { + let end = self.lifecycle.active.then_some(LifecycleEnd::Discarded); + self.lifecycle.reset(); + end + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A stack with frames at indices `0..frames`, as revm's loop builds it. + fn stack(frames: usize) -> FrameStack<u8> { + let mut stack = FrameStack::new_prealloc(frames.max(1)); + if frames > 0 { + let token = stack.start_init().consume(); + unsafe { stack.end_init(token) }; + for _ in 1..frames { + let token = stack.get_next().consume(); + unsafe { stack.push(token) }; + } + } + stack + } + + fn split(id: u32, parent: Option<u32>, depth: usize) -> FrameSplit { + FrameSplit { id, parent, depth } + } + + /// Opens the transaction's start and one child per frame, as a nested run does. + fn open_nested(stack: &mut FrameStack<u8>, frames: usize) { + stack.clear(); + stack.open_start(0).unwrap(); + for i in 0..frames { + stack.index = Some(i); + stack.open_start(i + 1).unwrap(); + } + } + + #[test] + fn test_a_nested_run_opens_one_start_per_frame_under_its_parent() { + let mut stack = stack(2); + stack.clear(); + assert_eq!(stack.open_start(0), Ok(split(1, None, 0))); + stack.index = Some(0); + assert_eq!(stack.open_start(1), Ok(split(2, Some(1), 1))); + stack.index = Some(1); + assert_eq!(stack.open_start(2), Ok(split(3, Some(2), 2))); + assert!(stack.lifecycle_active()); + assert!(!stack.lifecycle_settled()); + assert_eq!(stack.running_start().map(|s| s.id()), Some(2)); + assert_eq!(stack.pending_start().map(|s| s.id()), Some(3)); + } + + #[test] + fn test_each_settlement_closes_the_start_of_its_slot_innermost_first() { + let mut stack = stack(2); + open_nested(&mut stack, 2); + let settled = stack.close_start(2, SettleStatus::Revert, None, 7).unwrap(); + assert_eq!( + (settled.id, settled.depth, settled.status), + (3, 2, SettleStatus::Revert) + ); + assert_eq!(settled.held_reservoir, 7); + stack.index = Some(0); + let settled = stack + .close_start(1, SettleStatus::Ok, Some(true), 0) + .unwrap(); + assert_eq!((settled.id, settled.created), (2, Some(true))); + stack.clear(); + assert_eq!( + stack + .close_start(0, SettleStatus::Halt, None, 0) + .map(|s| s.id), + Ok(1) + ); + assert!(stack.lifecycle_settled()); + assert!( + stack.lifecycle_active(), + "only a boundary ends the lifecycle" + ); + } + + #[test] + fn test_identities_are_never_reused_within_a_transaction() { + let mut stack = stack(1); + open_nested(&mut stack, 1); + stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!( + stack.open_start(1).map(|s| s.id), + Ok(3), + "the frame's second child" + ); + stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + stack.clear(); + stack.close_start(0, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!(stack.settle_lifecycle(), Ok(Some(LifecycleEnd::Settled))); + assert_eq!( + stack.open_start(0).map(|s| s.id), + Ok(1), + "the next transaction restarts" + ); + } + + #[test] + fn test_a_second_start_in_an_occupied_slot_is_stale() { + let mut stack = stack(1); + open_nested(&mut stack, 1); + assert_eq!(stack.open_start(1), Err(StartLifecycleError::Stale)); + stack.clear(); + assert_eq!(stack.open_start(0), Err(StartLifecycleError::Stale)); + stack.index = Some(0); + assert_eq!( + stack.pending_start().map(|s| s.id()), + Some(2), + "nothing changed" + ); + } + + #[test] + fn test_a_child_under_a_frame_with_no_start_has_no_parent() { + let mut stack = stack(2); + assert_eq!(stack.open_start(1), Err(StartLifecycleError::NoParent)); + stack.clear(); + stack.open_start(0).unwrap(); + stack.index = Some(1); + assert_eq!(stack.open_start(2), Err(StartLifecycleError::NoParent)); + assert!(stack.pending_start().is_none(), "nothing opened"); + } + + #[test] + fn test_a_settlement_with_nothing_open_is_refused() { + let mut stack = stack(1); + stack.clear(); + assert_eq!( + stack.close_start(0, SettleStatus::Ok, None, 0), + Err(StartLifecycleError::NotOpen) + ); + stack.open_start(0).unwrap(); + stack.close_start(0, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!( + stack.close_start(0, SettleStatus::Ok, None, 0), + Err(StartLifecycleError::NotOpen), + "a start settles once" + ); + stack.index = Some(0); + assert_eq!( + stack.close_start(1, SettleStatus::Ok, None, 0), + Err(StartLifecycleError::NotOpen), + "a frame that made no child" + ); + } + + #[test] + fn test_an_exhausted_sequence_opens_nothing() { + let mut stack = stack(1); + open_nested(&mut stack, 0); + stack.lifecycle.next = u32::MAX - 1; + stack.index = Some(0); + assert_eq!( + stack.open_start(1).map(|s| s.id), + Ok(u32::MAX), + "the last identity" + ); + stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!(stack.open_start(1), Err(StartLifecycleError::Exhausted)); + assert!(stack.pending_start().is_none(), "nothing opened"); + assert_eq!(stack.discard_lifecycle(), Some(LifecycleEnd::Discarded)); + stack.clear(); + assert_eq!( + stack.open_start(0).map(|s| s.id), + Ok(1), + "the next transaction restarts" + ); + } + + #[test] + fn test_the_successful_boundary_needs_every_start_settled() { + let mut stack = stack(1); + open_nested(&mut stack, 1); + stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + stack.clear(); + assert_eq!( + stack.settle_lifecycle(), + Err(StartLifecycleError::Unsettled) + ); + assert!( + stack.lifecycle_active(), + "the record is left for the discard" + ); + assert_eq!(stack.pending_start().map(|s| s.id()), Some(1)); + stack.close_start(0, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!(stack.settle_lifecycle(), Ok(Some(LifecycleEnd::Settled))); + assert!(!stack.lifecycle_active()); + assert_eq!( + stack.settle_lifecycle(), + Ok(None), + "no lifecycle is under way" + ); + } + + #[test] + fn test_the_fatal_boundary_discards_once() { + let mut stack = stack(2); + open_nested(&mut stack, 2); + assert_eq!(stack.discard_lifecycle(), Some(LifecycleEnd::Discarded)); + assert_eq!( + stack.discard_lifecycle(), + None, + "a second discard owes nothing" + ); + assert!(stack.lifecycle_settled() && !stack.lifecycle_active()); + assert_eq!(stack.index(), Some(1), "the frame stack is clear's"); + stack.clear(); + assert_eq!(stack.open_start(0).map(|s| s.id), Ok(1)); + } + + #[test] + fn test_what_an_inspector_did_reaches_the_settlement() { + let mut stack = stack(1); + open_nested(&mut stack, 1); + let pending = stack.pending_start().unwrap(); + pending.set_inspector_answer(); + pending.set_outcome_rebuilt(); + let running = stack.running_start().unwrap(); + running.set_gas_replaced(); + let child = stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + assert!(child.inspector_answer && child.outcome_rebuilt && !child.gas_replaced); + stack.clear(); + let root = stack.close_start(0, SettleStatus::Ok, None, 0).unwrap(); + assert!(!root.inspector_answer && !root.outcome_rebuilt && root.gas_replaced); + } +} diff --git a/crates/context/interface/src/local/mirror.rs b/crates/context/interface/src/local/mirror.rs new file mode 100644 index 0000000000..0316825e66 --- /dev/null +++ b/crates/context/interface/src/local/mirror.rs @@ -0,0 +1,228 @@ +//! A consumer-side check of the start lifecycle: a stack driven only by the lifecycle hooks, as a +//! consumer's own ledger would be, which asserts that every event the hooks receive fits it. +//! +//! revm's own context keeps one in its local context in debug builds and feeds it from its +//! [`Host`](crate::Host) hooks ([`LocalContextTr::lifecycle_mirror`](super::LocalContextTr::lifecycle_mirror)); +//! a release build keeps none. + +use crate::host::{FrameSettle, FrameSplit, LifecycleEnd}; +use std::vec::Vec; + +/// An event of the start lifecycle, as a hook received it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LifecycleEvent { + /// [`Host::frame_split`](crate::Host::frame_split). + Split(FrameSplit), + /// [`Host::frame_settle`](crate::Host::frame_settle). + Settle(FrameSettle), + /// [`Host::frame_lifecycle_end`](crate::Host::frame_lifecycle_end). + End(LifecycleEnd), +} + +/// The starts the hooks reported open, innermost last, and the events of the lifecycle under way +/// or, once it ended, of the last one. +/// +/// It lives in the context, so a context cloned for a simulation carries a copy. The simulation's +/// first event is its own transaction's start, which resets the copy: each execution is checked +/// from its own first start, and the original context's mirror is untouched. +#[derive(Clone, Debug, Default)] +pub struct LifecycleMirror { + open: Vec<(u32, usize)>, + events: Vec<LifecycleEvent>, +} + +impl LifecycleMirror { + /// Checks a split and pushes its start. The transaction's start, the one with no parent, + /// begins a lifecycle: it must be at depth 0, and it resets the mirror. A child start's + /// parent must be the start on top, one frame shallower. + /// + /// # Panics + /// + /// When the split does not fit. + pub fn split(&mut self, split: &FrameSplit) { + match split.parent { + None => { + assert_eq!( + split.depth, 0, + "start lifecycle: the transaction's start {} at depth {}", + split.id, split.depth + ); + self.open.clear(); + self.events.clear(); + } + Some(parent) => { + let top = self.open.last().copied(); + assert_eq!( + top.map(|(id, _)| id), + Some(parent), + "start lifecycle: start {} opened under {parent} while {top:?} was on top", + split.id + ); + assert_eq!( + top.map(|(_, depth)| depth + 1), + Some(split.depth), + "start lifecycle: start {} at depth {} under a parent at {top:?}", + split.id, + split.depth + ); + } + } + self.open.push((split.id, split.depth)); + self.events.push(LifecycleEvent::Split(*split)); + } + + /// Checks a settlement and pops its start, which must be the one on top, at the same depth. + /// + /// # Panics + /// + /// When the settlement does not fit. + pub fn settle(&mut self, settle: &FrameSettle) { + let top = self.open.pop(); + assert_eq!( + top, + Some((settle.id, settle.depth)), + "start lifecycle: settled ({}, depth {}) while {top:?} was on top", + settle.id, + settle.depth + ); + self.events.push(LifecycleEvent::Settle(*settle)); + } + + /// Checks the end of a lifecycle: a settled one leaves no start open. Either end empties the + /// stack. + /// + /// # Panics + /// + /// When a lifecycle ends settled with a start open. + pub fn end(&mut self, end: LifecycleEnd) { + if end == LifecycleEnd::Settled { + assert!( + self.open.is_empty(), + "start lifecycle: settled with starts open: {:?}", + self.open + ); + } + self.open.clear(); + self.events.push(LifecycleEvent::End(end)); + } + + /// The events of the lifecycle under way or, once it ended, of the last one. + pub fn events(&self) -> &[LifecycleEvent] { + &self.events + } + + /// The starts open, innermost last, as `(identity, depth)`. + pub fn open(&self) -> &[(u32, usize)] { + &self.open + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::SettleStatus; + + fn split(id: u32, parent: Option<u32>, depth: usize) -> FrameSplit { + FrameSplit { id, parent, depth } + } + + fn settle(id: u32, depth: usize) -> FrameSettle { + FrameSettle { + id, + depth, + status: SettleStatus::Ok, + created: None, + inspector_answer: false, + gas_replaced: false, + outcome_rebuilt: false, + held_reservoir: 0, + } + } + + #[test] + fn test_a_paired_lifecycle_fits() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.split(&split(2, Some(1), 1)); + mirror.settle(&settle(2, 1)); + mirror.settle(&settle(1, 0)); + mirror.end(LifecycleEnd::Settled); + assert!(mirror.open().is_empty()); + assert_eq!(mirror.events().len(), 5); + } + + #[test] + fn test_the_transactions_start_resets_what_a_clone_brought() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.split(&split(2, Some(1), 1)); + let mut simulation = mirror.clone(); + simulation.split(&split(1, None, 0)); + assert_eq!(simulation.open(), &[(1, 0)]); + assert_eq!( + simulation.events(), + &[LifecycleEvent::Split(split(1, None, 0))] + ); + assert_eq!( + mirror.open(), + &[(1, 0), (2, 1)], + "the original is untouched" + ); + } + + #[test] + fn test_a_discarded_lifecycle_may_leave_starts_open() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.end(LifecycleEnd::Discarded); + assert!(mirror.open().is_empty()); + } + + #[test] + #[should_panic(expected = "the transaction's start 1 at depth 5")] + fn test_a_transaction_start_off_depth_zero_does_not_fit() { + LifecycleMirror::default().split(&split(1, None, 5)); + } + + #[test] + #[should_panic(expected = "start 2 at depth 3 under a parent at Some((1, 0))")] + fn test_a_child_off_its_parents_depth_does_not_fit() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.split(&split(2, Some(1), 3)); + } + + #[test] + #[should_panic(expected = "start 3 opened under 1 while Some((2, 1)) was on top")] + fn test_a_child_under_another_start_does_not_fit() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.split(&split(2, Some(1), 1)); + mirror.split(&split(3, Some(1), 1)); + } + + #[test] + #[should_panic(expected = "settled (1, depth 0) while Some((2, 1)) was on top")] + fn test_a_settlement_out_of_order_does_not_fit() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.split(&split(2, Some(1), 1)); + mirror.settle(&settle(1, 0)); + } + + #[test] + #[should_panic(expected = "settled (1, depth 27) while Some((1, 0)) was on top")] + fn test_a_settlement_off_its_splits_depth_does_not_fit() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.settle(&settle(1, 27)); + } + + #[test] + #[should_panic(expected = "settled with starts open: [(1, 0)]")] + fn test_a_settled_end_with_a_start_open_does_not_fit() { + let mut mirror = LifecycleMirror::default(); + mirror.split(&split(1, None, 0)); + mirror.end(LifecycleEnd::Settled); + } +} diff --git a/crates/context/src/context.rs b/crates/context/src/context.rs index acf70ce460..bcf1b8f333 100644 --- a/crates/context/src/context.rs +++ b/crates/context/src/context.rs @@ -438,6 +438,33 @@ impl< LOCAL: LocalContextTr, > Host for Context<BLOCK, TX, CFG, DB, JOURNAL, CHAIN, LOCAL> { + /* Start lifecycle: in debug builds, the local context's mirror checks every event. */ + + #[cfg(debug_assertions)] + fn frame_split(&mut self, split: &context_interface::host::FrameSplit) { + if let Some(mirror) = self.local.lifecycle_mirror() { + mirror.split(split); + } + } + + #[cfg(debug_assertions)] + fn frame_settle( + &mut self, + settle: &context_interface::host::FrameSettle, + _gas: &mut context_interface::cfg::gas::GasTracker, + ) { + if let Some(mirror) = self.local.lifecycle_mirror() { + mirror.settle(settle); + } + } + + #[cfg(debug_assertions)] + fn frame_lifecycle_end(&mut self, end: context_interface::host::LifecycleEnd) { + if let Some(mirror) = self.local.lifecycle_mirror() { + mirror.end(end); + } + } + /* Block */ fn basefee(&self) -> U256 { diff --git a/crates/context/src/local.rs b/crates/context/src/local.rs index 1026721b73..0fdede1fd9 100644 --- a/crates/context/src/local.rs +++ b/crates/context/src/local.rs @@ -1,4 +1,6 @@ //! Local context that is filled by execution. +#[cfg(debug_assertions)] +use context_interface::LifecycleMirror; use context_interface::LocalContextTr; use core::cell::RefCell; use std::{rc::Rc, string::String, vec::Vec}; @@ -10,6 +12,10 @@ pub struct LocalContext { pub shared_memory_buffer: Rc<RefCell<Vec<u8>>>, /// Optional precompile error message to bubble up. pub precompile_error_message: Option<String>, + /// The start lifecycle's mirror, in debug builds only + /// ([`LocalContextTr::lifecycle_mirror`]). + #[cfg(debug_assertions)] + lifecycle_mirror: LifecycleMirror, } impl Default for LocalContext { @@ -17,6 +23,8 @@ impl Default for LocalContext { Self { shared_memory_buffer: Rc::new(RefCell::new(Vec::with_capacity(1024 * 4))), precompile_error_message: None, + #[cfg(debug_assertions)] + lifecycle_mirror: LifecycleMirror::default(), } } } @@ -28,6 +36,12 @@ impl LocalContextTr for LocalContext { self.precompile_error_message = None; } + #[cfg(debug_assertions)] + #[inline] + fn lifecycle_mirror(&mut self) -> Option<&mut LifecycleMirror> { + Some(&mut self.lifecycle_mirror) + } + fn shared_memory_buffer(&self) -> &Rc<RefCell<Vec<u8>>> { &self.shared_memory_buffer } From b74d3f6a9721149438cb3c209a83c1a2becd2b1d Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 11:48:30 +0800 Subject: [PATCH 083/110] feat(handler): open, settle and end the start lifecycle on revm's runners A start opens where revm consumes a frame's init: a NewFrame in EvmTr::frame_run and InspectorEvmTr::inspect_frame_run, the transaction's frame in Handler::execution and InspectorHandler::inspect_execution, and the stand-in in Handler::runtime_oog_result. It settles in Evm::frame_return_result after return_result, and in last_frame_result after settle_first_frame, where revm's halt rule follows the hook. execution_result finishes the lifecycle and catch_error discards it. A refused step is a fatal error of the transaction in every build. The lifecycle module holds the helpers a chain's handler, a custom EVM or a hand-driven runner calls, and states the reuse contract for a caller of run_without_catch_error. The hand-run first frame in reservoir_share and the custom EVM in custom_frame open and settle as revm's runners now do. --- crates/handler/src/evm.rs | 40 +- crates/handler/src/handler.rs | 41 +- crates/handler/src/lib.rs | 1 + crates/handler/src/lifecycle.rs | 258 ++++++++++ crates/handler/tests/reservoir_share.rs | 2 + crates/inspector/src/handler.rs | 2 + crates/inspector/src/traits.rs | 7 + crates/inspector/tests/custom_frame.rs | 17 +- crates/inspector/tests/start_lifecycle.rs | 590 ++++++++++++++++++++++ 9 files changed, 936 insertions(+), 22 deletions(-) create mode 100644 crates/handler/src/lifecycle.rs create mode 100644 crates/inspector/tests/start_lifecycle.rs diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index 7728f9c3a6..72e59bc841 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -1,6 +1,8 @@ use crate::{ - instructions::InstructionProvider, item_or_result::FrameInitOrResult, EthFrame, FrameResult, - ItemOrResult, PrecompileProvider, + instructions::InstructionProvider, + item_or_result::FrameInitOrResult, + lifecycle::{close_frame_start, Returning}, + EthFrame, FrameResult, ItemOrResult, PrecompileProvider, }; use auto_impl::auto_impl; use context::{ContextTr, Database, Evm, FrameStack}; @@ -113,6 +115,10 @@ pub trait EvmTr { /// Run the frame from the top of the stack. Returns the frame init or result. /// /// If frame has returned result it would mark it as finished. + /// + /// A frame init it returns opens the child's start under the frame's own + /// ([`lifecycle::open_frame_start`](crate::lifecycle::open_frame_start)); a + /// reimplementation makes the same call for the init it consumed. fn frame_run( &mut self, ) -> Result<FrameInitOrResult<Self::Frame>, ContextDbError<Self::Context>>; @@ -153,6 +159,10 @@ pub trait EvmTr { /// Returns the result of the frame to the caller. Frame is popped from the frame stack. /// Consumes the frame result or returns it if there is more frames to run. + /// + /// A result returned into a caller closes the start the caller opened for it + /// ([`lifecycle::close_frame_start`](crate::lifecycle::close_frame_start)); a + /// reimplementation makes the same call after it returns the result. fn frame_return_result( &mut self, result: <Self::Frame as FrameTr>::FrameResult, @@ -229,7 +239,8 @@ where })) } - /// Run the frame from the top of the stack. Returns the frame init or result. + /// Run the frame from the top of the stack. Returns the frame init or result, and opens the + /// start of a frame init. #[inline] fn frame_run(&mut self) -> Result<FrameInitOrResult<Self::Frame>, ContextDbError<CTX>> { let frame = self.frame_stack.get(); @@ -242,14 +253,16 @@ where context, ); - frame.process_next_action(context, action).inspect(|i| { - if i.is_result() { - frame.set_finished(true); - } - }) + let next = frame.process_next_action::<_, ContextDbError<CTX>>(context, action)?; + match &next { + ItemOrResult::Item(init) => crate::lifecycle::open_frame_start(self, init)?, + ItemOrResult::Result(_) => frame.set_finished(true), + } + Ok(next) } - /// Returns the result of the frame to the caller. Frame is popped from the frame stack. + /// Returns the result of the frame to the caller, and closes its start. Frame is popped from + /// the frame stack. #[inline] fn frame_return_result( &mut self, @@ -261,9 +274,12 @@ where if self.frame_stack.index().is_none() { return Ok(Some(result)); } - self.frame_stack - .get() - .return_result::<_, ContextDbError<Self::Context>>(&mut self.ctx, result)?; + let caller = self.frame_stack.get(); + let returning = Returning::new(&result, caller); + caller.return_result::<_, ContextDbError<Self::Context>>(&mut self.ctx, result)?; + close_frame_start(&mut self.ctx, &mut self.frame_stack, returning, |caller| { + caller + })?; Ok(None) } } diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index d965c7aaed..77071ca0fc 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -1,6 +1,6 @@ use crate::{ evm::FrameTr, - execution, + execution, lifecycle, post_execution::{self, build_result_gas}, pre_execution::{self, apply_eip7702_auth_list, PreExecutionOutput}, validation, EvmTr, FrameResult, ItemOrResult, @@ -159,6 +159,9 @@ pub trait Handler { /// [Handler::pre_execution], [Handler::execution], [Handler::post_execution]. /// /// Returns any errors without catching them or calling [`Handler::catch_error`]. + /// A caller that drops an error makes `catch_error`'s cleanup before it reuses + /// the EVM, the frame stack's included: see the start lifecycle's "Reuse after + /// an error" ([`lifecycle`](crate::lifecycle)). #[inline] fn run_without_catch_error( &mut self, @@ -269,6 +272,9 @@ pub trait Handler { /// ([`Handler::runtime_oog_result`]). /// /// Always calls [Handler::last_frame_result] to handle returned gas from the call. + /// + /// The first frame's init opens the transaction's start + /// ([`lifecycle::open_frame_start`]), which `last_frame_result` closes. #[inline] fn execution( &mut self, @@ -287,6 +293,8 @@ pub trait Handler { }; // The runtime gas phase is complete: commit its state changes. evm.ctx().journal_mut().checkpoint_commit(); + // The transaction's start opens with the frame init revm made for it. + lifecycle::open_frame_start(evm, &first_frame_input)?; // Run execution loop let mut frame_result = self.run_exec_loop(evm, first_frame_input)?; @@ -305,6 +313,10 @@ pub trait Handler { /// skipped, all regular gas is consumed (the reservoir is returned), and /// the runtime state changes were already reverted when the phase bailed /// out. + /// + /// The stand-in opens the transaction's start + /// ([`lifecycle::open_transaction_start`]) and settles on it as the + /// transaction's frame would. #[inline] fn runtime_oog_result( &mut self, @@ -318,6 +330,9 @@ pub trait Handler { // result; the settle below consumes all regular gas and returns the // reservoir. *gas = self.tx_gas(evm, init_and_floor_gas); + // The stand-in settles as the transaction's frame would, so it opens the transaction's + // start. + lifecycle::open_transaction_start(evm)?; let tx_gas_limit = evm.ctx().tx().gas_limit(); // The stand-in takes the whole reservoir and every pool out of the transaction's gas, as // the first frame would (`create_init_frame`), so the settle adds them back once. @@ -508,8 +523,11 @@ pub trait Handler { /// which carries it into the post-execution phase. /// /// The settlement is [`execution::settle_first_frame`], which also refunds - /// the first frame's start charge. An override calls it rather than copying - /// this body, and copies the gas into the frame result itself. + /// the first frame's start charge. It is followed by the close of the + /// transaction's start ([`lifecycle::close_transaction_start`], given the + /// reservoir the gas held before the settlement). An override calls both + /// rather than copying this body, and copies the gas into the frame result + /// itself. /// /// [`handle_reservoir_remaining_gas`]: crate::handle_reservoir_remaining_gas #[inline] @@ -520,8 +538,10 @@ pub trait Handler { parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { // Settle the frame into the transaction-level gas like a parent frame, and refund what - // its failure gives back. + // its failure gives back; then close the transaction's start. + let held_reservoir = parent_gas.reservoir(); execution::settle_first_frame::<_, Self::Error>(evm.ctx(), frame_result, parent_gas)?; + lifecycle::close_transaction_start(evm, frame_result, parent_gas, held_reservoir)?; // The frame result carries the transaction-level gas onward to the // post-execution phase. @@ -633,6 +653,11 @@ pub trait Handler { /// /// This method, retrieves the final state from the journal, converts internal results to the external output format. /// Internal state is cleared and EVM is prepared for the next transaction. + /// + /// It is the start lifecycle's successful boundary: after the recorded error is + /// taken, every start the transaction opened must have settled + /// ([`lifecycle::finish_transaction`]), or the transaction fails with a fatal + /// error. An override makes the same call in the same place. #[inline] fn execution_result( &mut self, @@ -641,6 +666,8 @@ pub trait Handler { result_gas: ResultGas, ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> { take_error::<Self::Error, _>(evm.ctx().error())?; + // The successful boundary: every start the transaction opened has settled. + lifecycle::finish_transaction(evm)?; let exec_result = post_execution::output(evm.ctx(), result, result_gas); @@ -656,12 +683,18 @@ pub trait Handler { /// /// Ensures the journal state is properly cleared before propagating the error. /// On happy path journal is cleared in [`Handler::execution_result`] method. + /// + /// It is the start lifecycle's fatal boundary: the starts still open are + /// discarded ([`lifecycle::discard_transaction`]) in the cleanup every error + /// reaches. An override makes the same call in its cleanup. #[inline] fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, ) -> Result<ExecutionResult<Self::HaltReason>, Self::Error> { + // The fatal boundary: the starts still open are discarded. + lifecycle::discard_transaction(evm); // clean up local context. Initcode cache needs to be discarded. evm.ctx().local_mut().clear(); evm.ctx().journal_mut().discard_tx(); diff --git a/crates/handler/src/lib.rs b/crates/handler/src/lib.rs index 7ee2311c6d..80a5b28329 100644 --- a/crates/handler/src/lib.rs +++ b/crates/handler/src/lib.rs @@ -20,6 +20,7 @@ pub mod handler; /// EVM instruction set implementations and tables. pub mod instructions; mod item_or_result; +pub mod lifecycle; mod mainnet_builder; mod mainnet_handler; /// Post-execution operations including gas refunds and state finalization. diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs new file mode 100644 index 0000000000..568c9d41e3 --- /dev/null +++ b/crates/handler/src/lifecycle.rs @@ -0,0 +1,258 @@ +//! The start lifecycle: revm's pairing of every frame start with its settlement. +//! +//! A start opens where revm consumes a frame's init, just before it initialises the frame: a +//! frame's `NewFrame` action, consumed by [`EvmTr::frame_run`] (and by the inspector's +//! `inspect_frame_run`), opens a child start under the frame's own ([`open_frame_start`]); the +//! transaction's frame opens the transaction's start in [`Handler::execution`] (and the +//! inspector's `inspect_execution`), and so does the stand-in [`Handler::runtime_oog_result`] +//! builds for a frame that never runs ([`open_transaction_start`]). +//! +//! A start closes where revm settles the frame's result into its caller: a child's in +//! [`EvmTr::frame_return_result`], after `EthFrame::return_result` ([`close_frame_start`]), and +//! the transaction's in [`Handler::last_frame_result`], after +//! [`settle_first_frame`](crate::execution::settle_first_frame) ([`close_transaction_start`]). +//! +//! The lifecycle ends at one of the transaction's two boundaries: the successful one in +//! [`Handler::execution_result`], where every start must have settled ([`finish_transaction`]), +//! and the fatal one in [`Handler::catch_error`], which discards the starts still open +//! ([`discard_transaction`]). +//! +//! The record is revm's frame stack ([`FrameStack`]), which no inspector is handed. Each step is +//! handed to the context's lifecycle hooks ([`Host::frame_split`], [`Host::frame_settle`], +//! [`Host::frame_lifecycle_end`]). A step the record refuses ([`StartLifecycleError`]) is a fatal +//! error of the transaction in every build. +//! +//! A chain's handler that overrides one of these methods makes the call the mainnet method makes, +//! in the same place: [`close_transaction_start`] in `last_frame_result`, [`finish_transaction`] +//! in `execution_result` and [`discard_transaction`] in `catch_error`. An EVM that reimplements +//! `frame_run` or `inspect_frame_run` calls [`open_frame_start`] for the init it consumed, and one +//! that reimplements `frame_return_result` calls [`close_frame_start`]. A runner that drives the +//! transaction's frame itself, outside [`Handler::execution`], opens the transaction's start first +//! ([`open_frame_start`] with the frame's init, or [`open_transaction_start`] for a frame it never +//! initialises). +//! +//! # Reuse after an error +//! +//! [`Handler::run`] hands an error to [`Handler::catch_error`], whose cleanup discards the +//! lifecycle, the journal's transaction, the local context and the frame stack. A caller of +//! [`Handler::run_without_catch_error`] that drops an error must make the same cleanup before it +//! reuses the EVM: call `catch_error`, or call [`discard_transaction`], discard the journal's +//! transaction, clear the local context and clear the frame stack ([`FrameStack::clear`]). +//! Discarding the lifecycle alone is not enough: a frame left on the stack makes the next +//! transaction's start a child of a frame with no start, which the record refuses. +//! +//! [`Handler::execution`]: crate::Handler::execution +//! [`Handler::runtime_oog_result`]: crate::Handler::runtime_oog_result +//! [`Handler::last_frame_result`]: crate::Handler::last_frame_result +//! [`Handler::execution_result`]: crate::Handler::execution_result +//! [`Handler::catch_error`]: crate::Handler::catch_error +//! [`Handler::run`]: crate::Handler::run +//! [`Handler::run_without_catch_error`]: crate::Handler::run_without_catch_error + +use crate::{evm::ContextDbError, EthFrame, EvmTr, FrameResult}; +use context_interface::{ + context::ContextError, host::SettleStatus, FrameStack, Host, StartLifecycleError, +}; +use interpreter::{interpreter::EthInterpreter, interpreter_action::FrameInit, GasTracker}; +use std::string::ToString; + +/// A refused step as the transaction's fatal error. +#[cold] +fn fatal<E>(error: StartLifecycleError) -> ContextError<E> { + ContextError::Custom(error.to_string()) +} + +/// What a settlement reports of `result`'s status. +#[inline] +pub const fn settle_status(result: &FrameResult) -> SettleStatus { + let result = result.instruction_result(); + if result.is_ok() { + SettleStatus::Ok + } else if result.is_revert() { + SettleStatus::Revert + } else { + SettleStatus::Halt + } +} + +/// For a creation's `result`, whether it took an address; `None` for a call's. +#[inline] +const fn created(result: &FrameResult) -> Option<bool> { + match result { + FrameResult::Call(_) => None, + FrameResult::Create(outcome) => Some(outcome.address.is_some()), + } +} + +/// Opens the start of the frame `init` makes, which revm consumed and initialises next: the child +/// of the frame on top of the stack, or the transaction's start when the stack is empty. Hands it +/// to [`Host::frame_split`]. +/// +/// # Errors +/// +/// The record's refusal ([`FrameStack::open_start`]), as a fatal error. +#[inline] +pub fn open_frame_start<EVM: EvmTr + ?Sized>( + evm: &mut EVM, + init: &FrameInit, +) -> Result<(), ContextDbError<EVM::Context>> { + let (ctx, _, _, frame_stack) = evm.all_mut(); + let split = frame_stack.open_start(init.depth).map_err(fatal)?; + ctx.frame_split(&split); + Ok(()) +} + +/// Opens the transaction's start for a transaction frame revm does not initialise: the stand-in +/// for a frame that never runs, or the frame of a runner that settles one it built itself. Hands +/// it to [`Host::frame_split`]. The frame stack must be empty. +/// +/// # Errors +/// +/// The record's refusal ([`FrameStack::open_start`]), as a fatal error. +#[inline] +pub fn open_transaction_start<EVM: EvmTr + ?Sized>( + evm: &mut EVM, +) -> Result<(), ContextDbError<EVM::Context>> { + let (ctx, _, _, frame_stack) = evm.all_mut(); + debug_assert!( + frame_stack.index().is_none(), + "the transaction's start opens on an empty frame stack" + ); + let split = frame_stack.open_start(0).map_err(fatal)?; + ctx.frame_split(&split); + Ok(()) +} + +/// A frame's result on its way into its caller: what its settlement reports, read before +/// `EthFrame::return_result` consumes it ([`close_frame_start`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Returning { + depth: usize, + status: SettleStatus, + created: Option<bool>, + held_reservoir: u64, +} + +impl Returning { + /// `result`, about to be returned into `caller`, the frame on top of the stack. + #[inline] + pub const fn new(result: &FrameResult, caller: &EthFrame<EthInterpreter>) -> Self { + Self { + depth: caller.depth + 1, + status: settle_status(result), + created: created(result), + held_reservoir: caller.interpreter.gas.reservoir(), + } + } +} + +/// Closes the start of the frame whose result was just returned into the frame on top of +/// `frame_stack`, its caller, after `EthFrame::return_result` settled it, and hands the settlement +/// to [`Host::frame_settle`] with the caller's gas. `caller` reaches the caller's `EthFrame` from +/// the stack's frame. +/// +/// # Errors +/// +/// [`StartLifecycleError::NotOpen`] when the caller has no open start, as a fatal error. +#[inline] +pub fn close_frame_start<CTX, F, E>( + ctx: &mut CTX, + frame_stack: &mut FrameStack<F>, + returning: Returning, + caller: impl FnOnce(&mut F) -> &mut EthFrame<EthInterpreter>, +) -> Result<(), ContextError<E>> +where + CTX: Host + ?Sized, +{ + let settle = frame_stack + .close_start( + returning.depth, + returning.status, + returning.created, + returning.held_reservoir, + ) + .map_err(fatal)?; + let caller = caller(frame_stack.get()); + ctx.frame_settle(&settle, caller.interpreter.gas.tracker_mut()); + Ok(()) +} + +/// Closes the transaction's start into the transaction-level `gas`, after +/// [`settle_first_frame`](crate::execution::settle_first_frame) settled `result` into it, and +/// hands the settlement to [`Host::frame_settle`]. `held_reservoir` is the reservoir `gas` held +/// before that settlement. After a halt, revm's halt rule follows the hook: the regular gas left +/// in `gas` is consumed, as the settlement's own refunds are. The frame stack must be empty. +/// +/// # Errors +/// +/// [`StartLifecycleError::NotOpen`] when the transaction's start is not open, as a fatal error. +#[inline] +pub fn close_transaction_start<EVM: EvmTr + ?Sized>( + evm: &mut EVM, + result: &FrameResult, + gas: &mut GasTracker, + held_reservoir: u64, +) -> Result<(), ContextDbError<EVM::Context>> { + let status = settle_status(result); + let (ctx, _, _, frame_stack) = evm.all_mut(); + debug_assert!( + frame_stack.index().is_none(), + "the transaction's start closes on an empty frame stack" + ); + let settle = frame_stack + .close_start(0, status, created(result), held_reservoir) + .map_err(fatal)?; + ctx.frame_settle(&settle, gas); + if status == SettleStatus::Halt { + gas.spend_all(); + } + Ok(()) +} + +/// The successful boundary: every start the transaction opened must have settled. Ends the +/// lifecycle ([`LifecycleEnd::Settled`](context_interface::host::LifecycleEnd::Settled), handed to +/// [`Host::frame_lifecycle_end`] when a lifecycle was under way) and resets the record for the +/// next transaction. +/// +/// # Errors +/// +/// [`StartLifecycleError::Unsettled`] when a start is still open, a missed settlement, as a fatal +/// error. The lifecycle is then discarded +/// ([`LifecycleEnd::Discarded`](context_interface::host::LifecycleEnd::Discarded)), so the handler's +/// `catch_error` that reports the error owes no second end. +#[inline] +pub fn finish_transaction<EVM: EvmTr + ?Sized>( + evm: &mut EVM, +) -> Result<(), ContextDbError<EVM::Context>> { + let (ctx, _, _, frame_stack) = evm.all_mut(); + match frame_stack.settle_lifecycle() { + Ok(end) => { + if let Some(end) = end { + ctx.frame_lifecycle_end(end); + } + Ok(()) + } + Err(error) => { + if let Some(end) = frame_stack.discard_lifecycle() { + ctx.frame_lifecycle_end(end); + } + Err(fatal(error)) + } + } +} + +/// The fatal boundary: discards the starts still open, ends the lifecycle +/// ([`LifecycleEnd::Discarded`](context_interface::host::LifecycleEnd::Discarded), handed to +/// [`Host::frame_lifecycle_end`] when a lifecycle was under way) and resets the record for the +/// next transaction. Idempotent: a lifecycle already ended owes nothing. +/// +/// It resets the lifecycle only. Before the EVM runs another transaction, the frame stack must be +/// cleared too, as [`Handler::catch_error`](crate::Handler::catch_error) does (see the module's +/// "Reuse after an error"). +#[inline] +pub fn discard_transaction<EVM: EvmTr + ?Sized>(evm: &mut EVM) { + let (ctx, _, _, frame_stack) = evm.all_mut(); + if let Some(end) = frame_stack.discard_lifecycle() { + ctx.frame_lifecycle_end(end); + } +} diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index 5b3e70aed3..f542c49949 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -963,6 +963,8 @@ fn test_a_first_frame_settled_into_gas_with_unlimited_pools_and_no_reservoir_set let mut evm = Run::new(ends(Vec::new())).evm(); let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); + // A runner that settles a first frame it built itself opens the transaction's start first. + revm_handler::lifecycle::open_transaction_start(&mut evm).expect("the start opens"); Mainnet::default() .last_frame_result(&mut evm, &mut result, &mut gas) diff --git a/crates/inspector/src/handler.rs b/crates/inspector/src/handler.rs index 8297d850f1..154622c554 100644 --- a/crates/inspector/src/handler.rs +++ b/crates/inspector/src/handler.rs @@ -100,6 +100,8 @@ where }; // The runtime gas phase is complete: commit its state changes. evm.ctx().journal_mut().checkpoint_commit(); + // The transaction's start opens with the frame init revm made for it. + handler::lifecycle::open_frame_start(evm, &first_frame_input)?; // Run execution loop let mut frame_result = self.inspect_run_exec_loop(evm, first_frame_input)?; diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index 59425b4d5f..12e42fde6f 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -153,6 +153,9 @@ pub trait InspectorEvmTr: /// If frame has returned result it would hand it to [`EvmTr::frame_run_result`], then to the /// inspector's `frame_end`, and mark the frame as finished. A frame without an `EthFrame` is /// run by [`EvmTr::frame_run`], and its result handed to [`EvmTr::frame_run_result`] only. + /// + /// A frame init it returns opens the child's start, as [`EvmTr::frame_run`] does + /// ([`handler::lifecycle::open_frame_start`]). #[inline] fn inspect_frame_run( &mut self, @@ -175,6 +178,10 @@ pub trait InspectorEvmTr: instructions.gas_table(), ); let mut result = frame.process_next_action(ctx, next_action); + // revm consumed the frame's `NewFrame` action: the child's start opens. + if let Ok(ItemOrResult::Item(init)) = &result { + handler::lifecycle::open_frame_start(self, init)?; + } if let Ok(ItemOrResult::Result(frame_result)) = &mut result { self.frame_run_result(frame_result)?; diff --git a/crates/inspector/tests/custom_frame.rs b/crates/inspector/tests/custom_frame.rs index 4c939ae523..d3c79de9af 100644 --- a/crates/inspector/tests/custom_frame.rs +++ b/crates/inspector/tests/custom_frame.rs @@ -15,8 +15,8 @@ use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, instructions::{EthInstructions, InstructionProvider}, - EthFrame, EthPrecompiles, EvmTr, FrameInitOrResult, FrameResult, Handler, ItemOrResult, - MainContext, MainnetContext, + lifecycle, EthFrame, EthPrecompiles, EvmTr, FrameInitOrResult, FrameResult, Handler, + ItemOrResult, MainContext, MainnetContext, }; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, CallOutcome, FrameInput, @@ -198,6 +198,10 @@ impl EvmTr for Consumer { if let Ok(ItemOrResult::Result(_)) = &result { frame.set_finished(true); } + // An EVM that runs its frames itself opens the start of the child init it consumed. + if let Ok(ItemOrResult::Item(init)) = &result { + lifecycle::open_frame_start(self, init)?; + } result } @@ -214,10 +218,11 @@ impl EvmTr for Consumer { if frame_stack.index().is_none() { return Ok(Some(result)); } - frame_stack - .get() - .0 - .return_result::<_, ContextDbError<Ctx>>(ctx, result)?; + // An EVM that returns results itself settles the caller's open start after the return. + let caller = &mut frame_stack.get().0; + let returning = lifecycle::Returning::new(&result, caller); + caller.return_result::<_, ContextDbError<Ctx>>(ctx, result)?; + lifecycle::close_frame_start(ctx, frame_stack, returning, |frame| &mut frame.0)?; Ok(None) } } diff --git a/crates/inspector/tests/start_lifecycle.rs b/crates/inspector/tests/start_lifecycle.rs new file mode 100644 index 0000000000..d362af93b5 --- /dev/null +++ b/crates/inspector/tests/start_lifecycle.rs @@ -0,0 +1,590 @@ +//! The start lifecycle on revm's own runners, plain and inspected: every start revm opens settles +//! once, innermost first, and the transaction's boundary ends the lifecycle. +//! +//! The tests of the record and of the fatal errors run in every build. The tests that read the +//! events the hooks received need the lifecycle mirror the context keeps in debug builds only. +//! +//! [`PARENT`] calls [`CHILD`] (or the callee a test names) and then writes its slot 0; [`CHILD`] +//! writes its slot 0. + +use context::{ + context_interface::context::ContextError, + result::{EVMError, HaltReason}, + Context, ContextSetters, ContextTr, Evm, JournalTr, LocalContextTr, TxEnv, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + execution::settle_first_frame, instructions::EthInstructions, lifecycle, EthFrame, + EthPrecompiles, EvmTr, ExecuteEvm, FrameResult, Handler, ItemOrResult, MainBuilder, + MainContext, MainnetContext, MainnetHandler, +}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, + FrameInput, Gas, GasTracker, InstructionResult, Interpreter, InterpreterAction, + InterpreterResult, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{InspectEvm, Inspector, InspectorHandler}; +use state::{ + bytecode::opcode::{CALL, CREATE, PUSH0, PUSH1, PUSH20, PUSH3, SSTORE, STOP}, + AccountInfo, Bytecode, +}; +use std::convert::Infallible; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; +type MainEvm<I> = Evm<Ctx, I, EthInstructions<EthInterpreter, Ctx>, EthPrecompiles, EthFrame>; +type Error = EVMError<Infallible>; + +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +const CHILD: Address = address!("0x00000000000000000000000000000000000c0de1"); +const CREATOR: Address = address!("0x00000000000000000000000000000000000c0de2"); +const ECRECOVER: Address = address!("0x0000000000000000000000000000000000000001"); +const GAS_LIMIT: u64 = 1_000_000; + +/// What an inspector does to the run. Most modes are read by the event tests, which need a debug +/// build. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(debug_assertions), allow(dead_code))] +enum Mode { + Observe, + /// In `step_end` after the `CALL`: a fresh interpreter in place of the running one, which + /// returns at once. + ReplaceInterpreter, + /// In `step_end` after the `CALL`: the running frame's input depth rewritten, and the + /// `NewFrame` replaced with a return. + RewriteInputDepth, + /// In `step_end` after the `CALL`: the `NewFrame`'s input dropped and a copy put in its place. + ReplaceInput, + /// In `call(CHILD)`: a transaction run on a clone of the running context. + CloneSimulation, + /// In `call(CHILD)`: a transaction run on an EVM of its own. + IndependentEvm, + /// In `call(CHILD)`, once: a fatal error recorded on the context, as a failed lookup records + /// one. + FatalChildError, +} + +struct Edit { + mode: Mode, + done: bool, +} + +impl Edit { + const fn new(mode: Mode) -> Self { + Self { mode, done: false } + } +} + +impl Inspector<Ctx> for Edit { + fn step_end(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + if self.done { + return; + } + let Some(InterpreterAction::NewFrame(FrameInput::Call(inputs))) = interp.bytecode.action() + else { + return; + }; + let copy = (**inputs).clone(); + let ret = InterpreterAction::Return(InterpreterResult::new( + InstructionResult::Return, + Bytes::new(), + Gas::new(0), + )); + match self.mode { + Mode::ReplaceInterpreter => { + *interp = Interpreter::default(); + interp.bytecode.set_action(ret); + } + Mode::RewriteInputDepth => { + interp.input.depth += 1; + *interp.bytecode.action() = Some(ret); + } + Mode::ReplaceInput => { + drop(interp.bytecode.action().take()); + *interp.bytecode.action() = Some(InterpreterAction::NewFrame(FrameInput::Call( + Box::new(copy), + ))); + } + _ => return, + } + self.done = true; + } + + fn call(&mut self, ctx: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + if inputs.target_address != CHILD || self.done { + return None; + } + match self.mode { + Mode::CloneSimulation => { + let mut nested = ctx.clone().build_mainnet(); + let tx = precompile_tx().nonce(1).build_fill(); + assert!(nested + .transact(tx) + .expect("the simulation runs") + .result + .is_success()); + } + Mode::IndependentEvm => { + let mut nested = Context::mainnet().with_db(Db::default()).build_mainnet(); + let tx = precompile_tx().build_fill(); + assert!(nested + .transact(tx) + .expect("the nested EVM runs") + .result + .is_success()); + } + Mode::FatalChildError => { + *ctx.error() = Err(ContextError::Custom("injected".into())); + } + _ => return None, + } + self.done = true; + None + } +} + +fn precompile_tx() -> context::tx::TxEnvBuilder { + TxEnv::builder_for_bench() + .kind(TxKind::Call(ECRECOVER)) + .gas_price(0) + .gas_limit(GAS_LIMIT) +} + +fn account(code: Vec<u8>) -> AccountInfo { + let code = Bytecode::new_raw(code.into()); + AccountInfo::new(U256::ZERO, 1, code.hash_slow(), code) +} + +/// [`PARENT`] calling `callee`, [`CHILD`], and [`CREATOR`], which creates an empty contract. +fn db(callee: Address) -> Db { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + let mut parent = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + parent.extend_from_slice(callee.as_slice()); + parent.extend_from_slice(&[PUSH3, 0x01, 0x00, 0x00, CALL, PUSH1, 1, PUSH0, SSTORE, STOP]); + db.insert_account_info(PARENT, account(parent)); + db.insert_account_info(CHILD, account(vec![PUSH1, 2, PUSH0, SSTORE, STOP])); + db.insert_account_info(CREATOR, account(vec![PUSH0, PUSH0, PUSH0, CREATE, STOP])); + db +} + +fn context(callee: Address, spec: SpecId) -> Ctx { + Context::mainnet() + .with_db(db(callee)) + .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(spec)) +} + +fn evm() -> MainEvm<()> { + context(CHILD, SpecId::OSAKA).build_mainnet() +} + +fn inspected(mode: Mode) -> MainEvm<Edit> { + context(CHILD, SpecId::OSAKA).build_mainnet_with_inspector(Edit::new(mode)) +} + +fn tx(to: Address, nonce: u64) -> TxEnv { + TxEnv::builder_for_bench() + .kind(TxKind::Call(to)) + .nonce(nonce) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill() +} + +/// The record is as a transaction's boundary leaves it: no lifecycle under way, nothing open. +fn assert_clear<I>(evm: &mut MainEvm<I>) { + assert!( + !evm.frame_stack.lifecycle_active(), + "a lifecycle is still under way" + ); + assert!(evm.frame_stack.lifecycle_settled(), "a start is still open"); +} + +fn assert_fatal<T: core::fmt::Debug>(result: Result<T, Error>, message: &str) { + match result { + Err(EVMError::Custom(error)) => assert!(error.contains(message), "{error}"), + other => panic!("expected the fatal error {message:?}, got {other:?}"), + } +} + +/// Every transaction a reused EVM runs, plain and inspected, starts from a clear record and +/// leaves one. (`transact` commits nothing to the database, so each runs at nonce 0.) +#[test] +fn test_a_reused_evm_runs_each_transaction_on_a_clear_record() { + let mut evm = inspected(Mode::Observe); + for _ in 0..3 { + assert!(evm + .transact(tx(PARENT, 0)) + .expect("runs") + .result + .is_success()); + assert_clear(&mut evm); + assert!(evm + .inspect_tx(tx(PARENT, 0)) + .expect("runs") + .result + .is_success()); + assert_clear(&mut evm); + } +} + +/// A fatal error in a child discards the lifecycle at the handler's fatal boundary, and the EVM +/// runs the next transaction. +#[test] +fn test_a_fatal_child_error_discards_the_lifecycle_and_the_evm_is_reused() { + let mut evm = inspected(Mode::FatalChildError); + assert_fatal(evm.inspect_tx(tx(PARENT, 0)), "injected"); + assert_clear(&mut evm); + assert!(evm + .inspect_tx(tx(PARENT, 0)) + .expect("reused") + .result + .is_success()); + assert_clear(&mut evm); +} + +/// A caller of `run_without_catch_error` that drops an error makes the cleanup `catch_error` +/// makes before it reuses the EVM: discarding the lifecycle alone leaves the frame stack's index, +/// so the next transaction's start would open under a frame with no start. +#[test] +fn test_reuse_after_an_uncaught_error_needs_the_frame_stack_cleared() { + let fail = |evm: &mut MainEvm<Edit>| { + evm.inspector.done = false; + evm.ctx.set_tx(tx(PARENT, 0)); + let mut handler = MainnetHandler::<_, Error, EthFrame>::default(); + assert!(handler.inspect_run_without_catch_error(evm).is_err()); + assert!( + evm.frame_stack.lifecycle_active(), + "nothing discarded the lifecycle" + ); + }; + + // With nothing cleaned up, the journal still holds the dropped transaction's nonce. + let mut evm = inspected(Mode::FatalChildError); + fail(&mut evm); + assert_fatal( + evm.inspect_tx(tx(PARENT, 1)), + "a start opened where one is still open", + ); + + let mut evm = inspected(Mode::FatalChildError); + fail(&mut evm); + lifecycle::discard_transaction(&mut evm); + evm.ctx.journal_mut().discard_tx(); + assert_fatal(evm.inspect_tx(tx(PARENT, 0)), "under a frame with no start"); + + let mut evm = inspected(Mode::FatalChildError); + fail(&mut evm); + lifecycle::discard_transaction(&mut evm); + evm.ctx.journal_mut().discard_tx(); + evm.ctx.local_mut().clear(); + evm.frame_stack.clear(); + assert!(evm + .inspect_tx(tx(PARENT, 0)) + .expect("reused") + .result + .is_success()); + assert_clear(&mut evm); +} + +/// The mainnet handler with a `last_frame_result` that settles the transaction's frame but does +/// not close the transaction's start, as an override that misses the call would. +#[derive(Default)] +struct MissesTheClose; + +impl Handler for MissesTheClose { + type Evm = MainEvm<()>; + type Error = Error; + type HaltReason = HaltReason; + + fn last_frame_result( + &mut self, + evm: &mut Self::Evm, + frame_result: &mut FrameResult, + parent_gas: &mut GasTracker, + ) -> Result<(), Self::Error> { + settle_first_frame::<_, Self::Error>(evm.ctx(), frame_result, parent_gas)?; + *frame_result.gas_mut().tracker_mut() = *parent_gas; + Ok(()) + } +} + +/// A missed settlement is a fatal error at the successful boundary, in every build, and the +/// boundary discards the lifecycle, so the EVM runs the next transaction. +#[test] +fn test_a_missed_settlement_fails_the_transaction_at_the_successful_boundary() { + let mut evm = evm(); + evm.ctx.set_tx(tx(PARENT, 0)); + assert_fatal( + MissesTheClose.run(&mut evm), + "the transaction ended with a start open", + ); + assert_clear(&mut evm); + assert!(evm + .transact(tx(PARENT, 0)) + .expect("reused") + .result + .is_success()); +} + +/// A runner that drives the transaction's frame itself without opening the transaction's start: +/// the frame's child has no parent, and the transaction's settlement finds no open start. +#[test] +fn test_a_runner_that_skips_the_transactions_start_is_refused() { + let mut runner = evm(); + runner.ctx.set_tx(tx(PARENT, 0)); + let mut handler = MainnetHandler::<_, Error, EthFrame>::default(); + let mut gas = handler.tx_gas(&mut runner, &Default::default()); + let init = handler + .first_frame_input(&mut runner, &mut gas) + .expect("the frame's input") + .expect("the runtime gas phase passes"); + let ItemOrResult::Item(_) = runner.frame_init(init).expect("the frame starts") else { + panic!("PARENT runs"); + }; + let error = runner.frame_run().expect_err("the call opens no start"); + assert!( + matches!(&error, ContextError::Custom(e) if e.contains("under a frame with no start")), + "{error:?}" + ); + + let mut evm = evm(); + let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); + let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); + let error = handler + .last_frame_result(&mut evm, &mut result, &mut gas) + .expect_err("the transaction's start is not open"); + assert!( + matches!(&error, EVMError::Custom(e) if e.contains("found no open start")), + "{error:?}" + ); +} + +/// The events the hooks received, which the mirror the context keeps in debug builds records. +#[cfg(debug_assertions)] +mod events { + use super::*; + use context::context_interface::{ + host::{FrameSplit, LifecycleEnd}, + FrameStack, Host, LifecycleEvent, + }; + + fn describe(event: &LifecycleEvent) -> String { + match event { + LifecycleEvent::Split(split) => format!( + "split {} parent {:?} depth {}", + split.id, split.parent, split.depth + ), + LifecycleEvent::Settle(settle) => { + let mut line = format!( + "settle {} depth {} {:?}", + settle.id, settle.depth, settle.status + ); + if let Some(created) = settle.created { + line.push_str(&format!(" created {created}")); + } + for (flag, name) in [ + (settle.inspector_answer, "inspector-answer"), + (settle.gas_replaced, "gas-replaced"), + (settle.outcome_rebuilt, "outcome-rebuilt"), + ] { + if flag { + line.push(' '); + line.push_str(name); + } + } + line + } + LifecycleEvent::End(end) => format!("end {end:?}"), + } + } + + pub(super) fn events<I>(evm: &mut MainEvm<I>) -> Vec<String> { + let mirror = evm + .ctx + .local + .lifecycle_mirror() + .expect("a debug build keeps one"); + mirror.events().iter().map(describe).collect() + } + + pub(super) const PAIRED: [&str; 5] = [ + "split 1 parent None depth 0", + "split 2 parent Some(1) depth 1", + "settle 2 depth 1 Ok", + "settle 1 depth 0 Ok", + "end Settled", + ]; + + const ROOT_ONLY: [&str; 3] = [ + "split 1 parent None depth 0", + "settle 1 depth 0 Ok", + "end Settled", + ]; + + fn inspect(mode: Mode, callee: Address) -> Vec<String> { + let mut evm = context(callee, SpecId::OSAKA).build_mainnet_with_inspector(Edit::new(mode)); + let result = evm.inspect_tx(tx(PARENT, 0)).expect("runs"); + assert!(result.result.is_success(), "{mode:?}: {:?}", result.result); + events(&mut evm) + } + + #[test] + fn test_a_plain_run_settles_one_start_per_frame() { + let mut evm = evm(); + assert!(evm + .transact(tx(PARENT, 0)) + .expect("runs") + .result + .is_success()); + assert_eq!(events(&mut evm), PAIRED); + } + + #[test] + fn test_an_observed_run_settles_one_start_per_frame() { + assert_eq!(inspect(Mode::Observe, CHILD), PAIRED); + } + + #[test] + fn test_a_precompiles_answer_settles_the_start_it_answers() { + assert_eq!(inspect(Mode::Observe, ECRECOVER), PAIRED); + } + + #[test] + fn test_a_replaced_interpreter_leaves_no_start_open() { + assert_eq!(inspect(Mode::ReplaceInterpreter, CHILD), ROOT_ONLY); + } + + #[test] + fn test_a_rewritten_input_depth_changes_no_start() { + assert_eq!(inspect(Mode::RewriteInputDepth, CHILD), ROOT_ONLY); + } + + #[test] + fn test_a_replaced_input_opens_its_own_start() { + assert_eq!(inspect(Mode::ReplaceInput, CHILD), PAIRED); + } + + #[test] + fn test_a_simulation_on_a_cloned_context_leaves_the_outer_lifecycle_paired() { + assert_eq!(inspect(Mode::CloneSimulation, CHILD), PAIRED); + } + + #[test] + fn test_an_independent_nested_evm_leaves_the_outer_lifecycle_paired() { + assert_eq!(inspect(Mode::IndependentEvm, CHILD), PAIRED); + } + + #[test] + fn test_a_fatal_child_error_ends_the_lifecycle_discarded() { + let mut evm = inspected(Mode::FatalChildError); + assert!(evm.inspect_tx(tx(PARENT, 0)).is_err()); + assert_eq!( + events(&mut evm), + [ + "split 1 parent None depth 0", + "split 2 parent Some(1) depth 1", + "end Discarded", + ] + ); + assert!(evm + .inspect_tx(tx(PARENT, 0)) + .expect("reused") + .result + .is_success()); + assert_eq!(events(&mut evm), PAIRED); + } + + #[test] + fn test_a_creation_reports_the_address_it_took() { + let mut evm = evm(); + assert!(evm + .transact(tx(CREATOR, 0)) + .expect("runs") + .result + .is_success()); + assert_eq!( + events(&mut evm), + [ + "split 1 parent None depth 0", + "split 2 parent Some(1) depth 1", + "settle 2 depth 1 Ok created true", + "settle 1 depth 0 Ok", + "end Settled", + ] + ); + let creation = TxEnv::builder_for_bench() + .kind(TxKind::Create) + .data(Bytes::from_static(&[STOP])) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill(); + assert!(evm.transact(creation).expect("runs").result.is_success()); + assert_eq!( + events(&mut evm), + [ + "split 1 parent None depth 0", + "settle 1 depth 0 Ok created true", + "end Settled", + ] + ); + } + + /// A transaction whose runtime gas phase runs out of gas settles the stand-in for its frame + /// on the transaction's start. + #[test] + fn test_the_runtime_out_of_gas_stand_in_settles_the_transactions_start() { + use primitives::{eip2780, eip8038}; + let mut evm = Context::mainnet() + .with_db(db(CHILD)) + .modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM); + cfg.tx_gas_limit_cap = Some(u64::MAX); + }) + .build_mainnet(); + let empty = address!("0x00000000000000000000000000000000000000ab"); + let tx = TxEnv::builder_for_bench() + .kind(TxKind::Call(empty)) + .value(U256::from(1)) + .gas_price(0) + .gas_limit( + eip2780::TX_BASE_COST + eip8038::COLD_ACCOUNT_ACCESS + eip2780::TX_VALUE_COST, + ) + .build_fill(); + assert!(evm.transact(tx).expect("included").result.is_halt()); + assert_eq!( + events(&mut evm), + [ + "split 1 parent None depth 0", + "settle 1 depth 0 Halt", + "end Settled", + ] + ); + } + + #[test] + fn test_a_system_call_settles_every_start() { + use handler::SystemCallEvm; + let mut evm = evm(); + let result = evm + .system_call_one(PARENT, Bytes::new()) + .expect("the system call runs"); + assert!(result.is_success()); + assert_eq!(events(&mut evm), PAIRED); + } + + /// The context hands every event to its mirror: one that does not fit fails the check. + #[test] + #[should_panic(expected = "the transaction's start 1 at depth 5")] + fn test_the_contexts_hooks_feed_the_mirror() { + let mut ctx = context(CHILD, SpecId::OSAKA); + let mut stack = FrameStack::<EthFrame>::new(); + let split: FrameSplit = stack.open_start(5).expect("the record opens it"); + ctx.frame_split(&split); + ctx.frame_lifecycle_end(LifecycleEnd::Settled); + } +} From 0094ea46ad86b170681791b2c9485b90a7dbe1e4 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 11:55:58 +0800 Subject: [PATCH 084/110] feat(inspector): report an inspector's answer, a replaced tracker and a rebuilt outcome on the settlement revm marks a start's result just before an inspector's end callbacks and checks the marks just after: a StartMark (u32) on the gas tracker and an OutcomeMark (u16) on the call or creation outcome, each in existing padding. The settlement reports inspector_answer, gas_replaced and outcome_rebuilt from what the inspected run recorded on the start. The marks take no part in the values: they always compare equal, hash to nothing, are left out of the debug output, which keeps the derived output, and are not encoded. The outcomes gain the public start_mark field, which a struct literal names. --- crates/context/interface/src/cfg/gas.rs | 49 +++- .../context/interface/src/cfg/gas/encoding.rs | 1 + crates/context/interface/src/cfg/gas/mark.rs | 128 ++++++++++ crates/handler/src/frame.rs | 5 +- crates/handler/src/lifecycle.rs | 49 +++- crates/inspector/src/traits.rs | 31 ++- crates/inspector/tests/start_lifecycle.rs | 226 ++++++++++++++++++ .../src/interpreter_action/call_outcome.rs | 30 ++- .../src/interpreter_action/create_outcome.rs | 25 +- crates/interpreter/src/lib.rs | 4 +- crates/interpreter/tests/start_marks.rs | 105 ++++++++ 11 files changed, 640 insertions(+), 13 deletions(-) create mode 100644 crates/context/interface/src/cfg/gas/mark.rs create mode 100644 crates/interpreter/tests/start_marks.rs diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index b2b885eebe..84c32c8c27 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -8,11 +8,13 @@ mod encoding; mod failed_charge; mod forward; mod history_allowance; +mod mark; mod pools; mod start_charge; mod withheld; pub use forward::ChildShares; +pub use mark::{OutcomeMark, StartMark}; pub use pools::{PoolAmounts, PoolId}; pub use start_charge::StartCharge; pub use withheld::WithheldCrossing; @@ -90,7 +92,11 @@ pub use withheld::WithheldCrossing; /// as with upstream's own field additions: it reads the old fields in their places and then /// looks for the new ones, so a tracker persisted in such a format must not cross an upgrade of /// this crate that adds a field. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +/// +/// The tracker also carries the [`StartMark`] revm writes on a frame result's tracker before an +/// inspector's end callbacks. The mark is no part of the tracker's value: equality, hashing, the +/// debug output and the encoding leave it out, and a decoded tracker carries none. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), @@ -207,6 +213,32 @@ pub struct GasTracker { /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as zero. history_allowance: u64, + /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)), in the padding + /// after `pool_crossings`. No part of the tracker's value, and not encoded. + start_mark: StartMark, +} + +impl core::fmt::Debug for GasTracker { + /// The output the derive gives the tracker's figures, in their order; the mark is left out. + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("GasTracker") + .field("gas_limit", &self.gas_limit) + .field("remaining", &self.remaining) + .field("reservoir", &self.reservoir) + .field("state_gas_spent", &self.state_gas_spent) + .field("state_gas_spilled", &self.state_gas_spilled) + .field("history_gas_spent", &self.history_gas_spent) + .field("refunded", &self.refunded) + .field("withheld", &self.withheld) + .field("withheld_crossing", &self.withheld_crossing) + .field("failed_charge_remaining", &self.failed_charge_remaining) + .field("failed_charge_recorded", &self.failed_charge_recorded) + .field("pools_remaining", &self.pools_remaining) + .field("pools_spent", &self.pools_spent) + .field("pool_crossings", &self.pool_crossings) + .field("history_allowance", &self.history_allowance) + .finish() + } } impl Default for GasTracker { @@ -237,9 +269,24 @@ impl GasTracker { pools_spent: [0; PoolId::COUNT], pool_crossings: 0, history_allowance: 0, + start_mark: StartMark::NONE, } } + /// The start revm marked this tracker for before an inspector's end callbacks, or + /// [`StartMark::NONE`]. + #[inline] + pub const fn start_mark(&self) -> StartMark { + self.start_mark + } + + /// Marks this tracker for a start. revm marks a start's result before an inspector's end + /// callbacks and reads the mark after them; a consumer has no reason to set it. + #[inline] + pub const fn set_start_mark(&mut self, mark: StartMark) { + self.start_mark = mark; + } + /// Creates a new `GasTracker` with the given used gas and reservoir. /// Remaining gas saturates at zero when used gas exceeds the gas limit. #[inline] diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index bf2d8ecbdf..3c9ffe5015 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -87,6 +87,7 @@ impl From<Encoded> for GasTracker { pools_spent: encoded.pools_spent, pool_crossings: 0, history_allowance: encoded.history_allowance, + start_mark: super::StartMark::NONE, }; tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); for (pool, crossing) in PoolId::ALL.into_iter().zip(encoded.pool_crossings) { diff --git a/crates/context/interface/src/cfg/gas/mark.rs b/crates/context/interface/src/cfg/gas/mark.rs new file mode 100644 index 0000000000..b0e2379f7f --- /dev/null +++ b/crates/context/interface/src/cfg/gas/mark.rs @@ -0,0 +1,128 @@ +//! The marks revm writes on a frame's result just before an inspector's end callbacks, and reads +//! just after, to tell whether the callbacks put another value in the result's place: the +//! [`StartMark`] on the result's gas tracker and the [`OutcomeMark`] on its outcome. +//! +//! A mark takes no part in the value it rides on: marks always compare equal, hash to nothing, +//! print nothing and are not serialized (a decoded value carries none). So a marked tracker or +//! outcome compares, hashes, prints and encodes as the same value unmarked. Each fits padding of +//! the type that carries it, so neither grows. + +/// The mark of a start on a gas tracker: the start's identity, or none. +/// +/// revm marks the tracker of a start's result for the start before an inspector's end callbacks; +/// a tracker that does not carry the mark after them is one the callbacks put in its place +/// ([`FrameSettle::gas_replaced`](crate::host::FrameSettle::gas_replaced)). A copy of the +/// tracker carries the mark with it. +#[derive(Clone, Copy, Default)] +pub struct StartMark(u32); + +impl StartMark { + /// No mark, as every tracker is built. + pub const NONE: Self = Self(0); + + /// The mark of the start `id`. + #[inline] + pub const fn for_start(id: u32) -> Self { + Self(id) + } + + /// Whether this is the mark of the start `id`. + #[inline] + pub const fn is_for(self, id: u32) -> bool { + self.0 != 0 && self.0 == id + } +} + +/// The mark of a start on a call's or creation's outcome: 16 bits of the start's identity, or +/// none. +/// +/// revm marks the outcome of a start's result for the start before an inspector's end callbacks; +/// an outcome that does not carry the mark after them is one the callbacks put in its place +/// ([`FrameSettle::outcome_rebuilt`](crate::host::FrameSettle::outcome_rebuilt)), such as one a +/// constructor built around the same result. A start's mark is never none, so a built outcome +/// never carries it; two starts share a mark only when their identities are 65,535 apart. +#[derive(Clone, Copy, Default)] +pub struct OutcomeMark(u16); + +impl OutcomeMark { + /// No mark, as every constructor builds an outcome. + pub const NONE: Self = Self(0); + + /// The mark of the start `id`: `(id - 1) % 65535 + 1`, never none. + #[inline] + pub const fn for_start(id: u32) -> Self { + Self((id.wrapping_sub(1) % 65535 + 1) as u16) + } + + /// Whether this is the mark of the start `id`. + #[inline] + pub const fn is_for(self, id: u32) -> bool { + self.0 == Self::for_start(id).0 + } +} + +macro_rules! transparent { + ($mark:ident) => { + impl PartialEq for $mark { + #[inline] + fn eq(&self, _: &Self) -> bool { + true + } + } + + impl Eq for $mark {} + + impl core::hash::Hash for $mark { + #[inline] + fn hash<H: core::hash::Hasher>(&self, _: &mut H) {} + } + + impl core::fmt::Debug for $mark { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(stringify!($mark)) + } + } + }; +} + +transparent!(StartMark); +transparent!(OutcomeMark); + +#[cfg(test)] +mod tests { + use super::{OutcomeMark, StartMark}; + + #[test] + fn test_a_start_mark_names_its_start_only() { + let mark = StartMark::for_start(7); + assert!(mark.is_for(7)); + assert!(!mark.is_for(8)); + assert!(!StartMark::NONE.is_for(0), "no mark names no start"); + } + + /// The outcome's mark is never none for a start, and two starts share one only 65,535 + /// identities apart. + #[test] + fn test_an_outcome_mark_is_never_none_and_repeats_every_65535_starts() { + for id in [ + 1u32, + 2, + 65_534, + 65_535, + 65_536, + 65_537, + 131_070, + 131_071, + u32::MAX - 1, + u32::MAX, + ] { + assert!(!OutcomeMark::NONE.is_for(id), "id {id} has no mark"); + assert!(OutcomeMark::for_start(id).is_for(id), "id {id}"); + if id > 1 { + assert!(!OutcomeMark::for_start(id).is_for(id - 1), "id {id}"); + } + } + assert!(OutcomeMark::for_start(1).is_for(65_536)); + assert!(!OutcomeMark::for_start(1).is_for(65_535)); + } +} diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 78930ff438..67ff82241a 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -18,7 +18,7 @@ use interpreter::{ interpreter_types::ReturnData, CallInput, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, CreateScheme, FrameInput, Gas, GasTracker, InputsImpl, InstructionResult, Interpreter, InterpreterAction, - InterpreterResult, InterpreterTypes, SharedMemory, StartCharge, + InterpreterResult, InterpreterTypes, OutcomeMark, SharedMemory, StartCharge, }; use primitives::{ constants::CALL_STACK_LIMIT, @@ -183,6 +183,7 @@ impl EthFrame<EthInterpreter> { charged_new_account_state_gas, charged_state_gas_address, charged_start, + start_mark: OutcomeMark::NONE, }))) }; @@ -245,6 +246,7 @@ impl EthFrame<EthInterpreter> { charged_new_account_state_gas, charged_state_gas_address, charged_start, + start_mark: OutcomeMark::NONE, }))); } @@ -330,6 +332,7 @@ impl EthFrame<EthInterpreter> { charged_create_state_gas, charged_state_gas_address, charged_start, + start_mark: OutcomeMark::NONE, }))) }; diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs index 568c9d41e3..b68c37e253 100644 --- a/crates/handler/src/lifecycle.rs +++ b/crates/handler/src/lifecycle.rs @@ -22,6 +22,12 @@ //! [`Host::frame_lifecycle_end`]). A step the record refuses ([`StartLifecycleError`]) is a fatal //! error of the transaction in every build. //! +//! An inspector's end callbacks may put another gas tracker or another outcome in a result's +//! place. revm marks the result for its start before them ([`mark_for_end_callbacks`]) and checks +//! the marks after them ([`check_end_callbacks`]), and an inspector's answer to a start is +//! recorded on it too ([`PendingStart::set_inspector_answer`]): the settlement reports all three +//! ([`FrameSettle`](context_interface::host::FrameSettle)). +//! //! A chain's handler that overrides one of these methods makes the call the mainnet method makes, //! in the same place: [`close_transaction_start`] in `last_frame_result`, [`finish_transaction`] //! in `execution_result` and [`discard_transaction`] in `catch_error`. An EVM that reimplements @@ -51,9 +57,11 @@ use crate::{evm::ContextDbError, EthFrame, EvmTr, FrameResult}; use context_interface::{ - context::ContextError, host::SettleStatus, FrameStack, Host, StartLifecycleError, + context::ContextError, host::SettleStatus, FrameStack, Host, PendingStart, StartLifecycleError, +}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, GasTracker, OutcomeMark, StartMark, }; -use interpreter::{interpreter::EthInterpreter, interpreter_action::FrameInit, GasTracker}; use std::string::ToString; /// A refused step as the transaction's fatal error. @@ -256,3 +264,40 @@ pub fn discard_transaction<EVM: EvmTr + ?Sized>(evm: &mut EVM) { ctx.frame_lifecycle_end(end); } } + +/// Marks `result`, the result of `start`, for the start, just before an inspector's end +/// callbacks (`frame_end`, `call_end`, `create_end`): its gas tracker with a [`StartMark`] and its +/// outcome with an [`OutcomeMark`]. Neither mark is part of the values' public semantics. +#[inline] +pub const fn mark_for_end_callbacks(result: &mut FrameResult, start: &PendingStart) { + let id = start.id(); + result + .gas_mut() + .tracker_mut() + .set_start_mark(StartMark::for_start(id)); + let mark = OutcomeMark::for_start(id); + match result { + FrameResult::Call(outcome) => outcome.start_mark = mark, + FrameResult::Create(outcome) => outcome.start_mark = mark, + } +} + +/// Records on `start`, just after an inspector's end callbacks, what they put in place of +/// `result`'s gas tracker and outcome: a tracker without the start's mark +/// ([`PendingStart::set_gas_replaced`]) and an outcome without it +/// ([`PendingStart::set_outcome_rebuilt`]). A callback that edits the values in place, or copies +/// them, keeps the marks. +#[inline] +pub const fn check_end_callbacks(result: &FrameResult, start: &mut PendingStart) { + let id = start.id(); + if !result.gas().tracker().start_mark().is_for(id) { + start.set_gas_replaced(); + } + let outcome_mark = match result { + FrameResult::Call(outcome) => outcome.start_mark, + FrameResult::Create(outcome) => outcome.start_mark, + }; + if !outcome_mark.is_for(id) { + start.set_outcome_rebuilt(); + } +} diff --git a/crates/inspector/src/traits.rs b/crates/inspector/src/traits.rs index 12e42fde6f..026be03137 100644 --- a/crates/inspector/src/traits.rs +++ b/crates/inspector/src/traits.rs @@ -2,7 +2,7 @@ use context::{ContextTr, FrameStack, JournalTr}; use handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, instructions::InstructionProvider, - EthFrame, EvmTr, FrameInitOrResult, FrameResult, ItemOrResult, + lifecycle, EthFrame, EvmTr, FrameInitOrResult, FrameResult, ItemOrResult, }; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, @@ -104,9 +104,18 @@ pub trait InspectorEvmTr: &mut self, mut frame_init: <Self::Frame as FrameTr>::FrameInit, ) -> Result<FrameInitResult<'_, Self::Frame>, ContextDbError<Self::Context>> { - let (ctx, inspector) = self.ctx_inspector(); + let (ctx, _, _, frame_stack, inspector) = self.all_mut_inspector(); if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + // The inspector answered the start revm opened for this init. + let start = frame_stack.pending_start(); + if let Some(start) = &start { + lifecycle::mark_for_end_callbacks(&mut output, start); + } frame_end(ctx, inspector, &frame_init.frame_input, &mut output); + if let Some(start) = start { + start.set_inspector_answer(); + lifecycle::check_end_callbacks(&output, start); + } return Ok(ItemOrResult::Result(output)); } @@ -130,7 +139,14 @@ pub trait InspectorEvmTr: inspector.log(ctx, log); } } + if let Some(start) = self.frame_stack().pending_start() { + lifecycle::mark_for_end_callbacks(&mut output, start); + } + let (ctx, inspector) = self.ctx_inspector(); frame_end(ctx, inspector, &frame_input, &mut output); + if let Some(start) = self.frame_stack().pending_start() { + lifecycle::check_end_callbacks(&output, start); + } return Ok(ItemOrResult::Result(output)); } @@ -155,7 +171,7 @@ pub trait InspectorEvmTr: /// run by [`EvmTr::frame_run`], and its result handed to [`EvmTr::frame_run_result`] only. /// /// A frame init it returns opens the child's start, as [`EvmTr::frame_run`] does - /// ([`handler::lifecycle::open_frame_start`]). + /// ([`lifecycle::open_frame_start`]). #[inline] fn inspect_frame_run( &mut self, @@ -180,17 +196,24 @@ pub trait InspectorEvmTr: let mut result = frame.process_next_action(ctx, next_action); // revm consumed the frame's `NewFrame` action: the child's start opens. if let Ok(ItemOrResult::Item(init)) = &result { - handler::lifecycle::open_frame_start(self, init)?; + lifecycle::open_frame_start(self, init)?; } if let Ok(ItemOrResult::Result(frame_result)) = &mut result { self.frame_run_result(frame_result)?; + // The result settles the start the frame runs for. + if let Some(start) = self.frame_stack().running_start() { + lifecycle::mark_for_end_callbacks(frame_result, start); + } let (ctx, inspector, frame) = self.ctx_inspector_frame(); // TODO When all_mut fn is added we can fetch inspector at the top of the function.s if let Some(frame) = frame.eth_frame() { frame_end(ctx, inspector, &frame.input, frame_result); frame.set_finished(true); } + if let Some(start) = self.frame_stack().running_start() { + lifecycle::check_end_callbacks(frame_result, start); + } }; result } diff --git a/crates/inspector/tests/start_lifecycle.rs b/crates/inspector/tests/start_lifecycle.rs index d362af93b5..7ef724cd16 100644 --- a/crates/inspector/tests/start_lifecycle.rs +++ b/crates/inspector/tests/start_lifecycle.rs @@ -364,6 +364,46 @@ fn test_a_runner_that_skips_the_transactions_start_is_refused() { ); } +/// A marked tracker and outcome compare, hash and print as the same values unmarked. +#[test] +fn test_the_marks_take_no_part_in_the_values() { + use interpreter::{CreateOutcome, OutcomeMark, StartMark}; + use std::hash::{BuildHasher, BuildHasherDefault, DefaultHasher}; + let hash = + |tracker: &GasTracker| BuildHasherDefault::<DefaultHasher>::default().hash_one(tracker); + + let plain = GasTracker::new(100, 90, 5); + let mut marked = plain; + marked.set_start_mark(StartMark::for_start(7)); + assert!(marked.start_mark().is_for(7)); + assert_eq!(marked, plain); + assert_eq!(hash(&marked), hash(&plain)); + assert_eq!(format!("{marked:?}"), format!("{plain:?}")); + + let result = InterpreterResult::new(InstructionResult::Stop, Bytes::new(), Gas::new(10)); + let call = CallOutcome::new(result.clone(), 0..0); + let marked_call = CallOutcome { + start_mark: OutcomeMark::for_start(7), + ..call.clone() + }; + assert_eq!(marked_call, call); + assert_eq!(format!("{marked_call:?}"), format!("{call:?}")); + let create = CreateOutcome::new(result, None); + let marked_create = CreateOutcome { + start_mark: OutcomeMark::for_start(7), + ..create.clone() + }; + assert_eq!(marked_create, create); + assert_eq!(format!("{marked_create:?}"), format!("{create:?}")); + for printed in [ + format!("{marked:?}"), + format!("{marked_call:?}"), + format!("{marked_create:?}"), + ] { + assert!(!printed.contains("Mark"), "{printed}"); + } +} + /// The events the hooks received, which the mirror the context keeps in debug builds records. #[cfg(debug_assertions)] mod events { @@ -577,6 +617,192 @@ mod events { assert_eq!(events(&mut evm), PAIRED); } + /// What an inspector does to a start's result, which revm reports on the settlement. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Flag { + /// `call` answers with an outcome a constructor built. + Answer, + /// `call_end` puts a constructor-built tracker in the result's gas. + ReplaceGas, + /// `call_end` restores the tracker it saved when the frame's interpreter started. + RestoreSnapshot, + /// `call_end` rewrites the status only. + RewriteStatus, + /// `call_end` builds a new outcome around the same result. + RebuildOutcome, + /// `call_end` rebuilds the outcome and its result, keeping the outcome's other fields and + /// the result's gas. + KeepOutcome, + /// `create_end` builds a new outcome around the same result and address. + RebuildCreation, + } + + struct Rewrite { + flag: Flag, + target: Address, + snapshot: Option<Gas>, + } + + impl Inspector<Ctx> for Rewrite { + fn initialize_interp(&mut self, interp: &mut Interpreter, _: &mut Ctx) { + if interp.input.target_address == self.target { + self.snapshot = Some(interp.gas); + } + } + + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + (self.flag == Flag::Answer && inputs.target_address == self.target).then(|| { + CallOutcome::new( + InterpreterResult::new( + InstructionResult::Return, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address != self.target { + return; + } + match self.flag { + Flag::ReplaceGas => outcome.result.gas = Gas::new(inputs.gas_limit), + Flag::RestoreSnapshot => { + outcome.result.gas = self.snapshot.expect("the frame's interpreter started"); + } + Flag::RewriteStatus => outcome.result.result = InstructionResult::Revert, + Flag::RebuildOutcome => { + *outcome = + CallOutcome::new(outcome.result.clone(), outcome.memory_offset.clone()); + } + Flag::KeepOutcome => { + let result = InterpreterResult::new( + outcome.result.result, + outcome.result.output.clone(), + outcome.result.gas, + ); + *outcome = CallOutcome { + result, + ..outcome.clone() + }; + } + Flag::Answer | Flag::RebuildCreation => {} + } + } + + fn create_end( + &mut self, + _: &mut Ctx, + _: &interpreter::CreateInputs, + outcome: &mut interpreter::CreateOutcome, + ) { + if self.flag == Flag::RebuildCreation { + *outcome = interpreter::CreateOutcome::new(outcome.result.clone(), outcome.address); + } + } + } + + /// The events of [`PARENT`]'s transaction, calling `callee`, under `flag`, or of + /// [`CREATOR`]'s for a creation's flag. + fn flagged(flag: Flag, target: Address, callee: Address) -> Vec<String> { + let mut evm = context(callee, SpecId::OSAKA).build_mainnet_with_inspector(Rewrite { + flag, + target, + snapshot: None, + }); + let to = if flag == Flag::RebuildCreation { + CREATOR + } else { + PARENT + }; + let result = evm.inspect_tx(tx(to, 0)).expect("runs"); + assert!(result.result.is_success(), "{flag:?}: {:?}", result.result); + events(&mut evm) + } + + /// [`PAIRED`] with the child's settlement as `child`. + fn paired_with(child: &str) -> Vec<String> { + let mut events = PAIRED.map(String::from).to_vec(); + events[2] = child.to_string(); + events + } + + #[test] + fn test_an_inspectors_answer_is_flagged() { + assert_eq!( + flagged(Flag::Answer, CHILD, CHILD), + paired_with("settle 2 depth 1 Ok inspector-answer") + ); + } + + #[test] + fn test_an_inspectors_answer_to_the_transactions_frame_is_flagged() { + assert_eq!( + flagged(Flag::Answer, PARENT, CHILD), + [ + "split 1 parent None depth 0", + "settle 1 depth 0 Ok inspector-answer", + "end Settled", + ] + ); + } + + #[test] + fn test_a_replaced_tracker_is_flagged() { + assert_eq!( + flagged(Flag::ReplaceGas, CHILD, CHILD), + paired_with("settle 2 depth 1 Ok gas-replaced") + ); + assert_eq!( + flagged(Flag::ReplaceGas, ECRECOVER, ECRECOVER), + paired_with("settle 2 depth 1 Ok gas-replaced"), + "a precompile's answer" + ); + } + + /// A snapshot taken before revm marked the result is a replacement, even of the same + /// start's tracker. + #[test] + fn test_a_restored_snapshot_is_flagged() { + assert_eq!( + flagged(Flag::RestoreSnapshot, CHILD, CHILD), + paired_with("settle 2 depth 1 Ok gas-replaced") + ); + } + + #[test] + fn test_a_status_only_rewrite_is_not_flagged() { + assert_eq!( + flagged(Flag::RewriteStatus, CHILD, CHILD), + paired_with("settle 2 depth 1 Revert") + ); + } + + #[test] + fn test_an_outcome_rebuilt_around_the_same_result_is_flagged() { + assert_eq!( + flagged(Flag::RebuildOutcome, CHILD, CHILD), + paired_with("settle 2 depth 1 Ok outcome-rebuilt") + ); + assert_eq!( + flagged(Flag::RebuildCreation, CHILD, CHILD), + [ + "split 1 parent None depth 0", + "split 2 parent Some(1) depth 1", + "settle 2 depth 1 Ok created true outcome-rebuilt", + "settle 1 depth 0 Ok", + "end Settled", + ] + ); + } + + #[test] + fn test_a_rebuild_that_keeps_the_outcome_and_the_gas_is_not_flagged() { + assert_eq!(flagged(Flag::KeepOutcome, CHILD, CHILD), PAIRED); + } + /// The context hands every event to its mirror: one that does not fit fails the check. #[test] #[should_panic(expected = "the transaction's start 1 at depth 5")] diff --git a/crates/interpreter/src/interpreter_action/call_outcome.rs b/crates/interpreter/src/interpreter_action/call_outcome.rs index 3c9271422e..68a51d9cbf 100644 --- a/crates/interpreter/src/interpreter_action/call_outcome.rs +++ b/crates/interpreter/src/interpreter_action/call_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, PoolAmounts, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark, PoolAmounts, StartCharge}; use core::ops::Range; use primitives::{Address, Bytes, Log}; use std::vec::Vec; @@ -12,7 +12,7 @@ use std::vec::Vec; /// /// * `result` - The result of the interpreter's execution, including output data and gas usage. /// * `memory_offset` - The range in memory where the output data is located. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CallOutcome { /// The result of the interpreter's execution, including output data and gas usage @@ -48,6 +48,31 @@ pub struct CallOutcome { /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, + /// The start revm marked this outcome for before an inspector's end callbacks + /// ([`OutcomeMark`]): none on an outcome a constructor builds. No part of the outcome's value: + /// equality, the debug output and the encoding leave it out, and a decoded outcome carries + /// none. + #[cfg_attr(feature = "serde", serde(skip))] + pub start_mark: OutcomeMark, +} + +impl core::fmt::Debug for CallOutcome { + /// The output the derive gives the outcome's other fields, in their order; the mark is left + /// out. + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("CallOutcome") + .field("result", &self.result) + .field("memory_offset", &self.memory_offset) + .field("was_precompile_called", &self.was_precompile_called) + .field("precompile_call_logs", &self.precompile_call_logs) + .field( + "charged_new_account_state_gas", + &self.charged_new_account_state_gas, + ) + .field("charged_state_gas_address", &self.charged_state_gas_address) + .field("charged_start", &self.charged_start) + .finish() + } } impl CallOutcome { @@ -68,6 +93,7 @@ impl CallOutcome { charged_new_account_state_gas: false, charged_state_gas_address: Address::ZERO, charged_start: StartCharge::new(0, PoolAmounts::ZERO), + start_mark: OutcomeMark::NONE, } } diff --git a/crates/interpreter/src/interpreter_action/create_outcome.rs b/crates/interpreter/src/interpreter_action/create_outcome.rs index 200508bb1a..3f20890d72 100644 --- a/crates/interpreter/src/interpreter_action/create_outcome.rs +++ b/crates/interpreter/src/interpreter_action/create_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, PoolAmounts, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark, PoolAmounts, StartCharge}; use primitives::{Address, Bytes}; /// Represents the outcome of a create operation in an interpreter. @@ -6,7 +6,7 @@ use primitives::{Address, Bytes}; /// This struct holds the result of the operation along with an optional address. /// /// It provides methods to determine the next action based on the result of the operation. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CreateOutcome { /// The result of the interpreter operation @@ -35,6 +35,26 @@ pub struct CreateOutcome { /// decode it as no charge. #[cfg_attr(feature = "serde", serde(default))] pub charged_start: StartCharge, + /// The start revm marked this outcome for before an inspector's end callbacks + /// ([`OutcomeMark`]): none on an outcome a constructor builds. No part of the outcome's value: + /// equality, the debug output and the encoding leave it out, and a decoded outcome carries + /// none. + #[cfg_attr(feature = "serde", serde(skip))] + pub start_mark: OutcomeMark, +} + +impl core::fmt::Debug for CreateOutcome { + /// The output the derive gives the outcome's other fields, in their order; the mark is left + /// out. + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("CreateOutcome") + .field("result", &self.result) + .field("address", &self.address) + .field("charged_create_state_gas", &self.charged_create_state_gas) + .field("charged_state_gas_address", &self.charged_state_gas_address) + .field("charged_start", &self.charged_start) + .finish() + } } impl CreateOutcome { @@ -55,6 +75,7 @@ impl CreateOutcome { charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, charged_start: StartCharge::new(0, PoolAmounts::ZERO), + start_mark: OutcomeMark::NONE, } } diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 22d3eadcce..201f458966 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,7 +36,9 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{ChildShares, Gas, GasTracker, PoolAmounts, PoolId, StartCharge}; +pub use gas::{ + ChildShares, Gas, GasTracker, OutcomeMark, PoolAmounts, PoolId, StartCharge, StartMark, +}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/start_marks.rs b/crates/interpreter/tests/start_marks.rs new file mode 100644 index 0000000000..4a2c2fd3f7 --- /dev/null +++ b/crates/interpreter/tests/start_marks.rs @@ -0,0 +1,105 @@ +//! The marks revm writes on a frame result before an inspector's end callbacks keep the values' +//! public semantics: a marked gas tracker and a marked outcome print exactly as the derived debug +//! output printed them before the marks existed, and encode without them. + +use revm_interpreter::{ + CallOutcome, CreateOutcome, Gas, GasTracker, InstructionResult, InterpreterResult, OutcomeMark, + StartMark, +}; + +/// The derived debug output of these values before the marks existed. +const TRACKER: &str = "GasTracker { gas_limit: 100, remaining: 90, reservoir: 5, \ + state_gas_spent: 0, state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, \ + withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, \ + pools_remaining: [18446744073709551615, 18446744073709551615, 18446744073709551615], \ + pools_spent: [0, 0, 0], pool_crossings: 0, history_allowance: 3 }"; +const RESULT: &str = "InterpreterResult { result: Stop, output: 0x, gas: Gas { tracker: \ + GasTracker { gas_limit: 10, remaining: 10, reservoir: 0, state_gas_spent: 0, \ + state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, withheld_crossing: \ + None, failed_charge_remaining: 0, failed_charge_recorded: false, pools_remaining: \ + [18446744073709551615, 18446744073709551615, 18446744073709551615], pools_spent: [0, 0, 0], \ + pool_crossings: 0, history_allowance: 0 }, memory: MemoryGas { words_num: 0, \ + expansion_cost: 0 } } }"; +const START_CHARGE: &str = "StartCharge { history: 0, pools: PoolAmounts([0, 0, 0]) }"; + +const fn tracker() -> GasTracker { + let mut tracker = GasTracker::new(100, 90, 5); + tracker.set_history_allowance(3); + tracker.set_start_mark(StartMark::for_start(7)); + tracker +} + +fn result() -> InterpreterResult { + let mut gas = Gas::new(10); + gas.tracker_mut().set_start_mark(StartMark::for_start(7)); + InterpreterResult::new(InstructionResult::Stop, Default::default(), gas) +} + +fn call() -> CallOutcome { + CallOutcome { + start_mark: OutcomeMark::for_start(7), + ..CallOutcome::new(result(), 1..2) + } +} + +fn create() -> CreateOutcome { + CreateOutcome { + start_mark: OutcomeMark::for_start(7), + ..CreateOutcome::new(result(), None) + } +} + +#[test] +fn test_marked_values_print_as_the_derived_output_did() { + assert_eq!(format!("{:?}", tracker()), TRACKER); + assert_eq!( + format!("{:?}", call()), + format!( + "CallOutcome {{ result: {RESULT}, memory_offset: 1..2, was_precompile_called: false, \ + precompile_call_logs: [], charged_new_account_state_gas: false, \ + charged_state_gas_address: 0x0000000000000000000000000000000000000000, \ + charged_start: {START_CHARGE} }}" + ) + ); + assert_eq!( + format!("{:?}", create()), + format!( + "CreateOutcome {{ result: {RESULT}, address: None, charged_create_state_gas: false, \ + charged_state_gas_address: 0x0000000000000000000000000000000000000000, \ + charged_start: {START_CHARGE} }}" + ) + ); +} + +#[test] +fn test_marked_values_equal_their_unmarked_selves() { + let mut unmarked = tracker(); + unmarked.set_start_mark(StartMark::NONE); + assert_eq!(tracker(), unmarked); + assert_eq!(call(), CallOutcome::new(result(), 1..2)); + assert_eq!(create(), CreateOutcome::new(result(), None)); +} + +/// An encoded value has no mark, and decodes equal with none. +#[cfg(feature = "serde")] +#[test] +fn test_marked_values_encode_without_their_marks() { + let json = serde_json::to_string(&tracker()).expect("encodes"); + assert!(!json.contains("mark"), "{json}"); + let decoded: GasTracker = serde_json::from_str(&json).expect("decodes"); + assert_eq!(decoded, tracker()); + assert!(!decoded.start_mark().is_for(7)); + + let json = serde_json::to_string(&call()).expect("encodes"); + assert!(!json.contains("mark"), "{json}"); + let decoded: CallOutcome = serde_json::from_str(&json).expect("decodes"); + assert_eq!(decoded, call()); + assert!(!decoded.start_mark.is_for(7)); + assert!(!decoded.result.gas.tracker().start_mark().is_for(7)); + + let json = serde_json::to_string(&create()).expect("encodes"); + assert!(!json.contains("mark"), "{json}"); + let decoded: CreateOutcome = serde_json::from_str(&json).expect("decodes"); + assert_eq!(decoded, create()); + assert!(!decoded.start_mark.is_for(7)); +} From ba0eefe671a479b5b340e9cc61f560bd3531ac52 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 11:58:16 +0800 Subject: [PATCH 085/110] feat(interpreter): a frame-start hook may name the child's reservoir it took FrameStart gains reservoir: Option<u64>, None when the hook is called. None keeps the instruction's forward, the schedule's share of the caller's reservoir. Some is the reservoir the frame's input carries: the instruction takes no share of its own and the caller keeps what the hook left (GasTracker::forward_to_child_with_reservoir). The pools are forwarded by the schedule either way. No hook in this workspace sets it. --- .../context/interface/src/cfg/gas/forward.rs | 23 ++++++- crates/context/interface/src/host.rs | 6 +- .../interface/src/host/instruction_hooks.rs | 17 +++++- .../interpreter/src/instructions/contract.rs | 10 ++-- .../src/instructions/instruction_hooks.rs | 24 +++++--- crates/interpreter/tests/instruction_hooks.rs | 60 +++++++++++++++++++ 6 files changed, 122 insertions(+), 18 deletions(-) diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs index e6b11470f2..59ce8939f9 100644 --- a/crates/context/interface/src/cfg/gas/forward.rs +++ b/crates/context/interface/src/cfg/gas/forward.rs @@ -47,8 +47,27 @@ impl GasTracker { /// gives the caller back exactly what it forwarded. #[inline] pub fn forward_to_child(&mut self, params: &GasParams) -> ChildShares { - let reservoir = params.reservoir_forward_share(self.reservoir); - self.forward_reservoir(reservoir); + self.forward_to_child_with_reservoir(params, None) + } + + /// [`forward_to_child`](Self::forward_to_child), for a start whose child reservoir the + /// frame-start hook may have named (`FrameStart::reservoir`). + /// + /// `Some(reservoir)` is the child's reservoir, which the hook took out of this tracker itself: + /// no share of the reservoir is taken here, and the child starts with `reservoir`. `None` takes + /// the schedule's share, as `forward_to_child` does. The pools are forwarded by the schedule's + /// shares either way. + #[inline] + pub fn forward_to_child_with_reservoir( + &mut self, + params: &GasParams, + reservoir: Option<u64>, + ) -> ChildShares { + let reservoir = reservoir.unwrap_or_else(|| { + let share = params.reservoir_forward_share(self.reservoir); + self.forward_reservoir(share); + share + }); let mut pools = PoolAmounts::ZERO; for pool in PoolId::ALL { let share = params.pool_forward_share(pool, self.pool_remaining(pool)); diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 517ffb78c8..5e89f07566 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -128,8 +128,10 @@ pub trait Host { /// frame's input is built. /// /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, - /// charging nothing after the hook: the frame's input copies its reservoir from `gas`. A - /// charge the hook makes that fails records as any failed charge does + /// charging nothing after the hook: the frame's input takes the schedule's share of the + /// reservoir in `gas`, or the child's reservoir the hook names on `start` if it took that out + /// of `gas` itself ([`FrameStart::reservoir`]). A charge the hook makes that fails records as + /// any failed charge does /// ([`GasTracker::failed_charge_remaining`]), whatever the answer. The part of its charge /// that the frame's failure gives back, the hook declares on `start` /// ([`FrameStart::charge`]). `true` goes on to start the frame, which the handler may still diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index 363edf6679..b7e12cf070 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -93,8 +93,9 @@ pub enum FrameStartKind { /// A frame an instruction is about to start: every charge the instruction makes has been made, the /// gas it forwards has been taken from the caller, and the frame's input is not built yet. /// -/// The hook is handed it mutably to declare the start's [`charge`](Self::charge); the instruction -/// reads nothing else back. +/// The hook is handed it mutably to declare the start's [`charge`](Self::charge) and, if it takes +/// the child's reservoir itself, the child's [`reservoir`](Self::reservoir); the instruction reads +/// nothing else back. /// /// Built with [`FrameStart::new`], so a later field is not a breaking change. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -127,6 +128,17 @@ pub struct FrameStart { /// gives back. Empty when the hook is called; the hook declares it here after charging it, /// and the instruction copies it onto the frame's input if the hook admits the start. pub charge: StartCharge, + /// The child's reservoir, when the hook took it out of the caller's reservoir itself. `None` + /// when the hook is called. + /// + /// `None` leaves the forward to the instruction, which takes the schedule's share of the + /// caller's reservoir as the hook left it ([`GasTracker::forward_to_child`]). `Some` is the + /// reservoir the frame's input carries: the instruction takes no share of its own, and the + /// caller keeps the reservoir the hook left it. The pools are forwarded by the schedule + /// either way. The instruction does not check the amount against what the hook took. + /// + /// [`GasTracker::forward_to_child`]: crate::cfg::gas::GasTracker::forward_to_child + pub reservoir: Option<u64>, } impl FrameStart { @@ -146,6 +158,7 @@ impl FrameStart { value, forward, charge: StartCharge::new(0, PoolAmounts::ZERO), + reservoir: None, } } } diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 6c2ca81460..392ff73898 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -194,8 +194,9 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( value, gas_limit, ); - let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let shares = forward_to_child(&mut context.interpreter.gas, context.host); + let (charged_start, reservoir) = + frame_starting(&mut context.interpreter.gas, context.host, start)?; + let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); create_inputs.set_gas_limit(gas_limit); create_inputs.set_reservoir(shares.reservoir); @@ -285,8 +286,9 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, }; let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); - let charged_start = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let shares = forward_to_child(&mut context.interpreter.gas, context.host); + let (charged_start, reservoir) = + frame_starting(&mut context.interpreter.gas, context.host, start)?; + let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); // Call host to interact with target contract context diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 7abb881f4a..d5a199fbc4 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -44,17 +44,18 @@ fn revert<IT: ITy>(interpreter: &mut Interpreter<IT>, output: Bytes) -> Result { } /// Hands `start`, whose forward the running instruction has taken from `gas`, to -/// [`Host::frame_starting`]. `true` returns the start charge the hook declared on `start`, for -/// the frame's input; `false` fails the instruction out of gas, and the charge goes with the -/// start it was declared for. +/// [`Host::frame_starting`]. `true` returns what the hook declared on `start` for the frame: the +/// start charge, for the frame's input, and the child's reservoir if the hook took it itself, for +/// the forward ([`forward_to_child`]); `false` fails the instruction out of gas, and the charge +/// goes with the start it was declared for. #[inline] pub(crate) fn frame_starting<H: Host + ?Sized>( gas: &mut Gas, host: &mut H, mut start: FrameStart, -) -> core::result::Result<StartCharge, InstructionResult> { +) -> core::result::Result<(StartCharge, Option<u64>), InstructionResult> { if host.frame_starting(&mut start, gas.tracker_mut()) { - Ok(start.charge) + Ok((start.charge, start.reservoir)) } else { cold_path(); Err(InstructionResult::OutOfGas) @@ -97,8 +98,15 @@ pub(crate) fn running_account<H: Host + ?Sized>( /// schedule's `reservoir_kept_percent` and `pool_kept_percent`s, and returns them: what the child's /// tracker starts with ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). /// Called once the frame-start hook has answered, so the shares are of the reservoir and the pools -/// as the hook left them. +/// as the hook left them. A child `reservoir` the hook named replaces the reservoir's share: the +/// child starts with it, and the caller keeps the reservoir the hook left +/// ([`GasTracker::forward_to_child_with_reservoir`](crate::GasTracker::forward_to_child_with_reservoir)). #[inline] -pub(crate) fn forward_to_child<H: Host + ?Sized>(gas: &mut Gas, host: &H) -> ChildShares { - gas.tracker_mut().forward_to_child(host.gas_params()) +pub(crate) fn forward_to_child<H: Host + ?Sized>( + gas: &mut Gas, + host: &H, + reservoir: Option<u64>, +) -> ChildShares { + gas.tracker_mut() + .forward_to_child_with_reservoir(host.gas_params(), reservoir) } diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index 3ced75e033..f94c7def6c 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -96,6 +96,9 @@ struct HookHost { charge: u64, verdict: WriteVerdict, admit: bool, + /// The reservoir the hook leaves the caller when it takes the child's reservoir itself and + /// names it on the start. + kept_reservoir: Option<u64>, /// Every write the hook saw, with the gas as the hook found it. writes: Vec<(Write, GasTracker)>, /// Every start the hook saw, with the gas as the hook found it. @@ -116,6 +119,7 @@ impl HookHost { charge: 0, verdict: WriteVerdict::Continue, admit: true, + kept_reservoir: None, writes: Vec::new(), starts: Vec::new(), } @@ -176,6 +180,11 @@ impl HookHost { self } + const fn keeping_reservoir(mut self, kept: u64) -> Self { + self.kept_reservoir = Some(kept); + self + } + const fn refuses_cold(&self, skip_cold_load: bool) -> Result<(), LoadError> { if self.cold && skip_cold_load { Err(LoadError::ColdLoadSkipped) @@ -215,6 +224,10 @@ impl Host for HookHost { if self.charge > 0 { let _ = gas.record_history_cost(self.charge); } + if let Some(kept) = self.kept_reservoir { + start.reservoir = Some(gas.reservoir() - kept); + gas.set_reservoir(kept); + } self.admit } @@ -1076,6 +1089,53 @@ fn test_the_input_copies_the_reservoir_the_hook_left() { } } +/// A hook that takes the child's reservoir out of the caller's itself names it on the start +/// ([`FrameStart::reservoir`]): the frame's input carries it, and the instruction takes no +/// reservoir share of its own, so the caller keeps what the hook left. The pools are forwarded by +/// the schedule as without the hook's reservoir. +#[test] +fn test_the_input_carries_the_child_reservoir_the_hook_names() { + let spec = SpecId::AMSTERDAM; + let pools = |input: &FrameInput| match input { + FrameInput::Call(inputs) => inputs.pool_shares, + FrameInput::Create(inputs) => inputs.pool_shares(), + FrameInput::Empty => panic!("an empty frame input"), + }; + for (name, code, _) in start_cases() { + let mut quiet = HookHost::new(spec); + let (quiet_action, quiet_gas) = run(spec, &code, AMPLE, 10_000, &mut quiet); + let quiet_input = started(quiet_action); + + let mut host = HookHost::new(spec).keeping_reservoir(4_000); + let (action, gas) = run(spec, &code, AMPLE, 10_000, &mut host); + let input = started(action); + + assert_eq!( + host.start().0.reservoir, + None, + "{name}: the hook is handed none" + ); + assert_eq!( + input_gas(&input), + (input_gas(&quiet_input).0, 6_000), + "{name}" + ); + assert_eq!( + gas.reservoir(), + 4_000, + "{name}: the caller keeps what the hook left" + ); + assert_eq!( + pools(&input), + pools(&quiet_input), + "{name}: the pools' shares" + ); + let pools_left = |gas: &Gas| gas.tracker().pools_remaining(); + assert_eq!(pools_left(&gas), pools_left(&quiet_gas), "{name}"); + assert_eq!(gas.remaining(), quiet_gas.remaining(), "{name}"); + } +} + /// `false` fails the instruction out of gas and starts no frame. The forward stays taken, so the /// halt records what the caller had left after it. #[test] From c3e1f5e1e6b02e4ae73bdf45c21f8fe36f1f5409 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 12:26:43 +0800 Subject: [PATCH 086/110] fix(context): the marks' docs say what their values print and when two starts share an outcome mark The marks themselves print their type's name; the tracker and the outcomes leave them out of their debug output. Two starts share an outcome mark when their identities are a multiple of 65,535 apart, and the tracker's mark fits padding without naming a field order. The record's sequence field is named for what it holds, the last identity allocated; settle_status is private, and a doc link drops its redundant target. --- crates/context/interface/src/cfg/gas.rs | 5 +++-- crates/context/interface/src/cfg/gas/mark.rs | 17 +++++++++-------- crates/context/interface/src/local/lifecycle.rs | 10 +++++----- crates/handler/src/handler.rs | 2 +- crates/handler/src/lifecycle.rs | 2 +- 5 files changed, 19 insertions(+), 17 deletions(-) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 84c32c8c27..55871a05b5 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -213,8 +213,9 @@ pub struct GasTracker { /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as zero. history_allowance: u64, - /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)), in the padding - /// after `pool_crossings`. No part of the tracker's value, and not encoded. + /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)). It fits padding + /// the tracker already had, so the tracker's size is unchanged. No part of the tracker's value, + /// and not encoded. start_mark: StartMark, } diff --git a/crates/context/interface/src/cfg/gas/mark.rs b/crates/context/interface/src/cfg/gas/mark.rs index b0e2379f7f..e5025fba69 100644 --- a/crates/context/interface/src/cfg/gas/mark.rs +++ b/crates/context/interface/src/cfg/gas/mark.rs @@ -2,10 +2,10 @@ //! just after, to tell whether the callbacks put another value in the result's place: the //! [`StartMark`] on the result's gas tracker and the [`OutcomeMark`] on its outcome. //! -//! A mark takes no part in the value it rides on: marks always compare equal, hash to nothing, -//! print nothing and are not serialized (a decoded value carries none). So a marked tracker or -//! outcome compares, hashes, prints and encodes as the same value unmarked. Each fits padding of -//! the type that carries it, so neither grows. +//! A mark takes no part in the value it rides on: marks always compare equal and hash to nothing, +//! and the tracker and the outcomes leave them out of their debug output and their encoding (a +//! decoded value carries none). So a marked tracker or outcome compares, hashes, prints and encodes +//! as the same value unmarked. Each fits padding of the type that carries it, so neither grows. /// The mark of a start on a gas tracker: the start's identity, or none. /// @@ -40,7 +40,8 @@ impl StartMark { /// an outcome that does not carry the mark after them is one the callbacks put in its place /// ([`FrameSettle::outcome_rebuilt`](crate::host::FrameSettle::outcome_rebuilt)), such as one a /// constructor built around the same result. A start's mark is never none, so a built outcome -/// never carries it; two starts share a mark only when their identities are 65,535 apart. +/// never carries it; two starts share a mark only when their identities are a multiple of 65,535 +/// apart. #[derive(Clone, Copy, Default)] pub struct OutcomeMark(u16); @@ -61,7 +62,7 @@ impl OutcomeMark { } } -macro_rules! transparent { +macro_rules! transparent_mark { ($mark:ident) => { impl PartialEq for $mark { #[inline] @@ -85,8 +86,8 @@ macro_rules! transparent { }; } -transparent!(StartMark); -transparent!(OutcomeMark); +transparent_mark!(StartMark); +transparent_mark!(OutcomeMark); #[cfg(test)] mod tests { diff --git a/crates/context/interface/src/local/lifecycle.rs b/crates/context/interface/src/local/lifecycle.rs index c561eb7ca8..ef5b40b666 100644 --- a/crates/context/interface/src/local/lifecycle.rs +++ b/crates/context/interface/src/local/lifecycle.rs @@ -106,7 +106,7 @@ impl core::error::Error for StartLifecycleError {} #[derive(Clone, Debug, Default)] pub(super) struct StartLifecycle { /// The last identity allocated in the transaction, 0 before the first. - next: u32, + last: u32, /// Whether a lifecycle is under way: its first start opened, and it has not ended. active: bool, /// The transaction's start. @@ -133,7 +133,7 @@ impl StartLifecycle { #[inline] fn reset(&mut self) { - self.next = 0; + self.last = 0; self.active = false; self.root = None; self.children.clear(); @@ -157,7 +157,7 @@ impl<T> FrameStack<T> { pub fn open_start(&mut self, depth: usize) -> Result<FrameSplit, StartLifecycleError> { let record = &mut self.lifecycle; let id = record - .next + .last .checked_add(1) .ok_or(StartLifecycleError::Exhausted)?; let parent = match self.index { @@ -186,7 +186,7 @@ impl<T> FrameStack<T> { id, ..Default::default() }); - record.next = id; + record.last = id; record.active = true; Ok(FrameSplit { id, parent, depth }) } @@ -444,7 +444,7 @@ mod tests { fn test_an_exhausted_sequence_opens_nothing() { let mut stack = stack(1); open_nested(&mut stack, 0); - stack.lifecycle.next = u32::MAX - 1; + stack.lifecycle.last = u32::MAX - 1; stack.index = Some(0); assert_eq!( stack.open_start(1).map(|s| s.id), diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 77071ca0fc..a57ae7a4b7 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -161,7 +161,7 @@ pub trait Handler { /// Returns any errors without catching them or calling [`Handler::catch_error`]. /// A caller that drops an error makes `catch_error`'s cleanup before it reuses /// the EVM, the frame stack's included: see the start lifecycle's "Reuse after - /// an error" ([`lifecycle`](crate::lifecycle)). + /// an error" ([`lifecycle`]). #[inline] fn run_without_catch_error( &mut self, diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs index b68c37e253..fcc8342e9d 100644 --- a/crates/handler/src/lifecycle.rs +++ b/crates/handler/src/lifecycle.rs @@ -72,7 +72,7 @@ fn fatal<E>(error: StartLifecycleError) -> ContextError<E> { /// What a settlement reports of `result`'s status. #[inline] -pub const fn settle_status(result: &FrameResult) -> SettleStatus { +const fn settle_status(result: &FrameResult) -> SettleStatus { let result = result.instruction_result(); if result.is_ok() { SettleStatus::Ok From e93df93e5e1604ed4248aff8c9ca8babd693be10 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 12:26:43 +0800 Subject: [PATCH 087/110] test(inspector): the runtime out-of-gas stand-in leaves the record clear in every build A transaction whose runtime gas phase runs out of gas is included as a halt on a reused EVM, which needs the stand-in's start to open and settle; the event test keeps the exact events for debug builds. --- crates/inspector/tests/start_lifecycle.rs | 65 ++++++++++++++++------- 1 file changed, 47 insertions(+), 18 deletions(-) diff --git a/crates/inspector/tests/start_lifecycle.rs b/crates/inspector/tests/start_lifecycle.rs index 7ef724cd16..4c03df7138 100644 --- a/crates/inspector/tests/start_lifecycle.rs +++ b/crates/inspector/tests/start_lifecycle.rs @@ -404,6 +404,47 @@ fn test_the_marks_take_no_part_in_the_values() { } } +/// An EVM on Amsterdam, where a value transfer to an empty account pays the account's state in the +/// transaction's runtime gas phase. +fn runtime_out_of_gas_evm() -> MainEvm<()> { + Context::mainnet() + .with_db(db(CHILD)) + .modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM); + cfg.tx_gas_limit_cap = Some(u64::MAX); + }) + .build_mainnet() +} + +/// A value transfer to an empty account funded for its intrinsic gas only: valid, and out of gas +/// in the runtime gas phase. +fn runtime_out_of_gas_tx() -> TxEnv { + use primitives::{eip2780, eip8038}; + TxEnv::builder_for_bench() + .kind(TxKind::Call(address!( + "0x00000000000000000000000000000000000000ab" + ))) + .value(U256::from(1)) + .gas_price(0) + .gas_limit(eip2780::TX_BASE_COST + eip8038::COLD_ACCOUNT_ACCESS + eip2780::TX_VALUE_COST) + .build_fill() +} + +/// The stand-in for the frame of a transaction whose runtime gas phase ran out of gas settles on +/// the transaction's start, so the transaction is included as a halt and leaves the record clear. +#[test] +fn test_the_runtime_out_of_gas_stand_in_leaves_the_record_clear() { + let mut evm = runtime_out_of_gas_evm(); + for _ in 0..2 { + assert!(evm + .transact(runtime_out_of_gas_tx()) + .expect("included") + .result + .is_halt()); + assert_clear(&mut evm); + } +} + /// The events the hooks received, which the mirror the context keeps in debug builds records. #[cfg(debug_assertions)] mod events { @@ -578,24 +619,12 @@ mod events { /// on the transaction's start. #[test] fn test_the_runtime_out_of_gas_stand_in_settles_the_transactions_start() { - use primitives::{eip2780, eip8038}; - let mut evm = Context::mainnet() - .with_db(db(CHILD)) - .modify_cfg_chained(|cfg| { - cfg.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM); - cfg.tx_gas_limit_cap = Some(u64::MAX); - }) - .build_mainnet(); - let empty = address!("0x00000000000000000000000000000000000000ab"); - let tx = TxEnv::builder_for_bench() - .kind(TxKind::Call(empty)) - .value(U256::from(1)) - .gas_price(0) - .gas_limit( - eip2780::TX_BASE_COST + eip8038::COLD_ACCOUNT_ACCESS + eip2780::TX_VALUE_COST, - ) - .build_fill(); - assert!(evm.transact(tx).expect("included").result.is_halt()); + let mut evm = runtime_out_of_gas_evm(); + assert!(evm + .transact(runtime_out_of_gas_tx()) + .expect("included") + .result + .is_halt()); assert_eq!( events(&mut evm), [ From 2fca497d9cca3aad1e8945fabbc1b34a38b95b69 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 13:30:32 +0800 Subject: [PATCH 088/110] fix(handler): a halted transaction consumes only the regular gas its settlement hook credited close_transaction_start consumed every unit of regular gas left after a halt, after the hook. revm's own settlement can leave some on a halt: an answer to the transaction's frame whose tracker hands back a reservoir unwinds the transaction's spill into regular gas, and the settlement keeps it. With the default hook the extra spend moved that figure (999,999 to 1,000,000 gas spent on the review's case). The rule now consumes only what the hook credited above what the settlement left, so a hook that credits nothing changes no figure. default_hook_figures runs 136 answer and rewrite shapes, on the transaction's frame and on a child, calls and creations, inspected and answered in a consumer's frame_init, against the figures recorded on b370b538; the review's case is its own test. --- crates/handler/src/lifecycle.rs | 68 +- .../inspector/tests/default_hook_figures.rs | 972 ++++++++++++++++++ 2 files changed, 1037 insertions(+), 3 deletions(-) create mode 100644 crates/inspector/tests/default_hook_figures.rs diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs index fcc8342e9d..dafbf2efcc 100644 --- a/crates/handler/src/lifecycle.rs +++ b/crates/handler/src/lifecycle.rs @@ -188,8 +188,11 @@ where /// Closes the transaction's start into the transaction-level `gas`, after /// [`settle_first_frame`](crate::execution::settle_first_frame) settled `result` into it, and /// hands the settlement to [`Host::frame_settle`]. `held_reservoir` is the reservoir `gas` held -/// before that settlement. After a halt, revm's halt rule follows the hook: the regular gas left -/// in `gas` is consumed, as the settlement's own refunds are. The frame stack must be empty. +/// before that settlement. The frame stack must be empty. +/// +/// After a halt, the regular gas the hook credited to `gas` is consumed, so a halted transaction +/// keeps none of its settlement hook's regular credits. What revm's own settlement left in `gas` +/// is left as it is: a hook that credits nothing, the default, changes no figure. /// /// # Errors /// @@ -210,13 +213,24 @@ pub fn close_transaction_start<EVM: EvmTr + ?Sized>( let settle = frame_stack .close_start(0, status, created(result), held_reservoir) .map_err(fatal)?; + let settled = gas.remaining(); ctx.frame_settle(&settle, gas); if status == SettleStatus::Halt { - gas.spend_all(); + consume_hook_credit(gas, settled); } Ok(()) } +/// Consumes the regular gas a halted transaction's settlement hook credited to `gas`: what `gas` +/// holds above `settled`, the regular gas revm's settlement left in it before the hook. A hook +/// that credited nothing, or debited, leaves `gas` as it is. +#[inline] +const fn consume_hook_credit(gas: &mut GasTracker, settled: u64) { + if gas.remaining() > settled { + gas.set_remaining(settled); + } +} + /// The successful boundary: every start the transaction opened must have settled. Ends the /// lifecycle ([`LifecycleEnd::Settled`](context_interface::host::LifecycleEnd::Settled), handed to /// [`Host::frame_lifecycle_end`] when a lifecycle was under way) and resets the record for the @@ -301,3 +315,51 @@ pub const fn check_end_callbacks(result: &FrameResult, start: &mut PendingStart) start.set_outcome_rebuilt(); } } + +#[cfg(test)] +mod tests { + use super::consume_hook_credit; + use interpreter::GasTracker; + + /// A transaction's gas after its settlement left it `remaining` regular gas, then credited + /// `credit` by refills a hook makes: one that unwinds the spill and one past it. + fn credited(remaining: u64, credit: u64) -> GasTracker { + let mut gas = GasTracker::new(1_000, remaining, 0); + gas.erase_cost(credit); + gas + } + + #[test] + fn test_a_halt_consumes_only_what_the_hook_credited() { + let mut gas = credited(1, 40); + consume_hook_credit(&mut gas, 1); + assert_eq!(gas.remaining(), 1, "the settlement's own gas is kept"); + + let mut gas = credited(0, 40); + consume_hook_credit(&mut gas, 0); + assert_eq!(gas.remaining(), 0); + } + + #[test] + fn test_a_halt_leaves_gas_a_hook_did_not_credit() { + let mut gas = credited(7, 0); + consume_hook_credit(&mut gas, 7); + assert_eq!(gas.remaining(), 7, "nothing credited, nothing consumed"); + + let mut gas = credited(7, 0); + assert!(gas.record_regular_cost(3)); + consume_hook_credit(&mut gas, 7); + assert_eq!(gas.remaining(), 4, "a debit stands"); + } + + #[test] + fn test_a_halt_consumes_a_credit_to_the_withheld_part_too() { + let mut gas = GasTracker::new(1_000, 10, 0); + gas.withhold(4); + let settled = gas.remaining(); + gas.erase_cost(5); + consume_hook_credit(&mut gas, settled); + assert_eq!(gas.remaining(), 10); + assert_eq!(gas.withheld(), 4, "the withheld part is kept"); + } +} diff --git a/crates/inspector/tests/default_hook_figures.rs b/crates/inspector/tests/default_hook_figures.rs new file mode 100644 index 0000000000..a84d421fb4 --- /dev/null +++ b/crates/inspector/tests/default_hook_figures.rs @@ -0,0 +1,972 @@ +//! With the default hooks, the start lifecycle changes no figure revm's settlement computes. +//! +//! Each case answers or rewrites a start's result the way an inspector or a consumer's +//! `frame_init` can, on the transaction's frame or on a child, and the transaction's figures must +//! be the ones revm computed before the lifecycle existed. The expected figures were recorded on +//! that revision (`b370b538`), so a lifecycle helper that moves a figure fails here. +//! +//! The transaction runs on Amsterdam with every gas regular (the cap is lifted), so the +//! transaction's frame starts with no reservoir and every state charge spills into regular gas: +//! a result that hands a reservoir back then unwinds the spill into regular gas, and a halt keeps +//! that gas. [`EMPTY`] is an account with no code; a value transfer to it pays for its leaf, as +//! a creation pays for the account it creates. + +use context::{ + result::{EVMError, ExecutionResult}, + Context, ContextSetters, Evm, FrameStack, TxEnv, +}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use handler::{ + evm::{ContextDbError, FrameInitResult}, + instructions::EthInstructions, + EthFrame, EthPrecompiles, EvmTr, ExecuteEvm, FrameInitOrResult, FrameResult, Handler, + ItemOrResult, MainBuilder, MainContext, MainnetContext, MainnetHandler, +}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, InterpreterResult, +}; +use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_inspector::{InspectEvm, Inspector}; +use state::{ + bytecode::opcode::{CALL, CREATE, PUSH0, PUSH1, PUSH20, PUSH3, STOP}, + AccountInfo, Bytecode, +}; +use std::convert::Infallible; + +type Db = CacheDB<EmptyDB>; +type Ctx = MainnetContext<Db>; +type MainEvm<I> = Evm<Ctx, I, EthInstructions<EthInterpreter, Ctx>, EthPrecompiles, EthFrame>; +type Error = EVMError<Infallible>; + +/// Calls [`EMPTY`] with a value of 1 and stops. +const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); +/// Creates an empty contract and stops. +const CREATOR: Address = address!("0x00000000000000000000000000000000000c0de2"); +/// No code, no balance, no nonce. +const EMPTY: Address = address!("0x00000000000000000000000000000000000000ab"); +const GAS_LIMIT: u64 = 1_000_000; + +/// The frame a case acts on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Target { + /// The transaction's frame: a value transfer to [`EMPTY`]. + Root, + /// [`PARENT`]'s call to [`EMPTY`], at depth 1. + Child, + /// The transaction's frame: a creation with no init code. + RootCreation, + /// [`CREATOR`]'s creation, at depth 1. + ChildCreation, +} + +impl Target { + /// The caller of the target's start. + const fn caller(self) -> Address { + match self { + Self::Root | Self::RootCreation => BENCH_CALLER, + Self::Child => PARENT, + Self::ChildCreation => CREATOR, + } + } + + const fn is_creation(self) -> bool { + matches!(self, Self::RootCreation | Self::ChildCreation) + } +} + +/// How much of the start's gas limit an answer's tracker has left. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Left { + All, + Half, +} + +/// What is done to the start's result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Shape { + /// The start is answered with a constructor-built outcome: `status`, a tracker with `left` of + /// the gas limit and a reservoir of the given amount. + Answer(InstructionResult, Left, u64), + /// The end callback puts a constructor-built tracker in the result, with `left` of the gas + /// limit and a reservoir of the given amount. + ReplaceGas(Left, u64), + /// The end callback builds a new outcome around the same result. + RebuildOutcome, + /// The end callback rewrites the status only. + RewriteStatus(InstructionResult), + /// The end callback rewrites the status and puts a constructor-built tracker with the whole + /// gas limit and a reservoir of the given amount in the result. + RewriteAndReplace(InstructionResult, u64), +} + +/// A tracker built as an answer builds one: `left` of `gas_limit` and `reservoir`. +fn built_gas(gas_limit: u64, left: Left, reservoir: u64) -> Gas { + let mut gas = Gas::new(gas_limit); + if left == Left::Half { + gas.tracker_mut().set_remaining(gas_limit / 2); + } + gas.tracker_mut().set_reservoir(reservoir); + gas +} + +/// Whether the start of `caller` is the target's. +fn targeted(target: Target, caller: Address, creation: bool) -> bool { + caller == target.caller() && creation == target.is_creation() +} + +/// `shape`'s end-callback edit of a result whose start had `gas_limit`. +fn edit(shape: Shape, gas_limit: u64, result: &mut InterpreterResult) { + match shape { + Shape::Answer(..) | Shape::RebuildOutcome => {} + Shape::ReplaceGas(left, reservoir) => result.gas = built_gas(gas_limit, left, reservoir), + Shape::RewriteStatus(status) => result.result = status, + Shape::RewriteAndReplace(status, reservoir) => { + result.result = status; + result.gas = built_gas(gas_limit, Left::All, reservoir); + } + } +} + +/// Acts on the target's start as an inspector. +struct Rewrites(Target, Shape); + +/// The answer `shape` makes to a start with `gas_limit`, if it answers. +fn answer(shape: Shape, gas_limit: u64) -> Option<InterpreterResult> { + let Shape::Answer(status, left, reservoir) = shape else { + return None; + }; + let gas = built_gas(gas_limit, left, reservoir); + Some(InterpreterResult::new(status, Bytes::new(), gas)) +} + +impl Inspector<Ctx> for Rewrites { + fn call(&mut self, _: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { + if !targeted(self.0, inputs.caller, false) { + return None; + } + let result = answer(self.1, inputs.gas_limit)?; + Some(CallOutcome::new( + result, + inputs.return_memory_offset.clone(), + )) + } + + fn call_end(&mut self, _: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { + if !targeted(self.0, inputs.caller, false) { + return; + } + if self.1 == Shape::RebuildOutcome { + *outcome = CallOutcome::new(outcome.result.clone(), outcome.memory_offset.clone()); + } + edit(self.1, inputs.gas_limit, &mut outcome.result); + } + + fn create(&mut self, _: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { + if !targeted(self.0, inputs.caller(), true) { + return None; + } + Some(CreateOutcome::new( + answer(self.1, inputs.gas_limit())?, + None, + )) + } + + fn create_end(&mut self, _: &mut Ctx, inputs: &CreateInputs, outcome: &mut CreateOutcome) { + if !targeted(self.0, inputs.caller(), true) { + return; + } + if self.1 == Shape::RebuildOutcome { + *outcome = CreateOutcome::new(outcome.result.clone(), outcome.address); + } + edit(self.1, inputs.gas_limit(), &mut outcome.result); + } +} + +/// revm's mainnet EVM whose `frame_init` answers the target's start, as a consumer's +/// `frame_init` answers a start it intercepts. +struct Answers { + evm: MainEvm<()>, + target: Target, + answer: (InstructionResult, Left, u64), +} + +impl EvmTr for Answers { + type Context = Ctx; + type Instructions = EthInstructions<EthInterpreter, Ctx>; + type Precompiles = EthPrecompiles; + type Frame = EthFrame; + + fn all( + &self, + ) -> ( + &Self::Context, + &Self::Instructions, + &Self::Precompiles, + &FrameStack<Self::Frame>, + ) { + self.evm.all() + } + + fn all_mut( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack<Self::Frame>, + ) { + self.evm.all_mut() + } + + fn frame_init( + &mut self, + frame_init: FrameInit, + ) -> Result<FrameInitResult<'_, EthFrame>, ContextDbError<Ctx>> { + let (status, left, reservoir) = self.answer; + let shape = Shape::Answer(status, left, reservoir); + match &frame_init.frame_input { + FrameInput::Call(inputs) if targeted(self.target, inputs.caller, false) => { + let result = answer(shape, inputs.gas_limit).expect("an answer"); + let offset = inputs.return_memory_offset.clone(); + Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome::new( + result, offset, + )))) + } + FrameInput::Create(inputs) if targeted(self.target, inputs.caller(), true) => { + let result = answer(shape, inputs.gas_limit()).expect("an answer"); + Ok(ItemOrResult::Result(FrameResult::Create( + CreateOutcome::new(result, None), + ))) + } + _ => self.evm.frame_init(frame_init), + } + } + + fn frame_run(&mut self) -> Result<FrameInitOrResult<EthFrame>, ContextDbError<Ctx>> { + self.evm.frame_run() + } + + fn frame_return_result( + &mut self, + result: FrameResult, + ) -> Result<Option<FrameResult>, ContextDbError<Ctx>> { + self.evm.frame_return_result(result) + } +} + +fn account(code: Vec<u8>, balance: u64) -> AccountInfo { + let code = Bytecode::new_raw(code.into()); + AccountInfo::new(U256::from(balance), 1, code.hash_slow(), code) +} + +fn context() -> Ctx { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + // PUSH0 PUSH0 PUSH0 PUSH0 (no data in or out), PUSH1 1 (the value), PUSH20 EMPTY, + // PUSH3 0x010000 (the gas), CALL, STOP. + let mut parent = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, 1, PUSH20]; + parent.extend_from_slice(EMPTY.as_slice()); + parent.extend_from_slice(&[PUSH3, 0x01, 0x00, 0x00, CALL, STOP]); + db.insert_account_info(PARENT, account(parent, 1)); + db.insert_account_info(CREATOR, account(vec![PUSH0, PUSH0, PUSH0, CREATE, STOP], 0)); + Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM); + cfg.tx_gas_limit_cap = Some(u64::MAX); + }) +} + +fn tx(target: Target) -> TxEnv { + let (kind, value) = match target { + Target::Root => (TxKind::Call(EMPTY), 1), + Target::Child => (TxKind::Call(PARENT), 0), + Target::RootCreation => (TxKind::Create, 0), + Target::ChildCreation => (TxKind::Call(CREATOR), 0), + }; + TxEnv::builder_for_bench() + .kind(kind) + .value(U256::from(value)) + .gas_price(0) + .gas_limit(GAS_LIMIT) + .build_fill() +} + +/// The figures a transaction's result carries: its kind, its gas and its output. +fn figures(result: &ExecutionResult) -> String { + let kind = match result { + ExecutionResult::Success { reason, .. } => format!("Success({reason:?})"), + ExecutionResult::Revert { .. } => "Revert".to_string(), + ExecutionResult::Halt { reason, .. } => format!("Halt({reason:?})"), + }; + let gas = result.gas(); + format!( + "{kind} spent {} state {} refunded {} floor {} output {}", + gas.total_gas_spent(), + gas.state_gas_spent_final(), + gas.inner_refunded(), + gas.floor_gas(), + result.output().cloned().unwrap_or_default(), + ) +} + +/// The transaction of `target`, run plain. +fn plain(target: Target) -> String { + let result = context() + .build_mainnet() + .transact(tx(target)) + .expect("runs"); + figures(&result.result) +} + +/// The transaction of `target`, inspected under `shape`. +fn inspected(target: Target, shape: Shape) -> String { + let mut evm = context().build_mainnet_with_inspector(Rewrites(target, shape)); + let result = evm.inspect_tx(tx(target)).expect("runs"); + figures(&result.result) +} + +/// The transaction of `target`, its start answered by the consumer's `frame_init`. +fn answered(target: Target, answer: (InstructionResult, Left, u64)) -> String { + let mut evm = Answers { + evm: context().build_mainnet(), + target, + answer, + }; + evm.evm.ctx.set_tx(tx(target)); + let result = MainnetHandler::<_, Error, EthFrame>::default() + .run(&mut evm) + .expect("runs"); + figures(&result) +} + +/// Every case, named. +fn cases() -> Vec<(String, String)> { + use InstructionResult::{OutOfGas, Revert, Stop}; + let mut shapes = Vec::new(); + for status in [Stop, Revert, OutOfGas] { + for left in [Left::All, Left::Half] { + for reservoir in [0, 1] { + shapes.push(Shape::Answer(status, left, reservoir)); + } + } + } + for left in [Left::All, Left::Half] { + for reservoir in [0, 1] { + shapes.push(Shape::ReplaceGas(left, reservoir)); + } + } + shapes.push(Shape::RebuildOutcome); + shapes.push(Shape::RewriteStatus(Revert)); + shapes.push(Shape::RewriteStatus(OutOfGas)); + shapes.push(Shape::RewriteAndReplace(OutOfGas, 1)); + shapes.push(Shape::RewriteAndReplace(Revert, 1)); + + let mut cases = Vec::new(); + for target in [ + Target::Root, + Target::Child, + Target::RootCreation, + Target::ChildCreation, + ] { + cases.push((format!("{target:?} plain"), plain(target))); + for shape in &shapes { + cases.push(( + format!("{target:?} inspected {shape:?}"), + inspected(target, *shape), + )); + if let Shape::Answer(status, left, reservoir) = *shape { + cases.push(( + format!("{target:?} frame_init {shape:?}"), + answered(target, (status, left, reservoir)), + )); + } + } + } + cases +} + +/// The figures revm computed for each case before the lifecycle existed (`b370b538`). +const EXPECTED: &[(&str, &str)] = &[ + ( + "Root plain", + "Success(Stop) spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Stop, All, 0)", + "Success(Stop) spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Stop, All, 0)", + "Success(Stop) spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Stop, All, 1)", + "Success(Stop) spent 204599 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Stop, All, 1)", + "Success(Stop) spent 204599 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Stop, Half, 0)", + "Success(Stop) spent 602300 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Stop, Half, 0)", + "Success(Stop) spent 602300 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Stop, Half, 1)", + "Success(Stop) spent 602299 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Stop, Half, 1)", + "Success(Stop) spent 602299 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Revert, All, 0)", + "Revert spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Revert, All, 0)", + "Revert spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Revert, All, 1)", + "Revert spent 204599 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Revert, All, 1)", + "Revert spent 204599 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Revert, Half, 0)", + "Revert spent 602300 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Revert, Half, 0)", + "Revert spent 602300 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(Revert, Half, 1)", + "Revert spent 602299 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(Revert, Half, 1)", + "Revert spent 602299 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(OutOfGas, All, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(OutOfGas, All, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(OutOfGas, All, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(OutOfGas, All, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(OutOfGas, Half, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(OutOfGas, Half, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected Answer(OutOfGas, Half, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root frame_init Answer(OutOfGas, Half, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected ReplaceGas(All, 0)", + "Success(Stop) spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected ReplaceGas(All, 1)", + "Success(Stop) spent 204599 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected ReplaceGas(Half, 0)", + "Success(Stop) spent 602300 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected ReplaceGas(Half, 1)", + "Success(Stop) spent 602299 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected RebuildOutcome", + "Success(Stop) spent 204600 state 183600 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected RewriteStatus(Revert)", + "Revert spent 21000 state 0 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected RewriteStatus(OutOfGas)", + "Halt(OutOfGas(Basic)) spent 1000000 state 0 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected RewriteAndReplace(OutOfGas, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 0 refunded 0 floor 21000 output 0x", + ), + ( + "Root inspected RewriteAndReplace(Revert, 1)", + "Revert spent 20999 state 0 refunded 0 floor 21000 output 0x", + ), + ( + "Child plain", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Stop, All, 0)", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Stop, All, 0)", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Stop, All, 1)", + "Success(Stop) spent 210616 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Stop, All, 1)", + "Success(Stop) spent 210616 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Stop, Half, 0)", + "Success(Stop) spent 244535 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Stop, Half, 0)", + "Success(Stop) spent 244535 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Stop, Half, 1)", + "Success(Stop) spent 244534 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Stop, Half, 1)", + "Success(Stop) spent 244534 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Revert, All, 0)", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Revert, All, 0)", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Revert, All, 1)", + "Success(Stop) spent 210616 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Revert, All, 1)", + "Success(Stop) spent 210616 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Revert, Half, 0)", + "Success(Stop) spent 244535 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Revert, Half, 0)", + "Success(Stop) spent 244535 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(Revert, Half, 1)", + "Success(Stop) spent 244534 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(Revert, Half, 1)", + "Success(Stop) spent 244534 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(OutOfGas, All, 0)", + "Success(Stop) spent 278453 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(OutOfGas, All, 0)", + "Success(Stop) spent 278453 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(OutOfGas, All, 1)", + "Success(Stop) spent 278452 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(OutOfGas, All, 1)", + "Success(Stop) spent 278452 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(OutOfGas, Half, 0)", + "Success(Stop) spent 278453 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(OutOfGas, Half, 0)", + "Success(Stop) spent 278453 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected Answer(OutOfGas, Half, 1)", + "Success(Stop) spent 278452 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child frame_init Answer(OutOfGas, Half, 1)", + "Success(Stop) spent 278452 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected ReplaceGas(All, 0)", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected ReplaceGas(All, 1)", + "Success(Stop) spent 210616 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected ReplaceGas(Half, 0)", + "Success(Stop) spent 244535 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected ReplaceGas(Half, 1)", + "Success(Stop) spent 244534 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected RebuildOutcome", + "Success(Stop) spent 210617 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected RewriteStatus(Revert)", + "Success(Stop) spent 27017 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected RewriteStatus(OutOfGas)", + "Success(Stop) spent 94853 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected RewriteAndReplace(OutOfGas, 1)", + "Success(Stop) spent 94852 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "Child inspected RewriteAndReplace(Revert, 1)", + "Success(Stop) spent 27016 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "RootCreation plain", + "Success(Return) spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Stop, All, 0)", + "Success(Stop) spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Stop, All, 0)", + "Success(Stop) spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Stop, All, 1)", + "Success(Stop) spent 207599 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Stop, All, 1)", + "Success(Stop) spent 207599 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Stop, Half, 0)", + "Success(Stop) spent 603800 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Stop, Half, 0)", + "Success(Stop) spent 603800 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Stop, Half, 1)", + "Success(Stop) spent 603799 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Stop, Half, 1)", + "Success(Stop) spent 603799 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Revert, All, 0)", + "Revert spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Revert, All, 0)", + "Revert spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Revert, All, 1)", + "Revert spent 207599 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Revert, All, 1)", + "Revert spent 207599 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Revert, Half, 0)", + "Revert spent 603800 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Revert, Half, 0)", + "Revert spent 603800 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(Revert, Half, 1)", + "Revert spent 603799 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(Revert, Half, 1)", + "Revert spent 603799 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(OutOfGas, All, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(OutOfGas, All, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(OutOfGas, All, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(OutOfGas, All, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(OutOfGas, Half, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(OutOfGas, Half, 0)", + "Halt(OutOfGas(Basic)) spent 1000000 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected Answer(OutOfGas, Half, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation frame_init Answer(OutOfGas, Half, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected ReplaceGas(All, 0)", + "Success(Return) spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected ReplaceGas(All, 1)", + "Success(Return) spent 207599 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected ReplaceGas(Half, 0)", + "Success(Return) spent 603800 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected ReplaceGas(Half, 1)", + "Success(Return) spent 603799 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected RebuildOutcome", + "Success(Return) spent 207600 state 183600 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected RewriteStatus(Revert)", + "Revert spent 24000 state 0 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected RewriteStatus(OutOfGas)", + "Halt(OutOfGas(Basic)) spent 1000000 state 0 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected RewriteAndReplace(OutOfGas, 1)", + "Halt(OutOfGas(Basic)) spent 999999 state 0 refunded 0 floor 24000 output 0x", + ), + ( + "RootCreation inspected RewriteAndReplace(Revert, 1)", + "Revert spent 23999 state 0 refunded 0 floor 24000 output 0x", + ), + ( + "ChildCreation plain", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Stop, All, 0)", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Stop, All, 0)", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Stop, All, 1)", + "Success(Stop) spent 210605 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Stop, All, 1)", + "Success(Stop) spent 210605 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Stop, Half, 0)", + "Success(Stop) spent 599136 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Stop, Half, 0)", + "Success(Stop) spent 599136 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Stop, Half, 1)", + "Success(Stop) spent 599135 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Stop, Half, 1)", + "Success(Stop) spent 599135 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Revert, All, 0)", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Revert, All, 0)", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Revert, All, 1)", + "Success(Stop) spent 210605 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Revert, All, 1)", + "Success(Stop) spent 210605 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Revert, Half, 0)", + "Success(Stop) spent 599136 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Revert, Half, 0)", + "Success(Stop) spent 599136 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(Revert, Half, 1)", + "Success(Stop) spent 599135 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(Revert, Half, 1)", + "Success(Stop) spent 599135 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(OutOfGas, All, 0)", + "Success(Stop) spent 987666 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(OutOfGas, All, 0)", + "Success(Stop) spent 987666 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(OutOfGas, All, 1)", + "Success(Stop) spent 987665 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(OutOfGas, All, 1)", + "Success(Stop) spent 987665 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(OutOfGas, Half, 0)", + "Success(Stop) spent 987666 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(OutOfGas, Half, 0)", + "Success(Stop) spent 987666 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected Answer(OutOfGas, Half, 1)", + "Success(Stop) spent 987665 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation frame_init Answer(OutOfGas, Half, 1)", + "Success(Stop) spent 987665 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected ReplaceGas(All, 0)", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected ReplaceGas(All, 1)", + "Success(Stop) spent 210605 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected ReplaceGas(Half, 0)", + "Success(Stop) spent 599136 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected ReplaceGas(Half, 1)", + "Success(Stop) spent 599135 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected RebuildOutcome", + "Success(Stop) spent 210606 state 183600 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected RewriteStatus(Revert)", + "Success(Stop) spent 27006 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected RewriteStatus(OutOfGas)", + "Success(Stop) spent 804066 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected RewriteAndReplace(OutOfGas, 1)", + "Success(Stop) spent 804065 state 0 refunded 0 floor 15000 output 0x", + ), + ( + "ChildCreation inspected RewriteAndReplace(Revert, 1)", + "Success(Stop) spent 27005 state 0 refunded 0 floor 15000 output 0x", + ), +]; + +#[test] +fn test_default_hooks_change_no_figure_the_settlement_computes() { + let actual = cases(); + let table: String = actual + .iter() + .map(|(name, figures)| format!(" ({name:?}, {figures:?}),\n")) + .collect(); + let expected: Vec<(String, String)> = EXPECTED + .iter() + .map(|(name, figures)| (name.to_string(), figures.to_string())) + .collect(); + assert!( + actual == expected, + "the figures moved; this revision's table:\n{table}" + ); +} + +/// The reviewer's case: the transaction's frame answered with an out-of-gas outcome whose tracker +/// hands back a reservoir of 1, which unwinds 1 of the transaction's spill into regular gas. The +/// halt keeps that gas, as revm's settlement left it, whether an inspector or the consumer's +/// `frame_init` answers. +#[test] +fn test_a_halted_answer_to_the_transactions_frame_keeps_the_gas_its_settlement_returned() { + let answer = (InstructionResult::OutOfGas, Left::All, 1); + for figures in [ + inspected(Target::Root, Shape::Answer(answer.0, answer.1, answer.2)), + answered(Target::Root, answer), + ] { + assert!( + figures.starts_with("Halt(OutOfGas(Basic)) spent 999999 "), + "{figures}" + ); + } +} From ef1b78bcd2a99732040ce67faae63fe8f88c82cf Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 13:30:40 +0800 Subject: [PATCH 089/110] perf(handler): frame_run opens a child's start as the frame consumes its NewFrame action The open used to follow process_next_action: frame_run bound its result, matched it by reference and rewrapped it, which moved the 264-byte init or result out of the Result and back into the return value. The child's start now opens before the action becomes the init, from the action's kind and the frame's depth (the init's depth is one below the frame's, always), and process_next_action(..).inspect(..) is the return value again, as it was before the lifecycle. --- crates/handler/src/evm.rs | 28 +++++++++++++++++++++------- crates/handler/src/lifecycle.rs | 17 ++++++++++++++++- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/handler/src/evm.rs b/crates/handler/src/evm.rs index 72e59bc841..70a69faf04 100644 --- a/crates/handler/src/evm.rs +++ b/crates/handler/src/evm.rs @@ -7,7 +7,10 @@ use crate::{ use auto_impl::auto_impl; use context::{ContextTr, Database, Evm, FrameStack}; use context_interface::context::ContextError; -use interpreter::{interpreter::EthInterpreter, interpreter_action::FrameInit, InterpreterResult}; +use interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, InterpreterAction, + InterpreterResult, +}; /// Type alias for database error within a context pub type ContextDbError<CTX> = ContextError<ContextTrDbError<CTX>>; @@ -253,12 +256,23 @@ where context, ); - let next = frame.process_next_action::<_, ContextDbError<CTX>>(context, action)?; - match &next { - ItemOrResult::Item(init) => crate::lifecycle::open_frame_start(self, init)?, - ItemOrResult::Result(_) => frame.set_finished(true), - } - Ok(next) + // The frame's `NewFrame` action is consumed here: the child's start opens before the + // action becomes the child's init, whose depth is one below the frame's. Reading only the + // action's kind and the frame's depth leaves the init to be built in the return value. + let frame = if let InterpreterAction::NewFrame(_) = &action { + let depth = frame.depth + 1; + crate::lifecycle::open_start(&mut self.ctx, &mut self.frame_stack, depth)?; + self.frame_stack.get() + } else { + frame + }; + frame + .process_next_action(&mut self.ctx, action) + .inspect(|i| { + if i.is_result() { + frame.set_finished(true); + } + }) } /// Returns the result of the frame to the caller, and closes its start. Frame is popped from diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs index dafbf2efcc..42f731cf16 100644 --- a/crates/handler/src/lifecycle.rs +++ b/crates/handler/src/lifecycle.rs @@ -105,7 +105,22 @@ pub fn open_frame_start<EVM: EvmTr + ?Sized>( init: &FrameInit, ) -> Result<(), ContextDbError<EVM::Context>> { let (ctx, _, _, frame_stack) = evm.all_mut(); - let split = frame_stack.open_start(init.depth).map_err(fatal)?; + open_start(ctx, frame_stack, init.depth) +} + +/// Opens the start of the frame at `depth` the next init makes, as [`open_frame_start`] does, from +/// the pieces of an EVM: for a frame run that opens the start as the frame consumes its +/// `NewFrame` action, before the init is built. +#[inline] +pub(crate) fn open_start<CTX, F, E>( + ctx: &mut CTX, + frame_stack: &mut FrameStack<F>, + depth: usize, +) -> Result<(), ContextError<E>> +where + CTX: Host + ?Sized, +{ + let split = frame_stack.open_start(depth).map_err(fatal)?; ctx.frame_split(&split); Ok(()) } From 67d0e863d9ea8834cfdb26ac0f69cf772c529f0a Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 13:30:40 +0800 Subject: [PATCH 090/110] perf(context): the record's child slots grow with the frame stack and outlive the transaction The slots were resized one level at a time, and emptied with clear() at every boundary, so every transaction grew them again level by level and a fresh EVM reallocated per new depth. They now grow, cold, to the frame stack's capacity the first time a child opens past them, and are never shrunk; a count of open children answers the boundary's check, and only a discard empties slots. Whether a lifecycle is under way is the last identity allocated being non-zero, which keeps the record at 40 bytes. --- .../context/interface/src/local/lifecycle.rs | 130 +++++++++++++----- 1 file changed, 99 insertions(+), 31 deletions(-) diff --git a/crates/context/interface/src/local/lifecycle.rs b/crates/context/interface/src/local/lifecycle.rs index ef5b40b666..77011a67b0 100644 --- a/crates/context/interface/src/local/lifecycle.rs +++ b/crates/context/interface/src/local/lifecycle.rs @@ -105,17 +105,24 @@ impl core::error::Error for StartLifecycleError {} /// it is making. #[derive(Clone, Debug, Default)] pub(super) struct StartLifecycle { - /// The last identity allocated in the transaction, 0 before the first. + /// The last identity allocated in the transaction, 0 before the first. The first start opened + /// is always the transaction's, so a lifecycle is under way exactly when this is not 0. last: u32, - /// Whether a lifecycle is under way: its first start opened, and it has not ended. - active: bool, + /// How many of `children`'s slots hold an open start. + open_children: u32, /// The transaction's start. root: Option<PendingStart>, - /// The open start of the frame at each stack index. + /// The open start of the frame at each stack index. Its length grows with the frame stack's + /// capacity and never shrinks, so frames and transactions reuse the slots without resizing. children: Vec<Option<PendingStart>>, } impl StartLifecycle { + #[inline] + const fn active(&self) -> bool { + self.last != 0 + } + /// The slot the next start opens in, and the next settlement closes: the transaction's on an /// empty stack, else that of the frame on top, at `index`. #[inline] @@ -127,16 +134,33 @@ impl StartLifecycle { } #[inline] - fn any_open(&self) -> bool { - self.root.is_some() || self.children.iter().any(Option::is_some) + const fn any_open(&self) -> bool { + self.root.is_some() || self.open_children != 0 } #[inline] fn reset(&mut self) { self.last = 0; - self.active = false; self.root = None; - self.children.clear(); + if self.open_children != 0 { + self.discard_children(); + } + } + + /// Empties the children's slots, which only a discarded lifecycle leaves open. + #[cold] + #[inline(never)] + fn discard_children(&mut self) { + self.children.fill(None); + self.open_children = 0; + } + + /// Gives the record a slot for every frame the stack has room for, `len`: the first child + /// start, and the first after the frame stack grew. + #[cold] + #[inline(never)] + fn grow_children(&mut self, len: usize) { + self.children.resize(len, None); } } @@ -155,13 +179,24 @@ impl<T> FrameStack<T> { /// [`StartLifecycleError::NoParent`] when the frame on top has no start of its own. #[inline] pub fn open_start(&mut self, depth: usize) -> Result<FrameSplit, StartLifecycleError> { + let capacity = self.stack.capacity(); let record = &mut self.lifecycle; let id = record .last .checked_add(1) .ok_or(StartLifecycleError::Exhausted)?; + let start = Some(PendingStart { + id, + ..Default::default() + }); let parent = match self.index { - None => None, + None => { + if record.root.is_some() { + return Err(StartLifecycleError::Stale); + } + record.root = start; + None + } Some(i) => { let parent = match i { 0 => record.root, @@ -170,24 +205,19 @@ impl<T> FrameStack<T> { let Some(parent) = parent else { return Err(StartLifecycleError::NoParent); }; - if record.children.len() <= i { - record.children.resize(i + 1, None); + if i >= record.children.len() { + record.grow_children(capacity.max(i + 1)); } + let slot = &mut record.children[i]; + if slot.is_some() { + return Err(StartLifecycleError::Stale); + } + *slot = start; + record.open_children += 1; Some(parent.id) } }; - let slot = record - .slot(self.index) - .expect("the slot of the frame on top exists"); - if slot.is_some() { - return Err(StartLifecycleError::Stale); - } - *slot = Some(PendingStart { - id, - ..Default::default() - }); record.last = id; - record.active = true; Ok(FrameSplit { id, parent, depth }) } @@ -208,11 +238,18 @@ impl<T> FrameStack<T> { created: Option<bool>, held_reservoir: u64, ) -> Result<FrameSettle, StartLifecycleError> { - let start = self - .lifecycle - .slot(self.index) - .and_then(Option::take) - .ok_or(StartLifecycleError::NotOpen)?; + let record = &mut self.lifecycle; + let start = match self.index { + None => record.root.take(), + Some(i) => { + let start = record.children.get_mut(i).and_then(Option::take); + if start.is_some() { + record.open_children -= 1; + } + start + } + } + .ok_or(StartLifecycleError::NotOpen)?; Ok(FrameSettle { id: start.id, depth, @@ -250,12 +287,12 @@ impl<T> FrameStack<T> { /// boundary ended it. #[inline] pub const fn lifecycle_active(&self) -> bool { - self.lifecycle.active + self.lifecycle.active() } /// Whether every start opened in the transaction has settled. #[inline] - pub fn lifecycle_settled(&self) -> bool { + pub const fn lifecycle_settled(&self) -> bool { !self.lifecycle.any_open() } @@ -273,7 +310,7 @@ impl<T> FrameStack<T> { if self.lifecycle.any_open() { return Err(StartLifecycleError::Unsettled); } - let end = self.lifecycle.active.then_some(LifecycleEnd::Settled); + let end = self.lifecycle.active().then_some(LifecycleEnd::Settled); self.lifecycle.reset(); Ok(end) } @@ -288,7 +325,7 @@ impl<T> FrameStack<T> { #[inline] #[must_use = "a lifecycle that was under way owes the consumer its end"] pub fn discard_lifecycle(&mut self) -> Option<LifecycleEnd> { - let end = self.lifecycle.active.then_some(LifecycleEnd::Discarded); + let end = self.lifecycle.active().then_some(LifecycleEnd::Discarded); self.lifecycle.reset(); end } @@ -504,6 +541,37 @@ mod tests { assert_eq!(stack.open_start(0).map(|s| s.id), Ok(1)); } + /// The children's slots are sized with the frame stack and outlive the transaction: no + /// boundary shrinks them, and a discard empties them. + #[test] + fn test_the_slots_outlive_the_transaction() { + // Two frames on a stack with room for eight. + let mut stack = FrameStack::<u8>::new_prealloc(8); + let token = stack.start_init().consume(); + unsafe { stack.end_init(token) }; + let token = stack.get_next().consume(); + unsafe { stack.push(token) }; + open_nested(&mut stack, 2); + let slots = stack.lifecycle.children.len(); + assert!( + slots >= stack.stack.capacity(), + "the first child gives a slot to every frame the stack has room for: {slots} of {}", + stack.stack.capacity() + ); + assert_eq!(stack.discard_lifecycle(), Some(LifecycleEnd::Discarded)); + assert_eq!(stack.lifecycle.children.len(), slots); + assert!(stack.lifecycle.children.iter().all(Option::is_none)); + + open_nested(&mut stack, 2); + stack.close_start(2, SettleStatus::Ok, None, 0).unwrap(); + stack.index = Some(0); + stack.close_start(1, SettleStatus::Ok, None, 0).unwrap(); + stack.clear(); + stack.close_start(0, SettleStatus::Ok, None, 0).unwrap(); + assert_eq!(stack.settle_lifecycle(), Ok(Some(LifecycleEnd::Settled))); + assert_eq!(stack.lifecycle.children.len(), slots); + } + #[test] fn test_what_an_inspector_did_reaches_the_settlement() { let mut stack = stack(1); From c7c847d119753c8352b069461924728a1651b1f8 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 13:54:13 +0800 Subject: [PATCH 091/110] test: the halt cases' docs describe the case, and the halt rule's test helper says what it credits --- crates/handler/src/lifecycle.rs | 4 ++-- crates/inspector/tests/default_hook_figures.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/handler/src/lifecycle.rs b/crates/handler/src/lifecycle.rs index 42f731cf16..fbbf5bc443 100644 --- a/crates/handler/src/lifecycle.rs +++ b/crates/handler/src/lifecycle.rs @@ -336,8 +336,8 @@ mod tests { use super::consume_hook_credit; use interpreter::GasTracker; - /// A transaction's gas after its settlement left it `remaining` regular gas, then credited - /// `credit` by refills a hook makes: one that unwinds the spill and one past it. + /// A transaction's gas whose settlement left it `remaining` regular gas, after a hook credited + /// it `credit` more. fn credited(remaining: u64, credit: u64) -> GasTracker { let mut gas = GasTracker::new(1_000, remaining, 0); gas.erase_cost(credit); diff --git a/crates/inspector/tests/default_hook_figures.rs b/crates/inspector/tests/default_hook_figures.rs index a84d421fb4..74b159526c 100644 --- a/crates/inspector/tests/default_hook_figures.rs +++ b/crates/inspector/tests/default_hook_figures.rs @@ -953,10 +953,10 @@ fn test_default_hooks_change_no_figure_the_settlement_computes() { ); } -/// The reviewer's case: the transaction's frame answered with an out-of-gas outcome whose tracker -/// hands back a reservoir of 1, which unwinds 1 of the transaction's spill into regular gas. The -/// halt keeps that gas, as revm's settlement left it, whether an inspector or the consumer's -/// `frame_init` answers. +/// The transaction's frame answered with an out-of-gas outcome whose tracker hands back a +/// reservoir of 1, which unwinds 1 of the transaction's spill into regular gas. The halt keeps that +/// gas, as revm's settlement left it, whether an inspector or the consumer's `frame_init` answers: +/// 999,999 of the 1,000,000 gas limit is spent. #[test] fn test_a_halted_answer_to_the_transactions_frame_keeps_the_gas_its_settlement_returned() { let answer = (InstructionResult::OutOfGas, Left::All, 1); From 337bc8661edca6c1aed5ee99e47a1fcd6989c9fb Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 14:30:03 +0800 Subject: [PATCH 092/110] fix(context): a stack of zero-sized frames grows its child slots by the frames it needs The record grew its child slots to the frame vector's capacity, which a vector of zero-sized frames reports as usize::MAX: the first child start on such a stack panicked with a capacity overflow. Zero-sized frames now name no room, so their slots grow to the index a child needs; ordinary frames keep growing the slots with the stack's capacity. --- .../context/interface/src/local/lifecycle.rs | 57 +++++++++++++++++-- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/context/interface/src/local/lifecycle.rs b/crates/context/interface/src/local/lifecycle.rs index 77011a67b0..47a82e5488 100644 --- a/crates/context/interface/src/local/lifecycle.rs +++ b/crates/context/interface/src/local/lifecycle.rs @@ -112,8 +112,9 @@ pub(super) struct StartLifecycle { open_children: u32, /// The transaction's start. root: Option<PendingStart>, - /// The open start of the frame at each stack index. Its length grows with the frame stack's - /// capacity and never shrinks, so frames and transactions reuse the slots without resizing. + /// The open start of the frame at each stack index. Its length grows with the room the frame + /// stack has ([`FrameStack::frame_room`]), or by the slots the frames need for zero-sized + /// frames, and never shrinks, so frames and transactions reuse the slots without resizing. children: Vec<Option<PendingStart>>, } @@ -155,8 +156,8 @@ impl StartLifecycle { self.open_children = 0; } - /// Gives the record a slot for every frame the stack has room for, `len`: the first child - /// start, and the first after the frame stack grew. + /// Gives the record `len` slots: a slot for every frame the stack has room for, at the first + /// child start and the first after the frame stack grew. #[cold] #[inline(never)] fn grow_children(&mut self, len: usize) { @@ -165,6 +166,19 @@ impl StartLifecycle { } impl<T> FrameStack<T> { + /// How many frames the stack has room for before its vector reallocates: the slots the record + /// gives the children when it grows, so that it grows with the stack. A vector of zero-sized + /// frames never reallocates and reports a capacity of `usize::MAX`, which names no room: the + /// record then grows by the slots its frames need. + #[inline] + const fn frame_room(&self) -> usize { + if size_of::<T>() == 0 { + 0 + } else { + self.stack.capacity() + } + } + /// Opens the start of the frame the next init makes, at `depth`: the child of the frame on /// top of the stack, or the transaction's start when the stack is empty. Returns the split to /// hand to [`Host::frame_split`](crate::Host::frame_split). @@ -179,7 +193,7 @@ impl<T> FrameStack<T> { /// [`StartLifecycleError::NoParent`] when the frame on top has no start of its own. #[inline] pub fn open_start(&mut self, depth: usize) -> Result<FrameSplit, StartLifecycleError> { - let capacity = self.stack.capacity(); + let room = self.frame_room(); let record = &mut self.lifecycle; let id = record .last @@ -206,7 +220,7 @@ impl<T> FrameStack<T> { return Err(StartLifecycleError::NoParent); }; if i >= record.children.len() { - record.grow_children(capacity.max(i + 1)); + record.grow_children(room.max(i + 1)); } let slot = &mut record.children[i]; if slot.is_some() { @@ -572,6 +586,37 @@ mod tests { assert_eq!(stack.lifecycle.children.len(), slots); } + /// A stack of zero-sized frames, whose vector reports a capacity of `usize::MAX`, opens its + /// children as any stack does. + #[test] + fn test_a_stack_of_zero_sized_frames_opens_its_children() { + let mut stack = FrameStack::<()>::new_prealloc(1); + assert_eq!(stack.open_start(0).map(|s| s.id), Ok(1)); + let token = stack.start_init().consume(); + unsafe { stack.end_init(token) }; + assert_eq!(stack.open_start(1).map(|s| s.id), Ok(2)); + } + + /// A stack of zero-sized frames gets one slot per frame a child opened under, the slots its + /// frames need, rather than the slots its vector's capacity would name. + #[test] + fn test_a_stack_of_zero_sized_frames_grows_its_slots_by_the_frames() { + let mut stack = FrameStack::<()>::new_prealloc(4); + stack.open_start(0).unwrap(); + let token = stack.start_init().consume(); + unsafe { stack.end_init(token) }; + for depth in 1..=4 { + if depth > 1 { + let token = stack.get_next().consume(); + unsafe { stack.push(token) }; + } + assert_eq!(stack.open_start(depth).map(|s| s.id), Ok(depth as u32 + 1)); + } + assert_eq!(stack.lifecycle.children.len(), 4); + assert_eq!(stack.discard_lifecycle(), Some(LifecycleEnd::Discarded)); + assert!(stack.lifecycle.children.iter().all(Option::is_none)); + } + #[test] fn test_what_an_inspector_did_reaches_the_settlement() { let mut stack = stack(1); From 778f71bdb47b2324116ba33d297a5ab60761100e Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 14:30:03 +0800 Subject: [PATCH 093/110] docs(context): frame_settle says a halted transaction consumes only the hook's net regular-gas credit The hook's doc still described the halt rule as consuming the regular gas left on a halt. revm consumes the regular gas the hook credited above what its own settlement left, keeps that gas, and leaves a debit. --- crates/context/interface/src/host.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 5e89f07566..f6a1a50c2e 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -164,11 +164,13 @@ pub trait Host { let _ = split; } - /// Called when revm settles the start `settle.id` into its caller's `gas`: after revm's own - /// settlement of the frame's result, and, for the transaction's frame, before revm's halt rule - /// consumes the regular gas left on a halt. + /// Called when revm settles the start `settle.id` into its caller's `gas`, after revm's own + /// settlement of the frame's result. /// - /// The hook may debit and credit `gas`, which goes on as the hook left it. + /// The hook may debit and credit `gas`, which goes on as the hook left it, but for a halted + /// transaction's frame: there revm then consumes the hook's net credit of regular gas, the + /// regular gas `gas` holds above what revm's own settlement left in it, and keeps the gas that + /// settlement left. A hook that debits keeps its debit. /// /// The default touches nothing. #[inline] From f095f3a435a33403facc8970b9c1bc8e0332c407 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 11:21:27 +0800 Subject: [PATCH 094/110] docs: a Start lifecycle entry under Hooks says where revm opens and settles a start, what a handler or runner that replaces those points must call, what the record refuses and what a consumer that sets nothing pays The pairing of a start with its settlement is revm's, so a custom EVM, a handler override and a hand-driven first frame take part in it, and a miss is a fatal error in release too. The entry names those obligations and the sizes; the rule 2 set does not grow. --- MEGAETH-FORK.md | 96 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index bca0691604..d1cabdb800 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -63,6 +63,7 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T Some of these a consumer could keep beside revm's gas through the hooks, at a cost in code and in the gas figures it has to restore; the next base-line move may take them out (see What the fork carries). Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing. Nothing else that implements MegaETH semantics enters the fork. + The start lifecycle carries no MegaETH figure, so it is a generic hook and the set does not grow with it (see Start lifecycle). An addition to the set needs all of these, argued in its pull request: - no hook that sees only the state revm exposes at that point can make the same decision, because the figure is read or written inside a charge, or has to be ordered with revm's own settlement; the pull request says why the consumer cannot keep it beside revm's gas; - it is mechanism, not policy: every amount, share, price and limit comes from the consumer, through the gas schedule or a hook, and a detail the fork has to fix itself, such as a rounding, is named in its entry; @@ -102,7 +103,7 @@ The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fo |---|---|---|---| | Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `EthFrame::return_result`, `create_init_frame`, `last_frame_result`), so that accounting is re-applied to the new base's versions of it. | | Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | -| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action and the frame-run-result hook | about 1,750 lines | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | +| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | about 1,750 lines | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | | Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. | | MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge, the history allowance | about 2,150 lines, of which the pools, the kept share, the start charge and the allowance are about 1,450 | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. The items that ride on the frame results (the pools, the start charge, the allowance) are the first candidates, since every consumer pays their size. | @@ -471,6 +472,99 @@ An id the fork once used for an entry with another default is left unused rather - **Default.** Does nothing, so every result and every callback is upstream's. Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured. +### Start lifecycle + +- **API.** + On `Host`, each with a no-op default: `frame_split(&mut self, split: &FrameSplit<'_>)`, `frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker)` and `frame_lifecycle_end(&mut self, end: LifecycleEnd)`. + `FrameSplit` (`id`, `parent`, `depth`, `start`), `FrameSettle` (`id`, `depth`, `status`, `created`, `inspector_answer`, `gas_replaced`, `outcome_rebuilt`, `held_reservoir`), `SettleStatus` (`Ok`, `Revert`, `Halt`) and `LifecycleEnd` (`Settled`, `Discarded`), in `revm_context_interface::host`. + `revm_handler::lifecycle`: `open_frame_start`, `open_transaction_start`, `close_transaction_start`, `finish_transaction`, `discard_transaction` and `settle_status`. + On `FrameStack`, the record: `open_start`, `close_start`, `lifecycle_active`, `lifecycle_settled` and `lifecycle_clear`. + `StartLifecycleError` (`Exhausted`, `Stale`, `NotOpen`, `NoParent`, `Unsettled`), `PendingStart`, `StartMark` and `OutcomeMark`. + `GasTracker::start_mark`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field). + `LocalContextTr::lifecycle_debug` and `LifecycleDebug`, the debug mirror (below). +- **Contract.** A *start* is one frame's beginning with the identity revm gave it; revm pairs every start it opens with exactly one settlement, last in first out, and the consumer does not pair them. + *Where revm opens one.* + - Where it consumes a `NewFrame` action: `Evm::frame_run` and `InspectorEvmTr::inspect_frame_run`, right after `process_next_action` returns the frame's init, so the child's start opens against the frame on top of the stack, its caller. + - Where it makes the transaction's first frame: `Handler::execution` and `InspectorHandler::inspect_execution`. + - In the default `Handler::runtime_oog_result`, for the stand-in result of a transaction whose EIP-2780 runtime phase ran out of gas. + + It opens before `Handler::frame_init` and so before an inspector's `frame_start`, `call` and `create`: an answer made in any of them, an inspector's or a consumer's own, settles on a start that is already open. + An action an inspector drops or replaces in `step_end` is replaced before revm consumes it, so a start it dropped was never opened, and a clone of the input opens its own. + A frame init revm answers without running a frame (a precompile, a start it refuses) opens a start and settles it like any other. + + *Where revm settles one.* + - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the start of the caller on top of the stack and calls `frame_settle` with the caller's tracker. + - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and a halt then consumes the regular gas the hook credited, as it does for the state refund. + + `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and `start`, a `FrameStart` read from the init revm consumed (`kind`, `caller`, `target`, `value`, `forward`; no `charge`). + `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. + `frame_lifecycle_end` is called once at the end of a transaction's lifecycle: `Settled` at the successful boundary, with every start settled, and `Discarded` when a fatal error ends the transaction and the open starts are dropped unsettled. + A transaction that ends before any start opened emits neither. + + *The record* is revm's `FrameStack`, which no inspector callback is handed: a per-transaction counter of identities, a slot for the transaction's start and one slot per frame on the stack for the start of the child that frame is making, at most one. + A child's parent is the start in the slot of the frame under it, and its depth is one more than its caller's. + Both boundaries reset it. + + *The lifecycle helpers.* A handler or an EVM type that replaces a method revm opens or settles in calls the helper that method calls: + + | It overrides or reimplements | It calls | + |---|---| + | `Handler::execution` or `InspectorHandler::inspect_execution` | `open_frame_start` where it makes the first frame's init | + | `Handler::runtime_oog_result`, building its own stand-in | `open_transaction_start`, with a `FrameStart` for the transaction, before it returns | + | `EvmTr::frame_run` or `InspectorEvmTr::inspect_frame_run` | `open_frame_start` after `process_next_action` returns an init | + | `EvmTr::frame_return_result` | `settle_status` before `return_result`, then `FrameStack::close_start` and `Host::frame_settle` with the caller's tracker after it | + | `Handler::last_frame_result` | `close_transaction_start` right after `settle_first_frame`, given the reservoir the caller's gas held before the settlement | + | `Handler::execution_result` | `finish_transaction`, after the context's recorded error is taken and before the output is built | + | `Handler::catch_error` | `discard_transaction`, in the cleanup every error reaches, before the frame stack is cleared | + + `finish_transaction` is the successful boundary: with every start settled it emits `LifecycleEnd::Settled` and resets the record. + `discard_transaction` is the fatal boundary: it emits `Discarded` only if a lifecycle is under way, resets the record, and is idempotent, so a cleanup that runs twice emits once. + A call sits where the mainnet method makes it and passes what that method passes. + + *Fatal errors.* The record refuses these, in a release build as in a debug build, as a `ContextError::Custom` that fails the transaction and that `catch_error` reports: + - `Stale`: a start opened where one is still open, so a boundary or a settlement was missed; + - `NoParent`: a child start under a frame with no start of its own, so a runner drove the transaction's frame without opening its start; + - `NotOpen`: a settlement found no start open; + - `Exhausted`: the transaction opened 4,294,967,295 starts; the start does not open; + - `Unsettled`: `finish_transaction` found a start open. A debug build asserts; a release build clears the record, emits `Discarded` and fails the transaction. + + *The marks and the flags.* Before it calls an inspector's end callbacks (`call_end`, `create_end`, `frame_end`) revm writes the start's identity on the result's tracker (`StartMark`, a `u32`) and a mark of the start on the outcome (`OutcomeMark`, a `u16`, `(id − 1) mod 65535 + 1`, never zero); after them it reads both. + `gas_replaced` is set on the start when the tracker's mark is no longer the start's, `outcome_rebuilt` when the outcome's is not, and `inspector_answer` when `frame_start`, `call` or `create` answered the start. + A constructor (`Gas::new`, `CallOutcome::new`, `CreateOutcome::new`) and a literal that names the mark as `Default::default()` leave it zero, so a value built afresh is always seen; a copy of another start's value is seen unless the two identities are 65,535 apart, and a copy made in the previous transaction at the same sequence position is not. + A tracker an inspector saved before the marking carries none, so restoring it at an end callback sets `gas_replaced` even when it came from the same start. + The flags say what an inspector did, never what the consumer did: the consumer's own answers are made in `frame_init`, before any end callback, and are never flagged. + Only the inspected path marks and flags; the plain path leaves all three clear. + Both marks take no part in equality, hashing, `Debug` or serde: they compare equal always, hash to nothing, are skipped by serde and decode as none, and `GasTracker`, `CallOutcome` and `CreateOutcome` have a hand-written `Debug` that lists the other fields in declaration order, so its output is the derived output without the mark. + A change to a field of those three types changes that `Debug` too. + An inspector can forge a mark or call a hook by hand through the `&mut` context: a forged mark changes only the flags, and a hand call desynchronises the consumer's own stack from the record without touching the record or its checks; both are outside the contract. + + *Reuse after an uncaught error.* `Handler::run_without_catch_error` skips the cleanup `catch_error` does. + A caller that drops its error must do all of it before it reuses the EVM: `discard_transaction`, clearing the local context, discarding the journal (`discard_tx`) and clearing the frame stack. + A frame stack left as the error left it makes the next transaction's opening a child under a frame whose start was discarded, and it fails with `NoParent`; a record left open fails the next opening with `Stale`. + Calling `catch_error` does all of it. + + *A hand-driven first frame.* A runner that makes and runs the transaction's first frame itself, or settles one it made, opens the transaction's start first (`open_transaction_start`, with a `FrameStart` for it), then closes it with `last_frame_result` or `close_transaction_start`, and ends the lifecycle with `execution_result` or `finish_transaction`. + Without the open, its first child fails with `NoParent` and a direct settlement with `NotOpen`. + A test that settles a first frame by hand does the same. + + *The debug mirror.* A debug build keeps, in `LocalContext`, a mirror of the hooks' order that `Context`'s own hooks check: a root split is at depth 0, a child's parent is the identity on top and its depth one more, a settle pops its own identity and depth, and `Settled` finds the mirror empty. + It runs only where a local context returns it from `lifecycle_debug`, and it resets at every root split, so a simulation on a cloned context or an independent EVM nested in an inspector callback checks itself from its own root. + A consumer's own ledger follows the same rule: it is initialised at the root split, not at construction or at clone time, and dropped at either end. + A context type that wraps `Context` and implements `Host` itself forwards the three hooks to the inner context, or the mirror never runs; the record and its checks run either way. +- **Consumer.** mega-evm keeps an entry of per-start accounting for each start on a stack of its own, driven only by `frame_split` and `frame_settle`, and ends it at `frame_lifecycle_end`. + Without the lifecycle it pairs a start with its settlement itself, from the frames it sees, and an inspector that replaces an interpreter, rewrites an input's depth or drops an action breaks the pairing it infers. + The flags are what it needs of an inspector's answers, rewrites and rebuilds to settle them as they settle today. + The lifecycle carries no MegaETH figure; what a start's entry holds is the consumer's. +- **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. +- **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. + What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record is a `StartLifecycle` of 40 bytes in `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) per frame on the stack, on the heap and reused. + The marks sit in the padding of the values they ride on, so `GasTracker` stays 144 bytes, `Gas` 160, `InterpreterResult` 200, `CallOutcome` and `FrameResult` 296 and `CreateOutcome` 280 (aarch64, the fork's release profile), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. + In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary, and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. + Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. + `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's. + The outcomes' public `start_mark` field is the one item a consumer can trip on: an outcome literal names it as `start_mark: Default::default()`, and it extends the exception the outcome literals already carry (see The start charge). + In a debug build `LocalContext` gains a public field for the mirror, so a literal of it in a debug build names it. + ### The original account info by reference - **API.** `revm_state::Account::original_info_ref(&self) -> &AccountInfo`. From 8f44bb22e0205d0ffb590ef4630563fc424548d4 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 12:43:42 +0800 Subject: [PATCH 095/110] docs: the start lifecycle entry matches the delivered API: a split carries no start, the settlement types are sealed, every refusal is fatal in every build, the mirror is a LifecycleMirror, the child's settlement goes through Returning and close_frame_start, FrameStart::reservoir is documented, and each of the three API breaks says what a consumer does The entry was written against the prototype; the delivered code differs in these places, and a statement that names a removed item or describes the old behaviour misleads a consumer. --- MEGAETH-FORK.md | 65 ++++++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index d1cabdb800..11c7a70f0b 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -289,7 +289,7 @@ An id the fork once used for an entry with another default is left unused rather ### Frame-start hook - **API.** `Host::frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. - `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, and `charge`, which `new` leaves empty) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. + `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, `charge`, which `new` leaves empty, and `reservoir`, which `new` leaves `None`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`. @@ -299,8 +299,9 @@ An id the fork once used for an entry with another default is left unused rather It is `None` only for a creation the handler fails before it takes an address: an endowment above the caller's balance, a caller's nonce at its maximum, or a creating frame at the depth limit. Such a creation reaches the hook only with EIP-8037 off; with it on, the instruction ends the creation before the hook. The address is fixed when the hook sees it. Something that changes the caller's nonce between the instruction and the frame does not move it, as on upstream's EIP-8037 path. An inspector that changes the creation's caller, scheme or init code (`CreateInputs::set_call`, `set_scheme`, `set_init_code`) clears it, and the handler computes the new one. `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input takes its share of the reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from a share of the reservoir the hook left (see The reservoir share). A charge the hook makes that fails records as any failed charge does, whatever the answer. - `start` is the hook's to declare the start charge on (`charge`, see The start charge); the instruction reads nothing else back from it. - After the hook the instruction copies that charge onto the frame's input and takes the child's shares of the reservoir and of each pool off `gas` for it (`GasTracker::forward_to_child`, see The reservoir share and Resource pools); the shares are of the reservoir and the pools as the hook left them. + `start` is the hook's to declare the start charge on (`charge`, see The start charge) and, if it takes the child's reservoir itself, the child's reservoir (`reservoir`); the instruction reads nothing else back from it. + `FrameStart::reservoir` is `None` when the hook is called. `Some(r)` means the hook took the child's reservoir out of `gas` itself: the instruction takes no reservoir share, the frame's input carries `r`, and the caller keeps what the hook left it. `None` keeps the schedule's share (see The reservoir share). The instruction does not check `r` against what the hook took. The pools are forwarded by the schedule either way. + After the hook the instruction copies that charge onto the frame's input and takes the child's shares of the reservoir (unless the hook named it) and of each pool off `gas` for it (`GasTracker::forward_to_child_with_reservoir`, which `forward_to_child` calls with `None`, see The reservoir share and Resource pools); the shares are of the reservoir and the pools as the hook left them. `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. @@ -360,8 +361,8 @@ An id the fork once used for an entry with another default is left unused rather ### The reservoir share - **API.** `GasId::reservoir_kept_percent` (id 249) and `GasParams::reservoir_forward_share(reservoir)`. - On `GasTracker`: `forward_reservoir(share)`, and `forward_to_child(&GasParams)` and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). -- **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. + On `GasTracker`: `forward_reservoir(share)`, `forward_to_child(&GasParams)`, `forward_to_child_with_reservoir(&GasParams, Option<u64>)` (the first with `None`) and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). +- **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir (unless the frame-start hook named the child's reservoir, `FrameStart::reservoir`, in which case it takes none and the input carries the hook's) out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. `reservoir_forward_share` is the reservoir less the caller's part, `reservoir_kept_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 2 kept the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool keeping 2 forwards 97 (its share is rounded down). Zero kept forwards the whole reservoir, as EIP-8037 does; a hundred or more forwards none. The two roundings are the fork's, not the schedule's: the reservoir's share takes the caller's part away as regular gas's forward does, and a pool's share is rounded down. A chain that needs the floor for the reservoir, or the subtraction for a pool, has no entry for it. The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. @@ -475,13 +476,15 @@ An id the fork once used for an entry with another default is left unused rather ### Start lifecycle - **API.** - On `Host`, each with a no-op default: `frame_split(&mut self, split: &FrameSplit<'_>)`, `frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker)` and `frame_lifecycle_end(&mut self, end: LifecycleEnd)`. - `FrameSplit` (`id`, `parent`, `depth`, `start`), `FrameSettle` (`id`, `depth`, `status`, `created`, `inspector_answer`, `gas_replaced`, `outcome_rebuilt`, `held_reservoir`), `SettleStatus` (`Ok`, `Revert`, `Halt`) and `LifecycleEnd` (`Settled`, `Discarded`), in `revm_context_interface::host`. - `revm_handler::lifecycle`: `open_frame_start`, `open_transaction_start`, `close_transaction_start`, `finish_transaction`, `discard_transaction` and `settle_status`. - On `FrameStack`, the record: `open_start`, `close_start`, `lifecycle_active`, `lifecycle_settled` and `lifecycle_clear`. - `StartLifecycleError` (`Exhausted`, `Stale`, `NotOpen`, `NoParent`, `Unsettled`), `PendingStart`, `StartMark` and `OutcomeMark`. - `GasTracker::start_mark`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field). - `LocalContextTr::lifecycle_debug` and `LifecycleDebug`, the debug mirror (below). + On `Host`, each with a no-op default: `frame_split(&mut self, split: &FrameSplit)`, `frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker)` and `frame_lifecycle_end(&mut self, end: LifecycleEnd)`. + `FrameSplit` (`id`, `parent`, `depth`), `FrameSettle` (`id`, `depth`, `status`, `created`, `inspector_answer`, `gas_replaced`, `outcome_rebuilt`, `held_reservoir`), `SettleStatus` (`Ok`, `Revert`, `Halt`) and `LifecycleEnd` (`Settled`, `Discarded`), in `revm_context_interface::host`. + `FrameSplit` and `FrameSettle` are `#[non_exhaustive]` and have no public constructor: only the record builds them (`FrameStack::open_start`, `FrameStack::close_start`), so a hook is called by hand only with a value the record made, and a field added later breaks no consumer. + `SettleStatus` and `LifecycleEnd` are exhaustive. + `revm_handler::lifecycle`: `open_frame_start`, `open_transaction_start`, `Returning` and `close_frame_start`, `close_transaction_start`, `finish_transaction`, `discard_transaction`, `mark_for_end_callbacks` and `check_end_callbacks`. + On `FrameStack`, the record: `open_start`, `close_start`, `pending_start`, `running_start`, `lifecycle_active`, `lifecycle_settled`, and its two boundaries `settle_lifecycle` and `discard_lifecycle`. + `StartLifecycleError` (`Exhausted`, `Stale`, `NotOpen`, `NoParent`, `Unsettled`; `#[non_exhaustive]`), `PendingStart` (its fields are private: the identity can be read and not written, and only the three flags can be set), `StartMark` and `OutcomeMark`. + `GasTracker::start_mark` and `set_start_mark`, `GasTracker::forward_to_child_with_reservoir`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field). + `LocalContextTr::lifecycle_mirror`, `LifecycleMirror` and `LifecycleEvent` (`Split`, `Settle`, `End`), the debug mirror (below). The types and the method exist in every profile. - **Contract.** A *start* is one frame's beginning with the identity revm gave it; revm pairs every start it opens with exactly one settlement, last in first out, and the consumer does not pair them. *Where revm opens one.* - Where it consumes a `NewFrame` action: `Evm::frame_run` and `InspectorEvmTr::inspect_frame_run`, right after `process_next_action` returns the frame's init, so the child's start opens against the frame on top of the stack, its caller. @@ -496,7 +499,7 @@ An id the fork once used for an entry with another default is left unused rather - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the start of the caller on top of the stack and calls `frame_settle` with the caller's tracker. - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and a halt then consumes the regular gas the hook credited, as it does for the state refund. - `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and `start`, a `FrameStart` read from the init revm consumed (`kind`, `caller`, `target`, `value`, `forward`; no `charge`). + `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input, which the consumer's `frame_init` is handed straight after the split, and what the consumer owes a start (its shares, its charge, its allowance) it parked at `frame_starting`. `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. `frame_lifecycle_end` is called once at the end of a transaction's lifecycle: `Settled` at the successful boundary, with every start settled, and `Discarded` when a fatal error ends the transaction and the open starts are dropped unsettled. A transaction that ends before any start opened emits neither. @@ -510,31 +513,34 @@ An id the fork once used for an entry with another default is left unused rather | It overrides or reimplements | It calls | |---|---| | `Handler::execution` or `InspectorHandler::inspect_execution` | `open_frame_start` where it makes the first frame's init | - | `Handler::runtime_oog_result`, building its own stand-in | `open_transaction_start`, with a `FrameStart` for the transaction, before it returns | + | `Handler::runtime_oog_result`, building its own stand-in | `open_transaction_start` before it returns | | `EvmTr::frame_run` or `InspectorEvmTr::inspect_frame_run` | `open_frame_start` after `process_next_action` returns an init | - | `EvmTr::frame_return_result` | `settle_status` before `return_result`, then `FrameStack::close_start` and `Host::frame_settle` with the caller's tracker after it | + | `EvmTr::frame_return_result` | `lifecycle::Returning::new(&result, caller)` before `return_result` consumes the result, then `lifecycle::close_frame_start` after it | | `Handler::last_frame_result` | `close_transaction_start` right after `settle_first_frame`, given the reservoir the caller's gas held before the settlement | | `Handler::execution_result` | `finish_transaction`, after the context's recorded error is taken and before the output is built | - | `Handler::catch_error` | `discard_transaction`, in the cleanup every error reaches, before the frame stack is cleared | + | `Handler::catch_error` | `discard_transaction`, first | - `finish_transaction` is the successful boundary: with every start settled it emits `LifecycleEnd::Settled` and resets the record. - `discard_transaction` is the fatal boundary: it emits `Discarded` only if a lifecycle is under way, resets the record, and is idempotent, so a cleanup that runs twice emits once. + `finish_transaction` is the successful boundary (`FrameStack::settle_lifecycle`): with every start settled it emits `LifecycleEnd::Settled` and resets the record. + `discard_transaction` is the fatal boundary (`FrameStack::discard_lifecycle`): it emits `Discarded` only if a lifecycle is under way, resets the record, and is idempotent, so a cleanup that runs twice emits once. It resets the lifecycle only; the frame stack is cleared separately (see Reuse after an uncaught error). + `close_frame_start` and `close_transaction_start` hand the settlement to `frame_settle` with the caller's tracker and the transaction's, and `close_transaction_start` applies the halt rule after the hook. A call sits where the mainnet method makes it and passes what that method passes. - *Fatal errors.* The record refuses these, in a release build as in a debug build, as a `ContextError::Custom` that fails the transaction and that `catch_error` reports: + *Fatal errors.* The record refuses these in every build, debug and release alike, as a `ContextError::Custom` carrying the error's `Display`, which fails the transaction and which `catch_error` reports: - `Stale`: a start opened where one is still open, so a boundary or a settlement was missed; - `NoParent`: a child start under a frame with no start of its own, so a runner drove the transaction's frame without opening its start; - `NotOpen`: a settlement found no start open; - `Exhausted`: the transaction opened 4,294,967,295 starts; the start does not open; - - `Unsettled`: `finish_transaction` found a start open. A debug build asserts; a release build clears the record, emits `Discarded` and fails the transaction. + - `Unsettled`: `finish_transaction` found a start open. It discards the lifecycle, emits `Discarded` and fails the transaction, so the `catch_error` that reports the error owes no second end. - *The marks and the flags.* Before it calls an inspector's end callbacks (`call_end`, `create_end`, `frame_end`) revm writes the start's identity on the result's tracker (`StartMark`, a `u32`) and a mark of the start on the outcome (`OutcomeMark`, a `u16`, `(id − 1) mod 65535 + 1`, never zero); after them it reads both. + The only `debug_assert!`s are on the helpers' own preconditions: the transaction's start opens and closes on an empty frame stack. + + *The marks and the flags.* Before it calls an inspector's end callbacks (`call_end`, `create_end`, `frame_end`) revm writes the start's identity on the result's tracker (`StartMark`, a `u32`, with `GasTracker::set_start_mark`) and a mark of the start on the outcome (`OutcomeMark`, a `u16`, `(id − 1) mod 65535 + 1`, never zero) (`mark_for_end_callbacks`); after them it reads both (`check_end_callbacks`). A consumer has no reason to set a mark. `gas_replaced` is set on the start when the tracker's mark is no longer the start's, `outcome_rebuilt` when the outcome's is not, and `inspector_answer` when `frame_start`, `call` or `create` answered the start. A constructor (`Gas::new`, `CallOutcome::new`, `CreateOutcome::new`) and a literal that names the mark as `Default::default()` leave it zero, so a value built afresh is always seen; a copy of another start's value is seen unless the two identities are 65,535 apart, and a copy made in the previous transaction at the same sequence position is not. A tracker an inspector saved before the marking carries none, so restoring it at an end callback sets `gas_replaced` even when it came from the same start. The flags say what an inspector did, never what the consumer did: the consumer's own answers are made in `frame_init`, before any end callback, and are never flagged. Only the inspected path marks and flags; the plain path leaves all three clear. - Both marks take no part in equality, hashing, `Debug` or serde: they compare equal always, hash to nothing, are skipped by serde and decode as none, and `GasTracker`, `CallOutcome` and `CreateOutcome` have a hand-written `Debug` that lists the other fields in declaration order, so its output is the derived output without the mark. + Both marks take no part in equality, hashing, `Debug` or serde: they compare equal always, hash to nothing, are skipped by serde and decode as none, and `GasTracker`, `CallOutcome` and `CreateOutcome` have a hand-written `Debug` that lists the other fields in declaration order, so its output is the derived output without the mark, and `GasTracker`'s encoding has no mark. A change to a field of those three types changes that `Debug` too. An inspector can forge a mark or call a hook by hand through the `&mut` context: a forged mark changes only the flags, and a hand call desynchronises the consumer's own stack from the record without touching the record or its checks; both are outside the contract. @@ -543,12 +549,13 @@ An id the fork once used for an entry with another default is left unused rather A frame stack left as the error left it makes the next transaction's opening a child under a frame whose start was discarded, and it fails with `NoParent`; a record left open fails the next opening with `Stale`. Calling `catch_error` does all of it. - *A hand-driven first frame.* A runner that makes and runs the transaction's first frame itself, or settles one it made, opens the transaction's start first (`open_transaction_start`, with a `FrameStart` for it), then closes it with `last_frame_result` or `close_transaction_start`, and ends the lifecycle with `execution_result` or `finish_transaction`. + *A hand-driven first frame.* A runner that makes and runs the transaction's first frame itself, or settles one it made, opens the transaction's start first (`open_frame_start` with the frame's init, or `open_transaction_start` for a frame it never initialises), then closes it with `last_frame_result` or `close_transaction_start`, and ends the lifecycle with `execution_result` or `finish_transaction`. Without the open, its first child fails with `NoParent` and a direct settlement with `NotOpen`. A test that settles a first frame by hand does the same. - *The debug mirror.* A debug build keeps, in `LocalContext`, a mirror of the hooks' order that `Context`'s own hooks check: a root split is at depth 0, a child's parent is the identity on top and its depth one more, a settle pops its own identity and depth, and `Settled` finds the mirror empty. - It runs only where a local context returns it from `lifecycle_debug`, and it resets at every root split, so a simulation on a cloned context or an independent EVM nested in an inspector callback checks itself from its own root. + *The debug mirror.* A debug build keeps, in `LocalContext`, a `LifecycleMirror` of the hooks' order that `Context`'s own hooks feed and that panics when an event does not fit: a root split is at depth 0, a child's parent is the identity on top and its depth one more, a settle pops its own identity and depth, and `Settled` finds the mirror empty. It holds the events as `LifecycleEvent`s (`events()`) and the open starts (`open()`). + The type and `LocalContextTr::lifecycle_mirror` exist in every profile, and a consumer's own ledger can be a `LifecycleMirror`; only `LocalContext`'s field and `Context`'s three hook overrides are debug-only, and a release build holds no mirror and calls none. + It runs only where a local context returns it from `lifecycle_mirror` (the default returns `None`), and it resets at every root split, so a simulation on a cloned context or an independent EVM nested in an inspector callback checks itself from its own root. A consumer's own ledger follows the same rule: it is initialised at the root split, not at construction or at clone time, and dropped at either end. A context type that wraps `Context` and implements `Host` itself forwards the three hooks to the inner context, or the mirror never runs; the record and its checks run either way. - **Consumer.** mega-evm keeps an entry of per-start accounting for each start on a stack of its own, driven only by `frame_split` and `frame_settle`, and ends it at `frame_lifecycle_end`. @@ -557,13 +564,15 @@ An id the fork once used for an entry with another default is left unused rather The lifecycle carries no MegaETH figure; what a start's entry holds is the consumer's. - **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. - **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. - What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record is a `StartLifecycle` of 40 bytes in `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) per frame on the stack, on the heap and reused. + What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) per frame on the stack, on the heap and reused. The marks sit in the padding of the values they ride on, so `GasTracker` stays 144 bytes, `Gas` 160, `InterpreterResult` 200, `CallOutcome` and `FrameResult` 296 and `CreateOutcome` 280 (aarch64, the fork's release profile), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary, and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's. - The outcomes' public `start_mark` field is the one item a consumer can trip on: an outcome literal names it as `start_mark: Default::default()`, and it extends the exception the outcome literals already carry (see The start charge). - In a debug build `LocalContext` gains a public field for the mirror, so a literal of it in a debug build names it. + The stage adds three breaks, which the pull request body lists as `api:exception` items with the consumers checked, and what a consumer does for each: + - The outcomes' public `start_mark` field (`CallOutcome` and `CreateOutcome`): a consumer that builds an outcome by literal names it as `start_mark: Default::default()`, or builds it with the constructors. It extends the exception the outcome literals already carry (see The start charge). + - `LocalContext` gains a private field in a debug build, so a debug build cannot build it with a struct literal; a consumer builds it with `LocalContext::default()` or `new`. A release build's is unchanged. + - A behaviour change no compiler finds: a runner that drives the transaction's frame, or settles it, without `Handler::execution` and `Handler::last_frame_result` must open and close the transaction's start (see A hand-driven first frame); otherwise the record refuses it with `NoParent` or `NotOpen`. ### The original account info by reference From a3f7dedf55794e15435fe7c519e3922ef83477ef Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 14:35:37 +0800 Subject: [PATCH 096/110] docs: the start lifecycle entry says where each frame_run opens, that a halt consumes only the hook's net regular-gas credit, that marks collide a multiple of 65,535 apart, and how the child slots are sized and grown --- MEGAETH-FORK.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 11c7a70f0b..35eb83db07 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -487,7 +487,9 @@ An id the fork once used for an entry with another default is left unused rather `LocalContextTr::lifecycle_mirror`, `LifecycleMirror` and `LifecycleEvent` (`Split`, `Settle`, `End`), the debug mirror (below). The types and the method exist in every profile. - **Contract.** A *start* is one frame's beginning with the identity revm gave it; revm pairs every start it opens with exactly one settlement, last in first out, and the consumer does not pair them. *Where revm opens one.* - - Where it consumes a `NewFrame` action: `Evm::frame_run` and `InspectorEvmTr::inspect_frame_run`, right after `process_next_action` returns the frame's init, so the child's start opens against the frame on top of the stack, its caller. + - Where it consumes a `NewFrame` action, so the child's start opens against the frame on top of the stack, its caller, at that frame's depth plus one, which is the init's depth: + the plain `Evm::frame_run` opens it as the frame consumes the action, before `process_next_action` builds the init, and `InspectorEvmTr::inspect_frame_run` right after `process_next_action` returns the init. + Nothing a consumer can observe happens between the two positions. - Where it makes the transaction's first frame: `Handler::execution` and `InspectorHandler::inspect_execution`. - In the default `Handler::runtime_oog_result`, for the stand-in result of a transaction whose EIP-2780 runtime phase ran out of gas. @@ -497,7 +499,7 @@ An id the fork once used for an entry with another default is left unused rather *Where revm settles one.* - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the start of the caller on top of the stack and calls `frame_settle` with the caller's tracker. - - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and a halt then consumes the regular gas the hook credited, as it does for the state refund. + - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and after a halt revm consumes the hook's net credit of regular gas and keeps the gas its own settlement left. `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input, which the consumer's `frame_init` is handed straight after the split, and what the consumer owes a start (its shares, its charge, its allowance) it parked at `frame_starting`. `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. @@ -522,7 +524,7 @@ An id the fork once used for an entry with another default is left unused rather `finish_transaction` is the successful boundary (`FrameStack::settle_lifecycle`): with every start settled it emits `LifecycleEnd::Settled` and resets the record. `discard_transaction` is the fatal boundary (`FrameStack::discard_lifecycle`): it emits `Discarded` only if a lifecycle is under way, resets the record, and is idempotent, so a cleanup that runs twice emits once. It resets the lifecycle only; the frame stack is cleared separately (see Reuse after an uncaught error). - `close_frame_start` and `close_transaction_start` hand the settlement to `frame_settle` with the caller's tracker and the transaction's, and `close_transaction_start` applies the halt rule after the hook. + `close_frame_start` and `close_transaction_start` hand the settlement to `frame_settle` with the caller's tracker and the transaction's, and `close_transaction_start` applies the halt rule after the hook: it consumes only the hook's net regular-gas credit, and a hook that credits nothing or debits leaves the gas as it is. A call sits where the mainnet method makes it and passes what that method passes. *Fatal errors.* The record refuses these in every build, debug and release alike, as a `ContextError::Custom` carrying the error's `Display`, which fails the transaction and which `catch_error` reports: @@ -536,7 +538,7 @@ An id the fork once used for an entry with another default is left unused rather *The marks and the flags.* Before it calls an inspector's end callbacks (`call_end`, `create_end`, `frame_end`) revm writes the start's identity on the result's tracker (`StartMark`, a `u32`, with `GasTracker::set_start_mark`) and a mark of the start on the outcome (`OutcomeMark`, a `u16`, `(id − 1) mod 65535 + 1`, never zero) (`mark_for_end_callbacks`); after them it reads both (`check_end_callbacks`). A consumer has no reason to set a mark. `gas_replaced` is set on the start when the tracker's mark is no longer the start's, `outcome_rebuilt` when the outcome's is not, and `inspector_answer` when `frame_start`, `call` or `create` answered the start. - A constructor (`Gas::new`, `CallOutcome::new`, `CreateOutcome::new`) and a literal that names the mark as `Default::default()` leave it zero, so a value built afresh is always seen; a copy of another start's value is seen unless the two identities are 65,535 apart, and a copy made in the previous transaction at the same sequence position is not. + A constructor (`Gas::new`, `CallOutcome::new`, `CreateOutcome::new`) and a literal that names the mark as `Default::default()` leave it zero, so a value built afresh is always seen; a copy of another start's value is seen unless the two identities are a multiple of 65,535 apart, and a copy made in the previous transaction at the same sequence position is not. A tracker an inspector saved before the marking carries none, so restoring it at an end callback sets `gas_replaced` even when it came from the same start. The flags say what an inspector did, never what the consumer did: the consumer's own answers are made in `frame_init`, before any end callback, and are never flagged. Only the inspected path marks and flags; the plain path leaves all three clear. @@ -564,7 +566,7 @@ An id the fork once used for an entry with another default is left unused rather The lifecycle carries no MegaETH figure; what a start's entry holds is the consumer's. - **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. - **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. - What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) per frame on the stack, on the heap and reused. + What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk, so a transaction's boundary does no `Vec` work. The marks sit in the padding of the values they ride on, so `GasTracker` stays 144 bytes, `Gas` 160, `InterpreterResult` 200, `CallOutcome` and `FrameResult` 296 and `CreateOutcome` 280 (aarch64, the fork's release profile), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary, and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. From 426217bb2e76c0a41d46907eb788250e8efa107c Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Mon, 26 Oct 2026 14:54:01 +0800 Subject: [PATCH 097/110] docs: the start lifecycle entry says a split does not guarantee a consumer init, that the child's return closes the child's start, names the plain and inspected init entry points, states the consumer side as a contract, says boundaries never resize the slots, and states the API exceptions as rules; the generic-hooks row drops its stale size --- MEGAETH-FORK.md | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 35eb83db07..f84162ef0f 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -103,7 +103,7 @@ The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fo |---|---|---|---| | Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `EthFrame::return_result`, `create_init_frame`, `last_frame_result`), so that accounting is re-applied to the new base's versions of it. | | Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | -| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | about 1,750 lines | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | +| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | not counted | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | | Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. | | MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge, the history allowance | about 2,150 lines, of which the pools, the kept share, the start charge and the allowance are about 1,450 | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. The items that ride on the frame results (the pools, the start charge, the allowance) are the first candidates, since every consumer pays their size. | @@ -493,15 +493,17 @@ An id the fork once used for an entry with another default is left unused rather - Where it makes the transaction's first frame: `Handler::execution` and `InspectorHandler::inspect_execution`. - In the default `Handler::runtime_oog_result`, for the stand-in result of a transaction whose EIP-2780 runtime phase ran out of gas. - It opens before `Handler::frame_init` and so before an inspector's `frame_start`, `call` and `create`: an answer made in any of them, an inspector's or a consumer's own, settles on a start that is already open. + It opens before `EvmTr::frame_init` on the plain path and before `InspectorEvmTr::inspect_frame_init` on the inspected one, and so before an inspector's `frame_start`, `call` and `create`: an answer made in any of them, an inspector's or a consumer's own, settles on a start that is already open. An action an inspector drops or replaces in `step_end` is replaced before revm consumes it, so a start it dropped was never opened, and a clone of the input opens its own. A frame init revm answers without running a frame (a precompile, a start it refuses) opens a start and settles it like any other. *Where revm settles one.* - - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the start of the caller on top of the stack and calls `frame_settle` with the caller's tracker. + - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the returning child's start, held in the slot of the caller on top of the stack (the caller's own start stays open), and calls `frame_settle` with the caller's tracker. - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and after a halt revm consumes the hook's net credit of regular gas and keeps the gas its own settlement left. - `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input, which the consumer's `frame_init` is handed straight after the split, and what the consumer owes a start (its shares, its charge, its allowance) it parked at `frame_starting`. + `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input. + Whether the consumer's `frame_init` is handed that input after the split is conditional: when initialisation reaches it, it receives the input as an inspector's `frame_start`, `call` or `create` left it; an inspector that answers the start does so before `frame_init` is called, and the stand-in for a runtime out-of-gas transaction has no init at all, so a start can split and settle with no `frame_init` between. + What an instruction's start owes (its shares, its charge, its allowance) is parked at `frame_starting`; the transaction's start does not pass through `frame_starting`. `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. `frame_lifecycle_end` is called once at the end of a transaction's lifecycle: `Settled` at the successful boundary, with every start settled, and `Discarded` when a fatal error ends the transaction and the open starts are dropped unsettled. A transaction that ends before any start opened emits neither. @@ -560,18 +562,20 @@ An id the fork once used for an entry with another default is left unused rather It runs only where a local context returns it from `lifecycle_mirror` (the default returns `None`), and it resets at every root split, so a simulation on a cloned context or an independent EVM nested in an inspector callback checks itself from its own root. A consumer's own ledger follows the same rule: it is initialised at the root split, not at construction or at clone time, and dropped at either end. A context type that wraps `Context` and implements `Host` itself forwards the three hooks to the inner context, or the mirror never runs; the record and its checks run either way. -- **Consumer.** mega-evm keeps an entry of per-start accounting for each start on a stack of its own, driven only by `frame_split` and `frame_settle`, and ends it at `frame_lifecycle_end`. - Without the lifecycle it pairs a start with its settlement itself, from the frames it sees, and an inspector that replaces an interpreter, rewrites an input's depth or drops an action breaks the pairing it infers. - The flags are what it needs of an inspector's answers, rewrites and rebuilds to settle them as they settle today. +- **Consumer.** A consumer that keeps per-start accounting keeps an entry for each start on a stack of its own, drives it only by `frame_split` and `frame_settle`, and ends it at `frame_lifecycle_end`; it does not pair a start with its settlement itself. + A consumer that pairs them from the frames it sees breaks when an inspector replaces an interpreter, rewrites an input's depth or drops an action. + The flags are what such a consumer needs of an inspector's answers, rewrites and rebuilds to settle them as it would without the inspector. The lifecycle carries no MegaETH figure; what a start's entry holds is the consumer's. - **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. - **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. - What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk, so a transaction's boundary does no `Vec` work. + What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk: a boundary neither resizes nor frees the slots, a successful end does not scan them, and discarding open children clears the retained slots, at a cost proportional to their retained length. The marks sit in the padding of the values they ride on, so `GasTracker` stays 144 bytes, `Gas` 160, `InterpreterResult` 200, `CallOutcome` and `FrameResult` 296 and `CreateOutcome` 280 (aarch64, the fork's release profile), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. - In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary, and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. + In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary (and, after a discard with open children, one clear of the retained slots), and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's. - The stage adds three breaks, which the pull request body lists as `api:exception` items with the consumers checked, and what a consumer does for each: + Three exceptions to that compatibility are carried, each an `api:exception` item. + A pull request that introduces such an exception lists it and checks the consumers against it. + What a consumer does for each: - The outcomes' public `start_mark` field (`CallOutcome` and `CreateOutcome`): a consumer that builds an outcome by literal names it as `start_mark: Default::default()`, or builds it with the constructors. It extends the exception the outcome literals already carry (see The start charge). - `LocalContext` gains a private field in a debug build, so a debug build cannot build it with a struct literal; a consumer builds it with `LocalContext::default()` or `new`. A release build's is unchanged. - A behaviour change no compiler finds: a runner that drives the transaction's frame, or settles it, without `Handler::execution` and `Handler::last_frame_result` must open and close the transaction's start (see A hand-driven first frame); otherwise the record refuses it with `NoParent` or `NotOpen`. From bd12d7b062cb1ad8647ae94e6ad34af2f758e477 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 17:29:49 +0800 Subject: [PATCH 098/110] chore: check the fork with Rust 1.97.0 1.97.0 carries the fix for a closure-call miscompilation. Its clippy adds manual_filter, which one upstream line in bundle_account.rs trips; the line takes the lint's own rewrite. --- crates/database/src/states/bundle_account.rs | 2 +- rust-toolchain.toml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/database/src/states/bundle_account.rs b/crates/database/src/states/bundle_account.rs index 4254770dbd..0c9c537da5 100644 --- a/crates/database/src/states/bundle_account.rs +++ b/crates/database/src/states/bundle_account.rs @@ -372,6 +372,6 @@ impl BundleAccount { } }; - account_revert.and_then(|acc| if acc.is_empty() { None } else { Some(acc) }) + account_revert.filter(|acc| !acc.is_empty()) } } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index d0898ae4fc..b01310b9ba 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -3,11 +3,11 @@ # Upstream floats on `stable` and fixes each release's new clippy lints in its # own code; this fork carries upstream code it does not edit, so it pins the # toolchain and moves the pin deliberately: with each base-line move, or in a -# `mega:` commit of its own when a newer compiler is wanted. The channel is the -# stable release upstream's own CI ran on when the base tag was cut, so the -# upstream code in the tree is lint-clean by construction. The MSRV consumers -# see is still `rust-version` in Cargo.toml. +# commit of its own when a newer compiler is wanted. The channel is the stable +# release upstream's own CI ran on when the base tag was cut, or a later stable +# release taken for a compiler fix. The MSRV consumers see is still +# `rust-version` in Cargo.toml. [toolchain] -channel = "1.95.0" +channel = "1.97.0" components = ["clippy", "rustfmt"] targets = ["riscv32imac-unknown-none-elf", "riscv64imac-unknown-none-elf"] From 2b1c7ab0d4209919c40415687916fd413169a31a Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 18:10:17 +0800 Subject: [PATCH 099/110] feat!: the pools, the start charge and the history allowance leave the gas tracker and the frame values A consumer keeps a frame start's budgets, the charge its failure gives back and its history allowance on a ledger of its own, driven by the start lifecycle's hooks, so revm no longer carries them: - GasTracker loses its three pools, their nets and crossings and the history allowance (144 to 88 bytes), and Gas the methods forwarding them; PoolId, PoolAmounts and StartCharge go; - CallInputs loses charged_start, pool_shares and history_allowance, CreateInputs its charged_start and pool shares, CallOutcome and CreateOutcome their charged_start; FrameStart loses charge; - return_result and settle_first_frame no longer refund a start charge, a precompile's answer adopts no pool shares, and the schedule loses the pool kept-percent entries (ids 246 to 248) and call_history_allowance (id 253), which stay unused; - ContextTr::admit_code_deposit is no longer lent the creating frame's tracker, which existed for drawing a pool: the signature is the hook's original one. The tests of the removed behaviour go with it. --- crates/context/interface/src/cfg/gas.rs | 81 +- .../context/interface/src/cfg/gas/encoding.rs | 68 +- .../context/interface/src/cfg/gas/forward.rs | 99 +- .../src/cfg/gas/history_allowance.rs | 99 -- crates/context/interface/src/cfg/gas/pools.rs | 924 ----------- .../interface/src/cfg/gas/start_charge.rs | 94 -- .../context/interface/src/cfg/gas/withheld.rs | 15 +- .../context/interface/src/cfg/gas_params.rs | 222 +-- crates/context/interface/src/context.rs | 30 +- .../interface/src/context/code_deposit.rs | 6 +- crates/context/interface/src/host.rs | 13 +- .../interface/src/host/instruction_hooks.rs | 19 +- crates/context/tests/schedule_shares.rs | 20 +- crates/handler/src/execution.rs | 22 +- crates/handler/src/execution/first_frame.rs | 33 +- crates/handler/src/frame.rs | 242 +-- crates/handler/src/frame/code_deposit.rs | 29 +- crates/handler/src/frame_data.rs | 29 +- crates/handler/src/handler.rs | 11 +- .../handler/tests/code_deposit_admission.rs | 122 +- crates/handler/tests/reservoir_share.rs | 77 +- crates/handler/tests/resource_pools.rs | 1392 ----------------- .../inspector/tests/code_deposit_admission.rs | 8 +- crates/inspector/tests/loop_hooks.rs | 7 +- crates/inspector/tests/reservoir_share.rs | 23 +- crates/inspector/tests/resource_pools.rs | 804 ---------- crates/interpreter/src/gas.rs | 1 - crates/interpreter/src/gas/pools.rs | 108 -- .../interpreter/src/instructions/contract.rs | 21 +- .../src/instructions/contract/call_helpers.rs | 23 +- .../src/instructions/instruction_hooks.rs | 22 +- .../src/interpreter_action/call_inputs.rs | 36 +- .../src/interpreter_action/call_outcome.rs | 12 +- .../src/interpreter_action/create_inputs.rs | 68 +- .../src/interpreter_action/create_outcome.rs | 12 +- crates/interpreter/src/lib.rs | 4 +- crates/interpreter/tests/instruction_hooks.rs | 23 +- crates/interpreter/tests/resource_pools.rs | 588 ------- .../interpreter/tests/resource_pools_serde.rs | 146 -- crates/interpreter/tests/start_marks.rs | 21 +- 40 files changed, 244 insertions(+), 5330 deletions(-) delete mode 100644 crates/context/interface/src/cfg/gas/history_allowance.rs delete mode 100644 crates/context/interface/src/cfg/gas/pools.rs delete mode 100644 crates/context/interface/src/cfg/gas/start_charge.rs delete mode 100644 crates/handler/tests/resource_pools.rs delete mode 100644 crates/inspector/tests/resource_pools.rs delete mode 100644 crates/interpreter/src/gas/pools.rs delete mode 100644 crates/interpreter/tests/resource_pools.rs delete mode 100644 crates/interpreter/tests/resource_pools_serde.rs diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 55871a05b5..20de2f26d6 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -7,16 +7,11 @@ use primitives::hardfork::SpecId; mod encoding; mod failed_charge; mod forward; -mod history_allowance; mod mark; -mod pools; -mod start_charge; mod withheld; pub use forward::ChildShares; pub use mark::{OutcomeMark, StartMark}; -pub use pools::{PoolAmounts, PoolId}; -pub use start_charge::StartCharge; pub use withheld::WithheldCrossing; /// Tracker for gas during execution. @@ -58,16 +53,11 @@ pub use withheld::WithheldCrossing; /// spendable part, so a consumer that caps a creating frame must not release before /// `return_create`, or those charges escape the cap. /// -/// Beside the gas, the tracker carries figures of the fork that are inert until a consumer uses -/// them: [`PoolId::COUNT`] resource pools ([`pool_remaining`](Self::pool_remaining), unlimited by -/// default, each forwarded to a child frame by its own share and settled with its gas) and the -/// history allowance ([`history_allowance`](Self::history_allowance), zero by default). -/// -/// A child frame starts with a share of its caller's reservoir and pools, which the caller's -/// tracker gives up while the child runs ([`forward_to_child`](Self::forward_to_child)); the -/// child's return adds what it left to what the caller kept +/// A child frame starts with a share of its caller's reservoir, which the caller's tracker gives +/// up while the child runs ([`forward_to_child`](Self::forward_to_child)); the child's return +/// adds what it left to what the caller kept /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)). Every schedule defined here -/// forwards the whole reservoir and every whole pool. +/// forwards the whole reservoir. /// /// The net counters (`state_gas_spent`, `history_gas_spent`) are `i64`, while charges and refills /// take `u64` amounts and convert them with saturation. The tracker assumes that the transaction @@ -78,13 +68,8 @@ pub use withheld::WithheldCrossing; /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). /// -/// Each pool's net ([`pool_spent`](Self::pool_spent)) is an `i64` too, and assumes the same bound -/// on its amounts: every draw and refill within `i64::MAX`, and the net with its children's merged -/// in within `±i64::MAX`. A debug build asserts it where a net moves. -/// -/// Encoded, the tracker has a field per figure, in the order below; the failed-charge record and -/// the pools' crossings, which share a word in memory, are encoded as an optional number and a -/// `bool` per pool in their own places. +/// Encoded, the tracker has a field per figure, in the order below; the failed-charge record, +/// a number and a flag in memory, is encoded as an optional number in its place. /// /// A field the fork added decodes with its default from an encoding made before it existed only /// in a format that carries field names, such as JSON, as each field says. A format that encodes @@ -96,7 +81,7 @@ pub use withheld::WithheldCrossing; /// The tracker also carries the [`StartMark`] revm writes on a frame result's tracker before an /// inspector's end callbacks. The mark is no part of the tracker's value: equality, hashing, the /// debug output and the encoding leave it out, and a decoded tracker carries none. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] #[cfg_attr( feature = "serde", derive(serde::Serialize, serde::Deserialize), @@ -186,36 +171,11 @@ pub struct GasTracker { failed_charge_remaining: u64, /// Whether `failed_charge_remaining` holds a record. A flag apart from the record rather than /// an `Option`, whose tag would take a word of its own, so it shares a word with - /// `pool_crossings`. + /// `start_mark`. failed_charge_recorded: bool, - /// The pools ([`pool_remaining`](Self::pool_remaining)): what this frame may still draw from - /// each. Unlimited unless a consumer sets a pool; nothing in this workspace draws one. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as every pool unlimited. - pools_remaining: [u64; PoolId::COUNT], - /// The frame's net draw of each pool ([`pool_spent`](Self::pool_spent)), signed as - /// `history_gas_spent` is, so a rollback can give it back and a merge can hand it on. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as zero for every pool. - pools_spent: [i64; PoolId::COUNT], - /// Whether a draw failed that a pool could not pay ([`pool_crossing`](Self::pool_crossing)), - /// a bit per pool, in the word `failed_charge_recorded` takes. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as no crossing on any pool. - pool_crossings: u8, - /// History gas this frame may spend before it charges its budget - /// ([`history_allowance`](Self::history_allowance)). Zero unless the schedule gives a value - /// call's child one. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as zero. - history_allowance: u64, /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)). It fits padding - /// the tracker already had, so the tracker's size is unchanged. No part of the tracker's value, - /// and not encoded. + /// the tracker already had, in the word `failed_charge_recorded` takes, so the tracker's size + /// is unchanged. No part of the tracker's value, and not encoded. start_mark: StartMark, } @@ -234,22 +194,10 @@ impl core::fmt::Debug for GasTracker { .field("withheld_crossing", &self.withheld_crossing) .field("failed_charge_remaining", &self.failed_charge_remaining) .field("failed_charge_recorded", &self.failed_charge_recorded) - .field("pools_remaining", &self.pools_remaining) - .field("pools_spent", &self.pools_spent) - .field("pool_crossings", &self.pool_crossings) - .field("history_allowance", &self.history_allowance) .finish() } } -impl Default for GasTracker { - /// A tracker with no gas, as [`new`](Self::new) builds it, so the pools start unlimited. - #[inline] - fn default() -> Self { - Self::new(0, 0, 0) - } -} - impl GasTracker { /// Creates a new `GasTracker` with the given remaining gas and reservoir. #[inline] @@ -266,10 +214,6 @@ impl GasTracker { withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, - pools_remaining: [u64::MAX; PoolId::COUNT], - pools_spent: [0; PoolId::COUNT], - pool_crossings: 0, - history_allowance: 0, start_mark: StartMark::NONE, } } @@ -580,10 +524,6 @@ impl GasTracker { /// pays for bytes the failing frame no longer appends. The term is zero on any chain that /// never calls [`record_history_cost`](Self::record_history_cost). /// - /// The pools unwind here too: each pool's net draw ([`pool_spent`](Self::pool_spent)) goes - /// back to it, which then reads as the pool the frame started with, for the same reason, and - /// the term is zero on any chain that never calls [`record_pool`](Self::record_pool). - /// /// On revert the resulting `remaining` (including the refilled spill) is /// returned to the parent; on halt the caller additionally zeroes `remaining` /// so the spilled gas is consumed while the reservoir is left untouched. @@ -601,7 +541,6 @@ impl GasTracker { self.state_gas_spent = 0; self.state_gas_spilled = 0; self.history_gas_spent = 0; - self.rollback_pools(); } /// Refills the reservoir with state gas that is returned by 0→x→0 storage diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index 3c9ffe5015..9fc1f0d025 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -1,16 +1,14 @@ //! The encoding of a [`GasTracker`]. //! //! In memory the failed-charge record is a number and a flag, and the flag shares a word with the -//! pools' crossings, a bit each. Encoded, the tracker keeps the fields, names and order the derived -//! encoding had: the failed-charge record is an optional number in its place, and the crossings a -//! `bool` per pool in their own. +//! tracker's start mark, which is not encoded. Encoded, the tracker keeps the fields, names and +//! order the derived encoding had: the failed-charge record is an optional number in its place. //! //! A format that carries field names, such as JSON, decodes an encoding made before a field -//! existed with the field's default. A format that encodes by position, such as bincode, does not: -//! the fields that predate the pools keep their places, but an encoding made before the pools' -//! fields were added lacks them and cannot be read (see [`GasTracker`]). +//! existed with the field's default. A format that encodes by position, such as bincode, does not +//! (see [`GasTracker`]). -use super::{GasTracker, PoolId, WithheldCrossing}; +use super::{GasTracker, WithheldCrossing}; /// A [`GasTracker`] as it is encoded: its fields in their order, with the defaults an encoding /// made before a field existed decodes to in a format that carries field names. Each field of the @@ -32,20 +30,6 @@ pub(super) struct Encoded { withheld_crossing: Option<WithheldCrossing>, #[serde(default)] failed_charge_remaining: Option<u64>, - #[serde(default = "unlimited_pools")] - pools_remaining: [u64; PoolId::COUNT], - #[serde(default)] - pools_spent: [i64; PoolId::COUNT], - #[serde(default)] - pool_crossings: [bool; PoolId::COUNT], - #[serde(default)] - history_allowance: u64, -} - -/// The pools a tracker starts with, and the pools an encoding that predates them decodes to in a -/// format that carries field names. -const fn unlimited_pools() -> [u64; PoolId::COUNT] { - [u64::MAX; PoolId::COUNT] } impl From<GasTracker> for Encoded { @@ -61,10 +45,6 @@ impl From<GasTracker> for Encoded { withheld: tracker.withheld, withheld_crossing: tracker.withheld_crossing, failed_charge_remaining: tracker.failed_charge_remaining(), - pools_remaining: tracker.pools_remaining, - pools_spent: tracker.pools_spent, - pool_crossings: PoolId::ALL.map(|pool| tracker.pool_crossing(pool)), - history_allowance: tracker.history_allowance, } } } @@ -83,49 +63,32 @@ impl From<Encoded> for GasTracker { withheld_crossing: encoded.withheld_crossing, failed_charge_remaining: 0, failed_charge_recorded: false, - pools_remaining: encoded.pools_remaining, - pools_spent: encoded.pools_spent, - pool_crossings: 0, - history_allowance: encoded.history_allowance, start_mark: super::StartMark::NONE, }; tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); - for (pool, crossing) in PoolId::ALL.into_iter().zip(encoded.pool_crossings) { - tracker.set_pool_crossing(pool, crossing); - } tracker } } #[cfg(test)] mod tests { - use super::super::{GasTracker, PoolId}; + use super::super::GasTracker; /// A tracker with every field away from its default: part of its regular gas withheld, a - /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a refund, - /// a pool drawn, a draw refused on another, a pool refilled below zero, and an allowance. + /// crossing and a failed charge recorded, a state charge spilled past the reservoir and a + /// refund. fn every_field_set() -> GasTracker { let mut tracker = GasTracker::new(1_000, 400, 300); tracker.withhold(100); assert!(!tracker.record_regular_cost(350)); assert!(tracker.record_state_cost(500)); - let [first, second, third] = PoolId::ALL; - tracker.set_pool_remaining(first, 900); - assert!(tracker.record_pool(first, 20)); - tracker.set_pool_remaining(second, 7); - assert!(!tracker.record_pool(second, 10_000)); - tracker.set_pool_remaining(third, 0); - tracker.refill_pool(third, 5); - tracker.set_history_allowance(160); tracker.record_refund(-3); tracker } - /// The encoding has the fields, the names and the order it had before the failed-charge - /// record and the crossings shared a word, so a format that encodes by position finds every - /// field in the place it had then; the failed-charge record is an optional number, and the - /// crossings a `bool` per pool. Such a format still cannot read an encoding made before the - /// pools' fields were added, which lacks them. + /// The encoding has the fields, the names and the order the derived encoding gave the + /// tracker's figures, so a format that encodes by position finds every field in its place; the + /// failed-charge record is an optional number. #[test] fn test_the_encoding_keeps_its_fields_and_their_order() { assert_eq!( @@ -133,9 +96,7 @@ mod tests { concat!( r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#, r#""state_gas_spilled":200,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, - r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#, - r#""pools_remaining":[880,7,5],"pools_spent":[20,0,-5],"#, - r#""pool_crossings":[false,true,false],"history_allowance":160}"#, + r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400}"#, ) ); assert_eq!( @@ -143,10 +104,7 @@ mod tests { concat!( r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#, r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#, - r#""withheld_crossing":null,"failed_charge_remaining":null,"#, - r#""pools_remaining":[18446744073709551615,18446744073709551615,"#, - r#"18446744073709551615],"pools_spent":[0,0,0],"#, - r#""pool_crossings":[false,false,false],"history_allowance":0}"#, + r#""withheld_crossing":null,"failed_charge_remaining":null}"#, ) ); } diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs index 59ce8939f9..faa5e8d876 100644 --- a/crates/context/interface/src/cfg/gas/forward.rs +++ b/crates/context/interface/src/cfg/gas/forward.rs @@ -1,27 +1,24 @@ //! What a frame start takes out of its caller's [`GasTracker`] for the child frame, beside the -//! regular gas: a share of the EIP-8037 reservoir and of each pool. +//! regular gas: a share of the EIP-8037 reservoir. //! //! The caller keeps the rest while the child runs, and the child's return adds what the child left -//! back to what the caller kept ([`absorb_returned_reservoir`](GasTracker::absorb_returned_reservoir), -//! [`absorb_returned_pools`](GasTracker::absorb_returned_pools)). The shares are the schedule's -//! ([`GasParams::reservoir_forward_share`], [`GasParams::pool_forward_share`]); every schedule -//! defined here forwards the whole reservoir and every whole pool, which is upstream's forward. +//! back to what the caller kept ([`absorb_returned_reservoir`](GasTracker::absorb_returned_reservoir)). +//! The share is the schedule's ([`GasParams::reservoir_forward_share`]); every schedule defined +//! here forwards the whole reservoir, which is upstream's forward. -use super::{GasTracker, PoolAmounts, PoolId}; +use super::GasTracker; use crate::cfg::GasParams; /// What a child frame's tracker starts with beside its regular gas, taken out of its caller's: its -/// reservoir and its pools. +/// reservoir. /// /// Returned by [`GasTracker::forward_to_child`] and [`GasTracker::forward_all_to_child`]; the -/// frame's input carries it (`reservoir` and `pool_shares`). +/// frame's input carries it (`reservoir`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ChildShares { /// The child's reservoir. pub reservoir: u64, - /// The child's pools. - pub pools: PoolAmounts, } impl GasTracker { @@ -37,12 +34,12 @@ impl GasTracker { self.reservoir = self.reservoir.saturating_sub(share); } - /// Takes the schedule's shares of the reservoir and of each pool out of this, the caller's, - /// tracker for a child frame, and returns them: what the child's tracker starts with. + /// Takes the schedule's share of the reservoir out of this, the caller's, tracker for a child + /// frame, and returns it: what the child's tracker starts with. /// /// The `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` instructions - /// call it once the frame-start hook has answered, so the shares are of the reservoir and the - /// pools as the hook left them. A consumer that builds a child frame's input itself calls it + /// call it once the frame-start hook has answered, so the share is of the reservoir as the + /// hook left it. A consumer that builds a child frame's input itself calls it /// too, so that the child's return, which adds what the child left to what the caller kept, /// gives the caller back exactly what it forwarded. #[inline] @@ -55,8 +52,7 @@ impl GasTracker { /// /// `Some(reservoir)` is the child's reservoir, which the hook took out of this tracker itself: /// no share of the reservoir is taken here, and the child starts with `reservoir`. `None` takes - /// the schedule's share, as `forward_to_child` does. The pools are forwarded by the schedule's - /// shares either way. + /// the schedule's share, as `forward_to_child` does. #[inline] pub fn forward_to_child_with_reservoir( &mut self, @@ -68,49 +64,36 @@ impl GasTracker { self.forward_reservoir(share); share }); - let mut pools = PoolAmounts::ZERO; - for pool in PoolId::ALL { - let share = params.pool_forward_share(pool, self.pool_remaining(pool)); - self.forward_pool(pool, share); - pools.set(pool, share); - } - ChildShares { reservoir, pools } + ChildShares { reservoir } } - /// Takes the whole reservoir and every whole pool out of this tracker for a child frame, and - /// returns them. + /// Takes the whole reservoir out of this tracker for a child frame, and returns it. /// - /// For the transaction's frame, which takes everything the transaction's tracker holds: the - /// schedule's shares apply to the frames below it. + /// For the transaction's frame, which takes the transaction's whole reservoir: the schedule's + /// share applies to the frames below it. #[inline] pub const fn forward_all_to_child(&mut self) -> ChildShares { let shares = ChildShares { reservoir: self.reservoir, - pools: self.pools_remaining(), }; self.reservoir = 0; - self.set_pools_remaining(PoolAmounts::ZERO); shares } } #[cfg(test)] mod tests { - use super::{ChildShares, GasTracker, PoolAmounts, PoolId}; + use super::{ChildShares, GasTracker}; use crate::cfg::{GasId, GasParams}; use primitives::hardfork::SpecId; - /// A caller with a reservoir of 1,000 and pools of 1,000, 500 and 100. + /// A caller with a reservoir of 1,000. fn caller() -> GasTracker { - let mut tracker = GasTracker::new(10_000, 10_000, 1_000); - for (pool, amount) in PoolId::ALL.into_iter().zip([1_000, 500, 100]) { - tracker.set_pool_remaining(pool, amount); - } - tracker + GasTracker::new(10_000, 10_000, 1_000) } - /// Every schedule forwards everything: the child gets the whole reservoir and every whole - /// pool, and the caller keeps nothing of them while the child runs. + /// Every schedule forwards the whole reservoir, and the caller keeps none of it while the + /// child runs. #[test] fn test_every_schedule_forwards_everything() { for spec in [SpecId::FRONTIER, SpecId::OSAKA, SpecId::AMSTERDAM] { @@ -120,13 +103,7 @@ mod tests { let shares = tracker.forward_to_child(¶ms); assert_eq!(shares.reservoir, 1_000, "{spec:?}"); - assert_eq!( - PoolId::ALL.map(|pool| shares.pools.get(pool)), - [1_000, 500, 100], - "{spec:?}" - ); assert_eq!(tracker.reservoir(), 0, "{spec:?}"); - assert_eq!(tracker.pools_remaining(), PoolAmounts::ZERO, "{spec:?}"); assert_eq!( tracker.remaining(), 10_000, @@ -135,55 +112,31 @@ mod tests { } } - /// Each figure is forwarded by its own share, rounded down, and the caller keeps the rest. + /// The reservoir is forwarded by the schedule's share, and the caller keeps the rest. #[test] fn test_each_share_is_the_schedules() { let mut params = GasParams::new_spec(SpecId::AMSTERDAM); - params.override_gas([ - (GasId::reservoir_kept_percent(), 2), - (GasId::pool_kept_percent(PoolId::new(0)), 2), - (GasId::pool_kept_percent(PoolId::new(1)), 50), - (GasId::pool_kept_percent(PoolId::new(2)), 100), - ]); + params.override_gas([(GasId::reservoir_kept_percent(), 2)]); let mut tracker = caller(); assert!(tracker.record_state_cost(1)); let shares = tracker.forward_to_child(¶ms); - // The reservoir's 999 less the caller's 2%, rounded down (19), is 980; 98% of 1,000 is - // 980; half of 500 is 250. + // The reservoir's 999 less the caller's 2%, rounded down (19), is 980. assert_eq!(shares.reservoir, 980); - assert_eq!( - PoolId::ALL.map(|pool| shares.pools.get(pool)), - [980, 250, 0] - ); assert_eq!(tracker.reservoir(), 19); - assert_eq!( - PoolId::ALL.map(|pool| tracker.pool_remaining(pool)), - [20, 250, 100] - ); assert_eq!(tracker.state_gas_spent(), 1, "a forward is not a charge"); } - /// The transaction's frame takes everything, whatever the schedule. + /// The transaction's frame takes the whole reservoir, whatever the schedule. #[test] fn test_the_first_frame_takes_everything() { let mut tracker = caller(); let shares = tracker.forward_all_to_child(); - assert_eq!( - shares, - ChildShares { - reservoir: 1_000, - pools: PoolAmounts::ZERO - .with(PoolId::new(0), 1_000) - .with(PoolId::new(1), 500) - .with(PoolId::new(2), 100), - } - ); + assert_eq!(shares, ChildShares { reservoir: 1_000 }); assert_eq!(tracker.reservoir(), 0); - assert_eq!(tracker.pools_remaining(), PoolAmounts::ZERO); } /// A caller that kept part of its reservoir when it forwarded a share gets the child's diff --git a/crates/context/interface/src/cfg/gas/history_allowance.rs b/crates/context/interface/src/cfg/gas/history_allowance.rs deleted file mode 100644 index 9b42c3ee3c..0000000000 --- a/crates/context/interface/src/cfg/gas/history_allowance.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! The history allowance of a [`GasTracker`]: history gas a frame may spend before it charges -//! its budget. -//! -//! The fork sets it on a value call's child, from the schedule's `call_history_allowance`, where -//! it adds the call stipend; it is zero on every schedule defined here and in every other frame. -//! Nothing in this workspace draws it: a consumer that charges history for a write draws the -//! allowance first ([`draw_history_allowance`](GasTracker::draw_history_allowance)) and charges -//! the rest. The allowance is the frame's alone: it is not returned, merged or rolled back. - -use super::GasTracker; - -impl GasTracker { - /// History gas this frame may spend before it charges its budget. - #[inline] - pub const fn history_allowance(&self) -> u64 { - self.history_allowance - } - - /// Sets the history allowance. - #[inline] - pub const fn set_history_allowance(&mut self, val: u64) { - self.history_allowance = val; - } - - /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` the - /// allowance did not cover, which the caller charges as history gas. - /// - /// With no allowance, which is the default, it returns `cost` whole and changes nothing. - #[inline] - #[must_use = "the part of the cost the allowance did not cover is still to be charged"] - pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { - let drawn = if cost < self.history_allowance { - cost - } else { - self.history_allowance - }; - self.history_allowance -= drawn; - cost - drawn - } -} - -#[cfg(test)] -mod tests { - use super::GasTracker; - - /// Every tracker starts with no allowance, and a draw on none is the whole cost. - #[test] - fn test_no_allowance_leaves_the_whole_cost_to_charge() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - assert_eq!(tracker.history_allowance(), 0); - assert_eq!(tracker.draw_history_allowance(100), 100); - assert_eq!(tracker, GasTracker::new(1_000, 1_000, 0)); - } - - /// A draw within the allowance leaves nothing to charge; one beyond it empties the allowance - /// and leaves the rest. - #[test] - fn test_draws_take_the_allowance_first() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_history_allowance(160); - - assert_eq!(tracker.draw_history_allowance(100), 0); - assert_eq!(tracker.history_allowance(), 60); - - assert_eq!(tracker.draw_history_allowance(100), 40); - assert_eq!(tracker.history_allowance(), 0); - - assert_eq!(tracker.draw_history_allowance(0), 0); - } - - /// The allowance touches no other figure of the tracker. - #[test] - fn test_the_allowance_is_its_own_figure() { - let mut tracker = GasTracker::new(1_000, 1_000, 300); - tracker.set_history_allowance(160); - assert_eq!(tracker.draw_history_allowance(50), 0); - assert_eq!(tracker.remaining(), 1_000); - assert_eq!(tracker.reservoir(), 300); - assert_eq!(tracker.history_gas_spent(), 0); - } - - /// JSON encodings made before the allowance existed decode with none. - #[cfg(feature = "serde")] - #[test] - fn test_serde_round_trip_and_older_json_payloads() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_history_allowance(160); - let encoded = serde_json::to_value(tracker).unwrap(); - assert_eq!( - serde_json::from_value::<GasTracker>(encoded.clone()).unwrap(), - tracker - ); - - let mut older = encoded; - older.as_object_mut().unwrap().remove("history_allowance"); - let decoded = serde_json::from_value::<GasTracker>(older).unwrap(); - assert_eq!(decoded.history_allowance(), 0); - } -} diff --git a/crates/context/interface/src/cfg/gas/pools.rs b/crates/context/interface/src/cfg/gas/pools.rs deleted file mode 100644 index bd427d7d3d..0000000000 --- a/crates/context/interface/src/cfg/gas/pools.rs +++ /dev/null @@ -1,924 +0,0 @@ -//! The resource pools of a [`GasTracker`]: budgets beside the gas, each forwarded to a child frame -//! by its own share and settled with the frame's gas. -//! -//! A tracker carries [`PoolId::COUNT`] pools, which a consumer gives their meaning (bytes appended, -//! records written, entries created); the fork knows them only by index. Each pool is a figure -//! beside the gas: `pool_remaining` is what the frame may still draw, and `pool_spent` the frame's -//! net draw so far, signed as the state and history nets are. A draw -//! ([`record_pool`](GasTracker::record_pool)) the pool cannot pay fails, takes nothing and sets -//! the pool's crossing ([`pool_crossing`](GasTracker::pool_crossing)). A frame that reverts or -//! halts gives its draws on every pool back ([`rollback_state_gas`](GasTracker::rollback_state_gas)), -//! and a frame that succeeds hands its nets to its caller, so a caller's rollback undoes its -//! children's draws too. Every pool starts unlimited (`u64::MAX`), and nothing in this workspace -//! draws one, so a consumer that sets no pool sees nothing of them. -//! -//! The nets are `i64`, as the gas nets are, while draws and refills take `u64` amounts. As the -//! tracker does for gas amounts, it assumes that every draw and refill is at most `i64::MAX`, and -//! that each net, with the nets of the children merged into it, stays within `±i64::MAX`, so it can -//! be negated ([`adopt_pool_share`](GasTracker::adopt_pool_share)); a pool itself may be anything -//! up to the unlimited `u64::MAX`. A release build does not check it: past it the net saturates, -//! and a rollback no longer restores the pool exactly. A debug build asserts it wherever a net -//! moves ([`record_pool`](GasTracker::record_pool), [`refill_pool`](GasTracker::refill_pool), -//! [`add_pool_spent`](GasTracker::add_pool_spent)). Reaching it takes about 9.2 × 10^18 units. - -use super::{saturating_signed, GasTracker}; - -/// One of a tracker's resource pools, by index. -/// -/// A consumer names the pools it uses with constants (`const PAGES: PoolId = PoolId::new(0);`); -/// [`new`](Self::new) refuses an index the tracker has no pool for, so such a constant does not -/// compile. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct PoolId(u8); - -impl PoolId { - /// How many pools a tracker carries. - pub const COUNT: usize = 3; - - /// Every pool, in index order. - pub const ALL: [Self; Self::COUNT] = [Self(0), Self(1), Self(2)]; - - /// The pool at `index`. - /// - /// # Panics - /// - /// If `index` is not below [`COUNT`](Self::COUNT); in a constant, that is a compile error. - #[inline] - pub const fn new(index: usize) -> Self { - assert!(index < Self::COUNT, "a tracker has no pool at this index"); - Self(index as u8) - } - - /// The pool's index, below [`COUNT`](Self::COUNT). - #[inline] - pub const fn index(self) -> usize { - self.0 as usize - } -} - -/// An amount for each of a tracker's pools: the shares a child frame's pools start with -/// ([`ChildShares::pools`](super::ChildShares::pools)), or what a frame start drew from its -/// caller's pools ([`StartCharge::pools`](super::StartCharge::pools)). -/// -/// Encoded as a sequence of one number per pool, in index order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr( - feature = "serde", - derive(serde::Serialize, serde::Deserialize), - serde(transparent) -)] -pub struct PoolAmounts([u64; PoolId::COUNT]); - -impl PoolAmounts { - /// Nothing in any pool. The default. - pub const ZERO: Self = Self([0; PoolId::COUNT]); - - /// Every pool unlimited: what a tracker starts with, and the share of a child whose caller - /// limits nothing. - pub const UNLIMITED: Self = Self([u64::MAX; PoolId::COUNT]); - - /// The amount for `pool`. - #[inline] - pub const fn get(&self, pool: PoolId) -> u64 { - self.0[pool.index()] - } - - /// Sets the amount for `pool`. - #[inline] - pub const fn set(&mut self, pool: PoolId, amount: u64) { - self.0[pool.index()] = amount; - } - - /// These amounts, with `amount` for `pool`. - #[inline] - #[must_use] - pub const fn with(mut self, pool: PoolId, amount: u64) -> Self { - self.set(pool, amount); - self - } - - /// Whether every amount is zero. - #[inline] - pub const fn is_zero(&self) -> bool { - let mut index = 0; - while index < PoolId::COUNT { - if self.0[index] != 0 { - return false; - } - index += 1; - } - true - } -} - -impl GasTracker { - /// The pool: what this frame may still draw from it. - /// - /// Starts at `u64::MAX`, an unlimited pool, in every tracker. A consumer that limits the pool - /// sets the transaction's ([`set_pool_remaining`](Self::set_pool_remaining)); every child - /// frame then receives a share of its caller's pool when it starts, and the caller keeps the - /// rest. - #[inline] - pub const fn pool_remaining(&self, pool: PoolId) -> u64 { - self.pools_remaining[pool.index()] - } - - /// Sets the pool. Its net draw ([`pool_spent`](Self::pool_spent)) is left as it is. - #[inline] - pub const fn set_pool_remaining(&mut self, pool: PoolId, val: u64) { - self.pools_remaining[pool.index()] = val; - } - - /// Every pool: what this frame may still draw from each. - #[inline] - pub const fn pools_remaining(&self) -> PoolAmounts { - PoolAmounts(self.pools_remaining) - } - - /// Sets every pool, as a child frame's are set to the shares its caller forwarded. The nets - /// are left as they are. - #[inline] - pub const fn set_pools_remaining(&mut self, pools: PoolAmounts) { - self.pools_remaining = pools.0; - } - - /// The frame's net draw of the pool so far: draws less refills, plus the nets of the children - /// that succeeded. - /// - /// Negative while the frame has refilled more than it drew, as - /// [`history_gas_spent`](Self::history_gas_spent) can be. A rollback adds it back to the pool. - /// It is exact while it stays within `±i64::MAX` and no single draw or refill exceeds - /// `i64::MAX`, which a debug build asserts. - #[inline] - pub const fn pool_spent(&self, pool: PoolId) -> i64 { - self.pools_spent[pool.index()] - } - - /// Sets the pool's net draw. - #[inline] - pub const fn set_pool_spent(&mut self, pool: PoolId, val: i64) { - self.pools_spent[pool.index()] = val; - } - - /// Adds `delta` to the pool's net draw, saturating. Used to merge a successful child's net - /// into its caller, so a later rollback of the caller undoes the child's draws too. - #[inline] - pub const fn add_pool_spent(&mut self, pool: PoolId, delta: i64) { - let spent = &mut self.pools_spent[pool.index()]; - debug_assert!( - matches!(spent.checked_add(delta), Some(net) if net != i64::MIN), - "a pool's net leaves the signed range" - ); - *spent = spent.saturating_add(delta); - } - - /// Draws `cost` from the pool. - /// - /// Returns `false` if the pool cannot pay, leaving it untouched and setting its crossing - /// ([`pool_crossing`](Self::pool_crossing)). A draw of zero always succeeds. The draw is - /// counted on [`pool_spent`](Self::pool_spent), so a rollback gives it back. - #[inline] - #[must_use = "a draw the pool cannot pay is the consumer's stop"] - pub const fn record_pool(&mut self, pool: PoolId, cost: u64) -> bool { - let index = pool.index(); - if let Some(left) = self.pools_remaining[index].checked_sub(cost) { - debug_assert!( - cost <= i64::MAX as u64 - && self.pools_spent[index].checked_add(cost as i64).is_some(), - "a pool's net leaves the signed range" - ); - self.pools_remaining[index] = left; - self.pools_spent[index] = - self.pools_spent[index].saturating_add(saturating_signed(cost)); - return true; - } - self.pool_crossings |= 1 << index; - false - } - - /// Gives `amount` back to the pool, for a draw the frame took back. - /// - /// The net draw falls by the same amount, below zero when the matching draw was a caller's, - /// which the merge on return reconciles, as [`refill_history`](Self::refill_history) does. - #[inline] - pub const fn refill_pool(&mut self, pool: PoolId, amount: u64) { - let index = pool.index(); - debug_assert!( - amount <= i64::MAX as u64 - && matches!( - self.pools_spent[index].checked_sub(amount as i64), - Some(net) if net != i64::MIN - ), - "a pool's net leaves the signed range" - ); - self.pools_remaining[index] = self.pools_remaining[index].saturating_add(amount); - self.pools_spent[index] = self.pools_spent[index].saturating_sub(saturating_signed(amount)); - } - - /// Takes `share` out of the pool for a child frame, which starts with it as its pool. - /// - /// Not a draw: the net is unchanged, since the share comes back when the child returns - /// ([`absorb_returned_pool`](Self::absorb_returned_pool)). `share` is at most the pool, which - /// the schedule's forward share guarantees; more saturates at an empty pool. - #[inline] - pub const fn forward_pool(&mut self, pool: PoolId, share: u64) { - let remaining = &mut self.pools_remaining[pool.index()]; - *remaining = remaining.saturating_sub(share); - } - - /// Adds back what a returning child left of its pool: its remaining pool when it succeeded, - /// the whole share it was given when it reverted or halted, since its rollback restored it. - #[inline] - pub const fn absorb_returned_pool(&mut self, pool: PoolId, remaining: u64) { - let own = &mut self.pools_remaining[pool.index()]; - *own = own.saturating_add(remaining); - } - - /// Takes `share` as the pool this tracker started with: the pool becomes `share` less the net - /// drawn so far, so that the pool and the net add up to `share`, as a frame's do. - /// - /// For a tracker built outside a frame, such as a precompile's answer, which may have drawn - /// before it learns the share its caller forwarded. A rollback then restores `share`. - /// - /// A net above `share` is a draw the share could not have paid, and fails closed: the pool is - /// emptied, the net is capped at `share` and the pool's crossing is set, as a draw the pool - /// refused sets it. The caller then gets back no more than it forwarded, whether the answer - /// succeeds or fails, and a consumer reads the crossing as it reads any. The answer's result - /// and every other pool are left as they are. - #[inline] - pub const fn adopt_pool_share(&mut self, pool: PoolId, share: u64) { - let index = pool.index(); - let spent = self.pools_spent[index]; - if spent > 0 && spent as u64 > share { - self.pools_remaining[index] = 0; - // `share < spent <= i64::MAX`, so the cast is exact. - self.pools_spent[index] = share as i64; - self.pool_crossings |= 1 << index; - return; - } - self.pools_remaining[index] = share.saturating_add_signed(spent.saturating_neg()); - } - - /// [`adopt_pool_share`](Self::adopt_pool_share) for every pool. - #[inline] - pub const fn adopt_pool_shares(&mut self, shares: PoolAmounts) { - let mut index = 0; - while index < PoolId::COUNT { - self.adopt_pool_share(PoolId::ALL[index], shares.0[index]); - index += 1; - } - } - - /// Settles every pool of a returning child into this, its caller's, tracker: the child's nets - /// merge into this tracker's when the child `succeeded`, and what the child left of each pool - /// is absorbed back whatever its end, as [`absorb_returned_pool`](Self::absorb_returned_pool) - /// says. A child that failed has already rolled its draws back. - #[inline] - pub const fn absorb_returned_pools(&mut self, child: &Self, succeeded: bool) { - let mut index = 0; - while index < PoolId::COUNT { - let pool = PoolId::ALL[index]; - if succeeded { - self.add_pool_spent(pool, child.pools_spent[index]); - } - self.absorb_returned_pool(pool, child.pools_remaining[index]); - index += 1; - } - } - - /// The pool's crossing: whether a draw failed that the pool could not pay, since the record - /// was last cleared, or a consumer set it with [`set_pool_crossing`](Self::set_pool_crossing). - /// - /// A consumer reads it from a halted frame's result to tell a frame that ran out of the pool - /// from one that ran out of gas, and turns it into a stop of its own class. The record says - /// that a draw failed, not what it asked for: the hook that drew knows its cost when the draw - /// fails. The failed draw took nothing, and no halt touches a pool, so the pool itself still - /// reads as it was at the failure until the frame's rollback. The record survives - /// [`spend_all`](Self::spend_all), starts empty in every child, and is not taken over by a - /// caller. Each pool's is a bit beside the failed-charge record - /// ([`failed_charge_remaining`](Self::failed_charge_remaining)), and each is set and cleared - /// apart from the others. - #[inline] - pub const fn pool_crossing(&self, pool: PoolId) -> bool { - self.pool_crossings & (1 << pool.index()) != 0 - } - - /// Clears the record returned by [`pool_crossing`](Self::pool_crossing). - #[inline] - pub const fn clear_pool_crossing(&mut self, pool: PoolId) { - self.pool_crossings &= !(1 << pool.index()); - } - - /// Sets the record returned by [`pool_crossing`](Self::pool_crossing); `false` clears it. The - /// pool is left as it is. - /// - /// For a consumer that marks a result it produced itself, such as an answer it gave without - /// running a frame, as a failed draw, so a classifier reading the record treats it as one the - /// tracker recorded. - #[inline] - pub const fn set_pool_crossing(&mut self, pool: PoolId, crossing: bool) { - if crossing { - self.pool_crossings |= 1 << pool.index(); - } else { - self.clear_pool_crossing(pool); - } - } - - /// Gives every pool's net draw back to it, which then reads as the pool the frame started - /// with, and zeroes the nets. Part of [`rollback_state_gas`](Self::rollback_state_gas). - #[inline] - pub(super) const fn rollback_pools(&mut self) { - let mut index = 0; - while index < PoolId::COUNT { - self.pools_remaining[index] = - self.pools_remaining[index].saturating_add_signed(self.pools_spent[index]); - self.pools_spent[index] = 0; - index += 1; - } - } -} - -#[cfg(test)] -mod tests { - use super::{GasTracker, PoolAmounts, PoolId}; - - /// A tracker with every pool at 1,000. - fn pools_1000() -> GasTracker { - let mut tracker = GasTracker::new(1_000, 1_000, 300); - for pool in PoolId::ALL { - tracker.set_pool_remaining(pool, 1_000); - } - tracker - } - - /// The pools other than `pool` as they were set: 1,000, nothing drawn, no record. - fn assert_untouched_but(tracker: &GasTracker, pool: PoolId) { - for other in PoolId::ALL.into_iter().filter(|&other| other != pool) { - assert_eq!(tracker.pool_remaining(other), 1_000, "{other:?}"); - assert_eq!(tracker.pool_spent(other), 0, "{other:?}"); - assert!(!tracker.pool_crossing(other), "{other:?}"); - } - } - - /// The tracker has the pools `ALL` names, each by its index; an index past them is refused. - #[test] - fn test_the_pools_are_named_by_index() { - assert_eq!(PoolId::COUNT, 3); - for (index, pool) in PoolId::ALL.into_iter().enumerate() { - assert_eq!(pool, PoolId::new(index)); - assert_eq!(pool.index(), index); - } - } - - #[test] - #[should_panic(expected = "a tracker has no pool at this index")] - fn test_an_index_past_the_pools_is_refused() { - let _ = PoolId::new(PoolId::COUNT); - } - - /// Amounts are read and set by pool; zero is the default and unlimited is every pool at - /// `u64::MAX`. - #[test] - fn test_pool_amounts_are_read_and_set_by_pool() { - assert_eq!(PoolAmounts::default(), PoolAmounts::ZERO); - assert!(PoolAmounts::ZERO.is_zero()); - let amounts = PoolAmounts::ZERO.with(PoolId::new(1), 40); - assert!(!amounts.is_zero()); - assert_eq!( - PoolId::ALL.map(|pool| amounts.get(pool)), - [0, 40, 0], - "only the pool set moves" - ); - assert_eq!( - PoolId::ALL.map(|pool| PoolAmounts::UNLIMITED.get(pool)), - [u64::MAX; 3] - ); - } - - /// Every tracker starts with every pool unlimited, nothing drawn and no record; `Default` is - /// `new(0, 0, 0)`. - #[test] - fn test_a_new_tracker_has_unlimited_pools() { - let tracker = GasTracker::new(1_000, 1_000, 300); - assert_eq!(tracker.pools_remaining(), PoolAmounts::UNLIMITED); - for pool in PoolId::ALL { - assert_eq!(tracker.pool_spent(pool), 0); - assert!(!tracker.pool_crossing(pool)); - } - assert_eq!(GasTracker::default(), GasTracker::new(0, 0, 0)); - assert_eq!( - GasTracker::default().pools_remaining(), - PoolAmounts::UNLIMITED - ); - } - - /// Each pool is a figure of its own: a draw, a failed draw, a refill, a forward and a record - /// on one leave the others as they were. - #[test] - fn test_each_pool_moves_alone() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(pool, 300)); - assert!(!tracker.record_pool(pool, 800)); - tracker.refill_pool(pool, 50); - tracker.forward_pool(pool, 100); - tracker.absorb_returned_pool(pool, 20); - tracker.add_pool_spent(pool, 7); - - assert_eq!(tracker.pool_remaining(pool), 670, "{pool:?}"); - assert_eq!(tracker.pool_spent(pool), 257, "{pool:?}"); - assert!(tracker.pool_crossing(pool), "{pool:?}"); - assert_untouched_but(&tracker, pool); - - tracker.clear_pool_crossing(pool); - assert!(!tracker.pool_crossing(pool), "{pool:?}"); - tracker.set_pool_crossing(pool, true); - assert_untouched_but(&tracker, pool); - } - } - - /// A pool's crossing shares a word with the failed-charge record and is a record of its own: a - /// failed draw records no failed charge, a failed charge records no crossing, and setting or - /// clearing either leaves the other as it is. - #[test] - fn test_the_crossings_and_the_failed_charge_record_are_independent() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(!tracker.record_pool(pool, 1_001)); - assert!(tracker.pool_crossing(pool)); - assert_eq!(tracker.failed_charge_remaining(), None); - - tracker.clear_pool_crossing(pool); - assert!(!tracker.record_regular_cost(1_001)); - assert_eq!(tracker.failed_charge_remaining(), Some(1_000)); - assert!(!tracker.pool_crossing(pool)); - - tracker.set_pool_crossing(pool, true); - tracker.set_failed_charge_remaining(None); - assert!(tracker.pool_crossing(pool)); - tracker.set_failed_charge_remaining(Some(0)); - tracker.clear_pool_crossing(pool); - assert_eq!(tracker.failed_charge_remaining(), Some(0)); - } - } - - #[test] - fn test_record_pool_draws_the_pool_and_counts_the_draw() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - - assert!(tracker.record_pool(pool, 300)); - assert!(tracker.record_pool(pool, 200)); - - assert_eq!(tracker.pool_remaining(pool), 500); - assert_eq!(tracker.pool_spent(pool), 500); - assert!(!tracker.pool_crossing(pool)); - } - } - - /// A draw the pool cannot pay takes nothing and leaves the record. - #[test] - fn test_a_draw_beyond_the_pool_fails_and_records_the_crossing() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(pool, 900)); - - assert!(!tracker.record_pool(pool, 101)); - - assert_eq!( - tracker.pool_remaining(pool), - 100, - "the failed draw took nothing" - ); - assert_eq!(tracker.pool_spent(pool), 900); - assert!(tracker.pool_crossing(pool)); - } - } - - /// A draw of exactly the pool succeeds, and a draw of zero succeeds on an empty pool. - #[test] - fn test_a_draw_of_the_whole_pool_succeeds_and_zero_always_does() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(pool, 1_000)); - assert_eq!(tracker.pool_remaining(pool), 0); - assert!(tracker.record_pool(pool, 0)); - assert!(!tracker.pool_crossing(pool)); - assert!(!tracker.record_pool(pool, 1)); - assert!(tracker.pool_crossing(pool)); - } - } - - /// The record stays until it is cleared: a later draw that succeeds leaves it, and a consumer - /// clears or sets it, which leaves the pool as it is. - #[test] - fn test_the_record_stays_until_cleared() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(!tracker.record_pool(pool, 1_001)); - assert!(tracker.record_pool(pool, 10)); - assert!(tracker.pool_crossing(pool)); - - tracker.clear_pool_crossing(pool); - assert!(!tracker.pool_crossing(pool)); - - tracker.set_pool_crossing(pool, true); - assert!(tracker.pool_crossing(pool)); - tracker.set_pool_crossing(pool, false); - assert!(!tracker.pool_crossing(pool)); - assert_eq!( - tracker.pool_remaining(pool), - 990, - "setting the record leaves the pool" - ); - } - } - - /// The halt that follows a failed draw zeroes the regular gas and nothing else: the record - /// and the pool are still readable after it. - #[test] - fn test_the_record_and_the_pool_survive_spend_all() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(pool, 600)); - assert!(!tracker.record_pool(pool, 500)); - - tracker.spend_all(); - - assert_eq!(tracker.remaining(), 0); - assert_eq!(tracker.pool_remaining(pool), 400); - assert!(tracker.pool_crossing(pool)); - } - } - - /// A refill gives back and lowers the net, below zero when the draw was a caller's. - #[test] - fn test_refill_pool_gives_back_and_can_take_the_net_below_zero() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(pool, 300)); - - tracker.refill_pool(pool, 500); - - assert_eq!(tracker.pool_remaining(pool), 1_200); - assert_eq!(tracker.pool_spent(pool), -200); - } - } - - /// Rolling a frame back gives every pool's net draw back, so each reads as the pool the frame - /// started with, and nothing else of the rollback changes. - #[test] - fn test_rollback_restores_every_pool_the_frame_started_with() { - let mut tracker = pools_1000(); - assert!(tracker.record_state_cost(200)); - let [first, second, third] = PoolId::ALL; - assert!(tracker.record_pool(first, 300)); - tracker.refill_pool(first, 100); - assert!(tracker.record_pool(first, 50)); - assert!(tracker.record_pool(second, 999)); - tracker.refill_pool(third, 40); - assert_eq!( - PoolId::ALL.map(|pool| tracker.pool_remaining(pool)), - [750, 1, 1_040] - ); - - tracker.rollback_state_gas(); - - for pool in PoolId::ALL { - assert_eq!(tracker.pool_remaining(pool), 1_000, "{pool:?}"); - assert_eq!(tracker.pool_spent(pool), 0, "{pool:?}"); - } - assert_eq!(tracker.reservoir(), 300, "the state rollback is as it was"); - assert_eq!(tracker.state_gas_spent(), 0); - } - - /// A rollback of a frame that refilled a caller's draw takes the refill back out. - #[test] - fn test_rollback_undoes_a_refill_of_a_callers_draw() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - tracker.refill_pool(pool, 100); - assert_eq!(tracker.pool_remaining(pool), 1_100); - - tracker.rollback_state_gas(); - - assert_eq!(tracker.pool_remaining(pool), 1_000); - assert_eq!(tracker.pool_spent(pool), 0); - } - } - - /// The forward takes the share out of the pool without counting it as a draw; the child's - /// return adds back what it left. - #[test] - fn test_forward_takes_the_share_and_the_return_adds_back_what_the_child_left() { - for pool in PoolId::ALL { - let mut parent = pools_1000(); - parent.forward_pool(pool, 980); - assert_eq!(parent.pool_remaining(pool), 20); - assert_eq!(parent.pool_spent(pool), 0, "a forward is not a draw"); - - parent.absorb_returned_pool(pool, 700); - assert_eq!(parent.pool_remaining(pool), 720); - } - } - - /// A child's pools settle into its caller's: on success its nets merge and what it left comes - /// back; on failure its rollback gave its draws back first, and no net merges. - #[test] - fn test_the_pools_of_a_returning_child_settle_into_its_caller() { - for kept in [true, false] { - let mut parent = pools_1000(); - let shares = [900, 500, 1_000]; - let mut child = GasTracker::new(500, 500, 0); - for (pool, share) in PoolId::ALL.into_iter().zip(shares) { - parent.forward_pool(pool, share); - child.set_pool_remaining(pool, share); - } - let [first, second, third] = PoolId::ALL; - assert!(child.record_pool(first, 100)); - assert!(child.record_pool(second, 20)); - child.refill_pool(third, 5); - if !kept { - child.rollback_state_gas(); - } - - parent.absorb_returned_pools(&child, kept); - - let (pools, spent) = if kept { - ([900, 980, 1_005], [100, 20, -5]) - } else { - ([1_000; 3], [0; 3]) - }; - assert_eq!( - PoolId::ALL.map(|pool| parent.pool_remaining(pool)), - pools, - "kept: {kept}" - ); - assert_eq!( - PoolId::ALL.map(|pool| parent.pool_spent(pool)), - spent, - "kept: {kept}" - ); - } - } - - /// A tracker that adopts a share keeps its net and takes the share less the net as its pool, - /// so a rollback restores the share: after draws, after a refill below zero, and after none. - #[test] - fn test_an_adopted_share_less_the_net_is_the_pool() { - for pool in PoolId::ALL { - for (name, draws, refills, expected) in [ - ("drew", 40, 0, 860), - ("refilled", 0, 25, 925), - ("nothing", 0, 0, 900), - ] { - let mut answer = GasTracker::new(500, 500, 0); - assert!(answer.record_pool(pool, draws)); - answer.refill_pool(pool, refills); - let spent = answer.pool_spent(pool); - - answer.adopt_pool_share(pool, 900); - - assert_eq!(answer.pool_remaining(pool), expected, "{pool:?} {name}"); - assert_eq!( - answer.pool_spent(pool), - spent, - "{pool:?} {name}: the net is kept" - ); - answer.rollback_state_gas(); - assert_eq!( - answer.pool_remaining(pool), - 900, - "{pool:?} {name}: a rollback restores the share" - ); - } - } - } - - /// A draw of exactly the share adopts as any draw within it does: an empty pool, the net kept - /// and no crossing. - #[test] - fn test_an_answer_that_drew_its_whole_share_adopts_it_unchanged() { - for pool in PoolId::ALL { - let mut answer = GasTracker::new(500, 500, 0); - assert!(answer.record_pool(pool, 100)); - - answer.adopt_pool_share(pool, 100); - - assert_eq!( - ( - answer.pool_remaining(pool), - answer.pool_spent(pool), - answer.pool_crossing(pool) - ), - (0, 100, false), - "{pool:?}" - ); - } - } - - /// An answer whose provider drew more than the share fails closed on that pool: the pool is - /// empty, the net is the share and the crossing is set, so the caller gets back exactly what - /// it held, whether the answer succeeds (and a later rollback of the caller undoes the draw) - /// or fails. Every other pool, and every crossing already set, is left as it was. - #[test] - fn test_an_answer_that_drew_past_its_share_is_a_crossing_capped_at_the_share() { - for pool in PoolId::ALL { - for succeeded in [true, false] { - // The caller forwards 100 of its 1,000 and keeps 900; the provider drew 150 on - // an answer whose pools were unlimited, and failed a draw on another pool. - let mut caller = pools_1000(); - caller.forward_pool(pool, 100); - let other = PoolId::new((pool.index() + 1) % PoolId::COUNT); - let mut answer = GasTracker::new(500, 500, 0); - answer.set_pool_remaining(other, 0); - assert!(!answer.record_pool(other, 1)); - assert!(answer.record_pool(pool, 150)); - - answer.adopt_pool_share(pool, 100); - - assert_eq!( - ( - answer.pool_remaining(pool), - answer.pool_spent(pool), - answer.pool_crossing(pool) - ), - (0, 100, true), - "{pool:?}" - ); - assert!( - answer.pool_crossing(other), - "{pool:?}: the other crossing stays" - ); - assert_eq!(answer.pool_spent(other), 0, "{pool:?}"); - - if !succeeded { - answer.rollback_state_gas(); - assert_eq!( - answer.pool_remaining(pool), - 100, - "{pool:?}: the rollback restores the share, not the draw" - ); - } - caller.absorb_returned_pools(&answer, succeeded); - let settled = if succeeded { (900, 100) } else { (1_000, 0) }; - assert_eq!( - (caller.pool_remaining(pool), caller.pool_spent(pool)), - settled, - "{pool:?} succeeded: {succeeded}" - ); - caller.rollback_state_gas(); - assert_eq!( - caller.pool_remaining(pool), - 1_000, - "{pool:?} succeeded: {succeeded}: the caller's rollback gives back what it held" - ); - } - } - } - - /// Every pool adopts its own share. - #[test] - fn test_adopted_shares_go_to_their_pools() { - let mut answer = GasTracker::new(500, 500, 0); - let [first, ..] = PoolId::ALL; - assert!(answer.record_pool(first, 40)); - - answer.adopt_pool_shares(PoolAmounts::ZERO.with(first, 900).with(PoolId::new(2), 7)); - - assert_eq!( - PoolId::ALL.map(|pool| answer.pool_remaining(pool)), - [860, 0, 7] - ); - } - - /// A forward above the pool and a return above `u64::MAX` saturate rather than wrap. - #[test] - fn test_forward_and_return_saturate() { - for pool in PoolId::ALL { - let mut tracker = pools_1000(); - tracker.forward_pool(pool, 5_000); - assert_eq!(tracker.pool_remaining(pool), 0); - - let mut unlimited = GasTracker::new(1, 1, 0); - unlimited.absorb_returned_pool(pool, 1); - assert_eq!(unlimited.pool_remaining(pool), u64::MAX); - } - } - - /// The net is exact up to `i64::MAX`: a draw of it from the unlimited pool, a refill of it, - /// and a child's net of it merged into its caller each roll back to the pool they started - /// from. - #[test] - fn test_the_net_is_exact_up_to_the_signed_maximum() { - const MAX: u64 = i64::MAX as u64; - for pool in PoolId::ALL { - let mut drawn = GasTracker::new(1_000, 1_000, 0); - assert!(drawn.record_pool(pool, MAX)); - assert_eq!(drawn.pool_spent(pool), i64::MAX); - drawn.rollback_state_gas(); - assert_eq!(drawn.pool_remaining(pool), u64::MAX); - - let mut refilled = GasTracker::new(1_000, 1_000, 0); - refilled.set_pool_remaining(pool, 0); - refilled.refill_pool(pool, MAX); - assert_eq!(refilled.pool_spent(pool), -i64::MAX); - refilled.rollback_state_gas(); - assert_eq!(refilled.pool_remaining(pool), 0); - - let mut caller = GasTracker::new(1_000, 1_000, 0); - caller.forward_pool(pool, u64::MAX); - let mut child = GasTracker::new(500, 500, 0); - assert!(child.record_pool(pool, MAX)); - caller.absorb_returned_pools(&child, true); - assert_eq!(caller.pool_spent(pool), i64::MAX); - caller.rollback_state_gas(); - assert_eq!(caller.pool_remaining(pool), u64::MAX); - } - } - - /// One unit past it the net would saturate, and a rollback would leave the unlimited pool one - /// short: a debug build refuses the draw. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "a pool's net leaves the signed range")] - fn test_a_draw_past_the_signed_maximum_panics_in_a_debug_build() { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - let _ = tracker.record_pool(PoolId::new(2), i64::MAX as u64 + 1); - } - - /// Below `-i64::MAX` the net would be `i64::MIN`, whose negation saturates, so a share - /// adopted against it would be one short: a debug build refuses the refill that gets there. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "a pool's net leaves the signed range")] - fn test_a_refill_past_the_signed_minimum_panics_in_a_debug_build() { - let pool = PoolId::new(1); - let mut tracker = GasTracker::new(1_000, 1_000, 0); - tracker.set_pool_remaining(pool, 0); - tracker.refill_pool(pool, i64::MAX as u64); - tracker.refill_pool(pool, 1); - } - - /// With the default pools, forwarding every pool whole and settling a child's return brings - /// the caller back to each pool less what the child drew and kept: a failed child's draws - /// come back whole. - #[test] - fn test_unlimited_pools_forwarded_whole_come_back_less_the_childs_draws() { - for fails in [false, true] { - let mut parent = GasTracker::new(1_000, 1_000, 0); - let shares = parent.pools_remaining(); - for pool in PoolId::ALL { - parent.forward_pool(pool, shares.get(pool)); - } - assert_eq!(parent.pools_remaining(), PoolAmounts::ZERO); - - let mut child = GasTracker::new(500, 500, 0); - child.set_pools_remaining(shares); - for pool in PoolId::ALL { - assert!(child.record_pool(pool, 100)); - } - if fails { - child.rollback_state_gas(); - } - parent.absorb_returned_pools(&child, !fails); - - let (remaining, spent) = if fails { - (u64::MAX, 0) - } else { - (u64::MAX - 100, 100) - }; - for pool in PoolId::ALL { - assert_eq!(parent.pool_remaining(pool), remaining, "fails: {fails}"); - assert_eq!(parent.pool_spent(pool), spent, "fails: {fails}"); - } - } - } - - /// JSON encodings made before the pools existed decode with unlimited pools, nothing drawn and - /// no record; the pools' own encoding round-trips. - #[cfg(feature = "serde")] - #[test] - fn test_serde_round_trip_and_older_json_payloads() { - let mut tracker = pools_1000(); - assert!(tracker.record_pool(PoolId::new(0), 300)); - assert!(!tracker.record_pool(PoolId::new(2), 1_800)); - let encoded = serde_json::to_value(tracker).unwrap(); - assert_eq!( - serde_json::from_value::<GasTracker>(encoded.clone()).unwrap(), - tracker - ); - - let mut older = encoded; - let fields = older.as_object_mut().unwrap(); - fields.remove("pools_remaining"); - fields.remove("pools_spent"); - fields.remove("pool_crossings"); - let decoded = serde_json::from_value::<GasTracker>(older).unwrap(); - assert_eq!(decoded.pools_remaining(), PoolAmounts::UNLIMITED); - for pool in PoolId::ALL { - assert_eq!(decoded.pool_spent(pool), 0); - assert!(!decoded.pool_crossing(pool)); - } - } -} diff --git a/crates/context/interface/src/cfg/gas/start_charge.rs b/crates/context/interface/src/cfg/gas/start_charge.rs deleted file mode 100644 index 94fce17e02..0000000000 --- a/crates/context/interface/src/cfg/gas/start_charge.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! The start charge a [`Host::frame_starting`](crate::Host::frame_starting) hook declares on the -//! [`FrameStart`](crate::host::FrameStart) it is handed, and the instruction copies onto the -//! frame's input. -//! -//! The hook charges the caller's gas for the frame it starts; the part of that charge the frame's -//! failure gives back is the start charge. The hook declares it on the start -//! ([`FrameStart::charge`](crate::host::FrameStart::charge)), the instruction copies it onto the -//! frame's input when the hook admits the start, and the handler refunds it to the caller when the -//! frame fails ([`GasTracker::refill_start_charge`]). - -use super::{GasTracker, PoolAmounts, PoolId}; - -/// What a frame start charged its caller and the frame's failure gives back: history gas and an -/// amount of each pool. -/// -/// Built with [`StartCharge::new`], so a later field is not a breaking change. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[non_exhaustive] -pub struct StartCharge { - /// History gas the start charged, refilled with - /// [`refill_history`](GasTracker::refill_history) when the frame fails. - pub history: u64, - /// What the start drew from each of the caller's pools, refilled with - /// [`refill_pool`](GasTracker::refill_pool) when the frame fails. - pub pools: PoolAmounts, -} - -impl StartCharge { - /// A start charge of `history` gas and `pools` from the caller's pools. - #[inline] - pub const fn new(history: u64, pools: PoolAmounts) -> Self { - Self { history, pools } - } - - /// Nothing to refund. - #[inline] - pub const fn is_zero(&self) -> bool { - self.history == 0 && self.pools.is_zero() - } -} - -impl GasTracker { - /// Gives `charge` back to this, the caller's, tracker: its history gas with - /// [`refill_history`](Self::refill_history), and each pool's amount with - /// [`refill_pool`](Self::refill_pool). - /// - /// The handler calls it when a frame whose start charged `charge` fails - /// (`FrameResult::refundable_start_charge`); a consumer that settles a frame's result itself - /// calls it on the same condition. - #[inline] - pub const fn refill_start_charge(&mut self, charge: StartCharge) { - self.refill_history(charge.history); - let mut index = 0; - while index < PoolId::COUNT { - let pool = PoolId::ALL[index]; - self.refill_pool(pool, charge.pools.get(pool)); - index += 1; - } - } -} - -#[cfg(test)] -mod tests { - use super::{GasTracker, PoolAmounts, PoolId, StartCharge}; - - /// The refill gives the history back the way `refill_history` does and each pool's amount to - /// its own pool, so a caller that drew them is where it was before the start. - #[test] - fn test_a_refilled_start_charge_puts_the_caller_back() { - let mut caller = GasTracker::new(10_000, 10_000, 0); - for pool in PoolId::ALL { - caller.set_pool_remaining(pool, 1_000); - } - let before = caller; - let charge = StartCharge::new( - 3_520, - PoolAmounts::ZERO - .with(PoolId::new(0), 40) - .with(PoolId::new(1), 1), - ); - assert!(caller.record_history_cost(charge.history)); - for pool in PoolId::ALL { - assert!(caller.record_pool(pool, charge.pools.get(pool))); - } - - caller.refill_start_charge(charge); - - assert_eq!(caller, before); - assert!(!charge.is_zero()); - assert!(StartCharge::default().is_zero()); - assert!(!StartCharge::new(0, PoolAmounts::ZERO.with(PoolId::new(2), 1)).is_zero()); - } -} diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index 4c71cddd7c..a3dc97c7e8 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,14 +236,13 @@ mod tests { assert_eq!(size_of::<Option<WithheldCrossing>>(), size_of::<u64>()); } - /// The tracker is 144 bytes: 72 with the withheld part and its record, two words more for the - /// failed-charge record, whose second word also holds the pools' crossings, two words for - /// each of the three pools (the pool and its net), and one for the history allowance. Copies - /// of the tracker, and of every `Gas` and frame result that holds one, grow with it, so a new - /// field is measured before this changes. - #[test] - fn test_the_tracker_is_144_bytes() { - assert_eq!(size_of::<GasTracker>(), 144); + /// The tracker is 88 bytes: 72 with the withheld part and its record, and two words more for + /// the failed-charge record, whose second word also holds the start mark. Copies of the + /// tracker, and of every `Gas` and frame result that holds one, grow with it, so a new field + /// is measured before this changes. + #[test] + fn test_the_tracker_is_88_bytes() { + assert_eq!(size_of::<GasTracker>(), 88); } /// Withholding moves gas between the parts and leaves the total alone. diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index 7587726dce..ae9f4de608 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -1,7 +1,7 @@ //! Gas table for dynamic gas constants. use crate::{ - cfg::gas::{self, get_tokens_in_calldata, InitialAndFloorGas, PoolId}, + cfg::gas::{self, get_tokens_in_calldata, InitialAndFloorGas}, context::SStoreResult, transaction::AccessListItemTr as _, Transaction, TransactionType, @@ -814,22 +814,6 @@ impl GasParams { .saturating_mul(len as u64) } - /// The share of a caller's `remaining` in `pool` a child frame receives when it starts: - /// `100 - `[`pool_kept_percent`](GasId::pool_kept_percent) per cent of it, rounded down; the - /// caller keeps the rest while the child runs. - /// - /// Zero kept, which every schedule here and every table without the entry has, forwards the - /// whole pool; a hundred or more forwards nothing. - #[inline] - pub fn pool_forward_share(&self, pool: PoolId, remaining: u64) -> u64 { - let kept = self.get(GasId::pool_kept_percent(pool)); - // The default, the whole pool, without the arithmetic. - if kept == 0 { - return remaining; - } - percent_of(remaining, 100u64.saturating_sub(kept)) - } - /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: all /// but the caller's part, which is [`reservoir_kept_percent`](GasId::reservoir_kept_percent) /// per cent of the reservoir, rounded down, and which the caller keeps while the child runs. @@ -849,13 +833,6 @@ impl GasParams { reservoir - percent_of(reservoir, kept) } - /// History gas a value call's child may spend before it charges its budget - /// ([`call_history_allowance`](GasId::call_history_allowance)). Zero on every schedule here. - #[inline] - pub fn call_history_allowance(&self) -> u64 { - self.get(GasId::call_history_allowance()) - } - /// Used in [GasParams::initial_tx_gas] to calculate the eip7702 per-auth cost. /// /// Pre-Amsterdam this is the pessimistic bundled `PER_EMPTY_ACCOUNT_COST` @@ -1318,10 +1295,6 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", - x if x == Self::call_history_allowance().as_u8() => "call_history_allowance", - x if x == Self::pool_kept_percent(PoolId::new(0)).as_u8() => "pool0_kept_percent", - x if x == Self::pool_kept_percent(PoolId::new(1)).as_u8() => "pool1_kept_percent", - x if x == Self::pool_kept_percent(PoolId::new(2)).as_u8() => "pool2_kept_percent", x if x == Self::reservoir_kept_percent().as_u8() => "reservoir_kept_percent", _ => "unknown", } @@ -1398,10 +1371,6 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), - "call_history_allowance" => Some(Self::call_history_allowance()), - "pool0_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(0))), - "pool1_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(1))), - "pool2_kept_percent" => Some(Self::pool_kept_percent(PoolId::new(2))), "reservoir_kept_percent" => Some(Self::reservoir_kept_percent()), _ => None, } @@ -1694,33 +1663,6 @@ impl GasId { Self::new(255) } - /// History gas a value call's child may spend before it charges its budget - /// ([`GasTracker::history_allowance`](crate::cfg::gas::GasTracker::history_allowance)). The - /// call instruction sets it on the child where it adds the call stipend. Zero on every - /// schedule defined here. - /// - /// A fork id, allocated from the top of the table below - /// [`code_deposit_history_gas`](Self::code_deposit_history_gas); id 254, between the two, is - /// left unused (see [`reservoir_kept_percent`](Self::reservoir_kept_percent)). - pub const fn call_history_allowance() -> GasId { - Self::new(253) - } - - /// The part of a caller's `pool` the caller keeps while its child frame runs, in per cent of - /// what the caller has left of it: the child receives the rest, rounded down - /// ([`GasParams::pool_forward_share`]). - /// - /// Zero, the whole pool forwarded, on every schedule defined here and in every table without - /// the entry, such as upstream's or one encoded before the entry existed; a chain that keeps - /// part of a pool for the caller raises it, and a hundred forwards none. - /// - /// Fork ids, one per pool, allocated downward below - /// [`reservoir_kept_percent`](Self::reservoir_kept_percent): pool `i` at `248 - i`, so a later - /// pool takes the next id below them. - pub const fn pool_kept_percent(pool: PoolId) -> GasId { - Self::new(248 - pool.index() as u8) - } - /// The part of a caller's EIP-8037 reservoir the caller keeps while its child frame runs, in /// per cent of the reservoir, rounded down: the child receives all but that /// ([`GasParams::reservoir_forward_share`]). @@ -1731,8 +1673,8 @@ impl GasId { /// hundred forwards none. /// /// A fork id, allocated from the top of the table below - /// [`call_history_allowance`](Self::call_history_allowance). Ids 254 and 250 to 252 are left - /// unused: earlier revisions of the fork put forward percentages there, 100 by default, which + /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). Ids 254 and 250 to 253, and + /// 246 to 248 below it, are left unused: earlier revisions of the fork put entries there, which /// a table encoded then still holds and which no entry reads. pub const fn reservoir_kept_percent() -> GasId { Self::new(249) @@ -1822,23 +1764,21 @@ mod tests { // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated // from the top of the table so upstream's next sequential id does not collide with them: - // `code_deposit_history_gas` at 255, `call_history_allowance` at 253, - // `reservoir_kept_percent` at 249 and the three pools' kept percents at 248, 247 and 246; - // 254 and 250 to 252 are unused. Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain(246..=249).chain([253, 255]).collect(); + // `code_deposit_history_gas` at 255 and `reservoir_kept_percent` at 249; 246 to 248 and + // 250 to 254 are unused. Every one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain([249, 255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), - 55, - "Expected 55 unique GasIds, found {}", + 51, + "Expected 51 unique GasIds, found {}", unique_names.len() ); } - /// Every schedule forwards every whole pool and the whole reservoir: each kept percent is - /// zero and the share is the amount itself, `u64::MAX` included. A schedule that keeps a - /// percentage forwards the rest, rounded down, and one that keeps a hundred or more forwards - /// nothing. + /// Every schedule forwards the whole reservoir: the kept percent is zero and the share is the + /// amount itself, `u64::MAX` included. A schedule that keeps a percentage forwards the rest, + /// and one that keeps a hundred or more forwards nothing. #[test] fn test_forward_shares_default_to_the_whole_amount() { let amounts = [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX]; @@ -1854,52 +1794,18 @@ mod tests { for amount in amounts { assert_eq!(params.reservoir_forward_share(amount), amount, "{spec:?}"); } - for pool in PoolId::ALL { - assert_eq!( - params.get(GasId::pool_kept_percent(pool)), - 0, - "{spec:?} {pool:?}" - ); - for amount in amounts { - assert_eq!( - params.pool_forward_share(pool, amount), - amount, - "{spec:?} {pool:?} {amount}" - ); - } - } } - // Each entry is its own: the reservoir keeps 2, the pools 2, 50 and 100. + // The reservoir's share is what is left once the caller's 2% is taken, rounded down, as + // regular gas's forward takes its part: a reservoir of 99 forwards 99 - 1 = 98. let mut params = GasParams::new_spec(SpecId::OSAKA); - params.override_gas([ - (GasId::reservoir_kept_percent(), 2), - (GasId::pool_kept_percent(PoolId::new(0)), 2), - (GasId::pool_kept_percent(PoolId::new(1)), 50), - (GasId::pool_kept_percent(PoolId::new(2)), 100), - ]); - let share = |amount| { - ( - params.reservoir_forward_share(amount), - PoolId::ALL.map(|pool| params.pool_forward_share(pool, amount)), - ) - }; - // A pool's share is the rest rounded down; the reservoir's is what is left once the - // caller's 2% is taken, rounded down, as regular gas's forward takes its part: 98% of 99 - // is 97.02, so a pool forwards 97 and the reservoir 99 - 1 = 98. - assert_eq!(share(0), (0, [0, 0, 0])); - assert_eq!(share(1), (1, [0, 0, 0])); - assert_eq!(share(99), (98, [97, 49, 0])); - assert_eq!(share(100), (98, [98, 50, 0])); - assert_eq!(share(149), (147, [146, 74, 0])); - assert_eq!(share(1_000), (980, [980, 500, 0])); - let max_98 = (u64::MAX as u128 * 98 / 100) as u64; - let max_less_2 = u64::MAX - (u64::MAX as u128 * 2 / 100) as u64; - assert_eq!( - share(u64::MAX), - (max_less_2, [max_98, u64::MAX / 2, 0]), - "no overflow" - ); + params.override_gas([(GasId::reservoir_kept_percent(), 2)]); + assert_eq!(params.reservoir_forward_share(0), 0); + assert_eq!(params.reservoir_forward_share(1), 1); + assert_eq!(params.reservoir_forward_share(99), 98); + assert_eq!(params.reservoir_forward_share(100), 98); + assert_eq!(params.reservoir_forward_share(149), 147); + assert_eq!(params.reservoir_forward_share(1_000), 980); for reservoir in (0..10_000).chain([u64::MAX - 1, u64::MAX]) { assert_eq!( params.reservoir_forward_share(reservoir), @@ -1908,46 +1814,26 @@ mod tests { ); } for (kept, share) in [(100, 0), (250, 0), (0, 1_000)] { - params.override_gas([ - (GasId::reservoir_kept_percent(), kept), - (GasId::pool_kept_percent(PoolId::new(1)), kept), - ]); - assert_eq!( - ( - params.reservoir_forward_share(1_000), - params.pool_forward_share(PoolId::new(1), 1_000) - ), - (share, share), - "kept {kept}" - ); + params.override_gas([(GasId::reservoir_kept_percent(), kept)]); + assert_eq!(params.reservoir_forward_share(1_000), share, "kept {kept}"); } - for (id, name) in [ - (GasId::reservoir_kept_percent(), "reservoir_kept_percent"), - ( - GasId::pool_kept_percent(PoolId::new(0)), - "pool0_kept_percent", - ), - ( - GasId::pool_kept_percent(PoolId::new(1)), - "pool1_kept_percent", - ), - ( - GasId::pool_kept_percent(PoolId::new(2)), - "pool2_kept_percent", - ), - ] { - assert_eq!(GasId::from_name(name), Some(id)); - assert_eq!(id.name(), name); - } - for unused in [250, 251, 252, 254] { + assert_eq!( + GasId::from_name("reservoir_kept_percent"), + Some(GasId::reservoir_kept_percent()) + ); + assert_eq!( + GasId::reservoir_kept_percent().name(), + "reservoir_kept_percent" + ); + for unused in [246, 247, 248, 250, 251, 252, 253, 254] { assert_eq!(GasId::new(unused).name(), "unknown", "{unused} is unused"); } } - /// Tables that lack the fork's share entries, each as a consumer could hold one: all zeros; + /// Tables that lack the fork's share entry, each as a consumer could hold one: all zeros; /// upstream's table, which has no entry above id 49, as is a table of the fork's release before - /// the shares, whose one entry above it (id 255) is zero by default; that table with the + /// the share, whose one entry above it (id 255) is zero by default; that table with the /// forward percentage an earlier revision put at id 254, at its default of 100 and at the 98 a /// consumer set; and with the forward percentages a later one put at ids 254 and 250 to 252, /// at their default of 100. @@ -1969,18 +1855,15 @@ mod tests { ] } - /// Whether `params` forwards the whole reservoir and every whole pool, as upstream does. + /// Whether `params` forwards the whole reservoir, as upstream does. fn forwards_everything(params: &GasParams) -> bool { - [0, 1, 99, 1_000, u64::MAX].into_iter().all(|amount| { - params.reservoir_forward_share(amount) == amount - && PoolId::ALL - .into_iter() - .all(|pool| params.pool_forward_share(pool, amount) == amount) - }) + [0, 1, 99, 1_000, u64::MAX] + .into_iter() + .all(|amount| params.reservoir_forward_share(amount) == amount) } - /// A table built raw, without the fork's share entries, forwards the whole reservoir and every - /// whole pool, as upstream does, and never nothing. + /// A table built raw, without the fork's share entry, forwards the whole reservoir, as + /// upstream does, and never nothing. #[test] fn test_a_raw_table_without_the_share_entries_forwards_everything() { for (name, table) in tables_without_the_share_entries() { @@ -1991,8 +1874,8 @@ mod tests { } } - /// A schedule encoded without the fork's share entries decodes to one that forwards the whole - /// reservoir and every whole pool. + /// A schedule encoded without the fork's share entry decodes to one that forwards the whole + /// reservoir. #[cfg(feature = "serde")] #[test] fn test_a_schedule_encoded_without_the_share_entries_forwards_everything() { @@ -2031,29 +1914,6 @@ mod tests { assert_eq!(params.call_stipend_reduction(99), 98); } - /// No schedule gives a value call's child a history allowance. - #[test] - fn test_call_history_allowance_defaults_to_zero() { - for spec in [SpecId::FRONTIER, SpecId::OSAKA, SpecId::AMSTERDAM] { - assert_eq!( - GasParams::new_spec(spec).call_history_allowance(), - 0, - "{spec:?}" - ); - } - let mut params = GasParams::new_spec(SpecId::OSAKA); - params.override_gas([(GasId::call_history_allowance(), 160)]); - assert_eq!(params.call_history_allowance(), 160); - assert_eq!( - GasId::from_name("call_history_allowance"), - Some(GasId::call_history_allowance()) - ); - assert_eq!( - GasId::call_history_allowance().name(), - "call_history_allowance" - ); - } - #[test] fn test_max_refund_quotient_defaults_and_override() { let frontier = GasParams::new_spec(SpecId::FRONTIER); diff --git a/crates/context/interface/src/context.rs b/crates/context/interface/src/context.rs index 9c98f740f2..86ad87cdec 100644 --- a/crates/context/interface/src/context.rs +++ b/crates/context/interface/src/context.rs @@ -2,8 +2,7 @@ //! Context trait and related types. pub use crate::journaled_state::StateLoad; use crate::{ - cfg::gas::GasTracker, result::FromStringError, Block, Cfg, Database, Host, JournalTr, - LocalContextTr, Transaction, + result::FromStringError, Block, Cfg, Database, Host, JournalTr, LocalContextTr, Transaction, }; use auto_impl::auto_impl; use primitives::{Bytes, StorageValue}; @@ -181,21 +180,14 @@ pub trait ContextTr: Host { /// [`gas_before`](CodeDeposit::gas_before) does not: an admitted deposit returns with the /// record, and a refused one, put back to `gas_before`, discards it. /// - /// `gas` is the creating frame's tracker, as [`gas_after`](CodeDeposit::gas_after) reads it - /// when the hook is called. The hook may debit and credit it, for instance draw the deployed - /// code from one of the frame's pools - /// ([`GasTracker::record_pool`](crate::cfg::gas::GasTracker::record_pool)); a charge it - /// makes that fails records as any failed charge does. - /// /// - `Ok(())` admits it: the checkpoint is committed and the code is written, as without this - /// hook, and the frame returns with `gas` as the hook left it. + /// hook. /// - `Err(output)` refuses it: the checkpoint is reverted, so no state change of the creation /// is kept and no code is written; the frame's gas is put back to - /// [`gas_before`](CodeDeposit::gas_before), so none of the deposit's charges is paid and - /// whatever the hook did to `gas` is undone, a crossing its failed draw recorded included; - /// and the creation ends as a `Revert` with `output` as its revert data. From there it - /// settles as a creation whose init code reverted: its caller gets its unspent gas back, a - /// zero address and `output` as return data. + /// [`gas_before`](CodeDeposit::gas_before), so none of the deposit's charges is paid; and the + /// creation ends as a `Revert` with `output` as its revert data. From there it settles as a + /// creation whose init code reverted: its caller gets its unspent gas back, a zero address + /// and `output` as return data. /// /// The deposit's charges are made before it is offered, and with them the lookup of its state /// gas price through [`Host::state_gas_price`]. So that lookup is made whether or not the @@ -205,14 +197,10 @@ pub trait ContextTr: Host { /// [`Host::state_gas_price`] lookup does, and refuses; the transaction then returns the /// error. /// - /// The default admits every deposit and leaves `gas` alone. + /// The default admits every deposit. #[inline] - fn admit_code_deposit( - &mut self, - deposit: &CodeDeposit<'_>, - gas: &mut GasTracker, - ) -> Result<(), Bytes> { - let _ = (deposit, gas); + fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + let _ = deposit; Ok(()) } } diff --git a/crates/context/interface/src/context/code_deposit.rs b/crates/context/interface/src/context/code_deposit.rs index df5aaf462e..54af68ec39 100644 --- a/crates/context/interface/src/context/code_deposit.rs +++ b/crates/context/interface/src/context/code_deposit.rs @@ -16,9 +16,7 @@ use primitives::{Address, Bytes}; /// /// The charges are read off the two trackers: [`gas_before`](Self::gas_before), the creating /// frame's gas before the first deposit charge, and [`gas_after`](Self::gas_after), the same gas -/// with every deposit charge recorded. Nothing else touches the frame's gas between the two. Both -/// are as `return_create` left them: the hook is lent the frame's gas itself beside the deposit, -/// and what it does to that gas shows on neither. +/// with every deposit charge recorded. Nothing else touches the frame's gas between the two. /// /// The fields are public to read. The type is `#[non_exhaustive]`, so it is built with /// [`new`](Self::new) outside this crate, and a field added later is not a breaking change. @@ -34,7 +32,7 @@ pub struct CodeDeposit<'a> { /// gas back to this. pub gas_before: &'a GasTracker, /// The creating frame's gas with every deposit charge recorded: what the frame returns with - /// when the deposit is admitted, unless the hook charges the gas it is lent. + /// when the deposit is admitted. /// /// Before Homestead, when the frame could not pay the code-deposit cost, nothing was charged /// and [`code`](Self::code) is empty. If that failed charge was a crossing of the frame's diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index f6a1a50c2e..f93388e30f 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -131,14 +131,11 @@ pub trait Host { /// charging nothing after the hook: the frame's input takes the schedule's share of the /// reservoir in `gas`, or the child's reservoir the hook names on `start` if it took that out /// of `gas` itself ([`FrameStart::reservoir`]). A charge the hook makes that fails records as - /// any failed charge does - /// ([`GasTracker::failed_charge_remaining`]), whatever the answer. The part of its charge - /// that the frame's failure gives back, the hook declares on `start` - /// ([`FrameStart::charge`]). `true` goes on to start the frame, which the handler may still - /// refuse or answer without running it, and the frame's input carries the declared charge. - /// `false` fails the instruction out of gas and starts no frame: the forward stays taken - /// unless the hook gave it back, the declared charge goes with the start, and the halt - /// records the regular gas the hook left unless a failed charge already did. + /// any failed charge does ([`GasTracker::failed_charge_remaining`]), whatever the answer. + /// `true` goes on to start the frame, which the handler may still refuse or answer without + /// running it. `false` fails the instruction out of gas and starts no frame: the forward stays + /// taken unless the hook gave it back, and the halt records the regular gas the hook left + /// unless a failed charge already did. /// /// The default returns `true` and touches nothing. #[inline] diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index b7e12cf070..d3fbe93f7a 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -6,10 +6,7 @@ //! and credit it; the instruction goes on with the gas as the hook left it. Their defaults touch //! nothing and let the instruction go on. -use crate::{ - cfg::gas::{PoolAmounts, StartCharge}, - context::{SStoreResult, SelfDestructResult}, -}; +use crate::context::{SStoreResult, SelfDestructResult}; use primitives::{Address, Bytes, StorageKey, U256}; /// A state write an instruction completed: the write is in the journal, and every charge the @@ -93,9 +90,8 @@ pub enum FrameStartKind { /// A frame an instruction is about to start: every charge the instruction makes has been made, the /// gas it forwards has been taken from the caller, and the frame's input is not built yet. /// -/// The hook is handed it mutably to declare the start's [`charge`](Self::charge) and, if it takes -/// the child's reservoir itself, the child's [`reservoir`](Self::reservoir); the instruction reads -/// nothing else back. +/// The hook is handed it mutably to name the child's [`reservoir`](Self::reservoir) if it takes +/// that itself; the instruction reads nothing else back. /// /// Built with [`FrameStart::new`], so a later field is not a breaking change. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -124,18 +120,14 @@ pub struct FrameStart { /// The regular gas the instruction took from the caller for the frame: the frame's gas limit /// without a value call's stipend, which the caller does not pay. pub forward: u64, - /// The start charge: what the hook charged the caller for this start that the frame's failure - /// gives back. Empty when the hook is called; the hook declares it here after charging it, - /// and the instruction copies it onto the frame's input if the hook admits the start. - pub charge: StartCharge, /// The child's reservoir, when the hook took it out of the caller's reservoir itself. `None` /// when the hook is called. /// /// `None` leaves the forward to the instruction, which takes the schedule's share of the /// caller's reservoir as the hook left it ([`GasTracker::forward_to_child`]). `Some` is the /// reservoir the frame's input carries: the instruction takes no share of its own, and the - /// caller keeps the reservoir the hook left it. The pools are forwarded by the schedule - /// either way. The instruction does not check the amount against what the hook took. + /// caller keeps the reservoir the hook left it. The instruction does not check the amount + /// against what the hook took. /// /// [`GasTracker::forward_to_child`]: crate::cfg::gas::GasTracker::forward_to_child pub reservoir: Option<u64>, @@ -157,7 +149,6 @@ impl FrameStart { target, value, forward, - charge: StartCharge::new(0, PoolAmounts::ZERO), reservoir: None, } } diff --git a/crates/context/tests/schedule_shares.rs b/crates/context/tests/schedule_shares.rs index b24b31f0fb..0b53d26a3b 100644 --- a/crates/context/tests/schedule_shares.rs +++ b/crates/context/tests/schedule_shares.rs @@ -1,12 +1,9 @@ -//! A configuration whose gas schedule lacks the fork's share entries forwards a child frame the -//! whole reservoir and every whole pool, as upstream does: the schedule a consumer builds raw and +//! A configuration whose gas schedule lacks the fork's share entry forwards a child frame the +//! whole reservoir, as upstream does: the schedule a consumer builds raw and //! hands to the configuration, and the one it decodes from a configuration encoded before the //! entries existed. -use context_interface::{ - cfg::{gas::PoolId, GasParams}, - Cfg, -}; +use context_interface::{cfg::GasParams, Cfg}; use primitives::hardfork::SpecId; use revm_context::CfgEnv; use std::sync::Arc; @@ -39,15 +36,12 @@ fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 4] { ] } -/// Whether `cfg`'s schedule forwards the whole reservoir and every whole pool. +/// Whether `cfg`'s schedule forwards the whole reservoir. fn forwards_everything(cfg: &CfgEnv) -> bool { let params = cfg.gas_params(); - [0, 1, 99, 1_000, u64::MAX].into_iter().all(|amount| { - params.reservoir_forward_share(amount) == amount - && PoolId::ALL - .into_iter() - .all(|pool| params.pool_forward_share(pool, amount) == amount) - }) + [0, 1, 99, 1_000, u64::MAX] + .into_iter() + .all(|amount| params.reservoir_forward_share(amount) == amount) } /// Each way to give a configuration a schedule other than the spec's default: at construction, diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index aa8767410e..426cd44176 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -6,7 +6,7 @@ use context_interface::{ }; use interpreter::{ CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - GasTracker, PoolAmounts, StartCharge, + GasTracker, }; use primitives::{Address, TxKind}; use state::Bytecode; @@ -16,11 +16,10 @@ mod first_frame; pub use first_frame::settle_first_frame; /// Creates the first [`FrameInput`] from the transaction and the -/// transaction-level `gas`, forwarding all remaining regular gas, the -/// reservoir and every pool to the frame. The reservoir and the pools are taken -/// out of `gas` ([`GasTracker::forward_all_to_child`]), as a frame start takes -/// a child's shares out of its caller's, and come back when the frame settles -/// into `gas`. +/// transaction-level `gas`, forwarding all remaining regular gas and the +/// reservoir to the frame. The reservoir is taken out of `gas` +/// ([`GasTracker::forward_all_to_child`]), as a frame start takes a child's share +/// out of its caller's, and comes back when the frame settles into `gas`. /// /// Under EIP-2780 this completes the runtime gas phase started at /// pre-execution (the authorization charges): the target is loaded once and @@ -125,8 +124,8 @@ pub fn create_init_frame<CTX: ContextTr>( } } - // The transaction's frame gets the whole reservoir and every whole pool, taken out - // of the transaction's gas: the schedule's shares are for the frames below it. + // The transaction's frame gets the whole reservoir, taken out of the transaction's + // gas: the schedule's share is for the frames below it. let shares = gas.forward_all_to_child(); Ok(Some(FrameInput::Call(Box::new(CallInputs { input: CallInput::Bytes(input), @@ -141,12 +140,6 @@ pub fn create_init_frame<CTX: ContextTr>( return_memory_offset: 0..0, reservoir: shares.reservoir, charged_new_account_state_gas, - // No start charge until a consumer that charged the transaction's gas for the - // frame puts one on this input (`Handler::first_frame_input`), and no allowance, - // which is a value call's below the transaction. - charged_start: StartCharge::new(0, PoolAmounts::ZERO), - pool_shares: shares.pools, - history_allowance: 0, })))) } TxKind::Create => { @@ -192,7 +185,6 @@ pub fn create_init_frame<CTX: ContextTr>( ); inputs.set_charged_create_state_gas(charged_create_state_gas); inputs.set_charged_state_gas_address(charged_state_gas_address); - inputs.set_pool_shares(shares.pools); Ok(Some(FrameInput::Create(Box::new(inputs)))) } } diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index 1805860655..e3c1ea4567 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -5,7 +5,7 @@ use crate::{frame::handle_reservoir_remaining_gas, FrameResult}; use context::result::FromStringError; use context_interface::{context::take_error, ContextTr, Database}; -use interpreter::{GasTracker, PoolId}; +use interpreter::GasTracker; use std::string::ToString; /// Settles the transaction's frame, the first frame, into the transaction-level `gas`, every step @@ -15,20 +15,16 @@ use std::string::ToString; /// The steps, each with the halt rule it takes: /// - `gas` spends all its regular gas, which was forwarded to the frame, and the frame settles /// into it as a child settles into its caller ([`handle_reservoir_remaining_gas`]): a failing -/// frame rolls back its state gas, history gas and pool draws, a halt consumes its regular gas, -/// and what the frame left returns to `gas`, its reservoir and its pools added to what `gas` -/// kept, which is nothing, since the frame took them whole; +/// frame rolls back its state gas and history gas, a halt consumes its regular gas, and what +/// the frame left returns to `gas`, its reservoir added to what `gas` kept, which is nothing, +/// since the frame took it whole; /// - the EIP-2780 refundable first-frame charge is refunded when no account leaf was created, /// priced through [`Host::state_gas_charge`](context_interface::Host::state_gas_charge) as it -/// was charged; after a halt the regular gas the refund credited is consumed; -/// - the start charge a consumer declared on the first frame's input -/// ([`FrameResult::refundable_start_charge`]) is refunded whole when the frame failed; after a -/// halt the regular gas the refund credited is consumed. +/// was charged; after a halt the regular gas the refund credited is consumed. /// -/// `gas` holds no reservoir and no limited pool on entry: the first frame took them whole +/// `gas` holds no reservoir on entry: the first frame took it whole /// ([`GasTracker::forward_all_to_child`]), and the settlement adds back what the frame left, so /// gas that still held what the frame was given would count it twice. A debug build asserts it. -/// An unlimited pool is exempt, since what comes back saturates at it. /// /// A chain whose handler overrides `last_frame_result` calls this rather than copying the mainnet /// body, so a step the fork adds here reaches its handler too. It applies its own rules to `gas` @@ -59,13 +55,6 @@ where "the transaction's gas still holds the reservoir its frame was given; the settlement \ would count it twice (take it with `GasTracker::forward_all_to_child`)" ); - debug_assert!( - PoolId::ALL - .into_iter() - .all(|pool| matches!(gas.pool_remaining(pool), 0 | u64::MAX)), - "the transaction's gas still holds a pool its frame was given; the settlement would \ - count it twice (take it with `GasTracker::forward_all_to_child`)" - ); // All regular gas was forwarded to the first frame: consume it on the // transaction-level gas; the settle below returns the frame's unused @@ -104,15 +93,5 @@ where } } - // Refund the start charge a consumer put on the first frame's input for what it charged - // the transaction's gas, whole, on the same condition and with the same halt rule, - // exactly like `EthFrame::return_result` refunds the start charges of inner frames. - if let Some(charge) = frame_result.refundable_start_charge() { - gas.refill_start_charge(charge); - if instruction_result.is_halt() { - gas.spend_all(); - } - } - Ok(()) } diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 67ff82241a..bbfd4a68a6 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -18,7 +18,7 @@ use interpreter::{ interpreter_types::ReturnData, CallInput, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, CreateScheme, FrameInput, Gas, GasTracker, InputsImpl, InstructionResult, Interpreter, InterpreterAction, - InterpreterResult, InterpreterTypes, OutcomeMark, SharedMemory, StartCharge, + InterpreterResult, InterpreterTypes, OutcomeMark, SharedMemory, }; use primitives::{ constants::CALL_STACK_LIMIT, @@ -159,16 +159,8 @@ impl EthFrame<EthInterpreter> { let reservoir_remaining_gas = inputs.reservoir; let charged_new_account_state_gas = inputs.charged_new_account_state_gas; let charged_state_gas_address = inputs.target_address; - let charged_start = inputs.charged_start; - // The child's pools are the shares its caller forwarded, and its history allowance what - // the call instruction gave it; both ride on the frame's gas, as the reservoir does, - // whether the handler runs the frame or answers the start without one. - let pool_shares = inputs.pool_shares; - let history_allowance = inputs.history_allowance; - let mut gas = + let gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas); - gas.tracker_mut().set_pools_remaining(pool_shares); - gas.set_history_allowance(history_allowance); let return_result = |instruction_result: InstructionResult| { Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome { @@ -182,7 +174,6 @@ impl EthFrame<EthInterpreter> { precompile_call_logs: Vec::new(), charged_new_account_state_gas, charged_state_gas_address, - charged_start, start_mark: OutcomeMark::NONE, }))) }; @@ -219,14 +210,7 @@ impl EthFrame<EthInterpreter> { let is_static = inputs.is_static; let gas_limit = inputs.gas_limit; - if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { - // The provider built the answer's gas from the inputs' regular gas and reservoir. The - // answer takes the caller's shares as the pools it started with, less what the - // provider drew on them (a draw past a share is held to it, with the pool's - // crossing), and the allowance the input carries, so the caller's settlement gets - // the shares back from the answer as it would from a frame. - result.gas.tracker_mut().adopt_pool_shares(pool_shares); - result.gas.set_history_allowance(history_allowance); + if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { let mut logs = Vec::new(); if result.result.is_ok() { // Preserve the reservoir on the result gas so it can be reimbursed. @@ -245,7 +229,6 @@ impl EthFrame<EthInterpreter> { precompile_call_logs: logs, charged_new_account_state_gas, charged_state_gas_address, - charged_start, start_mark: OutcomeMark::NONE, }))); } @@ -260,8 +243,7 @@ impl EthFrame<EthInterpreter> { } // Create interpreter and executes call and push new CallStackFrame. - let frame = this.get(EthFrame::invalid); - frame.clear( + this.get(EthFrame::invalid).clear( FrameData::Call(CallFrame { return_memory_range: inputs.return_memory_offset.clone(), }), @@ -276,15 +258,6 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); - frame - .interpreter - .gas - .tracker_mut() - .set_pools_remaining(pool_shares); - frame - .interpreter - .gas - .set_history_allowance(history_allowance); Ok(ItemOrResult::Item(this.consume())) } @@ -311,27 +284,19 @@ impl EthFrame<EthInterpreter> { // Recorded by whoever made the charge — the CREATE opcode or the EIP-2780 runtime phase // — because the created address is not derivable here on the early-fail paths. let charged_state_gas_address = inputs.charged_state_gas_address(); - let charged_start = inputs.charged_start(); - // The creation's pools are the shares its caller forwarded; they ride on the frame's - // gas, as the reservoir does, on an early failure too, so the caller's settlement gets - // them back. - let pool_shares = inputs.pool_shares(); let return_error = |e| { - let mut gas = Gas::new_with_regular_gas_and_reservoir( - inputs.gas_limit(), - reservoir_remaining_gas, - ); - gas.tracker_mut().set_pools_remaining(pool_shares); Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome { result: InterpreterResult { result: e, - gas, + gas: Gas::new_with_regular_gas_and_reservoir( + inputs.gas_limit(), + reservoir_remaining_gas, + ), output: Bytes::new(), }, address: None, charged_create_state_gas, charged_state_gas_address, - charged_start, start_mark: OutcomeMark::NONE, }))) }; @@ -394,8 +359,7 @@ impl EthFrame<EthInterpreter> { }; let gas_limit = inputs.gas_limit(); - let frame = this.get(EthFrame::invalid); - frame.clear( + this.get(EthFrame::invalid).clear( FrameData::Create(CreateFrame { created_address }), FrameInput::Create(inputs), depth, @@ -408,11 +372,6 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); - frame - .interpreter - .gas - .tracker_mut() - .set_pools_remaining(pool_shares); Ok(ItemOrResult::Item(this.consume())) } @@ -484,21 +443,16 @@ impl EthFrame<EthInterpreter> { // Propagate EIP-8037 new-account state-gas flag from the frame // input so the parent can refund the upfront charge if the call // ends in revert/halt. - // The start charge rides along for the same refund. - let (charged_new_account_state_gas, charged_state_gas_address, charged_start) = - match &self.input { - FrameInput::Call(inputs) => ( - inputs.charged_new_account_state_gas, - inputs.target_address, - inputs.charged_start, - ), - _ => (false, Address::ZERO, StartCharge::default()), - }; + let (charged_new_account_state_gas, charged_state_gas_address) = match &self.input { + FrameInput::Call(inputs) => { + (inputs.charged_new_account_state_gas, inputs.target_address) + } + _ => (false, Address::ZERO), + }; let mut outcome = CallOutcome::new(interpreter_result, frame.return_memory_range.clone()); outcome.charged_new_account_state_gas = charged_new_account_state_gas; outcome.charged_state_gas_address = charged_state_gas_address; - outcome.charged_start = charged_start; ItemOrResult::Result(FrameResult::Call(outcome)) } FrameData::Create(frame) => { @@ -515,18 +469,15 @@ impl EthFrame<EthInterpreter> { // inputs carry the address the charge site recorded, which is the one the // refund must use. An uncharged creation leaves it zero, so the field is // meaningful only when `charged_create_state_gas` is set. - let (charged_create_state_gas, charged_state_gas_address, charged_start) = - match &self.input { - FrameInput::Create(inputs) => ( - inputs.charged_create_state_gas(), - inputs.charged_state_gas_address(), - inputs.charged_start(), - ), - _ => (false, Address::ZERO, StartCharge::default()), - }; + let (charged_create_state_gas, charged_state_gas_address) = match &self.input { + FrameInput::Create(inputs) => ( + inputs.charged_create_state_gas(), + inputs.charged_state_gas_address(), + ), + _ => (false, Address::ZERO), + }; create_outcome.charged_create_state_gas = charged_create_state_gas; create_outcome.charged_state_gas_address = charged_state_gas_address; - create_outcome.charged_start = charged_start; ItemOrResult::Result(FrameResult::Create(create_outcome)) } }; @@ -563,10 +514,6 @@ impl EthFrame<EthInterpreter> { }, None => None, }; - // The start charge the frame-start hook charged this (parent) frame and declared on the - // start is refunded on the same condition, whole, by the same two refills a consumer's - // own take-back uses; it needs no price lookup, since the hook declared the amounts. - let refund_start_charge = result.refundable_start_charge(); // Insert result to the top frame. match result { @@ -657,12 +604,6 @@ impl EthFrame<EthInterpreter> { if let Some(charge) = refund_state_gas { self.interpreter.gas.refill_reservoir(charge); } - if let Some(charge) = refund_start_charge { - self.interpreter - .gas - .tracker_mut() - .refill_start_charge(charge); - } Ok(()) } @@ -690,14 +631,6 @@ impl EthFrame<EthInterpreter> { /// - net state gas, net history gas, the spilled portion, and the refund counter /// persist only on success; on revert/halt the child's state changes roll back /// and contribute nothing. -/// - each pool settles as the reservoir does, not as regular gas: the child's -/// rollback gives its draws back to its pools, so what it hands back is its -/// remaining pool on success and the whole share it was given on revert *and on -/// halt*, since a halted frame draws nothing; the parent, which kept what it -/// did not forward, always absorbs it. The child's net draws merge into the -/// parent's on success only, as the history net does, so a later rollback of -/// the parent undoes the child's draws too. With no pool set, every figure here -/// is the unlimited pool going out and coming back. #[inline] pub const fn handle_reservoir_remaining_gas( instruction_result: InstructionResult, @@ -743,7 +676,6 @@ pub const fn handle_reservoir_remaining_gas( parent_gas.record_refund(child_gas.refunded()); } parent_gas.absorb_returned_reservoir(child_gas.reservoir()); - parent_gas.absorb_returned_pools(child_gas, instruction_result.is_ok()); } /// Handles the result of a CREATE operation, including validation and state updates. @@ -910,7 +842,6 @@ pub fn return_create<CTX: ContextTr>( #[cfg(test)] mod tests { use super::*; - use interpreter::PoolId; #[test] fn sibling_refill_restores_parent_regular_gas() { @@ -947,135 +878,6 @@ mod tests { assert_eq!(parent.state_gas_spilled(), 0); } - /// A child with `share` of each of its caller's pools. - fn child_with_share(parent: &mut GasTracker, share: u64) -> GasTracker { - let mut child = GasTracker::new(500, 500, 0); - for pool in PoolId::ALL { - parent.forward_pool(pool, share); - child.set_pool_remaining(pool, share); - } - child - } - - /// A tracker with every pool at 1,000. - fn pools_1000() -> GasTracker { - let mut tracker = GasTracker::new(1_000, 1_000, 0); - for pool in PoolId::ALL { - tracker.set_pool_remaining(pool, 1_000); - } - tracker - } - - /// `(remaining, spent)` of every pool. - fn pools(tracker: &GasTracker) -> [(u64, i64); PoolId::COUNT] { - PoolId::ALL.map(|pool| (tracker.pool_remaining(pool), tracker.pool_spent(pool))) - } - - /// A child that succeeds hands back what it left of each share and its net draws; one that - /// reverts or halts hands back the whole shares, its draws undone, and no net. The caller - /// kept what it did not forward either way, and each pool settles alone. - #[test] - fn test_the_pools_settle_like_the_reservoir_not_like_regular_gas() { - for result in [ - InstructionResult::Stop, - InstructionResult::Revert, - InstructionResult::OutOfGas, - ] { - let mut parent = pools_1000(); - for pool in PoolId::ALL { - assert!(parent.record_pool(pool, 100)); - } - let mut child = child_with_share(&mut parent, 800); - assert_eq!(pools(&parent), [(100, 100); 3], "{result:?}: kept back"); - let [first, second, third] = PoolId::ALL; - assert!(child.record_pool(first, 300)); - assert!(child.record_pool(second, 1)); - child.refill_pool(third, 10); - - handle_reservoir_remaining_gas(result, &mut parent, &mut child); - - if result.is_ok() { - assert_eq!(pools(&parent), [(600, 400), (899, 101), (910, 90)]); - assert_eq!(pools(&child), [(500, 300), (799, 1), (810, -10)]); - } else { - assert_eq!(pools(&parent), [(900, 100); 3], "{result:?}"); - assert_eq!( - pools(&child), - [(800, 0); 3], - "{result:?}: a failed child's pools read as its shares" - ); - } - } - } - - /// A caller's rollback undoes the draws of a child that succeeded inside it: B's revert - /// gives A back the whole share it forwarded, C's draws included. - #[test] - fn test_a_callers_rollback_undoes_a_successful_childs_draws() { - let mut a = pools_1000(); - let mut b = child_with_share(&mut a, 1_000); - for pool in PoolId::ALL { - assert!(b.record_pool(pool, 100)); - } - let mut c = child_with_share(&mut b, 900); - for pool in PoolId::ALL { - assert!(c.record_pool(pool, 100)); - } - - handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); - assert_eq!(pools(&b), [(800, 200); 3]); - - handle_reservoir_remaining_gas(InstructionResult::Revert, &mut a, &mut b); - assert_eq!(pools(&a), [(1_000, 0); 3]); - } - - /// A child that gives back a draw its caller made goes below zero, and merging it into the - /// caller on success nets the two out, as a history refill does; on failure the refill is - /// undone with the rest. - #[test] - fn test_a_childs_refill_of_a_callers_draw_nets_out_on_success_only() { - for result in [InstructionResult::Stop, InstructionResult::Revert] { - let mut parent = pools_1000(); - for pool in PoolId::ALL { - assert!(parent.record_pool(pool, 100)); - } - let mut child = child_with_share(&mut parent, 900); - for pool in PoolId::ALL { - child.refill_pool(pool, 100); - } - assert_eq!(pools(&child), [(1_000, -100); 3]); - - handle_reservoir_remaining_gas(result, &mut parent, &mut child); - - let settled = if result.is_ok() { - (1_000, 0) - } else { - (900, 100) - }; - assert_eq!(pools(&parent), [settled; 3], "{result:?}"); - } - } - - /// With no pool set, the unlimited pools go out whole and come back, less only what was - /// drawn and kept, and the regular-gas settlement is what it was. - #[test] - fn test_unset_pools_settle_to_the_same_regular_gas() { - for result in [InstructionResult::Stop, InstructionResult::OutOfGas] { - let mut parent = GasTracker::new(1_000, 1_000, 0); - assert!(parent.record_regular_cost(500)); - let mut with_pools = parent; - let mut child = child_with_share(&mut with_pools, u64::MAX); - assert!(child.record_regular_cost(200)); - let mut plain_child = child; - - handle_reservoir_remaining_gas(result, &mut with_pools, &mut child); - handle_reservoir_remaining_gas(result, &mut parent, &mut plain_child); - - assert_eq!(with_pools.remaining(), parent.remaining(), "{result:?}"); - assert_eq!(pools(&with_pools), [(u64::MAX, 0); 3], "{result:?}"); - } - } - /// A caller that forwarded a share of its reservoir and kept the rest gets back, on top of /// what it kept: what the child left when it succeeded, the whole share when it reverted or /// halted, the child's state charges undone. Regular gas settles as it did. diff --git a/crates/handler/src/frame/code_deposit.rs b/crates/handler/src/frame/code_deposit.rs index 1f1e03ebf8..47a0728695 100644 --- a/crates/handler/src/frame/code_deposit.rs +++ b/crates/handler/src/frame/code_deposit.rs @@ -10,14 +10,13 @@ use primitives::Address; /// ([`ContextTr::admit_code_deposit`]), and returns whether it did. /// /// `interpreter_result` holds the code and the creating frame's gas with every deposit charge -/// recorded; `gas_before_deposit` is that gas before the first of them. The hook reads a copy of -/// the frame's gas as the deposit's `gas_after` and is lent the gas itself, which it may charge. A -/// refused deposit reverts `checkpoint`, puts the frame's gas back to `gas_before_deposit`, which -/// undoes whatever the hook did to it, and turns the result into a `Revert` carrying the output -/// the context named; `return_create` then returns without committing. +/// recorded; `gas_before_deposit` is that gas before the first of them. A refused deposit reverts +/// `checkpoint`, puts the frame's gas back to `gas_before_deposit` and turns the result into a +/// `Revert` carrying the output the context named; `return_create` then returns without +/// committing. /// -/// Inlined into `return_create`, so under the default hook, which admits and touches nothing, it -/// compiles away with the copies of the frame's gas it reads. +/// Inlined into `return_create`, so under the default hook, which admits, it compiles away with +/// the copy of the frame's gas it reads. #[inline(always)] pub(super) fn admit_code_deposit<CTX: ContextTr>( context: &mut CTX, @@ -26,16 +25,12 @@ pub(super) fn admit_code_deposit<CTX: ContextTr>( gas_before_deposit: &Gas, address: Address, ) -> bool { - let gas_after_deposit = interpreter_result.gas; - let admitted = context.admit_code_deposit( - &CodeDeposit::new( - address, - &interpreter_result.output, - gas_before_deposit.tracker(), - gas_after_deposit.tracker(), - ), - interpreter_result.gas.tracker_mut(), - ); + let admitted = context.admit_code_deposit(&CodeDeposit::new( + address, + &interpreter_result.output, + gas_before_deposit.tracker(), + interpreter_result.gas.tracker(), + )); let Err(output) = admitted else { return true; }; diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index fd3a8c3c16..cfda9f3844 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -3,9 +3,7 @@ use context_interface::{ result::Output, }; use core::ops::Range; -use interpreter::{ - CallOutcome, CreateOutcome, Gas, InstructionResult, InterpreterResult, StartCharge, -}; +use interpreter::{CallOutcome, CreateOutcome, Gas, InstructionResult, InterpreterResult}; use primitives::Address; /// Call Frame @@ -173,31 +171,6 @@ impl FrameResult { } } -impl FrameResult { - /// The start charge to refund, or `None` when there is nothing to refund: the frame - /// succeeded, or its start charged nothing. - /// - /// The frame-start hook charged the caller's gas before the frame ran and declared the charge - /// on the start (a consumer declares the transaction frame's on its input), and it rides on - /// the outcome's `charged_start`. The decision is the one - /// [`Self::refundable_state_gas_charge`] makes: a call refunds when it did not succeed, a - /// creation also when no contract address was deployed. The charge is refunded whole, with - /// `GasTracker::refill_start_charge`. - #[inline] - pub fn refundable_start_charge(&self) -> Option<StartCharge> { - let (failed, charge) = match self { - FrameResult::Call(outcome) => { - (!outcome.instruction_result().is_ok(), outcome.charged_start) - } - FrameResult::Create(outcome) => ( - outcome.address.is_none() || !outcome.instruction_result().is_ok(), - outcome.charged_start, - ), - }; - (failed && !charge.is_zero()).then_some(charge) - } -} - impl FrameData { /// Creates a new create frame data. pub const fn new_create(created_address: Address) -> Self { diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index a57ae7a4b7..697a673413 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -334,17 +334,13 @@ pub trait Handler { // start. lifecycle::open_transaction_start(evm)?; let tx_gas_limit = evm.ctx().tx().gas_limit(); - // The stand-in takes the whole reservoir and every pool out of the transaction's gas, as - // the first frame would (`create_init_frame`), so the settle adds them back once. + // The stand-in takes the whole reservoir out of the transaction's gas, as the first frame + // would (`create_init_frame`), so the settle adds it back once. let shares = gas.forward_all_to_child(); let mut frame_result = match evm.ctx().tx().kind() { TxKind::Call(_) => FrameResult::new_call_oog(tx_gas_limit, 0..0, shares.reservoir), TxKind::Create => FrameResult::new_create_oog(tx_gas_limit, shares.reservoir), }; - frame_result - .gas_mut() - .tracker_mut() - .set_pools_remaining(shares.pools); self.last_frame_result(evm, &mut frame_result, gas)?; Ok(frame_result) } @@ -522,8 +518,7 @@ pub trait Handler { /// The settled transaction-level gas is written back to the frame result, /// which carries it into the post-execution phase. /// - /// The settlement is [`execution::settle_first_frame`], which also refunds - /// the first frame's start charge. It is followed by the close of the + /// The settlement is [`execution::settle_first_frame`]. It is followed by the close of the /// transaction's start ([`lifecycle::close_transaction_start`], given the /// reservoir the gas held before the settlement). An override calls both /// rather than copying this body, and copies the gas into the frame result diff --git a/crates/handler/tests/code_deposit_admission.rs b/crates/handler/tests/code_deposit_admission.rs index 3f4111650c..3ee58db10e 100644 --- a/crates/handler/tests/code_deposit_admission.rs +++ b/crates/handler/tests/code_deposit_admission.rs @@ -5,8 +5,7 @@ //! admission hook, which records every deposit it is offered and admits, refuses with a named //! output, or fails fatally. Each case is compared with a twin: an admitting context against //! [`Context`] itself, and a refused deposit against the same creation whose init code reverts. -//! Two tests call `return_create` directly: on a frame whose regular gas is partly withheld, and -//! on a frame with a pool the hook draws the deposit from. +//! One test calls `return_create` directly, on a frame whose regular gas is partly withheld. use bytecode::opcode::{ CREATE, MSTORE, MSTORE8, PUSH0, PUSH1, PUSH3, PUSH4, RETURN, RETURNDATASIZE, REVERT, SSTORE, @@ -26,7 +25,7 @@ use context_interface::{ }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ - Gas, InstructionResult, InterpreterResult, PoolId, SStoreResult, SelfDestructResult, StateLoad, + Gas, InstructionResult, InterpreterResult, SStoreResult, SelfDestructResult, StateLoad, }; use primitives::{ address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, @@ -43,8 +42,6 @@ type DbError = <Db as Database>::Error; type Outcome = Result<ResultAndState, EVMError<DbError>>; /// Contract the call transactions call. -/// The pool the tests draw: any of the tracker's pools behaves the same. -const FIRST: PoolId = PoolId::new(0); const CONTRACT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Nonce of [`CONTRACT`], so the address its `CREATE` deploys at is known. const CONTRACT_NONCE: u64 = 1; @@ -63,7 +60,7 @@ const REVERT_32: [u8; 4] = [PUSH1, 32, PUSH0, REVERT]; const RETURN_EF: [u8; 8] = [PUSH1, 0xEF, PUSH0, MSTORE8, PUSH1, 1, PUSH0, RETURN]; /// What the context does with a deposit it is offered. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy)] enum Policy { Admit, Refuse, @@ -84,9 +81,6 @@ struct Offered { struct AdmissionContext { inner: MainnetContext<Db>, policy: Policy, - /// Bytes the hook draws from the creating frame's pool before it decides, as a consumer that - /// holds deployed code to a byte budget does; zero draws nothing. - draw: u64, offered: Vec<Offered>, /// The creating frame's gas before and after the deposit's charges, of every deposit offered. offered_gas: Vec<(GasTracker, GasTracker)>, @@ -134,13 +128,7 @@ impl ContextTr for AdmissionContext { self.inner.error() } - fn admit_code_deposit( - &mut self, - deposit: &CodeDeposit<'_>, - gas: &mut GasTracker, - ) -> Result<(), Bytes> { - // A draw the pool cannot pay records the crossing on `gas`, as any failed draw does. - let _ = gas.record_pool(FIRST, self.draw); + fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { self.offered.push(Offered { address: deposit.address, code: deposit.code.clone(), @@ -339,7 +327,6 @@ fn admission_context(db: Db, schedule: Schedule, policy: Policy) -> AdmissionCon AdmissionContext { inner: context(db, schedule), policy, - draw: 0, offered: Vec::new(), offered_gas: Vec::new(), deposit_prices: Vec::new(), @@ -660,18 +647,11 @@ fn return_create_on( history_per_byte: 0, }; let mut ctx = admission_context(db(None), schedule, policy); - let result = return_create_with(&mut ctx, gas, code); - (result, ctx) -} - -/// Calls `return_create` on `ctx` for a creation at [`CONTRACT`] that returned `code` with `gas`, -/// and returns the creation's result. -fn return_create_with<CTX: ContextTr>(ctx: &mut CTX, gas: Gas, code: Bytes) -> InterpreterResult { ctx.journal_mut().load_account(CONTRACT).unwrap(); let checkpoint = ctx.journal_mut().checkpoint(); let mut result = InterpreterResult::new(InstructionResult::Return, code, gas); - return_create(ctx, checkpoint, &mut result, CONTRACT); - result + return_create(&mut ctx, checkpoint, &mut result, CONTRACT); + (result, ctx) } /// Before Homestead a frame that cannot pay the code deposit does not fail: `return_create` @@ -739,96 +719,6 @@ fn test_a_pre_homestead_deposit_the_frame_cannot_pay_is_offered_with_its_crossin assert_eq!(result.result, InstructionResult::OutOfGas); } -/// The hook is lent the creating frame's gas, so it can draw the deployed code's bytes from the -/// frame's pool. A draw on an admitted deposit stays on the frame, a failed one with its crossing; -/// a refusal puts the gas back to `gas_before`, which undoes the draw and discards the crossing. -/// The default hook leaves the gas as the deposit's charges left it. -#[test] -fn test_the_hook_draws_the_deposit_from_the_frames_pool() { - const POOL: u64 = 1_000; - let mut gas = Gas::new(100_000); - gas.set_pool_remaining(FIRST, POOL); - let code = Bytes::from_static(&[0; 32]); - // OSAKA: the deposit is one regular charge, 200 per byte. - let charged = { - let mut charged = gas; - assert!(charged.record_regular_cost(32 * 200)); - charged - }; - let pool = |gas: &Gas| { - ( - gas.pool_remaining(FIRST), - gas.pool_spent(FIRST), - gas.pool_crossing(FIRST), - ) - }; - - let default = return_create_with(&mut context(db(None), SCHEDULES[0]), gas, code.clone()); - assert_eq!(default.result, InstructionResult::Return, "the default"); - assert_eq!( - default.gas, charged, - "the default hook leaves the gas alone" - ); - - for (name, policy, draw, result, figures) in [ - ( - "admitted", - Policy::Admit, - 32, - InstructionResult::Return, - (POOL - 32, 32, false), - ), - ( - "admitted, the draw failed", - Policy::Admit, - POOL + 1, - InstructionResult::Return, - (POOL, 0, true), - ), - ( - "refused", - Policy::Refuse, - 32, - InstructionResult::Revert, - (POOL, 0, false), - ), - ( - "refused, the draw failed", - Policy::Refuse, - POOL + 1, - InstructionResult::Revert, - (POOL, 0, false), - ), - ] { - let mut ctx = admission_context(db(None), SCHEDULES[0], policy); - ctx.draw = draw; - - let returned = return_create_with(&mut ctx, gas, code.clone()); - - assert_eq!(ctx.offered.len(), 1, "{name}"); - assert_eq!(returned.result, result, "{name}"); - assert_eq!(pool(&returned.gas), figures, "{name}"); - let [(before, after)] = ctx.offered_gas[..] else { - panic!("{name}: offered {} times", ctx.offered_gas.len()); - }; - assert_eq!(&before, gas.tracker(), "{name}: gas_before"); - assert_eq!( - &after, - charged.tracker(), - "{name}: gas_after, before the hook drew" - ); - if policy == Policy::Refuse { - assert_eq!(returned.gas, gas, "{name}: put back to gas_before"); - } else { - assert_eq!( - returned.gas.remaining(), - charged.remaining(), - "{name}: the deposit is paid" - ); - } - } -} - /// A hook that fails fatally records the cause and refuses; the transaction returns the cause, /// for a top-level creation and a nested one alike. #[test] diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_share.rs index f542c49949..b1bcd1b96c 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_share.rs @@ -28,7 +28,7 @@ use context_interface::{ use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, PoolAmounts, PoolId, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, }; use primitives::{ address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, TxKind, U256, @@ -106,21 +106,6 @@ const fn returned(result: &FrameResult) -> Returned { ) } -fn pool_shares_of(input: &FrameInput) -> PoolAmounts { - match input { - FrameInput::Call(inputs) => inputs.pool_shares, - FrameInput::Create(inputs) => inputs.pool_shares(), - FrameInput::Empty => unreachable!(), - } -} - -/// Finite pools a consumer gives the transaction's gas: a system call's in -/// [`ShareHandler::tx_gas`], or any transaction's with [`ShareHandler::tx_pools`]. -const LIMITED_POOLS: PoolAmounts = PoolAmounts::ZERO - .with(PoolId::new(0), 1_000) - .with(PoolId::new(1), 500) - .with(PoolId::new(2), 100); - fn reservoir_of(input: &FrameInput) -> u64 { match input { FrameInput::Call(inputs) => inputs.reservoir, @@ -139,8 +124,6 @@ struct ShareHandler { /// A reservoir to give the transaction's gas, as a consumer that splits a system call's gas /// does; mainnet gives a system call none. system_reservoir: Option<u64>, - /// Pools to give the transaction's gas, as a consumer that limits its figures does. - tx_pools: Option<PoolAmounts>, starts: Vec<u64>, returned: Vec<Returned>, /// The transaction's reservoir and net state gas after the first frame settled into it. @@ -149,10 +132,6 @@ struct ShareHandler { tx_reservoir: core::cell::Cell<Option<u64>>, /// The transaction's reservoir once the first frame's input was built. after_first_input: Option<u64>, - /// Every frame's pool shares as it started. - pool_starts: Vec<PoolAmounts>, - /// The transaction's pools after the first frame settled into them. - settled_pools: Option<PoolAmounts>, } impl ShareHandler { @@ -161,14 +140,11 @@ impl ShareHandler { mainnet: Mainnet::default(), too_deep: false, system_reservoir: None, - tx_pools: None, starts: Vec::new(), returned: Vec::new(), settled: None, tx_reservoir: core::cell::Cell::new(None), after_first_input: None, - pool_starts: Vec::new(), - settled_pools: None, } } } @@ -183,11 +159,6 @@ impl Handler for ShareHandler { if let Some(reservoir) = self.system_reservoir { gas.set_remaining(gas.remaining() - reservoir); gas.set_reservoir(reservoir); - // And pools, as a consumer that limits a system call's figures sets them. - gas.set_pools_remaining(LIMITED_POOLS); - } - if let Some(pools) = self.tx_pools { - gas.set_pools_remaining(pools); } self.tx_reservoir.set(Some(gas.reservoir())); gas @@ -213,8 +184,6 @@ impl Handler for ShareHandler { ) -> Result<FrameResult, TestError> { self.starts .push(reservoir_of(&first_frame_input.frame_input)); - self.pool_starts - .push(pool_shares_of(&first_frame_input.frame_input)); if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { self.returned.push(returned(&result)); return Ok(result); @@ -223,7 +192,6 @@ impl Handler for ShareHandler { let result = match evm.frame_run()? { ItemOrResult::Item(mut init) => { self.starts.push(reservoir_of(&init.frame_input)); - self.pool_starts.push(pool_shares_of(&init.frame_input)); if self.too_deep { init.depth = CALL_STACK_LIMIT as usize + 1; } @@ -253,7 +221,6 @@ impl Handler for ShareHandler { ) -> Result<(), TestError> { self.mainnet.last_frame_result(evm, frame_result, gas)?; self.settled = Some((gas.reservoir(), gas.state_gas_spent())); - self.settled_pools = Some(gas.pools_remaining()); Ok(()) } } @@ -716,7 +683,7 @@ fn test_an_answer_without_a_frame_hands_the_share_back() { } /// A system call's frame takes the whole reservoir its gas holds, a consumer's split of the -/// system call's gas, and every whole pool, and its children their shares, as a transaction's do. +/// system call's gas, and its children their shares, as a transaction's do. #[test] fn test_a_system_call_forwards_and_settles_its_reservoir() { for percent in [None, Some(PERCENT)] { @@ -748,10 +715,6 @@ fn test_a_system_call_forwards_and_settles_its_reservoir() { Some((RESERVOIR - CHARGED, CHARGED as i64)), "{percent:?}" ); - // The pools go the same way: the system call's frame takes them whole, the schedule - // forwards them whole, and they come back as they were, nothing drawn. - assert_eq!(handler.pool_starts, [LIMITED_POOLS; 2], "{percent:?}"); - assert_eq!(handler.settled_pools, Some(LIMITED_POOLS), "{percent:?}"); } } @@ -885,11 +848,10 @@ fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { } } -/// The same for a creation transaction, whose runtime phase charges the account it would create, -/// on a transaction's gas a consumer gave finite pools: the stand-in takes the whole reservoir -/// and every pool, and both settle back once. +/// The same for a creation transaction, whose runtime phase charges the account it would create: +/// the stand-in takes the whole reservoir, which settles back once. #[test] -fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the_pools_once() { +fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_once() { const LIMIT: u64 = 160_000; const CAP: u64 = 60_000; for percent in [None, Some(PERCENT)] { @@ -905,10 +867,7 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the .gas_limit(LIMIT) .build_fill(), ); - let mut handler = ShareHandler::new(); - handler.tx_pools = Some(LIMITED_POOLS); - - let (result, handler) = run.with(handler); + let (result, handler) = run.with(ShareHandler::new()); assert!( matches!(result, ExecutionResult::Halt { .. }), @@ -917,7 +876,6 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the let reservoir = handler.tx_reservoir.get().expect("tx_gas ran"); assert!(reservoir > 0, "{percent:?}"); assert_eq!(handler.settled, Some((reservoir, 0)), "{percent:?}"); - assert_eq!(handler.settled_pools, Some(LIMITED_POOLS), "{percent:?}"); assert_eq!( result.gas().total_gas_spent(), LIMIT - reservoir, @@ -926,7 +884,7 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_and_the } } -/// The transaction's frame took the whole reservoir and every whole pool, and its settlement adds +/// The transaction's frame took the whole reservoir, and its settlement adds /// back what it left. A runner that settles the frame into gas that still holds what the frame was /// given, because it built the frame without taking it or seeded the gas from the frame's own /// figures, would count it twice; a debug build refuses the settlement. @@ -941,25 +899,9 @@ fn test_a_first_frame_settled_into_gas_that_kept_the_reservoir_panics_in_a_debug let _ = Mainnet::default().last_frame_result(&mut evm, &mut result, &mut gas); } -/// The same for a pool the transaction's gas still holds. -#[cfg(debug_assertions)] -#[test] -#[should_panic(expected = "the transaction's gas still holds a pool its frame was given")] -fn test_a_first_frame_settled_into_gas_that_kept_a_pool_panics_in_a_debug_build() { - let mut evm = Run::new(ends(Vec::new())).evm(); - let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); - let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); - gas.set_pools_remaining(PoolAmounts::ZERO); - gas.set_pool_remaining(PoolId::new(2), 1_000); - - let _ = Mainnet::default().last_frame_result(&mut evm, &mut result, &mut gas); -} - -/// An unlimited pool the transaction's gas still holds cannot be counted twice, since what comes -/// back saturates at it: a runner that builds the gas with `GasTracker::new` and draws no pool, -/// with no reservoir, settles as before. +/// A runner that builds the gas with `GasTracker::new`, with no reservoir, settles as before. #[test] -fn test_a_first_frame_settled_into_gas_with_unlimited_pools_and_no_reservoir_settles() { +fn test_a_first_frame_settled_into_gas_with_no_reservoir_settles() { let mut evm = Run::new(ends(Vec::new())).evm(); let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, 0); let mut gas = GasTracker::new(GAS_LIMIT, 0, 0); @@ -970,6 +912,5 @@ fn test_a_first_frame_settled_into_gas_with_unlimited_pools_and_no_reservoir_set .last_frame_result(&mut evm, &mut result, &mut gas) .expect("the frame settles"); - assert_eq!(gas.pools_remaining(), PoolAmounts::UNLIMITED); assert_eq!(gas.reservoir(), 0); } diff --git a/crates/handler/tests/resource_pools.rs b/crates/handler/tests/resource_pools.rs deleted file mode 100644 index 887b436d0c..0000000000 --- a/crates/handler/tests/resource_pools.rs +++ /dev/null @@ -1,1392 +0,0 @@ -//! The resource pools, the start charge and the history allowance, as the mainnet handler forwards -//! and settles them. -//! -//! A consumer sets the transaction's pools on the gas `tx_gas` returns; every frame then starts -//! with the share its caller's instruction forwarded, and `handle_reservoir_remaining_gas` settles -//! what it left: its remaining pool when it succeeded, the whole share when it reverted or halted. -//! A start charge a hook declared rides on the frame's input and is refunded whole when the frame -//! fails. The handler here is the mainnet one, observed through overrides that leave its behaviour -//! alone, on the mainnet context with a start hook of the test's own ([`DeclaringContext`]), and -//! the frames draw the pool through instructions of the test's own, which stand in for a -//! consumer's hooks: `DRAW` draws bytes, `DECLARE` has the start hook charge and declare a start -//! charge at the next start, and `LOG` charges history after drawing the frame's allowance, as a -//! consumer's write hook would. The context's code-deposit admission hook draws deployed code's -//! bytes, and the precompile provider draws on the answers it builds, when a test asks them to. - -use bytecode::opcode::{ - CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, RETURN, REVERT, STOP, -}; -use context::{ - result::{EVMError, ExecutionResult}, - BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Journal, LocalContext, - TxEnv, -}; -use context_interface::{ - cfg::{gas::InitialAndFloorGas, GasId, GasParams, StateGasSite}, - context::CodeDeposit, - host::{FrameStart, LoadError}, - journaled_state::AccountInfoLoad, - Database, Host, -}; -use database::{CacheDB, EmptyDB, BENCH_CALLER}; -use interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, FrameInput, GasTracker, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, InterpreterResult, - PoolAmounts, PoolId, SStoreResult, SelfDestructResult, StartCharge, StateLoad, -}; -use primitives::{ - address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, AddressSet, Bytes, Log, - StorageKey, StorageValue, TxKind, B256, U256, -}; -use revm_handler::{ - instructions::EthInstructions, EthFrame, EthPrecompiles, EvmTr, FrameResult, Handler, - ItemOrResult, MainContext, MainnetContext, MainnetHandler, PrecompileProvider, -}; -use state::{AccountInfo, Bytecode}; - -type Db = CacheDB<EmptyDB>; -type DbError = <Db as Database>::Error; -type TestContext = DeclaringContext; -type TestEvm = Evm< - TestContext, - (), - EthInstructions<EthInterpreter, TestContext>, - DrawingPrecompiles, - EthFrame, ->; -type TestError = EVMError<DbError>; -type Mainnet = MainnetHandler<TestEvm, TestError, EthFrame<EthInterpreter>>; - -const SPEC: SpecId = SpecId::OSAKA; -const GAS_LIMIT: u64 = 3_000_000; -/// The pool the transaction's frame starts with. -const POOL: u64 = 1_000; -/// What `DRAW` draws. -const DRAW_BYTES: u64 = 100; -/// The pool the tests draw: any of the tracker's pools behaves the same. -const FIRST: PoolId = PoolId::new(0); -/// What the start hook charges and declares after `DECLARE`. -const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); -/// What `LOG` charges as history. -const HISTORY_COST: u64 = 100; -/// A value call's history allowance on a chain that gives one. -const ALLOWANCE: u64 = 160; - -/// The account the transaction calls. -const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); -/// Draws and stops. -const OK: Address = address!("0x0000000000000000000000000000000000000c00"); -/// Draws and reverts. -const REVERTER: Address = address!("0x000000000000000000000000000000000000c0fd"); -/// Draws and halts. -const HALTER: Address = address!("0x000000000000000000000000000000000000c0fe"); -/// Draws, calls [`OK`] and reverts. -const NESTER: Address = address!("0x000000000000000000000000000000000000c0e5"); -/// Charges history after drawing its allowance, and stops. -const LOGGER: Address = address!("0x000000000000000000000000000000000000c109"); -/// An account that does not exist. -const EMPTY: Address = address!("0x00000000000000000000000000000000000e3970"); -/// The `ECRECOVER` precompile, which costs 3,000. -const ECRECOVER: Address = address!("0x0000000000000000000000000000000000000001"); - -/// The test's instructions, on opcodes the EVM does not assign. -const DRAW: u8 = 0x0c; -const DECLARE: u8 = 0x0d; -const LOG: u8 = 0x0e; - -/// Draws [`DRAW_BYTES`] from the frame's pool; a draw the pool cannot pay is the frame's stop. -const fn draw( - context: InstructionContext<'_, TestContext, EthInterpreter>, -) -> InstructionExecResult { - let mut index = 0; - while index < PoolId::COUNT { - if !context - .interpreter - .gas - .record_pool(PoolId::ALL[index], DRAW_BYTES) - { - return Err(InstructionResult::OutOfGas); - } - index += 1; - } - Ok(()) -} - -/// Has the start hook charge and declare [`DECLARED`] at the start that follows. -const fn declare( - context: InstructionContext<'_, TestContext, EthInterpreter>, -) -> InstructionExecResult { - context.host.declare_next = true; - Ok(()) -} - -/// What a consumer's write hook does for a log: draws the frame's allowance for [`HISTORY_COST`] -/// and charges the rest as history. -const fn log( - context: InstructionContext<'_, TestContext, EthInterpreter>, -) -> InstructionExecResult { - let gas = &mut context.interpreter.gas; - let rest = gas.draw_history_allowance(HISTORY_COST); - if gas.record_history_cost(rest) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } -} - -/// A frame's pool figures as it returned, before its caller settled it: its result, its pool, -/// its net draw, whether a draw failed, its history gas and its allowance. -#[derive(Clone, Debug, PartialEq, Eq)] -struct Returned { - result: InstructionResult, - pool: u64, - spent: i64, - crossing: bool, - history: i64, - allowance: u64, -} - -impl Returned { - const fn of(result: &FrameResult) -> Self { - let gas = result.gas(); - Self { - result: result.instruction_result(), - pool: gas.pool_remaining(FIRST), - spent: gas.pool_spent(FIRST), - crossing: gas.pool_crossing(FIRST), - history: gas.history_gas_spent(), - allowance: gas.history_allowance(), - } - } - - const fn stopped(pool: u64, spent: i64) -> Self { - Self::ended(InstructionResult::Stop, pool, spent) - } - - const fn ended(result: InstructionResult, pool: u64, spent: i64) -> Self { - Self { - result, - pool, - spent, - crossing: false, - history: 0, - allowance: 0, - } - } -} - -/// What the code-deposit admission hook does with a deposit. -#[derive(Clone, Copy, Debug)] -enum Deposit { - /// Admits it and touches nothing, as the default hook does. - Untouched, - /// Draws the code's bytes from the creating frame's pool and admits it. - Drawn, - /// Draws the code's bytes from the creating frame's pool and refuses it. - DrawnAndRefused, -} - -/// The mainnet [`Context`] with a start hook that does what a consumer's does for a start -/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start; and an -/// admission hook that does with a code deposit what [`Deposit`] says. -struct DeclaringContext { - inner: MainnetContext<Db>, - /// Set by `DECLARE`, taken by the next start. - declare_next: bool, - deposit: Deposit, -} - -impl ContextTr for DeclaringContext { - type Block = BlockEnv; - type Tx = TxEnv; - type Cfg = CfgEnv; - type Db = Db; - type Journal = Journal<Db>; - type Chain = (); - type Local = LocalContext; - - fn all( - &self, - ) -> ( - &Self::Block, - &Self::Tx, - &Self::Cfg, - &Self::Db, - &Self::Journal, - &Self::Chain, - &Self::Local, - ) { - self.inner.all() - } - - fn all_mut( - &mut self, - ) -> ( - &Self::Block, - &Self::Tx, - &Self::Cfg, - &mut Self::Journal, - &mut Self::Chain, - &mut Self::Local, - ) { - self.inner.all_mut() - } - - fn error(&mut self) -> &mut Result<(), ContextError<DbError>> { - self.inner.error() - } - - fn admit_code_deposit( - &mut self, - deposit: &CodeDeposit<'_>, - gas: &mut GasTracker, - ) -> Result<(), Bytes> { - let refuses = match self.deposit { - Deposit::Untouched => return Ok(()), - Deposit::Drawn => false, - Deposit::DrawnAndRefused => true, - }; - assert!(gas.record_pool(FIRST, deposit.code.len() as u64)); - if refuses { - Err(Bytes::new()) - } else { - Ok(()) - } - } -} - -impl ContextSetters for DeclaringContext { - fn set_tx(&mut self, tx: Self::Tx) { - self.inner.set_tx(tx); - } - - fn set_block(&mut self, block: Self::Block) { - self.inner.set_block(block); - } -} - -impl Host for DeclaringContext { - fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { - if core::mem::take(&mut self.declare_next) { - assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); - start.charge = DECLARED; - } - true - } - - fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64> { - self.inner.state_gas_price(id, site) - } - - fn basefee(&self) -> U256 { - self.inner.basefee() - } - - fn blob_gasprice(&self) -> U256 { - self.inner.blob_gasprice() - } - - fn gas_limit(&self) -> U256 { - self.inner.gas_limit() - } - - fn difficulty(&self) -> U256 { - self.inner.difficulty() - } - - fn prevrandao(&self) -> Option<U256> { - self.inner.prevrandao() - } - - fn block_number(&self) -> U256 { - self.inner.block_number() - } - - fn timestamp(&self) -> U256 { - self.inner.timestamp() - } - - fn beneficiary(&self) -> Address { - self.inner.beneficiary() - } - - fn slot_num(&self) -> U256 { - self.inner.slot_num() - } - - fn chain_id(&self) -> U256 { - self.inner.chain_id() - } - - fn effective_gas_price(&self) -> U256 { - self.inner.effective_gas_price() - } - - fn caller(&self) -> Address { - self.inner.caller() - } - - fn blob_hash(&self, number: usize) -> Option<U256> { - self.inner.blob_hash(number) - } - - fn max_initcode_size(&self) -> usize { - self.inner.max_initcode_size() - } - - fn gas_params(&self) -> &GasParams { - self.inner.gas_params() - } - - fn is_amsterdam_eip8037_enabled(&self) -> bool { - self.inner.is_amsterdam_eip8037_enabled() - } - - fn block_hash(&mut self, number: u64) -> Option<B256> { - self.inner.block_hash(number) - } - - fn selfdestruct( - &mut self, - address: Address, - target: Address, - skip_cold_load: bool, - ) -> Result<StateLoad<SelfDestructResult>, LoadError> { - self.inner.selfdestruct(address, target, skip_cold_load) - } - - fn log(&mut self, log: Log) { - self.inner.log(log) - } - - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result<StateLoad<SStoreResult>, LoadError> { - self.inner - .sstore_skip_cold_load(address, key, value, skip_cold_load) - } - - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result<StateLoad<StorageValue>, LoadError> { - self.inner - .sload_skip_cold_load(address, key, skip_cold_load) - } - - fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { - self.inner.tstore(address, key, value) - } - - fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { - self.inner.tload(address, key) - } - - fn load_account_info_skip_cold_load( - &mut self, - address: Address, - load_code: bool, - skip_cold_load: bool, - ) -> Result<AccountInfoLoad<'_>, LoadError> { - self.inner - .load_account_info_skip_cold_load(address, load_code, skip_cold_load) - } -} - -/// [`EthPrecompiles`], whose answers the provider draws on when told to: it starts an answer's -/// pool at the share the input carries and draws `draw` bytes from it, as a provider that appends -/// bytes for a call would. Told not to `seed`, it draws `draw` from every pool of the answer as -/// [`EthPrecompiles`] built it, unlimited, without starting them at the shares. With nothing to -/// draw it is [`EthPrecompiles`]. -struct DrawingPrecompiles { - inner: EthPrecompiles, - draw: u64, - seed: bool, -} - -impl PrecompileProvider<TestContext> for DrawingPrecompiles { - type Output = InterpreterResult; - - fn set_spec(&mut self, spec: SpecId) -> bool { - PrecompileProvider::<TestContext>::set_spec(&mut self.inner, spec) - } - - fn run( - &mut self, - context: &mut TestContext, - inputs: &CallInputs, - ) -> Result<Option<InterpreterResult>, String> { - let mut answer = self.inner.run(context, inputs)?; - if let Some(answer) = answer.as_mut().filter(|_| self.draw > 0) { - if self.seed { - answer - .gas - .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); - assert!(answer.gas.record_pool(FIRST, self.draw)); - } else { - for pool in PoolId::ALL { - assert!(answer.gas.record_pool(pool, self.draw)); - } - } - } - Ok(answer) - } - - fn warm_addresses(&self) -> &AddressSet { - self.inner.warm_addresses() - } -} - -/// The figures of a frame's input as it started: its share, its start charge and its allowance. -type Started = (u64, StartCharge, u64); - -/// Every pool's share on a frame's input. -fn pool_shares(input: &FrameInput) -> PoolAmounts { - match input { - FrameInput::Call(inputs) => inputs.pool_shares, - FrameInput::Create(inputs) => inputs.pool_shares(), - FrameInput::Empty => unreachable!(), - } -} - -fn started(input: &FrameInput) -> Started { - match input { - FrameInput::Call(inputs) => ( - inputs.pool_shares.get(FIRST), - inputs.charged_start, - inputs.history_allowance, - ), - FrameInput::Create(inputs) => (inputs.pool_shares().get(FIRST), inputs.charged_start(), 0), - FrameInput::Empty => unreachable!(), - } -} - -/// The transaction's gas after the first frame settled into it: its pool, its net draw and its -/// history gas. -type Settled = (u64, i64, i64); - -/// The mainnet handler with the consumer's part: a pool set on the transaction's gas and a start -/// charge for the transaction's frame, and a record of every frame's start and return. -struct PoolHandler { - mainnet: Mainnet, - /// The pool the transaction's gas gets, if any. - pool: Option<u64>, - /// Whether the transaction's gas is charged [`DECLARED`] for its frame, declared on the - /// frame's input. - declare: bool, - /// Whether every frame below the transaction's starts one past the call-stack limit, where a - /// 1,025th nested start would. - too_deep: bool, - starts: Vec<Started>, - returned: Vec<Returned>, - settled: Option<Settled>, - /// Every pool's share as each frame started. - pool_starts: Vec<PoolAmounts>, - /// Every pool of the transaction's gas, `(remaining, spent)`, after the first frame settled - /// into it. - settled_pools: Option<[(u64, i64); PoolId::COUNT]>, -} - -impl PoolHandler { - fn new(pool: Option<u64>) -> Self { - Self { - mainnet: Mainnet::default(), - pool, - declare: false, - too_deep: false, - starts: Vec::new(), - returned: Vec::new(), - settled: None, - pool_starts: Vec::new(), - settled_pools: None, - } - } -} - -impl Handler for PoolHandler { - type Evm = TestEvm; - type Error = TestError; - type HaltReason = context::result::HaltReason; - - /// The mainnet gas, with the consumer's pool and, if told to, the start charge of the - /// transaction's frame, charged here as a consumer charges the body's records. - fn tx_gas(&self, evm: &mut TestEvm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { - let mut gas = self.mainnet.tx_gas(evm, init_and_floor_gas); - if let Some(pool) = self.pool { - for each in PoolId::ALL { - gas.set_pool_remaining(each, pool); - } - } - if self.declare { - assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); - } - gas - } - - /// The mainnet input, with the start charge `tx_gas` charged declared on it, if told to. - fn first_frame_input( - &mut self, - evm: &mut TestEvm, - gas: &mut GasTracker, - ) -> Result<Option<FrameInit>, TestError> { - let mut init = self.mainnet.first_frame_input(evm, gas)?; - if let (true, Some(init)) = (self.declare, &mut init) { - match &mut init.frame_input { - FrameInput::Call(inputs) => inputs.charged_start = DECLARED, - FrameInput::Create(inputs) => inputs.set_charged_start(DECLARED), - FrameInput::Empty => unreachable!(), - } - } - Ok(init) - } - - /// The default loop, recording each frame's input as it starts and its result as it - /// returns, before its caller settles it, and starting the frames below the transaction's - /// past the call-stack limit if told to. - fn run_exec_loop( - &mut self, - evm: &mut TestEvm, - first_frame_input: FrameInit, - ) -> Result<FrameResult, TestError> { - self.starts.push(started(&first_frame_input.frame_input)); - self.pool_starts - .push(pool_shares(&first_frame_input.frame_input)); - if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { - self.returned.push(Returned::of(&result)); - return Ok(result); - } - loop { - let result = match evm.frame_run()? { - ItemOrResult::Item(mut init) => { - self.starts.push(started(&init.frame_input)); - self.pool_starts.push(pool_shares(&init.frame_input)); - if self.too_deep { - init.depth = CALL_STACK_LIMIT as usize + 1; - } - match evm.frame_init(init)? { - ItemOrResult::Item(_) => continue, - ItemOrResult::Result(result) => result, - } - } - ItemOrResult::Result(mut result) => { - evm.frame_run_result(&mut result)?; - result - } - }; - self.returned.push(Returned::of(&result)); - if let Some(result) = evm.frame_return_result(result)? { - return Ok(result); - } - } - } - - /// The default, recording the transaction's gas as the first frame left it. - fn post_execution( - &self, - evm: &mut TestEvm, - exec_result: &mut FrameResult, - init_and_floor_gas: InitialAndFloorGas, - eip7702_refund: i64, - ) -> Result<context::result::ResultGas, TestError> { - let gas = exec_result.gas(); - // `post_execution` takes `&self`; the record goes through a cell. - SETTLED.with(|settled| { - settled.set(Some(( - gas.pool_remaining(FIRST), - gas.pool_spent(FIRST), - gas.history_gas_spent(), - ))) - }); - SETTLED_POOLS.with(|settled| { - settled.set(Some( - PoolId::ALL.map(|pool| (gas.pool_remaining(pool), gas.pool_spent(pool))), - )) - }); - self.mainnet - .post_execution(evm, exec_result, init_and_floor_gas, eip7702_refund) - } -} - -thread_local! { - static SETTLED: core::cell::Cell<Option<Settled>> = const { core::cell::Cell::new(None) }; - static SETTLED_POOLS: core::cell::Cell<Option<[(u64, i64); PoolId::COUNT]>> = - const { core::cell::Cell::new(None) }; -} - -/// `CALL(100_000, to, value, 0, 0, 0, 0)`, dropping the success flag. -fn call(to: Address, value: u8) -> Vec<u8> { - let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]; - code.extend_from_slice(to.as_slice()); - code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP]); - code -} - -/// `CALL(10, to, 0, 0, 0, 0, 0)`: too little gas for any precompile, dropping the success flag. -fn starved_call(to: Address) -> Vec<u8> { - let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; - code.extend_from_slice(to.as_slice()); - code.extend_from_slice(&[PUSH1, 10, CALL, POP]); - code -} - -/// `CREATE` of `initcode`, at most 32 bytes, endowed with nothing, dropping the address. -fn create(initcode: &[u8]) -> Vec<u8> { - let len = initcode.len() as u8; - let mut code = vec![PUSH0 + len]; - code.extend_from_slice(initcode); - code.extend_from_slice(&[ - PUSH0, - MSTORE, - PUSH1, - len, - PUSH1, - 32 - len, - PUSH0, - CREATE, - POP, - ]); - code -} - -fn ends(mut code: Vec<u8>) -> Vec<u8> { - code.push(STOP); - code -} - -/// A transaction on the accounts every test knows: a call to [`PARENT`], which holds `parent`, or -/// a creation with `parent` as its init code ([`Run::creation`]). -struct Run { - parent: Vec<u8>, - parent_balance: u64, - parent_nonce: u64, - /// `call_history_allowance` in the schedule. - allowance: u64, - deposit: Deposit, - /// What the precompile provider draws on each answer. - precompile_draw: u64, - /// Whether the provider starts an answer's pool at the share before it draws. - precompile_seeds: bool, - /// The per cent of [`FIRST`] a child receives, if not the default: the schedule's - /// `pool_kept_percent` is the rest. - forward_percent: Option<u64>, - /// The per cent of each pool a child receives, if not the default. - pool_percents: Option<[u64; PoolId::COUNT]>, - /// Whether the transaction creates a contract from `parent` instead of calling [`PARENT`]. - creates: bool, -} - -impl Run { - const fn new(parent: Vec<u8>) -> Self { - Self { - parent, - parent_balance: 10, - parent_nonce: 1, - allowance: 0, - deposit: Deposit::Untouched, - precompile_draw: 0, - precompile_seeds: true, - forward_percent: None, - pool_percents: None, - creates: false, - } - } - - /// A transaction that creates a contract from `initcode`. - const fn creation(initcode: Vec<u8>) -> Self { - let mut run = Self::new(initcode); - run.creates = true; - run - } - - const fn pool_percents(mut self, percents: [u64; PoolId::COUNT]) -> Self { - self.pool_percents = Some(percents); - self - } - - const fn forward_percent(mut self, percent: u64) -> Self { - self.forward_percent = Some(percent); - self - } - - const fn precompile_draw(mut self, draw: u64) -> Self { - self.precompile_draw = draw; - self - } - - /// The provider draws `draw` from every pool of each answer as built, without starting the - /// pools at the shares first. - const fn unseeded_precompile_draw(mut self, draw: u64) -> Self { - self.precompile_draw = draw; - self.precompile_seeds = false; - self - } - - const fn deposit(mut self, deposit: Deposit) -> Self { - self.deposit = deposit; - self - } - - const fn penniless(mut self) -> Self { - self.parent_balance = 0; - self - } - - const fn nonce(mut self, nonce: u64) -> Self { - self.parent_nonce = nonce; - self - } - - const fn allowance(mut self, allowance: u64) -> Self { - self.allowance = allowance; - self - } - - fn db(&self) -> Db { - let mut db = Db::default(); - db.insert_account_info( - BENCH_CALLER, - AccountInfo::from_balance(U256::from(10u128.pow(21))), - ); - let mut nester = vec![DRAW]; - nester.extend(call(OK, 0)); - nester.extend_from_slice(&[PUSH0, PUSH0, REVERT]); - let accounts: [(Address, Vec<u8>, u64, u64); 6] = [ - ( - PARENT, - self.parent.clone(), - self.parent_balance, - self.parent_nonce, - ), - (OK, vec![DRAW, STOP], 0, 1), - (REVERTER, vec![DRAW, PUSH0, PUSH0, REVERT], 0, 1), - (HALTER, vec![DRAW, INVALID], 0, 1), - (NESTER, nester, 0, 1), - (LOGGER, vec![LOG, STOP], 0, 1), - ]; - for (address, code, balance, nonce) in accounts { - let info = AccountInfo::from_balance(U256::from(balance)) - .with_nonce(nonce) - .with_code(Bytecode::new_raw(Bytes::from(code))); - db.insert_account_info(address, info); - } - db - } - - fn evm(&self) -> TestEvm { - let allowance = self.allowance; - let forward_percent = self.forward_percent; - let pool_percents = self.pool_percents; - let inner = Context::mainnet() - .with_db(self.db()) - .modify_cfg_chained(|cfg| { - cfg.set_spec_and_mainnet_gas_params(SPEC); - cfg.gas_params - .override_gas([(GasId::call_history_allowance(), allowance)]); - if let Some(percents) = pool_percents { - for (pool, percent) in PoolId::ALL.into_iter().zip(percents) { - cfg.gas_params - .override_gas([(GasId::pool_kept_percent(pool), 100 - percent)]); - } - } - if let Some(percent) = forward_percent { - cfg.gas_params - .override_gas([(GasId::pool_kept_percent(FIRST), 100 - percent)]); - } - }); - let ctx = DeclaringContext { - inner, - declare_next: false, - deposit: self.deposit, - }; - let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); - instructions.insert_instruction(DRAW, Instruction::new(draw), 0); - instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); - instructions.insert_instruction(LOG, Instruction::new(log), 0); - let precompiles = DrawingPrecompiles { - inner: EthPrecompiles::new(SPEC), - draw: self.precompile_draw, - seed: self.precompile_seeds, - }; - let mut evm: TestEvm = Evm::new(ctx, instructions, precompiles); - let (kind, data) = if self.creates { - (TxKind::Create, Bytes::from(self.parent.clone())) - } else { - (TxKind::Call(PARENT), Bytes::new()) - }; - evm.ctx.set_tx( - TxEnv::builder_for_bench() - .kind(kind) - .data(data) - .gas_price(0) - .gas_limit(GAS_LIMIT) - .build_fill(), - ); - evm - } - - /// Runs the transaction with `handler` and returns its result and the handler, with what it - /// recorded. - fn with(&self, mut handler: PoolHandler) -> (ExecutionResult, PoolHandler) { - SETTLED.with(|settled| settled.set(None)); - SETTLED_POOLS.with(|settled| settled.set(None)); - let result = handler.run(&mut self.evm()).expect("the transaction runs"); - handler.settled = SETTLED.with(|settled| settled.get()); - handler.settled_pools = SETTLED_POOLS.with(|settled| settled.get()); - (result, handler) - } - - /// Runs the transaction with the mainnet handler as it is. - fn on_mainnet(&self) -> ExecutionResult { - Mainnet::default() - .run(&mut self.evm()) - .expect("the transaction runs") - } -} - -/// [`PARENT`] draws, then calls a child that stops, one that reverts, one that halts and one -/// that calls a child of its own and reverts. -fn at_depth() -> Run { - let mut parent = vec![DRAW]; - for child in [OK, REVERTER, HALTER, NESTER] { - parent.extend(call(child, 0)); - } - Run::new(ends(parent)) -} - -/// The transaction's frame gets the whole pool, and every start forwards the whole pool its -/// caller has left. A child that succeeds hands back what it left and its net draw merges into -/// the caller's; a child that reverts or halts hands back the whole share, its draws undone, and -/// so do the draws of a child of its own that succeeded. -#[test] -fn test_the_pool_is_forwarded_whole_and_settled_at_depth() { - let (result, handler) = at_depth().with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{result:?}"); - let share = |pool| (pool, StartCharge::default(), 0); - assert_eq!( - handler.starts, - [ - share(POOL), - // PARENT drew 100. - share(900), - // OK drew 100 and stopped. - share(800), - // REVERTER and HALTER gave the whole share back. - share(800), - share(800), - // OK, inside NESTER, which drew 100 first. - share(700), - ] - ); - assert_eq!( - handler.returned, - [ - Returned::stopped(800, 100), - Returned::ended(InstructionResult::Revert, 700, 100), - Returned::ended(InstructionResult::InvalidFEOpcode, 700, 100), - // OK inside NESTER. - Returned::stopped(600, 100), - // NESTER: its own draw and OK's, before its rollback. - Returned::ended(InstructionResult::Revert, 600, 200), - // PARENT: its own draw and the first OK's. - Returned::stopped(800, 200), - ] - ); - assert_eq!(handler.settled, Some((800, 200, 0))); -} - -/// A draw the pool cannot pay takes nothing and records the crossing; the consumer's instruction -/// halts the frame, and the record is readable on the frame's result before its caller settles -/// it, with the pool as the failed draw found it. The caller gets the whole share back. -#[test] -fn test_a_failed_draw_halts_the_frame_with_a_record_the_caller_can_read() { - let mut parent = vec![DRAW]; - parent.extend(call(OK, 0)); - let run = Run::new(ends(parent)); - - let (result, handler) = run.with(PoolHandler::new(Some(150))); - - assert!(result.is_success(), "{result:?}"); - assert_eq!(handler.starts[1], (50, StartCharge::default(), 0)); - assert_eq!( - handler.returned, - [ - Returned { - crossing: true, - ..Returned::ended(InstructionResult::OutOfGas, 50, 0) - }, - Returned::stopped(50, 100), - ] - ); - assert_eq!(handler.settled, Some((50, 100, 0))); -} - -/// A start charge the start hook declared rides on the frame's input, and is refunded to the -/// caller whole when the frame fails: a revert, a halt, a start the handler refused before any -/// frame ran (a transfer the caller cannot pay), one it answered without a frame (a precompile -/// out of gas), a creation that reverted and one whose caller's nonce overflowed. A frame that -/// succeeds keeps the charge. -#[test] -fn test_the_start_charge_is_refunded_when_the_frame_fails() { - let reverting_initcode = [PUSH0, PUSH0, REVERT]; - let cases: Vec<(&str, Run, bool)> = vec![ - ("a child that stops", Run::new(call(OK, 0)), false), - ("a child that reverts", Run::new(call(REVERTER, 0)), true), - ("a child that halts", Run::new(call(HALTER, 0)), true), - ( - "a transfer the caller cannot pay", - Run::new(call(EMPTY, 1)).penniless(), - true, - ), - ( - "a precompile out of gas", - Run::new(starved_call(ECRECOVER)), - true, - ), - ( - "a creation that reverts", - Run::new(create(&reverting_initcode)), - true, - ), - ( - "a creation whose caller's nonce overflowed", - Run::new(create(&[STOP])).nonce(u64::MAX), - true, - ), - ]; - for (name, run, fails) in cases { - let mut parent = vec![DECLARE]; - parent.extend(run.parent.clone()); - let run = Run { - parent: ends(parent), - ..run - }; - - let (result, handler) = run.with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{name}: {result:?}"); - assert_eq!(handler.starts.len(), 2, "{name}"); - assert_eq!( - handler.starts[1], - (POOL - DECLARED.pools.get(FIRST), DECLARED, 0), - "{name}: the charge rides on the input" - ); - let settled = handler.settled.expect(name); - if fails { - assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); - } else { - let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; - assert_eq!( - settled, - (POOL - drawn, drawn as i64, DECLARED.history as i64), - "{name}: kept" - ); - } - } -} - -/// The transaction's frame gets the pool as the consumer left it after the body's charges, and -/// the start charge the consumer declared on its input, which is refunded whole when the frame -/// reverts or halts and kept when it succeeds: a call's frame and a creation's alike. -#[test] -fn test_the_first_frame_gets_the_pool_and_its_start_charge() { - let cases = [ - ("stops", vec![DRAW, STOP], false), - ("reverts", vec![DRAW, PUSH0, PUSH0, REVERT], true), - ("halts", vec![DRAW, INVALID], true), - ]; - let calls = cases - .clone() - .map(|(name, code, fails)| (name, Run::new(code), fails)); - let creations = cases.map(|(name, code, fails)| (name, Run::creation(code), fails)); - for (name, run, fails) in calls.into_iter().chain(creations) { - let name = format!( - "{} {name}", - if run.creates { "a creation" } else { "a call" } - ); - let name = name.as_str(); - let mut handler = PoolHandler::new(Some(POOL)); - handler.declare = true; - - let (result, handler) = run.with(handler); - - assert_eq!(result.is_success(), !fails, "{name}: {result:?}"); - assert_eq!( - handler.starts, - [(POOL - DECLARED.pools.get(FIRST), DECLARED, 0)], - "{name}" - ); - let settled = handler.settled.expect(name); - if fails { - assert_eq!(settled, (POOL, 0, 0), "{name}: refunded whole"); - } else { - let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; - assert_eq!( - settled, - (POOL - drawn, drawn as i64, DECLARED.history as i64), - "{name}: kept" - ); - } - } -} - -/// A value call's child starts with the schedule's history allowance and no other frame does; -/// nothing but the consumer draws it, so a frame that charges no history returns it whole, and a -/// consumer's charge takes the allowance before the budget. -#[test] -fn test_the_history_allowance_reaches_a_value_calls_child_and_only_the_consumer_draws_it() { - let mut parent = call(LOGGER, 1); - parent.extend(call(LOGGER, 0)); - parent.extend(call(OK, 1)); - let run = Run::new(ends(parent)).allowance(ALLOWANCE); - - let (result, handler) = run.with(PoolHandler::new(None)); - - assert!(result.is_success(), "{result:?}"); - let shares: Vec<u64> = handler.starts.iter().map(|start| start.0).collect(); - assert_eq!(shares, [u64::MAX; 4], "no pool was set"); - let allowances: Vec<u64> = handler.starts.iter().map(|start| start.2).collect(); - assert_eq!(allowances, [0, ALLOWANCE, 0, ALLOWANCE]); - assert_eq!( - handler.returned, - [ - // The value call's logger: the allowance paid the whole charge. - Returned { - allowance: ALLOWANCE - HISTORY_COST, - ..Returned::stopped(u64::MAX, 0) - }, - // The plain call's logger: no allowance, the budget paid. - Returned { - history: HISTORY_COST as i64, - ..Returned::stopped(u64::MAX, 0) - }, - // A value call that charges no history keeps its allowance whole. - Returned { - allowance: ALLOWANCE, - ..Returned::stopped(u64::MAX - DRAW_BYTES, DRAW_BYTES as i64) - }, - // PARENT, with the plain call's history charge merged in and no allowance of its own. - Returned { - history: HISTORY_COST as i64, - ..Returned::stopped(u64::MAX - DRAW_BYTES, DRAW_BYTES as i64) - }, - ] - ); - assert_eq!( - handler.settled, - Some(( - u64::MAX - DRAW_BYTES, - DRAW_BYTES as i64, - HISTORY_COST as i64 - )) - ); - - // On the default schedule no frame gets an allowance. - let (_, handler) = Run::new(ends(call(LOGGER, 1))).with(PoolHandler::new(None)); - assert_eq!(handler.starts[1].2, 0); - assert_eq!(handler.returned[0].history, HISTORY_COST as i64); -} - -/// A consumer that sets nothing runs on an unlimited pool, which every start forwards whole, less -/// only what the test's own draws took, and every return settles back; the transaction ends as it -/// does on the mainnet handler. -#[test] -fn test_a_consumer_that_sets_nothing_sees_the_mainnet_result() { - let run = at_depth(); - let (result, handler) = run.with(PoolHandler::new(None)); - - assert_eq!(result, run.on_mainnet()); - let shares: Vec<u64> = handler.starts.iter().map(|start| start.0).collect(); - let less = |draws: u64| u64::MAX - draws * DRAW_BYTES; - assert_eq!( - shares, - [less(0), less(1), less(2), less(2), less(2), less(3)], - "the unlimited pool, less the draws so far" - ); - assert_eq!(handler.settled, Some((less(2), 2 * DRAW_BYTES as i64, 0))); -} - -/// The admission hook draws deployed code's bytes from the creating frame's pool. An admitted -/// deposit's draw is the creation's own: its caller takes its net over and the transaction's net -/// counts it, as for any draw of a frame that succeeded. A refused deposit ends the creation as a -/// revert with the draw undone, and its caller gets the whole share back. -#[test] -fn test_a_deposit_drawn_at_admission_is_held_against_the_transaction() { - // Deploys 32 zero bytes. - let initcode = [PUSH1, 32, PUSH0, RETURN]; - for (name, deposit, returned, settled) in [ - ( - "admitted", - Deposit::Drawn, - Returned::ended(InstructionResult::Return, POOL - 32, 32), - (POOL - 32, 32, 0), - ), - ( - "refused", - Deposit::DrawnAndRefused, - Returned::ended(InstructionResult::Revert, POOL, 0), - (POOL, 0, 0), - ), - ] { - let run = Run::new(ends(create(&initcode))).deposit(deposit); - - let (result, handler) = run.with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{name}: {result:?}"); - assert_eq!( - handler.starts[1].0, POOL, - "{name}: the whole pool forwarded" - ); - assert_eq!(handler.returned[0], returned, "{name}"); - assert_eq!(handler.settled, Some(settled), "{name}"); - } -} - -/// A precompile's answer starts with its caller's share as its pool, less what the provider drew -/// on it, so its pool and its net add up to the share, as a frame's do: the caller takes the -/// provider's draw over when the call succeeds, and gets the whole share back when it fails. -#[test] -fn test_a_precompile_answer_keeps_what_its_provider_drew() { - const PROVIDER_DRAW: u64 = 40; - let mut succeeding = vec![DRAW]; - succeeding.extend(call(ECRECOVER, 0)); - let mut failing = vec![DRAW]; - failing.extend(starved_call(ECRECOVER)); - // PARENT drew 100 and forwards the 900 left; the provider draws 40 of them. - for (name, parent, returned, settled) in [ - ( - "succeeds", - succeeding, - Returned::ended(InstructionResult::Return, 860, 40), - (860, 140, 0), - ), - ( - "fails", - failing, - Returned::ended(InstructionResult::PrecompileOOG, 860, 40), - (900, 100, 0), - ), - ] { - let run = Run::new(ends(parent)).precompile_draw(PROVIDER_DRAW); - - let (result, handler) = run.with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{name}: {result:?}"); - assert_eq!(handler.starts[1].0, 900, "{name}"); - assert_eq!(handler.returned[0], returned, "{name}"); - assert_eq!(handler.settled, Some(settled), "{name}"); - } -} - -/// A provider that draws on an answer without starting its pools at the shares draws on the -/// unlimited pools the answer was built with, so it can draw past a share. Within the share the -/// answer is adopted as any is; past it, each pool fails closed: the answer holds an empty pool, -/// a net of exactly the share and the pool's crossing, and the caller ends with exactly what it -/// held, whether the call succeeds or fails. The answer's result is the provider's. -#[test] -fn test_a_precompile_answer_that_drew_past_its_share_is_a_crossing_held_to_the_share() { - let succeeding = call(ECRECOVER, 0); - let failing = starved_call(ECRECOVER); - // Every pool of 1,000 forwards 10%, 100, and PARENT keeps 900. - for (name, parent, draw, returned, settled) in [ - ( - "within, succeeds", - succeeding.clone(), - 40, - Returned::ended(InstructionResult::Return, 60, 40), - (960, 40), - ), - ( - "the whole share, succeeds", - succeeding.clone(), - 100, - Returned::ended(InstructionResult::Return, 0, 100), - (900, 100), - ), - ( - "past it, succeeds", - succeeding, - 150, - Returned { - crossing: true, - ..Returned::ended(InstructionResult::Return, 0, 100) - }, - (900, 100), - ), - ( - "past it, fails", - failing, - 150, - Returned { - crossing: true, - ..Returned::ended(InstructionResult::PrecompileOOG, 0, 100) - }, - (1_000, 0), - ), - ] { - let run = Run::new(ends(parent)) - .pool_percents([10; PoolId::COUNT]) - .unseeded_precompile_draw(draw); - - let (result, handler) = run.with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{name}: {result:?}"); - assert_eq!( - handler.pool_starts[1], - PoolAmounts::ZERO - .with(FIRST, 100) - .with(PoolId::new(1), 100) - .with(PoolId::new(2), 100), - "{name}" - ); - assert_eq!(handler.returned[0], returned, "{name}"); - assert_eq!( - handler.settled_pools, - Some([settled; PoolId::COUNT]), - "{name}: every pool" - ); - } -} - -/// A precompile's answer to a value call carries the history allowance the call instruction gave -/// the start, as a frame does, and an answer to a call without value carries none. -#[test] -fn test_a_precompile_answer_to_a_value_call_carries_the_allowance() { - let mut parent = call(ECRECOVER, 1); - parent.extend(call(ECRECOVER, 0)); - let run = Run::new(ends(parent)).allowance(ALLOWANCE); - - let (result, handler) = run.with(PoolHandler::new(None)); - - assert!(result.is_success(), "{result:?}"); - let allowances: Vec<u64> = handler.starts.iter().map(|start| start.2).collect(); - assert_eq!(allowances, [0, ALLOWANCE, 0]); - let answered = Returned::ended(InstructionResult::Return, u64::MAX, 0); - assert_eq!( - handler.returned[..2], - [ - Returned { - allowance: ALLOWANCE, - ..answered.clone() - }, - answered, - ] - ); -} - -/// A start the handler refuses for the call depth gives its caller the whole share and the start -/// charge back, as any start that fails does, for a call and a creation alike. The handler's loop -/// starts the frame one past the call-stack limit, where a 1,025th nested start would be. -#[test] -fn test_a_start_refused_for_the_depth_gives_the_share_and_the_start_charge_back() { - for (name, start) in [("a call", call(OK, 0)), ("a creation", create(&[STOP]))] { - let mut parent = vec![DRAW, DECLARE]; - parent.extend(start); - let mut handler = PoolHandler::new(Some(POOL)); - handler.too_deep = true; - - let (result, handler) = Run::new(ends(parent)).with(handler); - - assert!(result.is_success(), "{name}: {result:?}"); - let share = POOL - DRAW_BYTES - DECLARED.pools.get(FIRST); - assert_eq!(handler.starts[1], (share, DECLARED, 0), "{name}"); - assert_eq!( - handler.returned[0], - Returned::ended(InstructionResult::CallTooDeep, share, 0), - "{name}" - ); - assert_eq!( - handler.settled, - Some((POOL - DRAW_BYTES, DRAW_BYTES as i64, 0)), - "{name}: the start charge refunded, PARENT's own draw kept" - ); - } -} - -/// With [`FIRST`]'s `pool_kept_percent` at 2, every start forwards 98% of its caller's pool, rounded -/// down, and the caller keeps the rest; what a child hands back adds to what its caller kept, so -/// the transaction ends with the figures the whole-pool forward gives. -#[test] -fn test_a_share_below_the_whole_pool_is_forwarded_and_settled_at_depth() { - let (result, handler) = at_depth() - .forward_percent(98) - .with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{result:?}"); - let share = |pool| (pool, StartCharge::default(), 0); - assert_eq!( - handler.starts, - [ - // The transaction's frame takes the whole pool. - share(POOL), - // PARENT drew 100: 98% of 900, PARENT keeps 18. - share(882), - // OK left 782, PARENT holds 800 again: 98% of 800, PARENT keeps 16. - share(784), - share(784), - share(784), - // NESTER drew 100 of its 784: 98% of 684 is 670.32, NESTER keeps 14. - share(670), - ] - ); - assert_eq!( - handler.returned, - [ - Returned::stopped(782, 100), - Returned::ended(InstructionResult::Revert, 684, 100), - Returned::ended(InstructionResult::InvalidFEOpcode, 684, 100), - // OK inside NESTER. - Returned::stopped(570, 100), - // NESTER: the 14 it kept and the 570 OK left, before its rollback. - Returned::ended(InstructionResult::Revert, 584, 200), - // PARENT: 16 kept and the whole 784 NESTER gave back. - Returned::stopped(800, 200), - ] - ); - assert_eq!(handler.settled, Some((800, 200, 0))); -} - -/// Each pool is forwarded by its own share and settles alone: with the pools' percentages at 98, -/// 50 and 100, every start forwards that much of what its caller has left of each pool, rounded -/// down, and the caller keeps the rest of each; what a child hands back of each pool adds to what -/// its caller kept, so every pool ends where the whole-pool forward ends it. -#[test] -fn test_each_pool_is_forwarded_by_its_own_share_and_settled_at_depth() { - let (result, handler) = at_depth() - .pool_percents([98, 50, 100]) - .with(PoolHandler::new(Some(POOL))); - - assert!(result.is_success(), "{result:?}"); - // PARENT drew 100 of each pool before each start; OK drew 100 and handed back the rest, so - // PARENT holds 800 of each for the later starts. NESTER drew 100 of each of its shares (784, - // 400, 800) before calling OK. - let each = |shares: [u64; PoolId::COUNT]| { - PoolAmounts::ZERO - .with(PoolId::new(0), shares[0]) - .with(PoolId::new(1), shares[1]) - .with(PoolId::new(2), shares[2]) - }; - assert_eq!( - handler.pool_starts, - [ - each([POOL; 3]), - // 98%, 50% and 100% of 900. - each([882, 450, 900]), - // Of 800. - each([784, 400, 800]), - each([784, 400, 800]), - each([784, 400, 800]), - // Of 684, 300 and 700: 98% of 684 is 670.32. - each([670, 150, 700]), - ] - ); - assert_eq!(handler.settled_pools, Some([(800, 200); 3])); -} diff --git a/crates/inspector/tests/code_deposit_admission.rs b/crates/inspector/tests/code_deposit_admission.rs index 8d9cf508cb..b82004f3ff 100644 --- a/crates/inspector/tests/code_deposit_admission.rs +++ b/crates/inspector/tests/code_deposit_admission.rs @@ -7,7 +7,7 @@ use context::{ context_interface::{ - cfg::{gas::GasTracker, GasId, GasParams, StateGasSite}, + cfg::{GasId, GasParams, StateGasSite}, context::CodeDeposit, host::LoadError, journaled_state::AccountInfoLoad, @@ -88,11 +88,7 @@ impl ContextTr for RefusingContext { self.inner.error() } - fn admit_code_deposit( - &mut self, - _deposit: &CodeDeposit<'_>, - _gas: &mut GasTracker, - ) -> Result<(), Bytes> { + fn admit_code_deposit(&mut self, _deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { self.offered += 1; Err(Bytes::from_static(REFUSAL)) } diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index 77ef133dc7..f15d4091b6 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -98,8 +98,8 @@ struct Plan { enum AtStart { /// A return carrying [`AT_START`]. Return, - /// A creation with no init code on [`CREATION_GAS`] and the shares of the frame's reservoir - /// and pools; once it returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. + /// A creation with no init code on [`CREATION_GAS`] and the share of the frame's reservoir; + /// once it returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. Create, /// The creation of [`AtStart::Create`]; once it returned into [`CHILD`], nothing, so /// [`CHILD`] runs its code. @@ -274,7 +274,7 @@ impl EvmTr for Consumer { "the frame pays the creation" ); let shares = gas.tracker_mut().forward_to_child(¶ms); - let mut inputs = CreateInputs::new( + let inputs = CreateInputs::new( CHILD, CreateScheme::Create, U256::ZERO, @@ -282,7 +282,6 @@ impl EvmTr for Consumer { CREATION_GAS, shares.reservoir, ); - inputs.set_pool_shares(shares.pools); InterpreterAction::NewFrame(FrameInput::Create(Box::new(inputs))) } }; diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_share.rs index f5ffe0eb98..700c857397 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_share.rs @@ -19,7 +19,7 @@ use handler::{ }; use interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, InterpreterResult, PoolAmounts, + InstructionResult, InterpreterResult, }; use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{InspectEvm, Inspector}; @@ -71,7 +71,7 @@ enum Answer { Runs, /// Answers it with a revert built on `Gas::new`, as a tool does. AsBuilt, - /// Answers it with a revert that carries the input's reservoir and pool shares. + /// Answers it with a revert that carries the input's reservoir. WithTheShares, } @@ -84,18 +84,16 @@ struct Answering { } impl Answering { - /// The gas of the answer to a start of `gas_limit` given `reservoir` and `pools`, or `None` - /// to let the start run. - const fn gas(&mut self, gas_limit: u64, reservoir: u64, pools: PoolAmounts) -> Option<Gas> { + /// The gas of the answer to a start of `gas_limit` given `reservoir`, or `None` to let the + /// start run. + const fn gas(&mut self, gas_limit: u64, reservoir: u64) -> Option<Gas> { self.given = Some(reservoir); match self.answer { Answer::Runs => None, Answer::AsBuilt => Some(Gas::new(gas_limit)), - Answer::WithTheShares => { - let mut gas = Gas::new_with_regular_gas_and_reservoir(gas_limit, reservoir); - gas.tracker_mut().set_pools_remaining(pools); - Some(gas) - } + Answer::WithTheShares => Some(Gas::new_with_regular_gas_and_reservoir( + gas_limit, reservoir, + )), } } } @@ -105,7 +103,7 @@ impl Inspector<Ctx, EthInterpreter> for Answering { if inputs.target_address != OK { return None; } - let gas = self.gas(inputs.gas_limit, inputs.reservoir, inputs.pool_shares)?; + let gas = self.gas(inputs.gas_limit, inputs.reservoir)?; Some(CallOutcome::new( InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), inputs.return_memory_offset.clone(), @@ -113,7 +111,7 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } fn create(&mut self, _: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { - let gas = self.gas(inputs.gas_limit(), inputs.reservoir(), inputs.pool_shares())?; + let gas = self.gas(inputs.gas_limit(), inputs.reservoir())?; let mut outcome = CreateOutcome::new( InterpreterResult::new(InstructionResult::Revert, Bytes::new(), gas), None, @@ -121,7 +119,6 @@ impl Inspector<Ctx, EthInterpreter> for Answering { if let Answer::WithTheShares = self.answer { outcome.charged_create_state_gas = inputs.charged_create_state_gas(); outcome.charged_state_gas_address = inputs.charged_state_gas_address(); - outcome.charged_start = inputs.charged_start(); } Some(outcome) } diff --git a/crates/inspector/tests/resource_pools.rs b/crates/inspector/tests/resource_pools.rs deleted file mode 100644 index 432f6ef97a..0000000000 --- a/crates/inspector/tests/resource_pools.rs +++ /dev/null @@ -1,804 +0,0 @@ -//! The resource pools, the start charge and the history allowance on the plain and the inspected -//! path. -//! -//! `transact` runs the frames in the handler's loop and `inspect_tx` in the inspector's; both -//! build frames with `make_call_frame` and `make_create_frame` and settle them with -//! `return_result`, so a child's share, its start charge and its allowance travel the same way -//! and settle to the same figures. Each test runs a transaction both ways on the mainnet context, -//! with a start hook of the test's own ([`DeclaringContext`]) and instructions of the test's own, -//! which stand in for a consumer's hooks, and checks that the two paths end the same way; an -//! inspector records each frame's input as it starts and its outcome as it ends, before its caller -//! settles it, and the figures are checked on the inspected path (the handler's tests check them -//! on the plain one). Two tests run on the inspected path alone: an outcome the inspector builds -//! or rewrites itself has no counterpart on the plain path. - -use context::{ - context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, - host::{FrameStart, LoadError}, - journaled_state::AccountInfoLoad, - }, - result::ResultAndState, - BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Host, Journal, - LocalContext, TxEnv, -}; -use database::{CacheDB, EmptyDB, BENCH_CALLER}; -use handler::{ - instructions::EthInstructions, EthFrame, EthPrecompiles, ExecuteEvm, MainContext, - MainnetContext, -}; -use interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - GasTracker, Instruction, InstructionContext, InstructionExecResult, InstructionResult, - InterpreterResult, PoolAmounts, PoolId, SStoreResult, SelfDestructResult, StartCharge, - StateLoad, -}; -use primitives::{ - address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, -}; -use revm_inspector::{InspectEvm, Inspector}; -use state::{ - bytecode::opcode::{ - CALL, CREATE, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH3, REVERT, STOP, - }, - AccountInfo, Bytecode, -}; - -type Db = CacheDB<EmptyDB>; -type DbError = <Db as context::Database>::Error; -type Ctx = DeclaringContext; -type PoolEvm = Evm<Ctx, Figures, EthInstructions<EthInterpreter, Ctx>, EthPrecompiles, EthFrame>; - -const SPEC: SpecId = SpecId::OSAKA; -const GAS_LIMIT: u64 = 3_000_000; -/// What `DRAW` draws. -const DRAW_BYTES: u64 = 100; -/// The pool the tests draw: any of the tracker's pools behaves the same. -const FIRST: PoolId = PoolId::new(0); -/// What the start hook charges and declares after `DECLARE`. -const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); -/// What `LOG` charges as history. -const HISTORY_COST: u64 = 100; -/// A value call's history allowance on a chain that gives one. -const ALLOWANCE: u64 = 160; -/// The pool nobody set. -const UNLIMITED: u64 = u64::MAX; -/// The pool `LIMIT` sets. -const LIMITED: u64 = 1_000; - -/// The account the transaction calls. -const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); -/// Draws and stops. -const OK: Address = address!("0x0000000000000000000000000000000000000c00"); -/// Draws and reverts. -const REVERTER: Address = address!("0x000000000000000000000000000000000000c0fd"); -/// Draws and halts. -const HALTER: Address = address!("0x000000000000000000000000000000000000c0fe"); -/// Draws, calls [`OK`] and reverts. -const NESTER: Address = address!("0x000000000000000000000000000000000000c0e5"); -/// Draws more than any pool holds. -const DRAINER: Address = address!("0x000000000000000000000000000000000000d7a1"); -/// Charges history after drawing its allowance, and stops. -const LOGGER: Address = address!("0x000000000000000000000000000000000000c109"); - -/// The test's instructions, on opcodes the EVM does not assign. -const DRAW: u8 = 0x0c; -const DECLARE: u8 = 0x0d; -const LOG: u8 = 0x0e; -const DRAIN: u8 = 0x0f; -const LIMIT: u8 = 0x10; - -const fn draw(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - if context.interpreter.gas.record_pool(FIRST, DRAW_BYTES) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } -} - -const fn drain(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - if context.interpreter.gas.record_pool(FIRST, u64::MAX) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } -} - -/// Sets the frame's pool to [`LIMITED`], as a consumer sets the transaction's. -const fn limit(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - context.interpreter.gas.set_pool_remaining(FIRST, LIMITED); - Ok(()) -} - -/// Has the start hook charge and declare [`DECLARED`] at the start that follows. -const fn declare(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - context.host.declare_next = true; - Ok(()) -} - -/// What a consumer's write hook does for a log. -const fn log(context: InstructionContext<'_, Ctx, EthInterpreter>) -> InstructionExecResult { - let gas = &mut context.interpreter.gas; - let rest = gas.draw_history_allowance(HISTORY_COST); - if gas.record_history_cost(rest) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } -} - -/// The mainnet [`Context`] with a start hook that does what a consumer's does for a start -/// `DECLARE` marked: charges [`DECLARED`] on the caller's gas and declares it on the start. -struct DeclaringContext { - inner: MainnetContext<Db>, - /// Set by `DECLARE`, taken by the next start. - declare_next: bool, -} - -impl ContextTr for DeclaringContext { - type Block = BlockEnv; - type Tx = TxEnv; - type Cfg = CfgEnv; - type Db = Db; - type Journal = Journal<Db>; - type Chain = (); - type Local = LocalContext; - - fn all( - &self, - ) -> ( - &Self::Block, - &Self::Tx, - &Self::Cfg, - &Self::Db, - &Self::Journal, - &Self::Chain, - &Self::Local, - ) { - self.inner.all() - } - - fn all_mut( - &mut self, - ) -> ( - &Self::Block, - &Self::Tx, - &Self::Cfg, - &mut Self::Journal, - &mut Self::Chain, - &mut Self::Local, - ) { - self.inner.all_mut() - } - - fn error(&mut self) -> &mut Result<(), ContextError<DbError>> { - self.inner.error() - } -} - -impl ContextSetters for DeclaringContext { - fn set_tx(&mut self, tx: Self::Tx) { - self.inner.set_tx(tx); - } - - fn set_block(&mut self, block: Self::Block) { - self.inner.set_block(block); - } -} - -impl Host for DeclaringContext { - fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { - if core::mem::take(&mut self.declare_next) { - assert!(gas.record_history_cost(DECLARED.history)); - assert!(gas.record_pool(FIRST, DECLARED.pools.get(FIRST))); - start.charge = DECLARED; - } - true - } - - fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64> { - self.inner.state_gas_price(id, site) - } - - fn basefee(&self) -> U256 { - self.inner.basefee() - } - - fn blob_gasprice(&self) -> U256 { - self.inner.blob_gasprice() - } - - fn gas_limit(&self) -> U256 { - self.inner.gas_limit() - } - - fn difficulty(&self) -> U256 { - self.inner.difficulty() - } - - fn prevrandao(&self) -> Option<U256> { - self.inner.prevrandao() - } - - fn block_number(&self) -> U256 { - self.inner.block_number() - } - - fn timestamp(&self) -> U256 { - self.inner.timestamp() - } - - fn beneficiary(&self) -> Address { - self.inner.beneficiary() - } - - fn slot_num(&self) -> U256 { - self.inner.slot_num() - } - - fn chain_id(&self) -> U256 { - self.inner.chain_id() - } - - fn effective_gas_price(&self) -> U256 { - self.inner.effective_gas_price() - } - - fn caller(&self) -> Address { - self.inner.caller() - } - - fn blob_hash(&self, number: usize) -> Option<U256> { - self.inner.blob_hash(number) - } - - fn max_initcode_size(&self) -> usize { - self.inner.max_initcode_size() - } - - fn gas_params(&self) -> &GasParams { - self.inner.gas_params() - } - - fn is_amsterdam_eip8037_enabled(&self) -> bool { - self.inner.is_amsterdam_eip8037_enabled() - } - - fn block_hash(&mut self, number: u64) -> Option<B256> { - self.inner.block_hash(number) - } - - fn selfdestruct( - &mut self, - address: Address, - target: Address, - skip_cold_load: bool, - ) -> Result<StateLoad<SelfDestructResult>, LoadError> { - self.inner.selfdestruct(address, target, skip_cold_load) - } - - fn log(&mut self, log: Log) { - self.inner.log(log) - } - - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result<StateLoad<SStoreResult>, LoadError> { - self.inner - .sstore_skip_cold_load(address, key, value, skip_cold_load) - } - - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result<StateLoad<StorageValue>, LoadError> { - self.inner - .sload_skip_cold_load(address, key, skip_cold_load) - } - - fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { - self.inner.tstore(address, key, value) - } - - fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { - self.inner.tload(address, key) - } - - fn load_account_info_skip_cold_load( - &mut self, - address: Address, - load_code: bool, - skip_cold_load: bool, - ) -> Result<AccountInfoLoad<'_>, LoadError> { - self.inner - .load_account_info_skip_cold_load(address, load_code, skip_cold_load) - } -} - -/// A frame's figures as it ended, before its caller settled it. -#[derive(Clone, Debug, PartialEq, Eq)] -struct Ended { - result: InstructionResult, - pool: u64, - spent: i64, - crossing: bool, - history: i64, - allowance: u64, - charged_start: StartCharge, -} - -impl Ended { - const fn stopped(pool: u64, spent: i64) -> Self { - Self::with(InstructionResult::Stop, pool, spent) - } - - const fn with(result: InstructionResult, pool: u64, spent: i64) -> Self { - Self { - result, - pool, - spent, - crossing: false, - history: 0, - allowance: 0, - charged_start: StartCharge::new(0, PoolAmounts::ZERO.with(FIRST, 0)), - } - } -} - -/// What the inspector does with a call to [`OK`]. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum Answer { - /// Lets the frame run. - #[default] - Runs, - /// Answers the start with a revert built by `CallOutcome::new`, as a tool builds one. - AsBuilt, - /// Answers the start with a revert that carries the input's share and start charge. - WithShareAndCharge, - /// Lets the frame run, and rewrites its success into a revert at `call_end`. - RewrittenIntoRevert, -} - -/// Every frame's input as it started (share, start charge, allowance) and its outcome as it -/// ended; and what the inspector does with a call to [`OK`]. -#[derive(Default)] -struct Figures { - starts: Vec<(u64, StartCharge, u64)>, - ends: Vec<Ended>, - answer: Answer, -} - -impl Figures { - fn end(&mut self, result: InstructionResult, gas: &Gas, charged: StartCharge) { - self.ends.push(Ended { - result, - pool: gas.pool_remaining(FIRST), - spent: gas.pool_spent(FIRST), - crossing: gas.pool_crossing(FIRST), - history: gas.history_gas_spent(), - allowance: gas.history_allowance(), - charged_start: charged, - }); - } -} - -impl Inspector<Ctx, EthInterpreter> for Figures { - fn call(&mut self, _context: &mut Ctx, inputs: &mut CallInputs) -> Option<CallOutcome> { - self.starts.push(( - inputs.pool_shares.get(FIRST), - inputs.charged_start, - inputs.history_allowance, - )); - let answers = matches!(self.answer, Answer::AsBuilt | Answer::WithShareAndCharge); - if !answers || inputs.target_address != OK { - return None; - } - let revert = InterpreterResult::new( - InstructionResult::Revert, - Bytes::new(), - Gas::new(inputs.gas_limit), - ); - let mut outcome = CallOutcome::new(revert, inputs.return_memory_offset.clone()); - if self.answer == Answer::WithShareAndCharge { - outcome - .result - .gas - .set_pool_remaining(FIRST, inputs.pool_shares.get(FIRST)); - outcome.charged_start = inputs.charged_start; - } - Some(outcome) - } - - fn create(&mut self, _context: &mut Ctx, inputs: &mut CreateInputs) -> Option<CreateOutcome> { - self.starts - .push((inputs.pool_shares().get(FIRST), inputs.charged_start(), 0)); - None - } - - fn call_end(&mut self, _context: &mut Ctx, inputs: &CallInputs, outcome: &mut CallOutcome) { - if self.answer == Answer::RewrittenIntoRevert && inputs.target_address == OK { - outcome.result.result = InstructionResult::Revert; - } - self.end( - *outcome.instruction_result(), - &outcome.result.gas, - outcome.charged_start, - ); - } - - fn create_end( - &mut self, - _context: &mut Ctx, - _inputs: &CreateInputs, - outcome: &mut CreateOutcome, - ) { - self.end( - *outcome.instruction_result(), - &outcome.result.gas, - outcome.charged_start, - ); - } -} - -/// `CALL(100_000, to, value, 0, 0, 0, 0)`, dropping the success flag. -fn call(to: Address, value: u8) -> Vec<u8> { - let mut code = vec![PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]; - code.extend_from_slice(to.as_slice()); - code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, CALL, POP]); - code -} - -/// `CREATE` of `initcode`, at most 32 bytes, endowed with nothing, dropping the address. -fn create(initcode: &[u8]) -> Vec<u8> { - let len = initcode.len() as u8; - let mut code = vec![PUSH0 + len]; - code.extend_from_slice(initcode); - code.extend_from_slice(&[ - PUSH0, - MSTORE, - PUSH1, - len, - PUSH1, - 32 - len, - PUSH0, - CREATE, - POP, - ]); - code -} - -fn ends(mut code: Vec<u8>) -> Vec<u8> { - code.push(STOP); - code -} - -/// A transaction to [`PARENT`], holding `parent`, on the accounts every test knows. -struct Run { - parent: Vec<u8>, - allowance: u64, -} - -impl Run { - const fn new(parent: Vec<u8>) -> Self { - Self { - parent, - allowance: 0, - } - } - - const fn allowance(mut self, allowance: u64) -> Self { - self.allowance = allowance; - self - } - - fn evm(&self) -> PoolEvm { - let mut db = Db::default(); - db.insert_account_info( - BENCH_CALLER, - AccountInfo::from_balance(U256::from(10u128.pow(21))), - ); - let mut nester = vec![DRAW]; - nester.extend(call(OK, 0)); - nester.extend_from_slice(&[PUSH0, PUSH0, REVERT]); - let accounts: [(Address, Vec<u8>); 7] = [ - (PARENT, self.parent.clone()), - (OK, vec![DRAW, STOP]), - (REVERTER, vec![DRAW, PUSH0, PUSH0, REVERT]), - (HALTER, vec![DRAW, INVALID]), - (NESTER, nester), - (DRAINER, vec![DRAIN, STOP]), - (LOGGER, vec![LOG, STOP]), - ]; - for (address, code) in accounts { - let info = AccountInfo::from_balance(U256::from(10)) - .with_nonce(1) - .with_code(Bytecode::new_raw(Bytes::from(code))); - db.insert_account_info(address, info); - } - let allowance = self.allowance; - let inner = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { - cfg.set_spec_and_mainnet_gas_params(SPEC); - cfg.gas_params - .override_gas([(GasId::call_history_allowance(), allowance)]); - }); - let ctx = DeclaringContext { - inner, - declare_next: false, - }; - let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); - instructions.insert_instruction(DRAW, Instruction::new(draw), 0); - instructions.insert_instruction(DRAIN, Instruction::new(drain), 0); - instructions.insert_instruction(LIMIT, Instruction::new(limit), 0); - instructions.insert_instruction(DECLARE, Instruction::new(declare), 0); - instructions.insert_instruction(LOG, Instruction::new(log), 0); - Evm::new_with_inspector( - ctx, - Figures::default(), - instructions, - EthPrecompiles::new(SPEC), - ) - } - - fn tx() -> TxEnv { - TxEnv::builder() - .caller(BENCH_CALLER) - .kind(TxKind::Call(PARENT)) - .gas_price(0) - .gas_limit(GAS_LIMIT) - .build() - .unwrap() - } - - /// The transaction with `transact` and with `inspect_tx`, which must end the same way. - /// Returns the outcome and the figures the inspector saw. - fn on_both_paths(&self) -> (ResultAndState, Figures) { - let mut plain = self.evm(); - let transacted = plain.transact(Self::tx()).expect("the transaction runs"); - let mut inspected = self.evm(); - let inspected_outcome = inspected - .inspect_tx(Self::tx()) - .expect("the transaction runs"); - assert_eq!(inspected_outcome, transacted, "both paths end the same way"); - (transacted, inspected.inspector) - } - - /// The transaction with `inspect_tx` alone, the inspector doing `answer` with a call to - /// [`OK`]. Returns the outcome and the figures the inspector saw. - fn inspected(&self, answer: Answer) -> (ResultAndState, Figures) { - let mut evm = self.evm(); - evm.inspector.answer = answer; - let outcome = evm.inspect_tx(Self::tx()).expect("the transaction runs"); - (outcome, evm.inspector) - } -} - -/// Both paths forward the whole pool, less the draws so far, and settle a child's return the -/// same way: what it left on success, the whole share on revert and on halt, a nested success's -/// draws undone with its caller's revert. -#[test] -fn test_both_paths_forward_and_settle_the_pool_at_depth() { - let mut parent = vec![DRAW]; - for child in [OK, REVERTER, HALTER, NESTER] { - parent.extend(call(child, 0)); - } - let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let less = |draws: u64| UNLIMITED - draws * DRAW_BYTES; - let share = |pool| (pool, StartCharge::default(), 0); - assert_eq!( - figures.starts, - [ - share(less(0)), - share(less(1)), - share(less(2)), - share(less(2)), - share(less(2)), - share(less(3)), - ] - ); - assert_eq!( - figures.ends, - [ - Ended::stopped(less(2), 100), - Ended::with(InstructionResult::Revert, less(3), 100), - Ended::with(InstructionResult::InvalidFEOpcode, less(3), 100), - Ended::stopped(less(4), 100), - Ended::with(InstructionResult::Revert, less(4), 200), - Ended::stopped(less(2), 200), - ] - ); -} - -/// A draw the pool cannot pay records a crossing the inspector reads off the frame's outcome, -/// with the pool as the draw found it, on both paths. -#[test] -fn test_both_paths_record_a_failed_draw() { - let mut parent = vec![DRAW]; - parent.extend(call(DRAINER, 0)); - let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!( - figures.ends, - [ - Ended { - crossing: true, - ..Ended::with(InstructionResult::OutOfGas, UNLIMITED - DRAW_BYTES, 0) - }, - Ended::stopped(UNLIMITED - DRAW_BYTES, DRAW_BYTES as i64), - ] - ); -} - -/// A declared start charge rides on the input and the outcome, and the caller gets it back whole -/// when the frame reverts, halts or is a creation that reverts, and keeps it when the frame -/// succeeds, on both paths. -#[test] -fn test_both_paths_refund_the_start_charge_when_the_frame_fails() { - let reverting_initcode = [PUSH0, PUSH0, REVERT]; - for (name, start, fails) in [ - ("a child that stops", call(OK, 0), false), - ("a child that reverts", call(REVERTER, 0), true), - ("a child that halts", call(HALTER, 0), true), - ("a creation that reverts", create(&reverting_initcode), true), - ] { - let mut parent = vec![DECLARE]; - parent.extend(start); - let (outcome, figures) = Run::new(ends(parent)).on_both_paths(); - - assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!( - figures.starts[1], - (UNLIMITED - DECLARED.pools.get(FIRST), DECLARED, 0), - "{name}: the charge rides on the input" - ); - assert_eq!( - figures.ends[0].charged_start, DECLARED, - "{name}: and on the outcome" - ); - let parent_end = figures.ends.last().unwrap(); - if fails { - assert_eq!( - (parent_end.pool, parent_end.spent, parent_end.history), - (UNLIMITED, 0, 0), - "{name}: refunded whole" - ); - } else { - let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; - assert_eq!( - (parent_end.pool, parent_end.spent, parent_end.history), - (UNLIMITED - drawn, drawn as i64, DECLARED.history as i64), - "{name}: kept" - ); - } - } -} - -/// A value call's child starts with the schedule's allowance on both paths, and a consumer's -/// charge takes it before the budget. -#[test] -fn test_both_paths_give_a_value_calls_child_the_allowance() { - let mut parent = call(LOGGER, 1); - parent.extend(call(LOGGER, 0)); - let (outcome, figures) = Run::new(ends(parent)).allowance(ALLOWANCE).on_both_paths(); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let allowances: Vec<u64> = figures.starts.iter().map(|start| start.2).collect(); - assert_eq!(allowances, [0, ALLOWANCE, 0]); - assert_eq!( - figures.ends, - [ - Ended { - allowance: ALLOWANCE - HISTORY_COST, - ..Ended::stopped(UNLIMITED, 0) - }, - Ended { - history: HISTORY_COST as i64, - ..Ended::stopped(UNLIMITED, 0) - }, - Ended { - history: HISTORY_COST as i64, - ..Ended::stopped(UNLIMITED, 0) - }, - ] - ); -} - -/// [`PARENT`] limits its pool to [`LIMITED`] and calls [`OK`] with a start charge declared, on -/// the inspected path alone, the inspector doing `answer`. Returns the share the call was given, -/// [`OK`]'s outcome as the inspector left it, and [`PARENT`]'s pool, net and history after the -/// settlement. -fn limited_call_to_ok(answer: Answer) -> (u64, Ended, (u64, i64, i64)) { - let parent = ends([vec![LIMIT, DECLARE], call(OK, 0)].concat()); - let (outcome, figures) = Run::new(parent).inspected(answer); - - assert!( - outcome.result.is_success(), - "{answer:?}: {:?}", - outcome.result - ); - let [ok, parent_end] = &figures.ends[..] else { - panic!("{answer:?}: {} ends", figures.ends.len()); - }; - assert_eq!(figures.starts[1].1, DECLARED, "{answer:?}"); - ( - figures.starts[1].0, - ok.clone(), - (parent_end.pool, parent_end.spent, parent_end.history), - ) -} - -/// An outcome the inspector builds to answer a start settles as built, as revm settles its own -/// upfront state charge on such an outcome. `CallOutcome::new` carries no start charge and an -/// unlimited pool, so a caller whose start the inspector answers with a revert keeps the start -/// charge, and its limited pool, plus the unlimited one absorbed, saturates to `u64::MAX`. An -/// answer that carries the input's share and charge settles as the frame's own revert would: the -/// caller gets the share and the charge back. -#[test] -fn test_an_outcome_the_inspector_builds_settles_as_built() { - let share = LIMITED - DECLARED.pools.get(FIRST); - for (answer, answered, kept) in [ - ( - Answer::AsBuilt, - Ended::with(InstructionResult::Revert, UNLIMITED, 0), - ( - UNLIMITED, - DECLARED.pools.get(FIRST) as i64, - DECLARED.history as i64, - ), - ), - ( - Answer::WithShareAndCharge, - Ended { - charged_start: DECLARED, - ..Ended::with(InstructionResult::Revert, share, 0) - }, - (LIMITED, 0, 0), - ), - ] { - assert_eq!( - limited_call_to_ok(answer), - (share, answered, kept), - "{answer:?}: the share, the answer as built, the caller after the settlement" - ); - } -} - -/// A frame's outcome carries its input's start charge, so a success the inspector rewrites into a -/// revert at `call_end` refunds the charge and rolls the frame's draws back, as the frame's own -/// revert would; the frame left alone keeps both. -#[test] -fn test_a_success_the_inspector_rewrites_into_a_revert_refunds_the_start_charge() { - let share = LIMITED - DECLARED.pools.get(FIRST); - let drawn = DECLARED.pools.get(FIRST) + DRAW_BYTES; - for (answer, result, kept) in [ - ( - Answer::Runs, - InstructionResult::Stop, - (LIMITED - drawn, drawn as i64, DECLARED.history as i64), - ), - ( - Answer::RewrittenIntoRevert, - InstructionResult::Revert, - (LIMITED, 0, 0), - ), - ] { - let ended = Ended { - charged_start: DECLARED, - ..Ended::with(result, share - DRAW_BYTES, DRAW_BYTES as i64) - }; - assert_eq!( - limited_call_to_ok(answer), - (share, ended, kept), - "{answer:?}: the share, the frame's outcome as the inspector left it, the caller after \ - the settlement" - ); - } -} diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index 49f0a62126..796eeaed50 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -3,7 +3,6 @@ pub use context_interface::cfg::gas::*; mod failed_charge; -mod pools; mod withheld; /// Represents the state of gas during execution. diff --git a/crates/interpreter/src/gas/pools.rs b/crates/interpreter/src/gas/pools.rs deleted file mode 100644 index e9a26cf32a..0000000000 --- a/crates/interpreter/src/gas/pools.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! The resource pools and the history allowance, on [`Gas`]. -//! -//! Each method forwards to the [`GasTracker`](super::GasTracker) method of the same name, which -//! documents it. - -use super::{Gas, PoolId}; - -impl Gas { - /// The pool: what this frame may still draw from it. Unlimited unless a consumer set it. - /// - /// See [`GasTracker::pool_remaining`](super::GasTracker::pool_remaining). - #[inline] - pub const fn pool_remaining(&self, pool: PoolId) -> u64 { - self.tracker.pool_remaining(pool) - } - - /// Sets the pool. - /// - /// See [`GasTracker::set_pool_remaining`](super::GasTracker::set_pool_remaining). - #[inline] - pub const fn set_pool_remaining(&mut self, pool: PoolId, val: u64) { - self.tracker.set_pool_remaining(pool, val); - } - - /// The frame's net draw of the pool so far, signed. - /// - /// See [`GasTracker::pool_spent`](super::GasTracker::pool_spent). - #[inline] - pub const fn pool_spent(&self, pool: PoolId) -> i64 { - self.tracker.pool_spent(pool) - } - - /// Sets the pool's net draw. - /// - /// See [`GasTracker::set_pool_spent`](super::GasTracker::set_pool_spent). - #[inline] - pub const fn set_pool_spent(&mut self, pool: PoolId, val: i64) { - self.tracker.set_pool_spent(pool, val); - } - - /// Draws `cost` from the pool; `false` if the pool cannot pay, which sets its crossing - /// ([`pool_crossing`](Self::pool_crossing)). - /// - /// See [`GasTracker::record_pool`](super::GasTracker::record_pool). - #[inline] - #[must_use = "a draw the pool cannot pay is the consumer's stop"] - pub const fn record_pool(&mut self, pool: PoolId, cost: u64) -> bool { - self.tracker.record_pool(pool, cost) - } - - /// Gives `amount` back to the pool. - /// - /// See [`GasTracker::refill_pool`](super::GasTracker::refill_pool). - #[inline] - pub const fn refill_pool(&mut self, pool: PoolId, amount: u64) { - self.tracker.refill_pool(pool, amount); - } - - /// Whether a draw failed that the pool could not pay, since the record was last cleared. - /// - /// See [`GasTracker::pool_crossing`](super::GasTracker::pool_crossing). - #[inline] - pub const fn pool_crossing(&self, pool: PoolId) -> bool { - self.tracker.pool_crossing(pool) - } - - /// Clears the record returned by [`pool_crossing`](Self::pool_crossing). - /// - /// See [`GasTracker::clear_pool_crossing`](super::GasTracker::clear_pool_crossing). - #[inline] - pub const fn clear_pool_crossing(&mut self, pool: PoolId) { - self.tracker.clear_pool_crossing(pool); - } - - /// Sets the record returned by [`pool_crossing`](Self::pool_crossing). - /// - /// See [`GasTracker::set_pool_crossing`](super::GasTracker::set_pool_crossing). - #[inline] - pub const fn set_pool_crossing(&mut self, pool: PoolId, crossing: bool) { - self.tracker.set_pool_crossing(pool, crossing); - } - - /// History gas this frame may spend before it charges its budget. - /// - /// See [`GasTracker::history_allowance`](super::GasTracker::history_allowance). - #[inline] - pub const fn history_allowance(&self) -> u64 { - self.tracker.history_allowance() - } - - /// Sets the history allowance. - /// - /// See [`GasTracker::set_history_allowance`](super::GasTracker::set_history_allowance). - #[inline] - pub const fn set_history_allowance(&mut self, val: u64) { - self.tracker.set_history_allowance(val); - } - - /// Draws `min(cost, allowance)` from the allowance and returns the part of `cost` it did not - /// cover. - /// - /// See [`GasTracker::draw_history_allowance`](super::GasTracker::draw_history_allowance). - #[inline] - #[must_use = "the part of the cost the allowance did not cover is still to be charged"] - pub const fn draw_history_allowance(&mut self, cost: u64) -> u64 { - self.tracker.draw_history_allowance(cost) - } -} diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 392ff73898..fee76465c9 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -194,14 +194,11 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( value, gas_limit, ); - let (charged_start, reservoir) = - frame_starting(&mut context.interpreter.gas, context.host, start)?; + let reservoir = frame_starting(&mut context.interpreter.gas, context.host, start)?; let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); create_inputs.set_gas_limit(gas_limit); create_inputs.set_reservoir(shares.reservoir); - create_inputs.set_charged_start(charged_start); - create_inputs.set_pool_shares(shares.pools); context .interpreter .bytecode @@ -245,14 +242,8 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, get_memory_input_and_out_ranges(context.interpreter, context.host.gas_params())?; let is_call = KIND == CALL; - let ( - gas_limit, - bytecode, - bytecode_hash, - charged_new_account_state_gas, - forward, - history_allowance, - ) = load_acc_and_calc_forward(&mut context, to, has_transfer, is_call, local_gas_limit)?; + let (gas_limit, bytecode, bytecode_hash, charged_new_account_state_gas, forward) = + load_acc_and_calc_forward(&mut context, to, has_transfer, is_call, local_gas_limit)?; let target_address = if matches!(KIND, CALLCODE | DELEGATECALL) { context.interpreter.input.target_address() @@ -286,8 +277,7 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, }; let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); - let (charged_start, reservoir) = - frame_starting(&mut context.interpreter.gas, context.host, start)?; + let reservoir = frame_starting(&mut context.interpreter.gas, context.host, start)?; let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); // Call host to interact with target contract @@ -308,9 +298,6 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, return_memory_offset, reservoir: shares.reservoir, charged_new_account_state_gas, - charged_start, - pool_shares: shares.pools, - history_allowance, }, )))); Err(InstructionResult::Suspend) diff --git a/crates/interpreter/src/instructions/contract/call_helpers.rs b/crates/interpreter/src/instructions/contract/call_helpers.rs index 9b4ebf2e13..78f67d1a34 100644 --- a/crates/interpreter/src/instructions/contract/call_helpers.rs +++ b/crates/interpreter/src/instructions/contract/call_helpers.rs @@ -77,20 +77,15 @@ pub fn load_acc_and_calc_gas<H: Host + ?Sized>( create_empty_account, stack_gas_limit, ) - .map(|(gas_limit, bytecode, code_hash, charged, _, _)| { - (gas_limit, bytecode, code_hash, charged) - }) + .map(|(gas_limit, bytecode, code_hash, charged, _)| (gas_limit, bytecode, code_hash, charged)) } /// [`load_acc_and_calc_gas`], also returning the forward, the gas taken from the caller for the -/// frame, which is the frame's gas limit without a value call's stipend, and the frame's history -/// allowance, the schedule's `call_history_allowance` for a call that transfers value and zero -/// otherwise, decided where the stipend is. +/// frame, which is the frame's gas limit without a value call's stipend. /// -/// Returns `(gas_limit, bytecode, code_hash, charged_new_account_state_gas, forward, -/// history_allowance)`. The forward and the allowance come last, after the fields -/// [`load_acc_and_calc_gas`] returns: placed second, the forward changed how the others are -/// stored and cost two more instructions per call. +/// Returns `(gas_limit, bytecode, code_hash, charged_new_account_state_gas, forward)`. The forward +/// comes last, after the fields [`load_acc_and_calc_gas`] returns: placed second, it changed how +/// the others are stored and cost two more instructions per call. #[inline(never)] pub(super) fn load_acc_and_calc_forward<H: Host + ?Sized>( context: &mut Ictx<'_, H, impl ITy>, @@ -98,7 +93,7 @@ pub(super) fn load_acc_and_calc_forward<H: Host + ?Sized>( transfers_value: bool, create_empty_account: bool, stack_gas_limit: u64, -) -> Result<(u64, Bytecode, B256, bool, u64, u64), InstructionResult> { +) -> Result<(u64, Bytecode, B256, bool, u64), InstructionResult> { // Transfer value cost if transfers_value { gas!( @@ -140,12 +135,9 @@ pub(super) fn load_acc_and_calc_forward<H: Host + ?Sized>( let forward = gas_limit; - // Add call stipend if there is value to be transferred, and with it the history allowance - // the schedule gives a value call's child (zero on every schedule defined here). - let mut history_allowance = 0; + // Add call stipend if there is value to be transferred. if transfers_value { gas_limit = gas_limit.saturating_add(host.gas_params().call_stipend()); - history_allowance = host.gas_params().call_history_allowance(); } Ok(( @@ -154,7 +146,6 @@ pub(super) fn load_acc_and_calc_forward<H: Host + ?Sized>( code_hash, charged_new_account_state_gas, forward, - history_allowance, )) } diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index d5a199fbc4..04b1c3138a 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -4,7 +4,7 @@ use crate::{ interpreter_types::{InterpreterTypes as ITy, LoopControl}, ChildShares, CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, - Interpreter, InterpreterAction, StartCharge, + Interpreter, InterpreterAction, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Address, Bytes, U256}; @@ -44,18 +44,17 @@ fn revert<IT: ITy>(interpreter: &mut Interpreter<IT>, output: Bytes) -> Result { } /// Hands `start`, whose forward the running instruction has taken from `gas`, to -/// [`Host::frame_starting`]. `true` returns what the hook declared on `start` for the frame: the -/// start charge, for the frame's input, and the child's reservoir if the hook took it itself, for -/// the forward ([`forward_to_child`]); `false` fails the instruction out of gas, and the charge -/// goes with the start it was declared for. +/// [`Host::frame_starting`]. `true` returns the child's reservoir if the hook took it itself and +/// named it on `start`, for the forward ([`forward_to_child`]); `false` fails the instruction out +/// of gas. #[inline] pub(crate) fn frame_starting<H: Host + ?Sized>( gas: &mut Gas, host: &mut H, mut start: FrameStart, -) -> core::result::Result<(StartCharge, Option<u64>), InstructionResult> { +) -> core::result::Result<Option<u64>, InstructionResult> { if host.frame_starting(&mut start, gas.tracker_mut()) { - Ok((start.charge, start.reservoir)) + Ok(start.reservoir) } else { cold_path(); Err(InstructionResult::OutOfGas) @@ -94,11 +93,10 @@ pub(crate) fn running_account<H: Host + ?Sized>( Ok((account.balance, account.nonce)) } -/// Takes the child's shares of the caller's reservoir and pools out of `gas`, all but the -/// schedule's `reservoir_kept_percent` and `pool_kept_percent`s, and returns them: what the child's -/// tracker starts with ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). -/// Called once the frame-start hook has answered, so the shares are of the reservoir and the pools -/// as the hook left them. A child `reservoir` the hook named replaces the reservoir's share: the +/// Takes the child's share of the caller's reservoir out of `gas`, all but the schedule's +/// `reservoir_kept_percent`, and returns it: what the child's tracker starts with +/// ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). Called once the +/// frame-start hook has answered, so the share is of the reservoir as the hook left it. A child `reservoir` the hook named replaces the reservoir's share: the /// child starts with it, and the caller keeps the reservoir the hook left /// ([`GasTracker::forward_to_child_with_reservoir`](crate::GasTracker::forward_to_child_with_reservoir)). #[inline] diff --git a/crates/interpreter/src/interpreter_action/call_inputs.rs b/crates/interpreter/src/interpreter_action/call_inputs.rs index bac1a3c263..bfa6d2d2da 100644 --- a/crates/interpreter/src/interpreter_action/call_inputs.rs +++ b/crates/interpreter/src/interpreter_action/call_inputs.rs @@ -1,8 +1,5 @@ use crate::interpreter_types::MemoryTr; -use context_interface::{ - cfg::gas::{PoolAmounts, StartCharge}, - ContextTr, LocalContextTr, -}; +use context_interface::{ContextTr, LocalContextTr}; use core::ops::Range; use primitives::{Address, Bytes, B256, U256}; use state::Bytecode; @@ -177,37 +174,6 @@ pub struct CallInputs { /// On revert/halt of the resulting frame the parent must refund this charge /// to the reservoir, matching the CREATE pattern. pub charged_new_account_state_gas: bool, - /// What the frame-start hook charged the caller for this call and the call's failure gives - /// back: history gas and an amount of each pool, refunded to the caller by `return_result` - /// when the call does not succeed, as `charged_new_account_state_gas` is. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as no charge. - #[cfg_attr(feature = "serde", serde(default))] - pub charged_start: StartCharge, - /// The share of each of the caller's pools the call receives: its pools when it starts. - /// Taken out of the caller's pools by the call instruction, all but the schedule's - /// `pool_kept_percent` of each, and given back with what the call left of them when it - /// returns. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as every pool unlimited. - #[cfg_attr(feature = "serde", serde(default = "unlimited_pools"))] - pub pool_shares: PoolAmounts, - /// History gas the call may spend before it charges its budget: the schedule's - /// `call_history_allowance` for a call that transfers value, set where the call instruction - /// adds the call stipend, and zero otherwise. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as zero. - #[cfg_attr(feature = "serde", serde(default))] - pub history_allowance: u64, -} - -/// The shares an encoding that predates the pools decodes to in a format that carries field names. -#[cfg(feature = "serde")] -const fn unlimited_pools() -> PoolAmounts { - PoolAmounts::UNLIMITED } impl CallInputs { diff --git a/crates/interpreter/src/interpreter_action/call_outcome.rs b/crates/interpreter/src/interpreter_action/call_outcome.rs index 68a51d9cbf..bcd70dfea8 100644 --- a/crates/interpreter/src/interpreter_action/call_outcome.rs +++ b/crates/interpreter/src/interpreter_action/call_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark, PoolAmounts, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark}; use core::ops::Range; use primitives::{Address, Bytes, Log}; use std::vec::Vec; @@ -40,14 +40,6 @@ pub struct CallOutcome { /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, - /// Copied from `CallInputs::charged_start`: what the frame-start hook charged the caller for - /// this call and the call's failure gives back, so the parent can refund it when the call - /// does not succeed. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as no charge. - #[cfg_attr(feature = "serde", serde(default))] - pub charged_start: StartCharge, /// The start revm marked this outcome for before an inspector's end callbacks /// ([`OutcomeMark`]): none on an outcome a constructor builds. No part of the outcome's value: /// equality, the debug output and the encoding leave it out, and a decoded outcome carries @@ -70,7 +62,6 @@ impl core::fmt::Debug for CallOutcome { &self.charged_new_account_state_gas, ) .field("charged_state_gas_address", &self.charged_state_gas_address) - .field("charged_start", &self.charged_start) .finish() } } @@ -92,7 +83,6 @@ impl CallOutcome { precompile_call_logs: Vec::new(), charged_new_account_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, PoolAmounts::ZERO), start_mark: OutcomeMark::NONE, } } diff --git a/crates/interpreter/src/interpreter_action/create_inputs.rs b/crates/interpreter/src/interpreter_action/create_inputs.rs index f15ee5f0e9..87135cbf11 100644 --- a/crates/interpreter/src/interpreter_action/create_inputs.rs +++ b/crates/interpreter/src/interpreter_action/create_inputs.rs @@ -1,12 +1,9 @@ -use context_interface::{ - cfg::gas::{PoolAmounts, StartCharge}, - CreateScheme, -}; +use context_interface::CreateScheme; use core::cell::OnceCell; use primitives::{keccak256, Address, Bytes, B256, U256}; /// Inputs for a create call -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CreateInputs { /// Caller address of the EVM @@ -33,23 +30,6 @@ pub struct CreateInputs { /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] charged_state_gas_address: Address, - /// What the frame-start hook charged the caller for this creation and the creation's failure - /// gives back: history gas and an amount of each pool, refunded to the caller by - /// `return_result` when the creation fails, as `charged_create_state_gas` is. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as no charge. - #[cfg_attr(feature = "serde", serde(default))] - charged_start: StartCharge, - /// The share of each of the caller's pools the creation receives: its pools when it starts. - /// Taken out of the caller's pools by the creation instruction, all but the schedule's - /// `pool_kept_percent` of each, and given back with what the creation left of them when it - /// returns. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as every pool unlimited. - #[cfg_attr(feature = "serde", serde(default = "unlimited_pools"))] - pool_shares: PoolAmounts, /// Cached created address. This is computed lazily and cached to avoid /// redundant keccak computations when inspectors call `created_address`. #[cfg_attr(feature = "serde", serde(skip))] @@ -61,27 +41,6 @@ pub struct CreateInputs { cached_init_code_hash: OnceCell<B256>, } -/// The shares an encoding that predates the pools decodes to in a format that carries field names. -#[cfg(feature = "serde")] -const fn unlimited_pools() -> PoolAmounts { - PoolAmounts::UNLIMITED -} - -impl Default for CreateInputs { - /// Empty inputs, as [`new`](Self::new) builds them, so the shares start unlimited. - #[inline] - fn default() -> Self { - Self::new( - Address::ZERO, - CreateScheme::Create, - U256::ZERO, - Bytes::new(), - 0, - 0, - ) - } -} - impl CreateInputs { /// Creates a new `CreateInputs` instance. pub const fn new( @@ -101,8 +60,6 @@ impl CreateInputs { reservoir, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, PoolAmounts::ZERO), - pool_shares: PoolAmounts::UNLIMITED, cached_address: OnceCell::new(), cached_init_code_hash: OnceCell::new(), } @@ -223,25 +180,4 @@ impl CreateInputs { pub const fn set_reservoir(&mut self, reservoir: u64) { self.reservoir = reservoir; } - - /// What the frame-start hook charged the caller for this creation and the creation's failure - /// gives back. - pub const fn charged_start(&self) -> StartCharge { - self.charged_start - } - - /// Records what the frame-start hook charged the caller for this creation. - pub const fn set_charged_start(&mut self, charge: StartCharge) { - self.charged_start = charge; - } - - /// The share of each of the caller's pools the creation receives: its pools when it starts. - pub const fn pool_shares(&self) -> PoolAmounts { - self.pool_shares - } - - /// Sets the share of each of the caller's pools the creation receives. - pub const fn set_pool_shares(&mut self, shares: PoolAmounts) { - self.pool_shares = shares; - } } diff --git a/crates/interpreter/src/interpreter_action/create_outcome.rs b/crates/interpreter/src/interpreter_action/create_outcome.rs index 3f20890d72..0207596a2e 100644 --- a/crates/interpreter/src/interpreter_action/create_outcome.rs +++ b/crates/interpreter/src/interpreter_action/create_outcome.rs @@ -1,4 +1,4 @@ -use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark, PoolAmounts, StartCharge}; +use crate::{Gas, InstructionResult, InterpreterResult, OutcomeMark}; use primitives::{Address, Bytes}; /// Represents the outcome of a create operation in an interpreter. @@ -27,14 +27,6 @@ pub struct CreateOutcome { /// decode it as [`Address::ZERO`]. #[cfg_attr(feature = "serde", serde(default))] pub charged_state_gas_address: Address, - /// Copied from `CreateInputs::charged_start`: what the frame-start hook charged the caller - /// for this creation and the creation's failure gives back, so the parent can refund it when - /// the creation fails. - /// - /// In a format that carries field names, such as JSON, encodings made before this field existed - /// decode it as no charge. - #[cfg_attr(feature = "serde", serde(default))] - pub charged_start: StartCharge, /// The start revm marked this outcome for before an inspector's end callbacks /// ([`OutcomeMark`]): none on an outcome a constructor builds. No part of the outcome's value: /// equality, the debug output and the encoding leave it out, and a decoded outcome carries @@ -52,7 +44,6 @@ impl core::fmt::Debug for CreateOutcome { .field("address", &self.address) .field("charged_create_state_gas", &self.charged_create_state_gas) .field("charged_state_gas_address", &self.charged_state_gas_address) - .field("charged_start", &self.charged_start) .finish() } } @@ -74,7 +65,6 @@ impl CreateOutcome { address, charged_create_state_gas: false, charged_state_gas_address: Address::ZERO, - charged_start: StartCharge::new(0, PoolAmounts::ZERO), start_mark: OutcomeMark::NONE, } } diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 201f458966..b41f53dd62 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,9 +36,7 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{ - ChildShares, Gas, GasTracker, OutcomeMark, PoolAmounts, PoolId, StartCharge, StartMark, -}; +pub use gas::{ChildShares, Gas, GasTracker, OutcomeMark, StartMark}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index f94c7def6c..a360b881f4 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -24,7 +24,7 @@ use revm_interpreter::{ instructions::gas_table_spec, interpreter::{EthInterpreter, ExtBytecode}, FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, PoolAmounts, SharedMemory, + InterpreterAction, SharedMemory, }; use state::AccountInfo; use std::borrow::Cow; @@ -850,7 +850,7 @@ fn input_gas(input: &FrameInput) -> (u64, u64) { /// Each frame-starting instruction hands its start to the hook once the forward is taken, and /// charges nothing after it: the instruction leaves the gas the hook was handed, apart from the -/// reservoir and the pools, whose shares go to the frame after the hook, and the frame's input carries the +/// reservoir, whose share goes to the frame after the hook, and the frame's input carries the /// forward, with a value call's stipend on top. #[test] fn test_a_start_reaches_the_hook_with_the_forward_taken() { @@ -895,12 +895,10 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { ); let mut after_the_forward = at_hook; after_the_forward.set_reservoir(0); - after_the_forward.set_pools_remaining(PoolAmounts::ZERO); assert_eq!( *gas.tracker(), after_the_forward, - "{name}: nothing is charged after the hook; the whole reservoir and every whole pool \ - are forwarded" + "{name}: nothing is charged after the hook; the whole reservoir is forwarded" ); let stipend = if matches!(op, CALL | CALLCODE) { params.call_stipend() @@ -1091,16 +1089,10 @@ fn test_the_input_copies_the_reservoir_the_hook_left() { /// A hook that takes the child's reservoir out of the caller's itself names it on the start /// ([`FrameStart::reservoir`]): the frame's input carries it, and the instruction takes no -/// reservoir share of its own, so the caller keeps what the hook left. The pools are forwarded by -/// the schedule as without the hook's reservoir. +/// reservoir share of its own, so the caller keeps what the hook left. #[test] fn test_the_input_carries_the_child_reservoir_the_hook_names() { let spec = SpecId::AMSTERDAM; - let pools = |input: &FrameInput| match input { - FrameInput::Call(inputs) => inputs.pool_shares, - FrameInput::Create(inputs) => inputs.pool_shares(), - FrameInput::Empty => panic!("an empty frame input"), - }; for (name, code, _) in start_cases() { let mut quiet = HookHost::new(spec); let (quiet_action, quiet_gas) = run(spec, &code, AMPLE, 10_000, &mut quiet); @@ -1125,13 +1117,6 @@ fn test_the_input_carries_the_child_reservoir_the_hook_names() { 4_000, "{name}: the caller keeps what the hook left" ); - assert_eq!( - pools(&input), - pools(&quiet_input), - "{name}: the pools' shares" - ); - let pools_left = |gas: &Gas| gas.tracker().pools_remaining(); - assert_eq!(pools_left(&gas), pools_left(&quiet_gas), "{name}"); assert_eq!(gas.remaining(), quiet_gas.remaining(), "{name}"); } } diff --git a/crates/interpreter/tests/resource_pools.rs b/crates/interpreter/tests/resource_pools.rs deleted file mode 100644 index 25afd62d7a..0000000000 --- a/crates/interpreter/tests/resource_pools.rs +++ /dev/null @@ -1,588 +0,0 @@ -//! The resource pools, the reservoir share, the start charge and the history allowance at the call -//! and creation instructions. -//! -//! Once [`Host::frame_starting`] has answered, the instruction copies the start charge the hook -//! declared on the start onto the frame's input, takes the child's shares of the caller's -//! reservoir and pools out of them and puts them on the input too, and, for a value call, gives -//! the input the schedule's history allowance. Each test runs one frame on [`PoolHost`], whose -//! start hook draws from a pool of the gas it is handed, declares a start charge, and admits or -//! refuses the start as the test tells it. - -use bytecode::{opcode::*, Bytecode}; -use context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, - context::{SStoreResult, SelfDestructResult, StateLoad}, - host::{CompletedWrite, FrameStart, FrameStartKind, LoadError, WriteVerdict}, - journaled_state::AccountInfoLoad, -}; -use primitives::{ - address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, B256, U256, -}; -use revm_interpreter::{ - host::DummyHost, - instruction_table, - instructions::gas_table_spec, - interpreter::{EthInterpreter, ExtBytecode}, - FrameInput, Gas, GasTracker, Host, InputsImpl, InstructionResult, Interpreter, - InterpreterAction, PoolAmounts, PoolId, SharedMemory, StartCharge, -}; -use state::AccountInfo; -use std::borrow::Cow; - -/// The account the frame runs as. -const CONTRACT: Address = address!("0x000000000000000000000000000000000000c0de"); -/// The frame's caller. -const CALLER: Address = address!("0x00000000000000000000000000000000000ca11e"); -/// The account a call names. -const TARGET: Address = address!("0x0000000000000000000000000000000000007a59"); -/// Gas enough for every frame here. -const AMPLE: u64 = 1_000_000; -/// The pool the frame starts with, unless a test leaves it unlimited. -const POOL: u64 = 1_000; -/// The pool the tests draw: any of the tracker's pools behaves the same. -const FIRST: PoolId = PoolId::new(0); -/// A start charge a hook declares. -const DECLARED: StartCharge = StartCharge::new(3_520, PoolAmounts::ZERO.with(FIRST, 160)); -/// What a chain's schedule sets: the child's share and a value call's allowance. -const PERCENT: u64 = 98; -const ALLOWANCE: u64 = 160; - -/// A [`DummyHost`] whose start hook draws [`PoolHost::draw`] bytes from the gas it is handed, -/// declares [`PoolHost::declare`] on the start, records what it saw, and answers -/// [`PoolHost::admit`]. -struct PoolHost { - dummy: DummyHost, - spec: SpecId, - params: GasParams, - draw: u64, - declare: StartCharge, - admit: bool, - /// Every start the hook saw and the gas, both as the hook found them, and whether its draw - /// paid. - starts: Vec<(FrameStart, GasTracker, bool)>, -} - -impl PoolHost { - fn new(spec: SpecId) -> Self { - Self { - dummy: DummyHost::new(spec), - spec, - params: GasParams::new_spec(spec), - draw: 0, - declare: StartCharge::default(), - admit: true, - starts: Vec::new(), - } - } - - /// The schedule of a chain that keeps part of the pool for the caller and gives a value - /// call's child an allowance. - fn on_a_chains_schedule(mut self) -> Self { - self.params.override_gas([ - (GasId::pool_kept_percent(FIRST), 100 - PERCENT), - (GasId::call_history_allowance(), ALLOWANCE), - ]); - self - } - - const fn drawing(mut self, draw: u64) -> Self { - self.draw = draw; - self - } - - const fn declaring(mut self, charge: StartCharge) -> Self { - self.declare = charge; - self - } - - const fn refusing(mut self) -> Self { - self.admit = false; - self - } - - /// The one start the hook saw. - fn start(&self) -> &(FrameStart, GasTracker, bool) { - assert_eq!(self.starts.len(), 1, "one start: {:?}", self.starts); - &self.starts[0] - } -} - -impl Host for PoolHost { - fn write_completed(&mut self, _: CompletedWrite<'_>, _: &mut GasTracker) -> WriteVerdict { - WriteVerdict::Continue - } - - fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { - let found = (*start, *gas); - let paid = gas.record_pool(FIRST, self.draw); - start.charge = self.declare; - self.starts.push((found.0, found.1, paid)); - self.admit && paid - } - - fn state_gas_price(&mut self, id: GasId, _site: StateGasSite) -> Option<u64> { - Some(self.gas_params().get(id)) - } - - fn basefee(&self) -> U256 { - self.dummy.basefee() - } - fn blob_gasprice(&self) -> U256 { - self.dummy.blob_gasprice() - } - fn gas_limit(&self) -> U256 { - self.dummy.gas_limit() - } - fn difficulty(&self) -> U256 { - self.dummy.difficulty() - } - fn prevrandao(&self) -> Option<U256> { - self.dummy.prevrandao() - } - fn block_number(&self) -> U256 { - self.dummy.block_number() - } - fn timestamp(&self) -> U256 { - self.dummy.timestamp() - } - fn beneficiary(&self) -> Address { - self.dummy.beneficiary() - } - fn slot_num(&self) -> U256 { - self.dummy.slot_num() - } - fn chain_id(&self) -> U256 { - self.dummy.chain_id() - } - fn effective_gas_price(&self) -> U256 { - self.dummy.effective_gas_price() - } - fn caller(&self) -> Address { - self.dummy.caller() - } - fn blob_hash(&self, number: usize) -> Option<U256> { - self.dummy.blob_hash(number) - } - fn max_initcode_size(&self) -> usize { - usize::MAX - } - fn gas_params(&self) -> &GasParams { - &self.params - } - fn is_amsterdam_eip8037_enabled(&self) -> bool { - self.dummy.is_amsterdam_eip8037_enabled() - } - fn block_hash(&mut self, number: u64) -> Option<B256> { - self.dummy.block_hash(number) - } - - fn selfdestruct( - &mut self, - _address: Address, - _target: Address, - _skip_cold_load: bool, - ) -> Result<StateLoad<SelfDestructResult>, LoadError> { - Ok(StateLoad::new(SelfDestructResult::default(), false)) - } - - fn log(&mut self, log: Log) { - self.dummy.log(log) - } - - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result<StateLoad<SStoreResult>, LoadError> { - self.dummy - .sstore_skip_cold_load(address, key, value, skip_cold_load) - } - - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result<StateLoad<StorageValue>, LoadError> { - self.dummy - .sload_skip_cold_load(address, key, skip_cold_load) - } - - fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { - self.dummy.tstore(address, key, value) - } - - fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { - self.dummy.tload(address, key) - } - - fn load_account_info_skip_cold_load( - &mut self, - _address: Address, - _load_code: bool, - _skip_cold_load: bool, - ) -> Result<AccountInfoLoad<'_>, LoadError> { - Ok(AccountInfoLoad { - account: Cow::Owned(AccountInfo::from_balance(U256::from(AMPLE))), - is_cold: false, - is_empty: false, - }) - } -} - -/// Runs `code` as [`CONTRACT`], called by [`CALLER`], with [`AMPLE`] gas and [`FIRST`] at -/// `pool`, if given, and returns what the frame asked for and its gas. -fn run(code: &[u8], pool: Option<u64>, host: &mut PoolHost) -> (InterpreterAction, Gas) { - run_on(code, host, |gas| { - if let Some(pool) = pool { - gas.set_pool_remaining(FIRST, pool); - } - }) -} - -/// Runs `code` as [`run`] does, on the gas `prepare` leaves. -fn run_on( - code: &[u8], - host: &mut PoolHost, - prepare: impl FnOnce(&mut Gas), -) -> (InterpreterAction, Gas) { - let spec = host.spec; - let mut interpreter = Interpreter::<EthInterpreter>::new( - SharedMemory::new(), - ExtBytecode::new(Bytecode::new_raw(Bytes::copy_from_slice(code))), - InputsImpl { - target_address: CONTRACT, - caller_address: CALLER, - ..Default::default() - }, - false, - spec, - AMPLE, - ); - prepare(&mut interpreter.gas); - let table = instruction_table::<EthInterpreter, PoolHost>(); - let action = interpreter.run_plain(&table, &gas_table_spec(spec), host); - (action, interpreter.gas) -} - -/// The frame a frame asked to start. -fn started(action: InterpreterAction) -> FrameInput { - match action { - InterpreterAction::NewFrame(input) => input, - other => panic!("expected a new frame, got {other:?}"), - } -} - -/// The result a frame returned with. -fn returned(action: InterpreterAction) -> InstructionResult { - match action { - InterpreterAction::Return(result) => result.result, - other => panic!("expected the frame to return, got {other:?}"), - } -} - -/// The pool figures of a started frame's input: its share, its start charge and its history -/// allowance (a creation has none). -fn figures(input: &FrameInput) -> (u64, StartCharge, u64) { - match input { - FrameInput::Call(inputs) => ( - inputs.pool_shares.get(FIRST), - inputs.charged_start, - inputs.history_allowance, - ), - FrameInput::Create(inputs) => (inputs.pool_shares().get(FIRST), inputs.charged_start(), 0), - FrameInput::Empty => unreachable!(), - } -} - -/// `op` (a call) to [`TARGET`] with `value` (for `CALL` and `CALLCODE`), no input and no output, -/// then `STOP`. -fn call_code(op: u8, value: u8) -> Vec<u8> { - let mut code = vec![PUSH1, 0, PUSH1, 0, PUSH1, 0, PUSH1, 0]; - if matches!(op, CALL | CALLCODE) { - code.extend_from_slice(&[PUSH1, value]); - } - code.push(PUSH20); - code.extend_from_slice(TARGET.as_slice()); - code.extend_from_slice(&[PUSH3, 0x01, 0x86, 0xa0, op, STOP]); - code -} - -/// `op` (`CREATE` or `CREATE2`) of one byte of memory, endowed with nothing, then `STOP`. -fn create_code(op: u8) -> Vec<u8> { - let mut code = Vec::new(); - if op == CREATE2 { - code.extend_from_slice(&[PUSH1, 0x5a]); - } - code.extend_from_slice(&[PUSH1, 1, PUSH1, 0, PUSH1, 0, op, STOP]); - code -} - -/// A start of each kind. -fn start_cases() -> Vec<(FrameStartKind, Vec<u8>)> { - vec![ - (FrameStartKind::Call, call_code(CALL, 1)), - (FrameStartKind::CallCode, call_code(CALLCODE, 1)), - (FrameStartKind::DelegateCall, call_code(DELEGATECALL, 0)), - (FrameStartKind::StaticCall, call_code(STATICCALL, 0)), - (FrameStartKind::Create, create_code(CREATE)), - (FrameStartKind::Create2, create_code(CREATE2)), - ] -} - -/// With the schedule as it is, every start forwards the whole pool: the child's share is the -/// caller's pool, the caller keeps nothing, and the forward is not a draw. The default hook -/// declares no start charge, and no frame gets an allowance. -#[test] -fn test_every_start_forwards_the_whole_pool_by_default() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA); - let (action, gas) = run(&code, Some(POOL), &mut host); - let input = started(action); - - assert_eq!(host.start().0.kind, kind); - assert_eq!( - figures(&input), - (POOL, StartCharge::default(), 0), - "{kind:?}" - ); - assert_eq!( - gas.pool_remaining(FIRST), - 0, - "{kind:?}: the caller keeps nothing" - ); - assert_eq!( - gas.pool_spent(FIRST), - 0, - "{kind:?}: a forward is not a draw" - ); - assert!(!gas.pool_crossing(FIRST), "{kind:?}"); - } -} - -/// A frame that was given no pool has an unlimited one, and forwards it unlimited. -#[test] -fn test_an_unlimited_pool_is_forwarded_unlimited() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA); - let (action, gas) = run(&code, None, &mut host); - let (share, _, _) = figures(&started(action)); - - assert_eq!(share, u64::MAX, "{kind:?}"); - assert_eq!(gas.pool_remaining(FIRST), 0, "{kind:?}"); - } -} - -/// The share is taken from the pool as the hook left it, by the schedule's percentage, rounded -/// down; the caller keeps the rest, and the hook's draw stays drawn. -#[test] -fn test_the_share_follows_the_schedule_after_the_hooks_draw() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA) - .on_a_chains_schedule() - .drawing(200); - let (action, gas) = run(&code, Some(POOL), &mut host); - let (share, _, _) = figures(&started(action)); - - let (_, found, paid) = host.start(); - assert_eq!( - found.pool_remaining(FIRST), - POOL, - "{kind:?}: the hook found the pool" - ); - assert!(paid); - // 800 left after the draw; 98% of it, rounded down. - assert_eq!(share, 784, "{kind:?}"); - assert_eq!( - gas.pool_remaining(FIRST), - 16, - "{kind:?}: the caller keeps the rest" - ); - assert_eq!( - gas.pool_spent(FIRST), - 200, - "{kind:?}: the hook's draw stays" - ); - } -} - -/// A start reaches the hook with nothing declared, and the start charge the hook declares on it -/// rides on the frame's input. -#[test] -fn test_the_declared_start_charge_rides_on_the_input() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA).declaring(DECLARED); - let (action, _) = run(&code, Some(POOL), &mut host); - let (_, charged, _) = figures(&started(action)); - - assert!(host.start().0.charge.is_zero(), "{kind:?}: none at first"); - assert_eq!(charged, DECLARED, "{kind:?}"); - } -} - -/// A start the hook refuses fails out of gas and starts no frame: the hook's draw stays, as the -/// forward of regular gas does, no share is taken, and the declared charge goes with the start. -#[test] -fn test_a_refused_start_forwards_no_bytes_and_discards_the_declared_charge() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA) - .drawing(200) - .declaring(DECLARED) - .refusing(); - let (action, gas) = run(&code, Some(POOL), &mut host); - - assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); - assert_eq!( - gas.pool_remaining(FIRST), - POOL - 200, - "{kind:?}: no share taken" - ); - assert_eq!(gas.pool_spent(FIRST), 200, "{kind:?}"); - assert!(!gas.pool_crossing(FIRST), "{kind:?}"); - } -} - -/// A draw the pool cannot pay takes nothing and records the crossing; the hook turns it into a -/// refusal, and the record, with the pool as it was, is readable after the halt zeroed the gas. -#[test] -fn test_a_draw_the_pool_cannot_pay_records_a_crossing_that_survives_the_halt() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA).drawing(POOL + 1); - let (action, gas) = run(&code, Some(POOL), &mut host); - - assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); - assert!(!host.start().2, "{kind:?}: the draw failed"); - assert_eq!( - gas.remaining(), - 0, - "{kind:?}: the halt zeroed the regular gas" - ); - assert_eq!( - gas.pool_remaining(FIRST), - POOL, - "{kind:?}: the failed draw took nothing" - ); - assert_eq!(gas.pool_spent(FIRST), 0, "{kind:?}"); - assert!(gas.pool_crossing(FIRST), "{kind:?}"); - } -} - -/// A value call's child gets the schedule's history allowance where it gets the call stipend; -/// no other start does, and the default schedule gives none. -#[test] -fn test_the_history_allowance_is_set_on_a_value_call_only() { - let cases = [ - ("CALL with value", call_code(CALL, 1), ALLOWANCE), - ("CALLCODE with value", call_code(CALLCODE, 1), ALLOWANCE), - ("CALL without value", call_code(CALL, 0), 0), - ("CALLCODE without value", call_code(CALLCODE, 0), 0), - ("DELEGATECALL", call_code(DELEGATECALL, 0), 0), - ("STATICCALL", call_code(STATICCALL, 0), 0), - ]; - for (name, code, allowance) in &cases { - let mut host = PoolHost::new(SpecId::OSAKA).on_a_chains_schedule(); - let (action, _) = run(code, Some(POOL), &mut host); - let (_, _, found) = figures(&started(action)); - assert_eq!(found, *allowance, "{name}"); - - let mut host = PoolHost::new(SpecId::OSAKA); - let (action, _) = run(code, Some(POOL), &mut host); - let (_, _, found) = figures(&started(action)); - assert_eq!(found, 0, "{name}: none on the default schedule"); - } -} - -/// The pools a frame holds in the tests of every pool, and its reservoir. -const POOLS: [u64; PoolId::COUNT] = [1_000, 500, 100]; -const RESERVOIR: u64 = 1_000; - -/// The reservoir and every pool's share of a started frame's input. -fn shares(input: &FrameInput) -> (u64, PoolAmounts) { - match input { - FrameInput::Call(inputs) => (inputs.reservoir, inputs.pool_shares), - FrameInput::Create(inputs) => (inputs.reservoir(), inputs.pool_shares()), - FrameInput::Empty => unreachable!(), - } -} - -/// [`POOLS`] and [`RESERVOIR`] on the frame's gas. -fn with_pools(gas: &mut Gas) { - for (pool, amount) in PoolId::ALL.into_iter().zip(POOLS) { - gas.set_pool_remaining(pool, amount); - } - gas.set_reservoir(RESERVOIR); -} - -/// `(reservoir, pools)` of `gas`. -fn held(gas: &GasTracker) -> (u64, [u64; PoolId::COUNT]) { - ( - gas.reservoir(), - PoolId::ALL.map(|pool| gas.pool_remaining(pool)), - ) -} - -/// By default every start forwards the whole reservoir and every whole pool, each taken out of -/// the caller, which holds none of them while the child runs; with the reservoir and each pool -/// given its own percentage, each is forwarded by its own share, rounded down, and the caller -/// keeps the rest of each. -#[test] -fn test_every_start_forwards_the_reservoir_and_each_pool_by_its_own_share() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA); - let (action, gas) = run_on(&code, &mut host, with_pools); - let (reservoir, pools) = shares(&started(action)); - assert_eq!( - (reservoir, PoolId::ALL.map(|pool| pools.get(pool))), - (RESERVOIR, POOLS), - "{kind:?}: everything forwarded" - ); - assert_eq!( - held(gas.tracker()), - (0, [0; 3]), - "{kind:?}: the caller holds none" - ); - assert_eq!( - held(&host.start().1), - (RESERVOIR, POOLS), - "{kind:?}: the hook found all" - ); - - let mut host = PoolHost::new(SpecId::OSAKA); - host.params.override_gas([ - (GasId::reservoir_kept_percent(), 2), - (GasId::pool_kept_percent(PoolId::new(0)), 2), - (GasId::pool_kept_percent(PoolId::new(1)), 50), - (GasId::pool_kept_percent(PoolId::new(2)), 100), - ]); - let (action, gas) = run_on(&code, &mut host, with_pools); - let (reservoir, pools) = shares(&started(action)); - assert_eq!( - (reservoir, PoolId::ALL.map(|pool| pools.get(pool))), - (980, [980, 250, 0]), - "{kind:?}: each by its share" - ); - assert_eq!( - held(gas.tracker()), - (20, [20, 250, 100]), - "{kind:?}: the caller keeps the rest" - ); - } -} - -/// A start the hook refuses takes no share of the reservoir or of any pool. -#[test] -fn test_a_refused_start_forwards_no_reservoir_and_no_pool() { - for (kind, code) in start_cases() { - let mut host = PoolHost::new(SpecId::OSAKA).refusing(); - let (action, gas) = run_on(&code, &mut host, with_pools); - - assert_eq!(returned(action), InstructionResult::OutOfGas, "{kind:?}"); - assert_eq!( - held(gas.tracker()), - (RESERVOIR, POOLS), - "{kind:?}: nothing taken" - ); - } -} diff --git a/crates/interpreter/tests/resource_pools_serde.rs b/crates/interpreter/tests/resource_pools_serde.rs deleted file mode 100644 index 7156d850b5..0000000000 --- a/crates/interpreter/tests/resource_pools_serde.rs +++ /dev/null @@ -1,146 +0,0 @@ -//! Serde encoding of the pool fields on the frame inputs and outcomes: the child's shares of the -//! pools, the start charge and a call's history allowance. -//! -//! New encodings carry the fields. In a format that carries field names, such as the JSON these -//! tests use, encodings made before they existed lack them and still decode: to unlimited -//! shares, no start charge and no allowance, which is what a frame of a consumer that uses none of -//! them carries. A format that encodes a struct by position, such as bincode, cannot read an -//! encoding made before they existed, as with upstream's own field additions. -#![cfg(feature = "serde")] - -use core::fmt::Debug; -use primitives::{address, Bytes, U256}; -use revm_interpreter::{ - CallInput, CallInputs, CallOutcome, CallScheme, CallValue, CreateInputs, CreateOutcome, - CreateScheme, Gas, InstructionResult, InterpreterResult, PoolAmounts, PoolId, StartCharge, -}; -use serde::{de::DeserializeOwned, Serialize}; -use serde_json::Value; -use state::Bytecode; - -/// The pool the tests draw: any of the tracker's pools behaves the same. -const FIRST: PoolId = PoolId::new(0); -const CHARGE: StartCharge = StartCharge::new( - 3_520, - PoolAmounts::ZERO.with(FIRST, 160).with(PoolId::new(2), 1), -); -/// Shares that differ by pool. -const SHARES: PoolAmounts = PoolAmounts::UNLIMITED - .with(FIRST, 980) - .with(PoolId::new(1), 0); - -/// Checks that `value` round-trips, and decodes to `without` once `fields` are removed from its -/// encoding. -fn assert_decodes_with_and_without<T>(value: &T, fields: &[&str], without: &T) -where - T: Serialize + DeserializeOwned + PartialEq + Debug, -{ - let encoded = serde_json::to_value(value).unwrap(); - assert_eq!( - &serde_json::from_value::<T>(encoded.clone()).unwrap(), - value - ); - - let Value::Object(mut object) = encoded else { - panic!("expected a JSON object, got {encoded}"); - }; - for field in fields { - assert!(object.remove(*field).is_some(), "{field} is encoded"); - } - assert_eq!( - &serde_json::from_value::<T>(Value::Object(object)).unwrap(), - without - ); -} - -const fn interpreter_result() -> InterpreterResult { - InterpreterResult::new( - InstructionResult::Revert, - Bytes::from_static(b"reverted"), - Gas::new(100_000), - ) -} - -#[test] -fn test_call_inputs_decode_from_json_with_and_without_the_pool_fields() { - let inputs = |share, charge, allowance| CallInputs { - input: CallInput::Bytes(Bytes::from_static(b"in")), - return_memory_offset: 0..8, - gas_limit: 100_000, - reservoir: 50_000, - bytecode_address: address!("0x00000000000000000000000000000000000c0de0"), - known_bytecode: (Default::default(), Bytecode::default()), - target_address: address!("0x00000000000000000000000000000000000c0de0"), - caller: address!("0x00000000000000000000000000000000000ca11e"), - value: CallValue::Transfer(U256::from(1)), - scheme: CallScheme::Call, - is_static: false, - charged_new_account_state_gas: true, - charged_start: charge, - pool_shares: share, - history_allowance: allowance, - }; - - assert_decodes_with_and_without( - &inputs(SHARES, CHARGE, 160), - &["pool_shares", "charged_start", "history_allowance"], - &inputs(PoolAmounts::UNLIMITED, StartCharge::default(), 0), - ); -} - -#[test] -fn test_create_inputs_decode_from_json_with_and_without_the_pool_fields() { - let inputs = |share, charge| { - let mut inputs = CreateInputs::new( - address!("0x00000000000000000000000000000000000c0de0"), - CreateScheme::Create, - U256::from(1), - Bytes::from_static(&[0x5f, 0x5f, 0xfd]), - 100_000, - 50_000, - ); - inputs.set_pool_shares(share); - inputs.set_charged_start(charge); - inputs - }; - - assert_decodes_with_and_without( - &inputs(SHARES, CHARGE), - &["pool_shares", "charged_start"], - &inputs(PoolAmounts::UNLIMITED, StartCharge::default()), - ); - assert_eq!( - CreateInputs::default().pool_shares(), - PoolAmounts::UNLIMITED - ); -} - -#[test] -fn test_call_outcome_decodes_from_json_with_and_without_the_start_charge() { - let outcome = |charge| { - let mut outcome = CallOutcome::new(interpreter_result(), 0..8); - outcome.charged_start = charge; - outcome - }; - - assert_decodes_with_and_without( - &outcome(CHARGE), - &["charged_start"], - &outcome(StartCharge::default()), - ); -} - -#[test] -fn test_create_outcome_decodes_from_json_with_and_without_the_start_charge() { - let outcome = |charge| { - let mut outcome = CreateOutcome::new(interpreter_result(), None); - outcome.charged_start = charge; - outcome - }; - - assert_decodes_with_and_without( - &outcome(CHARGE), - &["charged_start"], - &outcome(StartCharge::default()), - ); -} diff --git a/crates/interpreter/tests/start_marks.rs b/crates/interpreter/tests/start_marks.rs index 4a2c2fd3f7..83bdce5a7b 100644 --- a/crates/interpreter/tests/start_marks.rs +++ b/crates/interpreter/tests/start_marks.rs @@ -9,22 +9,17 @@ use revm_interpreter::{ /// The derived debug output of these values before the marks existed. const TRACKER: &str = "GasTracker { gas_limit: 100, remaining: 90, reservoir: 5, \ - state_gas_spent: 0, state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, \ - withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, \ - pools_remaining: [18446744073709551615, 18446744073709551615, 18446744073709551615], \ - pools_spent: [0, 0, 0], pool_crossings: 0, history_allowance: 3 }"; + state_gas_spent: 0, state_gas_spilled: 0, history_gas_spent: 0, refunded: 3, withheld: 0, \ + withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false }"; const RESULT: &str = "InterpreterResult { result: Stop, output: 0x, gas: Gas { tracker: \ GasTracker { gas_limit: 10, remaining: 10, reservoir: 0, state_gas_spent: 0, \ state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, withheld_crossing: \ - None, failed_charge_remaining: 0, failed_charge_recorded: false, pools_remaining: \ - [18446744073709551615, 18446744073709551615, 18446744073709551615], pools_spent: [0, 0, 0], \ - pool_crossings: 0, history_allowance: 0 }, memory: MemoryGas { words_num: 0, \ - expansion_cost: 0 } } }"; -const START_CHARGE: &str = "StartCharge { history: 0, pools: PoolAmounts([0, 0, 0]) }"; + None, failed_charge_remaining: 0, failed_charge_recorded: false }, memory: MemoryGas { \ + words_num: 0, expansion_cost: 0 } } }"; const fn tracker() -> GasTracker { let mut tracker = GasTracker::new(100, 90, 5); - tracker.set_history_allowance(3); + tracker.record_refund(3); tracker.set_start_mark(StartMark::for_start(7)); tracker } @@ -57,16 +52,14 @@ fn test_marked_values_print_as_the_derived_output_did() { format!( "CallOutcome {{ result: {RESULT}, memory_offset: 1..2, was_precompile_called: false, \ precompile_call_logs: [], charged_new_account_state_gas: false, \ - charged_state_gas_address: 0x0000000000000000000000000000000000000000, \ - charged_start: {START_CHARGE} }}" + charged_state_gas_address: 0x0000000000000000000000000000000000000000 }}" ) ); assert_eq!( format!("{:?}", create()), format!( "CreateOutcome {{ result: {RESULT}, address: None, charged_create_state_gas: false, \ - charged_state_gas_address: 0x0000000000000000000000000000000000000000, \ - charged_start: {START_CHARGE} }}" + charged_state_gas_address: 0x0000000000000000000000000000000000000000 }}" ) ); } From d7c42651c12255d20630bbd9525cdb90a51f025b Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 18:59:39 +0800 Subject: [PATCH 100/110] feat!: the reservoir is forwarded and settled as upstream's again A frame start copies its caller's EIP-8037 reservoir into the child's input and the caller keeps it while the child runs; the child's return replaces the caller's reservoir with what the child left, once that has unwound the caller's spill. The transaction's frame and the runtime out-of-gas stand-in are handed a copy of the transaction's reservoir the same way. That is upstream's forward and settlement: handle_reservoir_remaining_gas and GasTracker::absorb_returned_reservoir mean what they mean upstream again. The schedule's reservoir_kept_percent (id 249, now unused) and GasParams::reservoir_forward_share go, with GasTracker::forward_reservoir, forward_to_child, forward_to_child_with_reservoir, forward_all_to_child and ChildShares, and settle_first_frame's assertion that the transaction's gas holds no reservoir. A consumer that keeps part of a caller's reservoir takes it in the frame-start hook, names the child's reservoir on FrameStart::reservoir, and adds FrameSettle::held_reservoir back when revm settles the child. The tests that forwarded 98% through the schedule now keep 2% through those hooks and get the same figures. --- crates/context/interface/src/cfg/gas.rs | 48 +-- .../context/interface/src/cfg/gas/forward.rs | 177 -------- .../context/interface/src/cfg/gas_params.rs | 173 +------- crates/context/interface/src/host.rs | 6 +- .../interface/src/host/instruction_hooks.rs | 13 +- .../context/interface/src/host/lifecycle.rs | 8 + crates/context/tests/schedule_shares.rs | 84 ---- crates/handler/src/execution.rs | 12 +- crates/handler/src/execution/first_frame.rs | 13 +- crates/handler/src/frame.rs | 69 ++-- crates/handler/src/handler.rs | 12 +- ...rvoir_share.rs => reservoir_settlement.rs} | 381 +++++++++++++++--- crates/inspector/tests/loop_hooks.rs | 10 +- ...rvoir_share.rs => reservoir_settlement.rs} | 279 +++++++++++-- .../interpreter/src/instructions/contract.rs | 8 +- .../src/instructions/instruction_hooks.rs | 24 +- crates/interpreter/src/lib.rs | 2 +- crates/interpreter/tests/instruction_hooks.rs | 29 +- 18 files changed, 703 insertions(+), 645 deletions(-) delete mode 100644 crates/context/interface/src/cfg/gas/forward.rs delete mode 100644 crates/context/tests/schedule_shares.rs rename crates/handler/tests/{reservoir_share.rs => reservoir_settlement.rs} (72%) rename crates/inspector/tests/{reservoir_share.rs => reservoir_settlement.rs} (50%) diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 20de2f26d6..949081c101 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -6,11 +6,9 @@ use primitives::hardfork::SpecId; #[cfg(feature = "serde")] mod encoding; mod failed_charge; -mod forward; mod mark; mod withheld; -pub use forward::ChildShares; pub use mark::{OutcomeMark, StartMark}; pub use withheld::WithheldCrossing; @@ -53,12 +51,6 @@ pub use withheld::WithheldCrossing; /// spendable part, so a consumer that caps a creating frame must not release before /// `return_create`, or those charges escape the cap. /// -/// A child frame starts with a share of its caller's reservoir, which the caller's tracker gives -/// up while the child runs ([`forward_to_child`](Self::forward_to_child)); the child's return -/// adds what it left to what the caller kept -/// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)). Every schedule defined here -/// forwards the whole reservoir. -/// /// The net counters (`state_gas_spent`, `history_gas_spent`) are `i64`, while charges and refills /// take `u64` amounts and convert them with saturation. The tracker assumes that the transaction /// gas limit, and so any single charge or refill and the state plus history net a rollback adds @@ -292,22 +284,15 @@ impl GasTracker { self.reservoir = val; } - /// Adds a reservoir returned by a child frame to the part of the reservoir this (parent) - /// frame kept, and reconciles it with any outstanding state gas spilled into regular gas. - /// - /// The child started with a share of this frame's reservoir, which this frame gave up for it - /// ([`forward_to_child`](Self::forward_to_child)); what it returns is that share, less what it - /// spent, plus what it refilled. Every schedule defined here forwards the whole reservoir, so - /// this frame kept nothing and its reservoir becomes the child's, as upstream's settlement, - /// which replaced the parent's reservoir with the child's, made it. + /// Adopts a reservoir returned by a child frame and reconciles it with any + /// outstanding state gas spilled into regular gas. /// /// A successful child can refill state gas charged by an ancestor (for /// example, by clearing a slot created by a sibling). Since the child does /// not inherit the ancestor's [`Self::state_gas_spilled`] counter, that /// refill initially lands in the child's reservoir. On return it must first /// restore the parent's regular gas in last-in-first-out order; only the - /// excess joins the reservoir. The spill is unwound from the returned reservoir only; the - /// part this frame kept stays in its reservoir. + /// excess remains in the reservoir. /// /// This only reconciles the funding pools. The child's signed /// `state_gas_spent` has already accounted for the refill and is merged @@ -321,7 +306,7 @@ impl GasTracker { }; self.remaining = self.remaining.saturating_add(to_remaining); self.state_gas_spilled -= to_remaining; - self.reservoir = self.reservoir.saturating_add(reservoir - to_remaining); + self.reservoir = reservoir - to_remaining; } /// Returns the state gas spent. @@ -739,15 +724,13 @@ mod tests { /// A child that refills history its parent charged goes below zero, and merging it into the /// parent on success nets the two out. The merge follows the handler's order: the signed figure /// is read, added and written back, as the state counter's is, and then the parent absorbs the - /// child's reservoir, which the parent forwarded whole. + /// child's reservoir. #[test] fn test_a_child_refill_of_a_parent_charge_nets_out_on_merge() { let mut parent = GasTracker::new(1_000, 1_000, 500); assert!(parent.record_history_cost(100)); - let share = parent.reservoir(); - parent.forward_reservoir(share); - let mut child = GasTracker::new(300, 300, share); + let mut child = GasTracker::new(300, 300, parent.reservoir()); child.refill_history(100); assert_eq!(child.history_gas_spent(), -100); @@ -763,6 +746,25 @@ mod tests { assert_eq!(parent.reservoir(), 500); } + /// A returned reservoir replaces the caller's, once it has unwound the caller's outstanding + /// spill, last in first out: what the caller held beside it does not stay. + #[test] + fn test_a_returned_reservoir_replaces_the_callers() { + // The caller holds the 1,000 it gave the child, which returns 700 of it. + let mut caller = GasTracker::new(1_000, 1_000, 1_000); + caller.absorb_returned_reservoir(700); + assert_eq!((caller.reservoir(), caller.remaining()), (700, 1_000)); + + // A spill of 150 outstanding (a successful child's, merged before the absorb): the + // returned 100 unwinds 100 of it, and the 20 the caller held goes with the replace. + let mut spilled = GasTracker::new(1_000, 850, 20); + spilled.add_state_gas_spilled(150); + spilled.absorb_returned_reservoir(100); + assert_eq!(spilled.reservoir(), 0); + assert_eq!(spilled.remaining(), 950); + assert_eq!(spilled.state_gas_spilled(), 50); + } + /// Copying the counter through its getter and setter, as `PrecompileOutput` does for state gas, /// keeps a negative net. #[test] diff --git a/crates/context/interface/src/cfg/gas/forward.rs b/crates/context/interface/src/cfg/gas/forward.rs deleted file mode 100644 index faa5e8d876..0000000000 --- a/crates/context/interface/src/cfg/gas/forward.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! What a frame start takes out of its caller's [`GasTracker`] for the child frame, beside the -//! regular gas: a share of the EIP-8037 reservoir. -//! -//! The caller keeps the rest while the child runs, and the child's return adds what the child left -//! back to what the caller kept ([`absorb_returned_reservoir`](GasTracker::absorb_returned_reservoir)). -//! The share is the schedule's ([`GasParams::reservoir_forward_share`]); every schedule defined -//! here forwards the whole reservoir, which is upstream's forward. - -use super::GasTracker; -use crate::cfg::GasParams; - -/// What a child frame's tracker starts with beside its regular gas, taken out of its caller's: its -/// reservoir. -/// -/// Returned by [`GasTracker::forward_to_child`] and [`GasTracker::forward_all_to_child`]; the -/// frame's input carries it (`reservoir`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub struct ChildShares { - /// The child's reservoir. - pub reservoir: u64, -} - -impl GasTracker { - /// Takes `share` out of the reservoir for a child frame, which starts with it as its - /// reservoir. - /// - /// Not a charge: no counter moves, since the share comes back when the child returns - /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)). `share` is at most the - /// reservoir, which the schedule's forward share guarantees; more saturates at an empty - /// reservoir. - #[inline] - pub const fn forward_reservoir(&mut self, share: u64) { - self.reservoir = self.reservoir.saturating_sub(share); - } - - /// Takes the schedule's share of the reservoir out of this, the caller's, tracker for a child - /// frame, and returns it: what the child's tracker starts with. - /// - /// The `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` instructions - /// call it once the frame-start hook has answered, so the share is of the reservoir as the - /// hook left it. A consumer that builds a child frame's input itself calls it - /// too, so that the child's return, which adds what the child left to what the caller kept, - /// gives the caller back exactly what it forwarded. - #[inline] - pub fn forward_to_child(&mut self, params: &GasParams) -> ChildShares { - self.forward_to_child_with_reservoir(params, None) - } - - /// [`forward_to_child`](Self::forward_to_child), for a start whose child reservoir the - /// frame-start hook may have named (`FrameStart::reservoir`). - /// - /// `Some(reservoir)` is the child's reservoir, which the hook took out of this tracker itself: - /// no share of the reservoir is taken here, and the child starts with `reservoir`. `None` takes - /// the schedule's share, as `forward_to_child` does. - #[inline] - pub fn forward_to_child_with_reservoir( - &mut self, - params: &GasParams, - reservoir: Option<u64>, - ) -> ChildShares { - let reservoir = reservoir.unwrap_or_else(|| { - let share = params.reservoir_forward_share(self.reservoir); - self.forward_reservoir(share); - share - }); - ChildShares { reservoir } - } - - /// Takes the whole reservoir out of this tracker for a child frame, and returns it. - /// - /// For the transaction's frame, which takes the transaction's whole reservoir: the schedule's - /// share applies to the frames below it. - #[inline] - pub const fn forward_all_to_child(&mut self) -> ChildShares { - let shares = ChildShares { - reservoir: self.reservoir, - }; - self.reservoir = 0; - shares - } -} - -#[cfg(test)] -mod tests { - use super::{ChildShares, GasTracker}; - use crate::cfg::{GasId, GasParams}; - use primitives::hardfork::SpecId; - - /// A caller with a reservoir of 1,000. - fn caller() -> GasTracker { - GasTracker::new(10_000, 10_000, 1_000) - } - - /// Every schedule forwards the whole reservoir, and the caller keeps none of it while the - /// child runs. - #[test] - fn test_every_schedule_forwards_everything() { - for spec in [SpecId::FRONTIER, SpecId::OSAKA, SpecId::AMSTERDAM] { - let params = GasParams::new_spec(spec); - let mut tracker = caller(); - - let shares = tracker.forward_to_child(¶ms); - - assert_eq!(shares.reservoir, 1_000, "{spec:?}"); - assert_eq!(tracker.reservoir(), 0, "{spec:?}"); - assert_eq!( - tracker.remaining(), - 10_000, - "{spec:?}: regular gas is not touched" - ); - } - } - - /// The reservoir is forwarded by the schedule's share, and the caller keeps the rest. - #[test] - fn test_each_share_is_the_schedules() { - let mut params = GasParams::new_spec(SpecId::AMSTERDAM); - params.override_gas([(GasId::reservoir_kept_percent(), 2)]); - let mut tracker = caller(); - assert!(tracker.record_state_cost(1)); - - let shares = tracker.forward_to_child(¶ms); - - // The reservoir's 999 less the caller's 2%, rounded down (19), is 980. - assert_eq!(shares.reservoir, 980); - assert_eq!(tracker.reservoir(), 19); - assert_eq!(tracker.state_gas_spent(), 1, "a forward is not a charge"); - } - - /// The transaction's frame takes the whole reservoir, whatever the schedule. - #[test] - fn test_the_first_frame_takes_everything() { - let mut tracker = caller(); - - let shares = tracker.forward_all_to_child(); - - assert_eq!(shares, ChildShares { reservoir: 1_000 }); - assert_eq!(tracker.reservoir(), 0); - } - - /// A caller that kept part of its reservoir when it forwarded a share gets the child's - /// reservoir added to what it kept, and the returned reservoir, not the kept part, unwinds - /// the caller's outstanding spill. With nothing kept the result is the child's reservoir, as - /// a settlement that replaced the caller's reservoir gave. - #[test] - fn test_a_returned_reservoir_joins_the_part_the_caller_kept() { - // Kept 20 of 1,000, the child returns 700 of its 980. - let mut kept = GasTracker::new(1_000, 1_000, 1_000); - kept.forward_reservoir(980); - kept.absorb_returned_reservoir(700); - assert_eq!((kept.reservoir(), kept.remaining()), (720, 1_000)); - - // A spill of 150 outstanding (a successful child's, merged before the absorb): the - // returned 100 unwinds 100 of it, and the 20 kept stays in the reservoir. - let mut spilled = GasTracker::new(1_000, 850, 20); - spilled.add_state_gas_spilled(150); - spilled.absorb_returned_reservoir(100); - assert_eq!(spilled.reservoir(), 20); - assert_eq!(spilled.remaining(), 950); - assert_eq!(spilled.state_gas_spilled(), 50); - - // Nothing kept: the child's reservoir, whatever the caller held before the forward. - let mut whole = GasTracker::new(1_000, 1_000, 1_000); - whole.forward_reservoir(1_000); - whole.absorb_returned_reservoir(300); - assert_eq!(whole.reservoir(), 300); - } - - /// A forward above the reservoir saturates at an empty reservoir. - #[test] - fn test_a_reservoir_forward_saturates() { - let mut tracker = caller(); - tracker.forward_reservoir(5_000); - assert_eq!(tracker.reservoir(), 0); - } -} diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index ae9f4de608..c78d277f99 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -814,25 +814,6 @@ impl GasParams { .saturating_mul(len as u64) } - /// The share of a caller's EIP-8037 `reservoir` a child frame receives when it starts: all - /// but the caller's part, which is [`reservoir_kept_percent`](GasId::reservoir_kept_percent) - /// per cent of the reservoir, rounded down, and which the caller keeps while the child runs. - /// - /// The child's share is taken as [`call_stipend_reduction`](Self::call_stipend_reduction) takes - /// regular gas, by subtracting the caller's part: at 2 kept it is - /// `reservoir - reservoir * 2 / 100`, so a reservoir of 99 forwards 98. Zero kept, which every - /// schedule here and every table without the entry has, forwards the whole reservoir, as - /// EIP-8037 does; a hundred or more forwards nothing. - #[inline] - pub fn reservoir_forward_share(&self, reservoir: u64) -> u64 { - let kept = self.get(GasId::reservoir_kept_percent()); - // The default, the whole reservoir, without the arithmetic. - if kept == 0 { - return reservoir; - } - reservoir - percent_of(reservoir, kept) - } - /// Used in [GasParams::initial_tx_gas] to calculate the eip7702 per-auth cost. /// /// Pre-Amsterdam this is the pessimistic bundled `PER_EMPTY_ACCOUNT_COST` @@ -1295,7 +1276,6 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", - x if x == Self::reservoir_kept_percent().as_u8() => "reservoir_kept_percent", _ => "unknown", } } @@ -1371,7 +1351,6 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), - "reservoir_kept_percent" => Some(Self::reservoir_kept_percent()), _ => None, } } @@ -1662,34 +1641,6 @@ impl GasId { pub const fn code_deposit_history_gas() -> GasId { Self::new(255) } - - /// The part of a caller's EIP-8037 reservoir the caller keeps while its child frame runs, in - /// per cent of the reservoir, rounded down: the child receives all but that - /// ([`GasParams::reservoir_forward_share`]). - /// - /// Zero, the whole reservoir forwarded as EIP-8037 forwards it, on every schedule defined - /// here and in every table without the entry, such as upstream's or one encoded before the - /// entry existed; a chain that keeps part of the reservoir for the caller raises it, and a - /// hundred forwards none. - /// - /// A fork id, allocated from the top of the table below - /// [`code_deposit_history_gas`](Self::code_deposit_history_gas). Ids 254 and 250 to 253, and - /// 246 to 248 below it, are left unused: earlier revisions of the fork put entries there, which - /// a table encoded then still holds and which no entry reads. - pub const fn reservoir_kept_percent() -> GasId { - Self::new(249) - } -} - -/// `percent` per cent of `value`, rounded down; a hundred or more is the whole of it. -#[inline] -const fn percent_of(value: u64, percent: u64) -> u64 { - if percent >= 100 { - return value; - } - // `floor(value * percent / 100)` without widening: the quotient's part is exact, and the - // remainder's part is below a hundred times a hundred. - value / 100 * percent + value % 100 * percent / 100 } #[cfg(test)] @@ -1762,131 +1713,19 @@ mod tests { "Not all unique names are resolvable via from_str" ); - // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's, allocated - // from the top of the table so upstream's next sequential id does not collide with them: - // `code_deposit_history_gas` at 255 and `reservoir_kept_percent` at 249; 246 to 248 and - // 250 to 254 are unused. Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain([249, 255]).collect(); + // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's + // `code_deposit_history_gas` at 255, allocated from the top of the table so upstream's + // next sequential id does not collide with it. Every one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain([255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), - 51, - "Expected 51 unique GasIds, found {}", + 50, + "Expected 50 unique GasIds, found {}", unique_names.len() ); } - /// Every schedule forwards the whole reservoir: the kept percent is zero and the share is the - /// amount itself, `u64::MAX` included. A schedule that keeps a percentage forwards the rest, - /// and one that keeps a hundred or more forwards nothing. - #[test] - fn test_forward_shares_default_to_the_whole_amount() { - let amounts = [0, 1, 99, 100, 149, 1_000, u64::MAX - 1, u64::MAX]; - for spec in [ - SpecId::FRONTIER, - SpecId::LONDON, - SpecId::OSAKA, - SpecId::AMSTERDAM, - SpecId::default(), - ] { - let params = GasParams::new_spec(spec); - assert_eq!(params.get(GasId::reservoir_kept_percent()), 0, "{spec:?}"); - for amount in amounts { - assert_eq!(params.reservoir_forward_share(amount), amount, "{spec:?}"); - } - } - - // The reservoir's share is what is left once the caller's 2% is taken, rounded down, as - // regular gas's forward takes its part: a reservoir of 99 forwards 99 - 1 = 98. - let mut params = GasParams::new_spec(SpecId::OSAKA); - params.override_gas([(GasId::reservoir_kept_percent(), 2)]); - assert_eq!(params.reservoir_forward_share(0), 0); - assert_eq!(params.reservoir_forward_share(1), 1); - assert_eq!(params.reservoir_forward_share(99), 98); - assert_eq!(params.reservoir_forward_share(100), 98); - assert_eq!(params.reservoir_forward_share(149), 147); - assert_eq!(params.reservoir_forward_share(1_000), 980); - for reservoir in (0..10_000).chain([u64::MAX - 1, u64::MAX]) { - assert_eq!( - params.reservoir_forward_share(reservoir), - (reservoir as u128 - reservoir as u128 * 2 / 100) as u64, - "the reservoir's share is `reservoir - reservoir * 2 / 100`" - ); - } - for (kept, share) in [(100, 0), (250, 0), (0, 1_000)] { - params.override_gas([(GasId::reservoir_kept_percent(), kept)]); - assert_eq!(params.reservoir_forward_share(1_000), share, "kept {kept}"); - } - - assert_eq!( - GasId::from_name("reservoir_kept_percent"), - Some(GasId::reservoir_kept_percent()) - ); - assert_eq!( - GasId::reservoir_kept_percent().name(), - "reservoir_kept_percent" - ); - for unused in [246, 247, 248, 250, 251, 252, 253, 254] { - assert_eq!(GasId::new(unused).name(), "unknown", "{unused} is unused"); - } - } - - /// Tables that lack the fork's share entry, each as a consumer could hold one: all zeros; - /// upstream's table, which has no entry above id 49, as is a table of the fork's release before - /// the share, whose one entry above it (id 255) is zero by default; that table with the - /// forward percentage an earlier revision put at id 254, at its default of 100 and at the 98 a - /// consumer set; and with the forward percentages a later one put at ids 254 and 250 to 252, - /// at their default of 100. - fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 5] { - let mut upstream = *GasParams::new_spec(SpecId::AMSTERDAM).table(); - upstream[50..].fill(0); - let mut earlier_default = upstream; - earlier_default[254] = 100; - let mut earlier_98 = upstream; - earlier_98[254] = 98; - let mut later_default = earlier_default; - later_default[250..=252].fill(100); - [ - ("all zeros", [0; 256]), - ("upstream's", upstream), - ("an earlier revision's, at its default", earlier_default), - ("an earlier revision's, at 98", earlier_98), - ("a later revision's, at its defaults", later_default), - ] - } - - /// Whether `params` forwards the whole reservoir, as upstream does. - fn forwards_everything(params: &GasParams) -> bool { - [0, 1, 99, 1_000, u64::MAX] - .into_iter() - .all(|amount| params.reservoir_forward_share(amount) == amount) - } - - /// A table built raw, without the fork's share entry, forwards the whole reservoir, as - /// upstream does, and never nothing. - #[test] - fn test_a_raw_table_without_the_share_entries_forwards_everything() { - for (name, table) in tables_without_the_share_entries() { - assert!( - forwards_everything(&GasParams::new(Arc::new(table))), - "{name}" - ); - } - } - - /// A schedule encoded without the fork's share entry decodes to one that forwards the whole - /// reservoir. - #[cfg(feature = "serde")] - #[test] - fn test_a_schedule_encoded_without_the_share_entries_forwards_everything() { - for (name, table) in tables_without_the_share_entries() { - let encoded = serde_json::json!({ "table": table.to_vec() }); - let params: GasParams = serde_json::from_value(encoded).expect(name); - assert_eq!(params.table(), &table, "{name}"); - assert!(forwards_everything(¶ms), "{name}"); - } - } - /// A forward of 98/100 of the regular gas to a child, `remaining - remaining * 2 / 100` rounded /// down, is upstream's `call_stipend_reduction` with the quotient 50 in place of EIP-150's 64: /// the two agree on every amount, so a chain that forwards 98/100 of its regular gas needs no diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index f93388e30f..45e533c164 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -128,9 +128,9 @@ pub trait Host { /// frame's input is built. /// /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, - /// charging nothing after the hook: the frame's input takes the schedule's share of the - /// reservoir in `gas`, or the child's reservoir the hook names on `start` if it took that out - /// of `gas` itself ([`FrameStart::reservoir`]). A charge the hook makes that fails records as + /// charging nothing after the hook: the frame's input copies the reservoir in `gas`, or + /// carries the child's reservoir the hook names on `start` if it took that out of `gas` itself + /// ([`FrameStart::reservoir`]). A charge the hook makes that fails records as /// any failed charge does ([`GasTracker::failed_charge_remaining`]), whatever the answer. /// `true` goes on to start the frame, which the handler may still refuse or answer without /// running it. `false` fails the instruction out of gas and starts no frame: the forward stays diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index d3fbe93f7a..aa3d321766 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -123,13 +123,14 @@ pub struct FrameStart { /// The child's reservoir, when the hook took it out of the caller's reservoir itself. `None` /// when the hook is called. /// - /// `None` leaves the forward to the instruction, which takes the schedule's share of the - /// caller's reservoir as the hook left it ([`GasTracker::forward_to_child`]). `Some` is the - /// reservoir the frame's input carries: the instruction takes no share of its own, and the - /// caller keeps the reservoir the hook left it. The instruction does not check the amount - /// against what the hook took. + /// `None` leaves the forward to the instruction, whose frame's input copies the caller's + /// reservoir as the hook left it, and the caller keeps it, as upstream's instructions do. `Some` + /// is the reservoir the frame's input carries in its place, and the caller keeps the reservoir + /// the hook left it. The instruction does not check the amount against what the hook took. /// - /// [`GasTracker::forward_to_child`]: crate::cfg::gas::GasTracker::forward_to_child + /// Either way the child's settlement replaces the caller's reservoir with the one the child + /// returns. A hook that kept part of the caller's reservoir for it adds that back when the + /// child settles ([`FrameSettle::held_reservoir`](super::FrameSettle::held_reservoir)). pub reservoir: Option<u64>, } diff --git a/crates/context/interface/src/host/lifecycle.rs b/crates/context/interface/src/host/lifecycle.rs index fa48076718..e9900e900f 100644 --- a/crates/context/interface/src/host/lifecycle.rs +++ b/crates/context/interface/src/host/lifecycle.rs @@ -79,5 +79,13 @@ pub struct FrameSettle { /// this start, such as one a constructor built around the same result. pub outcome_rebuilt: bool, /// The reservoir the caller's gas held just before revm settled the result into it. + /// + /// revm's settlement replaces the caller's reservoir with the one the frame returns, once that + /// has unwound the caller's outstanding spill. A consumer that kept part of the caller's + /// reservoir when the start was made ([`FrameStart::reservoir`](super::FrameStart::reservoir)) + /// adds this back to it here, which gives the caller what the frame returned on top of the + /// part it kept, since the unwinding and every refill read the spill, not the reservoir. The + /// transaction's frame is handed a copy of the transaction's reservoir, which this then is: a + /// consumer adds back only what it kept. pub held_reservoir: u64, } diff --git a/crates/context/tests/schedule_shares.rs b/crates/context/tests/schedule_shares.rs deleted file mode 100644 index 0b53d26a3b..0000000000 --- a/crates/context/tests/schedule_shares.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! A configuration whose gas schedule lacks the fork's share entry forwards a child frame the -//! whole reservoir, as upstream does: the schedule a consumer builds raw and -//! hands to the configuration, and the one it decodes from a configuration encoded before the -//! entries existed. - -use context_interface::{cfg::GasParams, Cfg}; -use primitives::hardfork::SpecId; -use revm_context::CfgEnv; -use std::sync::Arc; - -/// Upstream's Osaka schedule: the fork's table with nothing above id 49, upstream's last. -fn upstream_table() -> [u64; 256] { - let mut table = *GasParams::new_spec(SpecId::OSAKA).table(); - table[50..].fill(0); - table -} - -/// Schedules without the share entries, as a configuration could have been encoded: upstream's; -/// with the forward percentage an earlier revision of the fork put at id 254, at its default of -/// 100 and at the 98 a consumer set; and with those a later revision put at ids 254 and 250 to -/// 252, at their default of 100. -#[cfg(feature = "serde")] -fn tables_without_the_share_entries() -> [(&'static str, [u64; 256]); 4] { - let upstream = upstream_table(); - let mut earlier = upstream; - earlier[254] = 100; - let mut earlier_98 = upstream; - earlier_98[254] = 98; - let mut later = earlier; - later[250..=252].fill(100); - [ - ("upstream's", upstream), - ("an earlier revision's", earlier), - ("an earlier revision's, at 98", earlier_98), - ("a later revision's", later), - ] -} - -/// Whether `cfg`'s schedule forwards the whole reservoir. -fn forwards_everything(cfg: &CfgEnv) -> bool { - let params = cfg.gas_params(); - [0, 1, 99, 1_000, u64::MAX] - .into_iter() - .all(|amount| params.reservoir_forward_share(amount) == amount) -} - -/// Each way to give a configuration a schedule other than the spec's default: at construction, -/// with the two builders and with the setter. -#[test] -fn test_a_cfg_given_a_raw_schedule_forwards_everything() { - let raw = GasParams::new(Arc::new(upstream_table())); - - let built = CfgEnv::new_with_spec_and_gas_params(SpecId::OSAKA, raw.clone()); - let chained = CfgEnv::new_with_spec(SpecId::OSAKA).with_gas_params(raw.clone()); - let respecced = - CfgEnv::new_with_spec(SpecId::PRAGUE).with_spec_and_gas_params(SpecId::OSAKA, raw.clone()); - let mut set = CfgEnv::new_with_spec(SpecId::OSAKA); - set.set_gas_params(raw); - - for (name, cfg) in [ - ("built", built), - ("chained", chained), - ("respecced", respecced), - ("set", set), - ] { - assert!(forwards_everything(&cfg), "{name}"); - } -} - -/// A configuration encoded with a schedule without the share entries decodes to one that forwards -/// everything. -#[cfg(feature = "serde")] -#[test] -fn test_a_cfg_encoded_without_the_share_entries_forwards_everything() { - for (name, table) in tables_without_the_share_entries() { - let mut encoded = serde_json::to_value(CfgEnv::new_with_spec(SpecId::OSAKA)).unwrap(); - encoded["gas_params"]["table"] = serde_json::json!(table.to_vec()); - - let cfg: CfgEnv = serde_json::from_value(encoded).expect(name); - - assert_eq!(cfg.gas_params().table(), &table, "{name}"); - assert!(forwards_everything(&cfg), "{name}"); - } -} diff --git a/crates/handler/src/execution.rs b/crates/handler/src/execution.rs index 426cd44176..6b25be989b 100644 --- a/crates/handler/src/execution.rs +++ b/crates/handler/src/execution.rs @@ -17,9 +17,7 @@ pub use first_frame::settle_first_frame; /// Creates the first [`FrameInput`] from the transaction and the /// transaction-level `gas`, forwarding all remaining regular gas and the -/// reservoir to the frame. The reservoir is taken out of `gas` -/// ([`GasTracker::forward_all_to_child`]), as a frame start takes a child's share -/// out of its caller's, and comes back when the frame settles into `gas`. +/// reservoir to the frame. /// /// Under EIP-2780 this completes the runtime gas phase started at /// pre-execution (the authorization charges): the target is loaded once and @@ -124,9 +122,6 @@ pub fn create_init_frame<CTX: ContextTr>( } } - // The transaction's frame gets the whole reservoir, taken out of the transaction's - // gas: the schedule's share is for the frames below it. - let shares = gas.forward_all_to_child(); Ok(Some(FrameInput::Call(Box::new(CallInputs { input: CallInput::Bytes(input), gas_limit: gas.remaining(), @@ -138,7 +133,7 @@ pub fn create_init_frame<CTX: ContextTr>( scheme: CallScheme::Call, is_static: false, return_memory_offset: 0..0, - reservoir: shares.reservoir, + reservoir: gas.reservoir(), charged_new_account_state_gas, })))) } @@ -174,14 +169,13 @@ pub fn create_init_frame<CTX: ContextTr>( } } let tx = ctx.tx(); - let shares = gas.forward_all_to_child(); let mut inputs = CreateInputs::new( tx.caller(), CreateScheme::Create, tx.value(), input, gas.remaining(), - shares.reservoir, + gas.reservoir(), ); inputs.set_charged_create_state_gas(charged_create_state_gas); inputs.set_charged_state_gas_address(charged_state_gas_address); diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index e3c1ea4567..6da838f3b5 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -16,16 +16,11 @@ use std::string::ToString; /// - `gas` spends all its regular gas, which was forwarded to the frame, and the frame settles /// into it as a child settles into its caller ([`handle_reservoir_remaining_gas`]): a failing /// frame rolls back its state gas and history gas, a halt consumes its regular gas, and what -/// the frame left returns to `gas`, its reservoir added to what `gas` kept, which is nothing, -/// since the frame took it whole; +/// the frame left returns to `gas`, its reservoir in place of the one `gas` gave it; /// - the EIP-2780 refundable first-frame charge is refunded when no account leaf was created, /// priced through [`Host::state_gas_charge`](context_interface::Host::state_gas_charge) as it /// was charged; after a halt the regular gas the refund credited is consumed. /// -/// `gas` holds no reservoir on entry: the first frame took it whole -/// ([`GasTracker::forward_all_to_child`]), and the settlement adds back what the frame left, so -/// gas that still held what the frame was given would count it twice. A debug build asserts it. -/// /// A chain whose handler overrides `last_frame_result` calls this rather than copying the mainnet /// body, so a step the fork adds here reaches its handler too. It applies its own rules to `gas` /// after this returns and then copies `gas` into the frame's result, as op-revm's handler does @@ -50,12 +45,6 @@ where { let instruction_result = frame_result.instruction_result(); - debug_assert!( - gas.reservoir() == 0, - "the transaction's gas still holds the reservoir its frame was given; the settlement \ - would count it twice (take it with `GasTracker::forward_all_to_child`)" - ); - // All regular gas was forwarded to the first frame: consume it on the // transaction-level gas; the settle below returns the frame's unused // part. diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index bbfd4a68a6..64991f508a 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -549,7 +549,7 @@ impl EthFrame<EthInterpreter> { } // Settle the child's gas and merge it into the parent (returns - // unused regular gas, adds back the reservoir, and propagates state + // unused regular gas, adopts the reservoir, and propagates state // gas / refunds on success). handle_reservoir_remaining_gas( ins_result, @@ -580,7 +580,7 @@ impl EthFrame<EthInterpreter> { let mut create_gas = *outcome.gas(); // Settle the child's gas and merge it into the parent (returns - // unused regular gas, adds back the reservoir, and propagates state + // unused regular gas, adopts the reservoir, and propagates state // gas / refunds on success). handle_reservoir_remaining_gas( instruction_result, @@ -600,7 +600,7 @@ impl EthFrame<EthInterpreter> { } // Refund the upfront state charge after the child's gas is settled - // (the settle adds the child's reservoir to what the parent kept). + // (the settle overwrites the reservoir with the child's). if let Some(charge) = refund_state_gas { self.interpreter.gas.refill_reservoir(charge); } @@ -622,12 +622,10 @@ impl EthFrame<EthInterpreter> { /// Then the parent *merges* the settled child: /// - unused regular gas (`remaining`, including any spill returned on revert) /// flows back to the parent on success or revert; a halt consumes it. -/// - the reservoir, the share of the parent's state-gas pool the child was given -/// at call time, is always added back from the child to what the parent kept -/// (restored to the inherited value on revert/halt). Every schedule defined -/// here forwards the whole reservoir, so the parent kept nothing and its -/// reservoir becomes the child's. Any returned reservoir first unwinds the -/// parent's outstanding spilled state gas in LIFO order. +/// - the reservoir, a shared state-gas pool the child inherited at call time, is +/// always adopted from the child (restored to the inherited value on +/// revert/halt). Any returned reservoir first unwinds the parent's outstanding +/// spilled state gas in LIFO order. /// - net state gas, net history gas, the spilled portion, and the refund counter /// persist only on success; on revert/halt the child's state changes roll back /// and contribute nothing. @@ -878,11 +876,23 @@ mod tests { assert_eq!(parent.state_gas_spilled(), 0); } - /// A caller that forwarded a share of its reservoir and kept the rest gets back, on top of - /// what it kept: what the child left when it succeeded, the whole share when it reverted or - /// halted, the child's state charges undone. Regular gas settles as it did. + /// Settles `child` into `parent` as revm does, then adds back the reservoir `parent` held + /// while the child ran, as a consumer that kept part of `parent`'s reservoir for it does. + fn settle_and_add_back( + result: InstructionResult, + parent: &mut GasTracker, + child: &mut GasTracker, + ) { + let held = parent.reservoir(); + handle_reservoir_remaining_gas(result, parent, child); + parent.set_reservoir(parent.reservoir() + held); + } + + /// The reservoir a child returns replaces its caller's: what the child left when it succeeded, + /// the whole reservoir it was given when it reverted or halted, the child's state charges + /// undone. Regular gas settles as it did. #[test] - fn test_the_reservoir_a_child_returns_joins_what_its_caller_kept() { + fn test_the_reservoir_a_child_returns_replaces_its_callers() { for result in [ InstructionResult::Stop, InstructionResult::Revert, @@ -890,9 +900,7 @@ mod tests { ] { let mut parent = GasTracker::new(10_000, 10_000, 1_000); assert!(parent.record_regular_cost(5_000)); - // 98% of 1,000 forwarded, 20 kept. - parent.forward_reservoir(980); - let mut child = GasTracker::new(5_000, 5_000, 980); + let mut child = GasTracker::new(5_000, 5_000, parent.reservoir()); assert!(child.record_state_cost(300)); handle_reservoir_remaining_gas(result, &mut parent, &mut child); @@ -913,18 +921,21 @@ mod tests { } } - /// A child that spends more than its share spills onto its regular gas, as a frame with no - /// reservoir left does, though its caller kept part of the reservoir: the share is the - /// child's whole reservoir. A caller's later rollback restores the reservoir it started with - /// and gives the spill back to regular gas. + /// A consumer that keeps part of a caller's reservoir gives the child the rest, and adds what + /// the caller held back once revm replaced the caller's reservoir with the child's: the caller + /// ends with what the child returned on top of the part it kept. A child that spends more than + /// its share spills onto its regular gas, as a frame with no reservoir left does, though its + /// caller kept part of the reservoir: the share is the child's whole reservoir. A caller's + /// later rollback restores the reservoir it started with and gives the spill back to regular + /// gas. #[test] fn test_a_child_spills_past_its_share_and_a_rollback_restores_the_callers_reservoir() { let mut a = GasTracker::new(10_000, 10_000, 1_000); assert!(a.record_regular_cost(10_000)); - a.forward_reservoir(1_000); - let mut b = GasTracker::new(10_000, 10_000, 1_000); + let mut b = GasTracker::new(10_000, 10_000, a.reservoir()); assert!(b.record_regular_cost(5_000)); - b.forward_reservoir(980); + // 98% of 1,000 forwarded, 20 kept. + b.set_reservoir(20); let mut c = GasTracker::new(5_000, 5_000, 980); assert!(c.record_state_cost(1_000)); assert_eq!( @@ -932,8 +943,8 @@ mod tests { (0, 4_980, 20) ); - handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); - assert_eq!(b.reservoir(), 20, "the part B kept is still there"); + settle_and_add_back(InstructionResult::Stop, &mut b, &mut c); + assert_eq!(b.reservoir(), 20, "the part B kept is back"); assert_eq!(b.state_gas_spilled(), 20); assert_eq!(b.remaining(), 9_980); @@ -982,10 +993,14 @@ mod tests { // B holds 1,000 of reservoir and forwards 5,000 of regular gas; C charges 1,000. let mut b = GasTracker::new(10_000, 10_000, 1_000); assert!(b.record_regular_cost(5_000)); - b.forward_reservoir(forwarded); let mut c = GasTracker::new(5_000, 5_000, forwarded); assert!(c.record_state_cost(1_000)); - handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); + if forwarded < 1_000 { + b.set_reservoir(1_000 - forwarded); + settle_and_add_back(InstructionResult::Stop, &mut b, &mut c); + } else { + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut b, &mut c); + } assert_eq!(figures(&b), after_child, "{forwarded}: after C"); // B writes a slot, 10 of state gas, and puts it back, a refill of 10. diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 697a673413..8892b6e6ac 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -334,12 +334,10 @@ pub trait Handler { // start. lifecycle::open_transaction_start(evm)?; let tx_gas_limit = evm.ctx().tx().gas_limit(); - // The stand-in takes the whole reservoir out of the transaction's gas, as the first frame - // would (`create_init_frame`), so the settle adds it back once. - let shares = gas.forward_all_to_child(); + let reservoir = gas.reservoir(); let mut frame_result = match evm.ctx().tx().kind() { - TxKind::Call(_) => FrameResult::new_call_oog(tx_gas_limit, 0..0, shares.reservoir), - TxKind::Create => FrameResult::new_create_oog(tx_gas_limit, shares.reservoir), + TxKind::Call(_) => FrameResult::new_call_oog(tx_gas_limit, 0..0, reservoir), + TxKind::Create => FrameResult::new_create_oog(tx_gas_limit, reservoir), }; self.last_frame_result(evm, &mut frame_result, gas)?; Ok(frame_result) @@ -510,8 +508,8 @@ pub trait Handler { /// ([`handle_reservoir_remaining_gas`]): a failing frame rolls its /// state-gas charges back in LIFO order and drops its refund counter, an /// exceptional halt additionally consumes its regular gas; unused regular - /// gas then returns to the transaction-level gas and the reservoir the - /// frame left is added back to it. The EIP-2780 refundable first-frame charge is + /// gas then returns to the transaction-level gas and the reservoir is + /// adopted from the frame. The EIP-2780 refundable first-frame charge is /// refunded from the outcome's `charged_*` flags, mirroring /// `EthFrame::return_result`. /// diff --git a/crates/handler/tests/reservoir_share.rs b/crates/handler/tests/reservoir_settlement.rs similarity index 72% rename from crates/handler/tests/reservoir_share.rs rename to crates/handler/tests/reservoir_settlement.rs index b1bcd1b96c..77bcd7b5ef 100644 --- a/crates/handler/tests/reservoir_share.rs +++ b/crates/handler/tests/reservoir_settlement.rs @@ -1,11 +1,16 @@ -//! The share of its caller's EIP-8037 reservoir a child frame receives, as the mainnet handler -//! forwards and settles it. +//! A child frame's EIP-8037 reservoir, as the mainnet handler forwards and settles it, and as a +//! consumer that keeps part of it for the caller settles it through the start lifecycle. //! -//! A frame start takes all but the schedule's `reservoir_kept_percent` of its caller's reservoir -//! out of the caller's tracker for the child, and the child's return adds what the child left to -//! what the caller kept. Every schedule keeps none and forwards the whole reservoir, which is -//! upstream's forward; these tests forward 98, a chain that keeps 2% of the reservoir for the -//! caller, and compare with it. +//! A frame start copies its caller's reservoir into the child's input, and the caller keeps it +//! while the child runs; the child's return replaces the caller's reservoir with what the child +//! left, once that has unwound the caller's outstanding spill. That is upstream's forward and +//! settlement, and the default. +//! +//! A consumer that keeps part of the reservoir for the caller takes it in the frame-start hook, +//! names the child's reservoir on the start (`FrameStart::reservoir`), and adds back the reservoir +//! the caller held (`FrameSettle::held_reservoir`) when revm settles the child. The tests here keep +//! 2% that way, through [`KeepingContext`], and get the figures a forward of 98% that adds the +//! child's return to the part the caller kept gives. //! //! The transactions run on Amsterdam with a gas limit [`RESERVOIR`] above the regular cap, so they //! start with a reservoir. The frames charge state gas through an instruction of the test's own, @@ -19,11 +24,15 @@ use bytecode::opcode::{ }; use context::{ result::{EVMError, ExecutionResult}, - Context, ContextSetters, ContextTr, Evm, TxEnv, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Journal, LocalContext, + TxEnv, }; use context_interface::{ - cfg::{gas::InitialAndFloorGas, GasId}, - Cfg, Database, + cfg::{gas::InitialAndFloorGas, GasId, GasParams, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::{FrameSettle, FrameSplit, FrameStart, LifecycleEnd, LoadError}, + journaled_state::AccountInfoLoad, + Cfg, Database, Host, }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use interpreter::{ @@ -31,7 +40,8 @@ use interpreter::{ Instruction, InstructionContext, InstructionExecResult, InstructionResult, }; use primitives::{ - address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, TxKind, U256, + address, constants::CALL_STACK_LIMIT, hardfork::SpecId, Address, Bytes, Log, StorageKey, + StorageValue, TxKind, B256, U256, }; use revm_handler::{ instructions::EthInstructions, system_call::SystemCallTx, EthFrame, EthPrecompiles, EvmTr, @@ -41,7 +51,7 @@ use state::{AccountInfo, Bytecode}; type Db = CacheDB<EmptyDB>; type DbError = <Db as Database>::Error; -type TestContext = MainnetContext<Db>; +type TestContext = KeepingContext; type TestEvm = Evm<TestContext, (), EthInstructions<EthInterpreter, TestContext>, EthPrecompiles, EthFrame>; type TestError = EVMError<DbError>; @@ -54,7 +64,7 @@ const GAS_LIMIT: u64 = 3_000_000; const RESERVOIR: u64 = 1_000_000; /// What `CHARGE` charges as state gas. const CHARGED: u64 = 1_000; -/// The share of a caller's reservoir a chain that keeps part of it forwards. +/// The share of a caller's reservoir a consumer that keeps part of it forwards. const PERCENT: u64 = 98; /// State gas of a new storage slot on Amsterdam's schedule. const SLOT: u64 = 97_920; @@ -97,6 +107,225 @@ const fn charge( /// its net state gas. type Returned = (InstructionResult, u64, i64); +/// The mainnet context, with the start lifecycle's hooks of a consumer that keeps part of each +/// caller's reservoir for the caller, when told to ([`KeepingContext::percent`]). +/// +/// The frame-start hook takes `100 - percent` per cent of the caller's reservoir, rounded down, +/// for the caller, and names the rest as the child's reservoir; the settlement hook adds the +/// reservoir the caller held back to it once revm has settled a child into it. The transaction's +/// frame is given the whole reservoir, so nothing is added back to the transaction's gas. Each +/// settlement's depth and held reservoir is recorded, told to keep or not. +struct KeepingContext { + inner: MainnetContext<Db>, + /// The per cent of a caller's reservoir a child receives, if the consumer keeps the rest. + percent: Option<u64>, + /// Every settlement's depth and `held_reservoir`, in the order revm settled them. + held: Vec<(usize, u64)>, +} + +impl ContextTr for KeepingContext { + type Block = BlockEnv; + type Tx = TxEnv; + type Cfg = CfgEnv; + type Db = Db; + type Journal = Journal<Db>; + type Chain = (); + type Local = LocalContext; + + fn all( + &self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &Self::Db, + &Self::Journal, + &Self::Chain, + &Self::Local, + ) { + self.inner.all() + } + + fn all_mut( + &mut self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &mut Self::Journal, + &mut Self::Chain, + &mut Self::Local, + ) { + self.inner.all_mut() + } + + fn error(&mut self) -> &mut Result<(), ContextError<DbError>> { + self.inner.error() + } +} + +impl ContextSetters for KeepingContext { + fn set_tx(&mut self, tx: Self::Tx) { + self.inner.set_tx(tx); + } + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } +} + +impl Host for KeepingContext { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + if let Some(percent) = self.percent { + let reservoir = gas.reservoir(); + let kept = reservoir * (100 - percent) / 100; + start.reservoir = Some(reservoir - kept); + gas.set_reservoir(kept); + } + true + } + + fn frame_split(&mut self, split: &FrameSplit) { + self.inner.frame_split(split); + } + + fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { + self.held.push((settle.depth, settle.held_reservoir)); + if self.percent.is_some() && settle.depth > 0 { + gas.set_reservoir(gas.reservoir() + settle.held_reservoir); + } + self.inner.frame_settle(settle, gas); + } + + fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { + self.inner.frame_lifecycle_end(end); + } + + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64> { + self.inner.state_gas_price(id, site) + } + + fn basefee(&self) -> U256 { + self.inner.basefee() + } + + fn blob_gasprice(&self) -> U256 { + self.inner.blob_gasprice() + } + + fn gas_limit(&self) -> U256 { + self.inner.gas_limit() + } + + fn difficulty(&self) -> U256 { + self.inner.difficulty() + } + + fn prevrandao(&self) -> Option<U256> { + self.inner.prevrandao() + } + + fn block_number(&self) -> U256 { + self.inner.block_number() + } + + fn timestamp(&self) -> U256 { + self.inner.timestamp() + } + + fn beneficiary(&self) -> Address { + self.inner.beneficiary() + } + + fn slot_num(&self) -> U256 { + self.inner.slot_num() + } + + fn chain_id(&self) -> U256 { + self.inner.chain_id() + } + + fn effective_gas_price(&self) -> U256 { + self.inner.effective_gas_price() + } + + fn caller(&self) -> Address { + self.inner.caller() + } + + fn blob_hash(&self, number: usize) -> Option<U256> { + self.inner.blob_hash(number) + } + + fn max_initcode_size(&self) -> usize { + self.inner.max_initcode_size() + } + + fn gas_params(&self) -> &GasParams { + self.inner.gas_params() + } + + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.inner.is_amsterdam_eip8037_enabled() + } + + fn block_hash(&mut self, number: u64) -> Option<B256> { + self.inner.block_hash(number) + } + + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result<StateLoad<SelfDestructResult>, LoadError> { + self.inner.selfdestruct(address, target, skip_cold_load) + } + + fn log(&mut self, log: Log) { + self.inner.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result<StateLoad<SStoreResult>, LoadError> { + self.inner + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result<StateLoad<StorageValue>, LoadError> { + self.inner + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.inner.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.inner.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result<AccountInfoLoad<'_>, LoadError> { + self.inner + .load_account_info_skip_cold_load(address, load_code, skip_cold_load) + } +} + const fn returned(result: &FrameResult) -> Returned { let gas = result.gas(); ( @@ -132,6 +361,8 @@ struct ShareHandler { tx_reservoir: core::cell::Cell<Option<u64>>, /// The transaction's reservoir once the first frame's input was built. after_first_input: Option<u64>, + /// Every settlement's depth and held reservoir, once the transaction's start settled. + held: Vec<(usize, u64)>, } impl ShareHandler { @@ -145,6 +376,7 @@ impl ShareHandler { settled: None, tx_reservoir: core::cell::Cell::new(None), after_first_input: None, + held: Vec::new(), } } } @@ -221,6 +453,7 @@ impl Handler for ShareHandler { ) -> Result<(), TestError> { self.mainnet.last_frame_result(evm, frame_result, gas)?; self.settled = Some((gas.reservoir(), gas.state_gas_spent())); + self.held = evm.ctx().held.clone(); Ok(()) } } @@ -254,8 +487,8 @@ fn ends(mut code: Vec<u8>) -> Vec<u8> { struct Run { parent: Vec<u8>, parent_balance: u64, - /// The per cent of the reservoir a child receives, if not the default: the schedule's - /// `reservoir_kept_percent` is the rest. + /// The per cent of the reservoir a child receives, if the consumer keeps the rest for the + /// caller ([`KeepingContext`]); by default it receives the whole reservoir. percent: Option<u64>, /// The transaction, if not a call to [`PARENT`] with [`GAS_LIMIT`]. tx: Option<TxEnv>, @@ -358,11 +591,12 @@ impl Run { .modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); cfg.tx_gas_limit_cap = Some(cap); - if let Some(percent) = percent { - cfg.gas_params - .override_gas([(GasId::reservoir_kept_percent(), 100 - percent)]); - } }); + let ctx = KeepingContext { + inner: ctx, + percent, + held: Vec::new(), + }; let mut instructions = EthInstructions::new_mainnet_with_spec(SPEC); instructions.insert_instruction(CHARGE, Instruction::new(charge), 0); let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(SPEC)); @@ -403,13 +637,15 @@ const fn share(reservoir: u64) -> u64 { reservoir - reservoir * (100 - PERCENT) / 100 } -/// Every start forwards 98% of its caller's reservoir, rounded down, and the caller keeps the -/// rest; what a child hands back adds to what its caller kept: what it left when it succeeded, -/// the whole share when it reverted or halted, a successful grandchild's charge included. The -/// transaction's frame takes the whole reservoir. No frame here spends past its share, so the +/// A consumer that keeps 2% of each caller's reservoir, rounded down, gives each start the rest; +/// revm's settlement replaces the caller's reservoir with what the child hands back, and the +/// consumer adds what the caller held, the part it kept: what the child left when it succeeded, +/// the whole share when it reverted or halted, a successful grandchild's charge included, joins +/// the kept part. The transaction's frame is given the whole reservoir, which the transaction's gas +/// holds as its copy, so nothing is added back to it. No frame here spends past its share, so the /// transaction ends with the figures the whole forward gives, and the same result. #[test] -fn test_the_reservoir_is_forwarded_by_its_share_and_settled_at_depth() { +fn test_a_consumer_that_keeps_part_of_the_reservoir_adds_back_what_the_caller_held() { let (result, handler) = at_depth().percent(PERCENT).run(); assert!(result.is_success(), "{result:?}"); @@ -472,19 +708,38 @@ fn test_the_reservoir_is_forwarded_by_its_share_and_settled_at_depth() { handler.settled, Some((RESERVOIR - 2 * CHARGED, 2 * charged)) ); + // What each caller held when revm settled its child: the 2% it kept, of 999,000, 998,000 and + // 977,040; the transaction's gas held the copy of the whole reservoir it gave its frame. + assert_eq!( + handler.held, + [ + (1, 19_980), + (1, 19_960), + (1, 19_960), + (2, 19_540), + (1, 19_960), + (0, RESERVOIR), + ] + ); let (whole, whole_handler) = at_depth().run(); assert_eq!(result, whole, "the shares change no result here"); assert_eq!(whole_handler.settled, handler.settled); } -/// The whole forward is upstream's: every start passes on all its caller has, and the caller -/// holds none while the child runs. +/// The default forward is upstream's: every start copies all its caller has into the child's +/// input, the caller keeps its reservoir while the child runs, and the child's return replaces it. +/// The transaction's gas keeps the reservoir it gives its frame, which its frame's return replaces. #[test] -fn test_every_start_forwards_the_whole_reservoir_by_default() { +fn test_every_start_copies_the_whole_reservoir_by_default() { let (result, handler) = at_depth().run(); assert!(result.is_success(), "{result:?}"); + assert_eq!( + handler.after_first_input, + Some(RESERVOIR), + "the transaction's gas keeps its reservoir" + ); let before_each = RESERVOIR - 2 * CHARGED; assert_eq!( handler.starts, @@ -508,10 +763,24 @@ fn test_every_start_forwards_the_whole_reservoir_by_default() { ) ); assert_eq!(handler.settled, Some((before_each, 2 * charged))); + // Each caller held the reservoir it copied to its child: PARENT 999,000 at its first call and + // 998,000, OK's return, at the others; NESTER 997,000; the transaction's gas the whole. + assert_eq!( + handler.held, + [ + (1, RESERVOIR - CHARGED), + (1, before_each), + (1, before_each), + (2, before_each - CHARGED), + (1, before_each), + (0, RESERVOIR), + ] + ); } /// A child whose charges pass its share spills onto its regular gas, as a frame whose reservoir -/// is empty does, though its caller holds the 2% it kept: the share is all the child has. On +/// is empty does, though its caller holds the 2% the consumer kept: the share is all the child +/// has. On /// return the caller holds what it kept beside the child's spill; when the caller's own frame /// returns, its reservoir unwinds that spill first, as any returned reservoir does (last in, first /// out), so the transaction ends as the whole forward ends it. @@ -585,8 +854,8 @@ fn test_a_child_that_cannot_pay_past_its_share_runs_out_of_gas() { } /// A child that clears a slot its caller created gets the slot's state gas back as an EIP-8037 -/// restoration, into its own reservoir; when it succeeds, the caller adds it with the rest of the -/// share to what it kept, and is back where it was before it created the slot. When it reverts, +/// restoration, into its own reservoir; when it succeeds, the caller gets it back with the rest of +/// the share and the part the consumer kept, and is back where it was before it created the slot. When it reverts, /// the restoration is undone with the rest of its frame and the caller gets the share back. #[test] fn test_a_restoration_in_the_child_comes_back_to_its_caller() { @@ -718,19 +987,6 @@ fn test_a_system_call_forwards_and_settles_its_reservoir() { } } -/// The schedule's entry is upstream's forward on every spec: the caller keeps none. -#[test] -fn test_the_schedule_forwards_the_whole_reservoir() { - let evm = Run::new(ends(Vec::new())).evm(); - assert_eq!( - evm.ctx - .cfg() - .gas_params() - .get(GasId::reservoir_kept_percent()), - 0 - ); -} - /// `CREATE` of the two bytes `CHARGE STOP`, endowed with nothing, dropping the address. fn create_charging() -> Vec<u8> { vec![ @@ -785,23 +1041,24 @@ fn test_a_creation_forwards_its_share_and_a_collision_hands_it_back() { assert_eq!(handler.settled, Some((after_parent, CHARGED as i64))); } -/// A creation transaction's frame takes the whole reservoir the transaction has left, whatever -/// the schedule, and settles back into it. +/// A creation transaction's frame is given the whole reservoir the transaction has left, which the +/// transaction's gas keeps as its copy, whether the consumer keeps part of a caller's reservoir or +/// not; the frame's return replaces it. #[test] -fn test_a_creation_transaction_takes_the_whole_reservoir() { +fn test_a_creation_transaction_is_given_the_whole_reservoir() { for percent in [None, Some(PERCENT)] { let mut run = Run::creation(vec![CHARGE, STOP]); run.percent = percent; let (result, handler) = run.run(); assert!(result.is_success(), "{percent:?}: {result:?}"); + let first = handler.starts[0]; + assert!(first > 0, "{percent:?}"); assert_eq!( handler.after_first_input, - Some(0), - "{percent:?}: all of it taken" + Some(first), + "{percent:?}: the transaction's gas keeps its copy" ); - let first = handler.starts[0]; - assert!(first > 0, "{percent:?}"); assert_eq!( handler.settled.map(|(reservoir, _)| reservoir), Some(first - CHARGED) @@ -810,7 +1067,8 @@ fn test_a_creation_transaction_takes_the_whole_reservoir() { } /// A transaction whose EIP-2780 runtime phase runs out of gas skips execution and is settled -/// from a stand-in for its first frame: all regular gas consumed and the reservoir returned once. +/// from a stand-in for its first frame: all regular gas consumed and the reservoir returned once, +/// the stand-in's replacing the copy the transaction's gas kept. #[test] fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { const LIMIT: u64 = 130_000; @@ -849,7 +1107,7 @@ fn test_a_runtime_out_of_gas_returns_the_reservoir_once() { } /// The same for a creation transaction, whose runtime phase charges the account it would create: -/// the stand-in takes the whole reservoir, which settles back once. +/// the stand-in carries the whole reservoir, which settles back once. #[test] fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_once() { const LIMIT: u64 = 160_000; @@ -884,19 +1142,22 @@ fn test_a_creation_transactions_runtime_out_of_gas_returns_the_reservoir_once() } } -/// The transaction's frame took the whole reservoir, and its settlement adds -/// back what it left. A runner that settles the frame into gas that still holds what the frame was -/// given, because it built the frame without taking it or seeded the gas from the frame's own -/// figures, would count it twice; a debug build refuses the settlement. -#[cfg(debug_assertions)] +/// A runner that settles a first frame into gas that still holds the reservoir the frame was given, +/// as the transaction's gas does, gets the frame's reservoir in its place, counted once. #[test] -#[should_panic(expected = "the transaction's gas still holds the reservoir its frame was given")] -fn test_a_first_frame_settled_into_gas_that_kept_the_reservoir_panics_in_a_debug_build() { +fn test_a_first_frame_settled_into_gas_that_kept_its_reservoir_counts_it_once() { let mut evm = Run::new(ends(Vec::new())).evm(); let mut result = FrameResult::new_call_oog(GAS_LIMIT, 0..0, RESERVOIR); let mut gas = GasTracker::new(GAS_LIMIT, 0, RESERVOIR); + // A runner that settles a first frame it built itself opens the transaction's start first. + revm_handler::lifecycle::open_transaction_start(&mut evm).expect("the start opens"); + + Mainnet::default() + .last_frame_result(&mut evm, &mut result, &mut gas) + .expect("the frame settles"); - let _ = Mainnet::default().last_frame_result(&mut evm, &mut result, &mut gas); + assert_eq!(gas.reservoir(), RESERVOIR); + assert_eq!(evm.ctx.held, [(0, RESERVOIR)]); } /// A runner that builds the gas with `GasTracker::new`, with no reservoir, settles as before. diff --git a/crates/inspector/tests/loop_hooks.rs b/crates/inspector/tests/loop_hooks.rs index f15d4091b6..964c02f3bf 100644 --- a/crates/inspector/tests/loop_hooks.rs +++ b/crates/inspector/tests/loop_hooks.rs @@ -19,7 +19,7 @@ use context::{ result::{EVMError, ExecutionResult, Output}, - Cfg, Context, ContextSetters, ContextTr, Evm, FrameStack, JournalTr, TxEnv, + Context, ContextSetters, ContextTr, Evm, FrameStack, JournalTr, TxEnv, }; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ @@ -98,8 +98,8 @@ struct Plan { enum AtStart { /// A return carrying [`AT_START`]. Return, - /// A creation with no init code on [`CREATION_GAS`] and the share of the frame's reservoir; - /// once it returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. + /// A creation with no init code on [`CREATION_GAS`] and the frame's reservoir; once it + /// returned into [`CHILD`], a return carrying [`AFTER_ITS_CHILD`]. Create, /// The creation of [`AtStart::Create`]; once it returned into [`CHILD`], nothing, so /// [`CHILD`] runs its code. @@ -262,7 +262,6 @@ impl EvmTr for Consumer { .plan .at_start .filter(|_| is_call_to(&frame_input.frame_input, CHILD)); - let params = self.evm.ctx.cfg().gas_params().clone(); let mut started = self.evm.frame_init(frame_input)?; if let (Some(at_start), ItemOrResult::Item(frame)) = (at_start, &mut started) { let action = match at_start { @@ -273,14 +272,13 @@ impl EvmTr for Consumer { gas.record_regular_cost(CREATION_GAS), "the frame pays the creation" ); - let shares = gas.tracker_mut().forward_to_child(¶ms); let inputs = CreateInputs::new( CHILD, CreateScheme::Create, U256::ZERO, Bytes::new(), CREATION_GAS, - shares.reservoir, + gas.reservoir(), ); InterpreterAction::NewFrame(FrameInput::Create(Box::new(inputs))) } diff --git a/crates/inspector/tests/reservoir_share.rs b/crates/inspector/tests/reservoir_settlement.rs similarity index 50% rename from crates/inspector/tests/reservoir_share.rs rename to crates/inspector/tests/reservoir_settlement.rs index 700c857397..d9ebe5108d 100644 --- a/crates/inspector/tests/reservoir_share.rs +++ b/crates/inspector/tests/reservoir_settlement.rs @@ -1,27 +1,39 @@ -//! An outcome an inspector builds to answer a start settles its reservoir as built, on top of -//! what the caller kept when it forwarded its share. +//! An outcome an inspector builds to answer a start settles its reservoir as built, in place of +//! the caller's, and a consumer that keeps part of the caller's reservoir adds back what the +//! caller held. //! -//! The caller's start takes the schedule's share of its reservoir out of its tracker, and the -//! answer's reservoir is added back to what the caller kept, as a frame's is. An answer built on -//! `Gas::new` carries no reservoir: with the whole reservoir forwarded, which every schedule does, -//! the caller is left with none, as upstream's settlement, which put the answer's reservoir in -//! place of the caller's, leaves it; with 98% forwarded, the caller is left with the 2% it kept. +//! The caller's start copies its reservoir into the input, and the answer's reservoir replaces the +//! caller's, as a frame's does. An answer built on `Gas::new` carries no reservoir: by default the +//! caller is left with none, as upstream's settlement leaves it; with 98% forwarded by a consumer +//! that keeps the rest for the caller ([`KeepingContext`]), the caller is left with the 2% it kept. //! An answer that carries the input's reservoir gives the caller back what it forwarded. //! //! A creation's answer settles through the same arm as a call's: the caller also paid the //! creation's upfront state charge before the forward, which an answer that copies the input's //! charge gives back and one built with `CreateOutcome::new` does not. -use context::{context_interface::cfg::GasId, Context, Evm, TxEnv}; +use context::{ + context_interface::{ + cfg::{GasId, GasParams, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::{FrameSettle, FrameSplit, FrameStart, LifecycleEnd, LoadError}, + journaled_state::AccountInfoLoad, + Database, + }, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Evm, Host, Journal, + LocalContext, TxEnv, +}; use database::{CacheDB, EmptyDB, BENCH_CALLER}; use handler::{ instructions::EthInstructions, EthFrame, EthPrecompiles, MainContext, MainnetContext, }; use interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, InterpreterResult, + GasTracker, InstructionResult, InterpreterResult, +}; +use primitives::{ + address, hardfork::SpecId, Address, Bytes, Log, StorageKey, StorageValue, TxKind, B256, U256, }; -use primitives::{address, hardfork::SpecId, Address, Bytes, TxKind, U256}; use revm_inspector::{InspectEvm, Inspector}; use state::{ bytecode::opcode::{CALL, CREATE, POP, PUSH0, PUSH1, PUSH20, PUSH3, SSTORE, STOP}, @@ -29,7 +41,8 @@ use state::{ }; type Db = CacheDB<EmptyDB>; -type Ctx = MainnetContext<Db>; +type DbError = <Db as Database>::Error; +type Ctx = KeepingContext; const SPEC: SpecId = SpecId::AMSTERDAM; const GAS_LIMIT: u64 = 3_000_000; @@ -39,7 +52,7 @@ const RESERVOIR: u64 = 1_000_000; const SLOT: u64 = 97_920; /// What [`PARENT`] holds when it calls [`OK`]. const BEFORE_THE_CALL: u64 = RESERVOIR - SLOT; -/// Its share at 98: all but the caller's 2%, rounded down (18,041.6 → 18,041). +/// Its share at 98: all but the 2% the consumer keeps, rounded down (18,041.6 → 18,041). const SHARE: u64 = 884_039; /// The state charge a creation's start pays for its account on Amsterdam's schedule, before the @@ -47,9 +60,228 @@ const SHARE: u64 = 884_039; const ACCOUNT: u64 = 183_600; /// What [`PARENT`] holds when it creates, once the creation's charge is paid. const BEFORE_THE_CREATION: u64 = BEFORE_THE_CALL - ACCOUNT; -/// Its share at 98: all but the caller's 2%, rounded down (14,369.6 → 14,369). +/// Its share at 98: all but the 2% the consumer keeps, rounded down (14,369.6 → 14,369). const CREATION_SHARE: u64 = 704_111; +/// The mainnet context, with the start lifecycle's hooks of a consumer that keeps part of each +/// caller's reservoir for the caller, when told to ([`KeepingContext::percent`]). +/// +/// The frame-start hook takes `100 - percent` per cent of the caller's reservoir, rounded down, +/// for the caller, and names the rest as the child's reservoir; the settlement hook adds the +/// reservoir the caller held back to it once revm has settled a child into it. The transaction's +/// frame is given the whole reservoir, so nothing is added back to the transaction's gas. Each +/// settlement's depth and held reservoir is recorded, told to keep or not. +struct KeepingContext { + inner: MainnetContext<Db>, + /// The per cent of a caller's reservoir a child receives, if the consumer keeps the rest. + percent: Option<u64>, + /// Every settlement's depth and `held_reservoir`, in the order revm settled them. + held: Vec<(usize, u64)>, +} + +impl ContextTr for KeepingContext { + type Block = BlockEnv; + type Tx = TxEnv; + type Cfg = CfgEnv; + type Db = Db; + type Journal = Journal<Db>; + type Chain = (); + type Local = LocalContext; + + fn all( + &self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &Self::Db, + &Self::Journal, + &Self::Chain, + &Self::Local, + ) { + self.inner.all() + } + + fn all_mut( + &mut self, + ) -> ( + &Self::Block, + &Self::Tx, + &Self::Cfg, + &mut Self::Journal, + &mut Self::Chain, + &mut Self::Local, + ) { + self.inner.all_mut() + } + + fn error(&mut self) -> &mut Result<(), ContextError<DbError>> { + self.inner.error() + } +} + +impl ContextSetters for KeepingContext { + fn set_tx(&mut self, tx: Self::Tx) { + self.inner.set_tx(tx); + } + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } +} + +impl Host for KeepingContext { + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + if let Some(percent) = self.percent { + let reservoir = gas.reservoir(); + let kept = reservoir * (100 - percent) / 100; + start.reservoir = Some(reservoir - kept); + gas.set_reservoir(kept); + } + true + } + + fn frame_split(&mut self, split: &FrameSplit) { + self.inner.frame_split(split); + } + + fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { + self.held.push((settle.depth, settle.held_reservoir)); + if self.percent.is_some() && settle.depth > 0 { + gas.set_reservoir(gas.reservoir() + settle.held_reservoir); + } + self.inner.frame_settle(settle, gas); + } + + fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { + self.inner.frame_lifecycle_end(end); + } + + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option<u64> { + self.inner.state_gas_price(id, site) + } + + fn basefee(&self) -> U256 { + self.inner.basefee() + } + + fn blob_gasprice(&self) -> U256 { + self.inner.blob_gasprice() + } + + fn gas_limit(&self) -> U256 { + self.inner.gas_limit() + } + + fn difficulty(&self) -> U256 { + self.inner.difficulty() + } + + fn prevrandao(&self) -> Option<U256> { + self.inner.prevrandao() + } + + fn block_number(&self) -> U256 { + self.inner.block_number() + } + + fn timestamp(&self) -> U256 { + self.inner.timestamp() + } + + fn beneficiary(&self) -> Address { + self.inner.beneficiary() + } + + fn slot_num(&self) -> U256 { + self.inner.slot_num() + } + + fn chain_id(&self) -> U256 { + self.inner.chain_id() + } + + fn effective_gas_price(&self) -> U256 { + self.inner.effective_gas_price() + } + + fn caller(&self) -> Address { + self.inner.caller() + } + + fn blob_hash(&self, number: usize) -> Option<U256> { + self.inner.blob_hash(number) + } + + fn max_initcode_size(&self) -> usize { + self.inner.max_initcode_size() + } + + fn gas_params(&self) -> &GasParams { + self.inner.gas_params() + } + + fn is_amsterdam_eip8037_enabled(&self) -> bool { + self.inner.is_amsterdam_eip8037_enabled() + } + + fn block_hash(&mut self, number: u64) -> Option<B256> { + self.inner.block_hash(number) + } + + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result<StateLoad<SelfDestructResult>, LoadError> { + self.inner.selfdestruct(address, target, skip_cold_load) + } + + fn log(&mut self, log: Log) { + self.inner.log(log) + } + + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result<StateLoad<SStoreResult>, LoadError> { + self.inner + .sstore_skip_cold_load(address, key, value, skip_cold_load) + } + + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result<StateLoad<StorageValue>, LoadError> { + self.inner + .sload_skip_cold_load(address, key, skip_cold_load) + } + + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) { + self.inner.tstore(address, key, value) + } + + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue { + self.inner.tload(address, key) + } + + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result<AccountInfoLoad<'_>, LoadError> { + self.inner + .load_account_info_skip_cold_load(address, load_code, skip_cold_load) + } +} + /// Writes a new slot, calls [`OK`] (or creates a contract with empty init code) and stops. const PARENT: Address = address!("0x00000000000000000000000000000000000c0de0"); /// Stops, when it runs. @@ -131,8 +363,8 @@ impl Inspector<Ctx, EthInterpreter> for Answering { } /// [`PARENT`]'s reservoir as its frame returned, and the reservoir its `start` was given, with -/// `percent` per cent of a caller's reservoir forwarded: the schedule's `reservoir_kept_percent` -/// is the rest. +/// `percent` per cent of a caller's reservoir forwarded by a consumer that keeps the rest +/// ([`KeepingContext`]), or the whole reservoir. fn run(answer: Answer, percent: Option<u64>, start: Start) -> (u64, u64) { let mut db = Db::default(); db.insert_account_info( @@ -162,11 +394,12 @@ fn run(answer: Answer, percent: Option<u64>, start: Start) -> (u64, u64) { let ctx = Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { cfg.set_spec_and_mainnet_gas_params(SPEC); cfg.tx_gas_limit_cap = Some(GAS_LIMIT - RESERVOIR); - if let Some(percent) = percent { - cfg.gas_params - .override_gas([(GasId::reservoir_kept_percent(), 100 - percent)]); - } }); + let ctx = KeepingContext { + inner: ctx, + percent, + held: Vec::new(), + }; let mut evm: Evm< Ctx, Answering, @@ -200,8 +433,8 @@ fn run(answer: Answer, percent: Option<u64>, start: Start) -> (u64, u64) { fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { for (answer, whole, kept_98) in [ (Answer::Runs, BEFORE_THE_CALL, BEFORE_THE_CALL), - // Upstream's settlement gives the caller the answer's empty reservoir in place of its - // own; the whole forward left the caller nothing to add it to, so the same. + // The settlement gives the caller the answer's empty reservoir in place of its own; the + // consumer that kept 2% adds that back. (Answer::AsBuilt, 0, BEFORE_THE_CALL - SHARE), (Answer::WithTheShares, BEFORE_THE_CALL, BEFORE_THE_CALL), ] { @@ -218,8 +451,8 @@ fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { } } -/// A creation's answer settles as a call's: as built, the caller keeps its kept part and the -/// creation's charge; with the shares and the input's charges, the caller gets back what it held +/// A creation's answer settles as a call's: as built, the caller gets back the part the consumer +/// kept, and keeps the creation's charge; with the shares and the input's charges, the caller gets back what it held /// before the creation's start. #[test] fn test_an_answer_the_inspector_builds_for_a_creation_settles_its_reservoir_as_built() { diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index fee76465c9..8bd8804df2 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -9,7 +9,7 @@ use call_helpers::load_acc_and_calc_forward; use crate::{ instructions::{ - instruction_hooks::{cache_created_address, forward_to_child, frame_starting}, + instruction_hooks::{cache_created_address, frame_starting}, utility::IntoAddress, }, interpreter_action::FrameInput, @@ -195,10 +195,9 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( gas_limit, ); let reservoir = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); create_inputs.set_gas_limit(gas_limit); - create_inputs.set_reservoir(shares.reservoir); + create_inputs.set_reservoir(reservoir.unwrap_or(context.interpreter.gas.reservoir())); context .interpreter .bytecode @@ -278,7 +277,6 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, let transferred = value.transfer().unwrap_or_default(); let start = FrameStart::new(kind, caller, Some(target_address), transferred, forward); let reservoir = frame_starting(&mut context.interpreter.gas, context.host, start)?; - let shares = forward_to_child(&mut context.interpreter.gas, context.host, reservoir); // Call host to interact with target contract context @@ -296,7 +294,7 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, scheme, is_static, return_memory_offset, - reservoir: shares.reservoir, + reservoir: reservoir.unwrap_or(context.interpreter.gas.reservoir()), charged_new_account_state_gas, }, )))); diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index 04b1c3138a..eeb97df459 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -3,8 +3,8 @@ use crate::{ interpreter_types::{InterpreterTypes as ITy, LoopControl}, - ChildShares, CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, - Interpreter, InterpreterAction, + CreateInputs, Gas, Host, InstructionExecResult as Result, InstructionResult, Interpreter, + InterpreterAction, }; use context_interface::host::{CompletedWrite, FrameStart, WriteVerdict}; use primitives::{constants::CALL_STACK_LIMIT, hints_util::cold_path, Address, Bytes, U256}; @@ -45,8 +45,8 @@ fn revert<IT: ITy>(interpreter: &mut Interpreter<IT>, output: Bytes) -> Result { /// Hands `start`, whose forward the running instruction has taken from `gas`, to /// [`Host::frame_starting`]. `true` returns the child's reservoir if the hook took it itself and -/// named it on `start`, for the forward ([`forward_to_child`]); `false` fails the instruction out -/// of gas. +/// named it on `start`, which the frame's input carries in place of the caller's reservoir; +/// `false` fails the instruction out of gas. #[inline] pub(crate) fn frame_starting<H: Host + ?Sized>( gas: &mut Gas, @@ -92,19 +92,3 @@ pub(crate) fn running_account<H: Host + ?Sized>( .account; Ok((account.balance, account.nonce)) } - -/// Takes the child's share of the caller's reservoir out of `gas`, all but the schedule's -/// `reservoir_kept_percent`, and returns it: what the child's tracker starts with -/// ([`GasTracker::forward_to_child`](crate::GasTracker::forward_to_child)). Called once the -/// frame-start hook has answered, so the share is of the reservoir as the hook left it. A child `reservoir` the hook named replaces the reservoir's share: the -/// child starts with it, and the caller keeps the reservoir the hook left -/// ([`GasTracker::forward_to_child_with_reservoir`](crate::GasTracker::forward_to_child_with_reservoir)). -#[inline] -pub(crate) fn forward_to_child<H: Host + ?Sized>( - gas: &mut Gas, - host: &H, - reservoir: Option<u64>, -) -> ChildShares { - gas.tracker_mut() - .forward_to_child_with_reservoir(host.gas_params(), reservoir) -} diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index b41f53dd62..252155a256 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -36,7 +36,7 @@ pub use context_interface::{ context::{SStoreResult, SelfDestructResult, StateLoad}, host, CreateScheme, Host, }; -pub use gas::{ChildShares, Gas, GasTracker, OutcomeMark, StartMark}; +pub use gas::{Gas, GasTracker, OutcomeMark, StartMark}; pub use instruction_context::InstructionContext; pub use instruction_result::*; pub use instructions::{ diff --git a/crates/interpreter/tests/instruction_hooks.rs b/crates/interpreter/tests/instruction_hooks.rs index a360b881f4..d633bb537c 100644 --- a/crates/interpreter/tests/instruction_hooks.rs +++ b/crates/interpreter/tests/instruction_hooks.rs @@ -849,9 +849,9 @@ fn input_gas(input: &FrameInput) -> (u64, u64) { } /// Each frame-starting instruction hands its start to the hook once the forward is taken, and -/// charges nothing after it: the instruction leaves the gas the hook was handed, apart from the -/// reservoir, whose share goes to the frame after the hook, and the frame's input carries the -/// forward, with a value call's stipend on top. +/// charges nothing after it: the instruction leaves the gas the hook was handed, its reservoir +/// included, which the frame's input copies, and the frame's input carries the forward, with a +/// value call's stipend on top. #[test] fn test_a_start_reaches_the_hook_with_the_forward_taken() { let spec = SpecId::OSAKA; @@ -893,12 +893,10 @@ fn test_a_start_reaches_the_hook_with_the_forward_taken() { before_forward - forward, "{name}: the hook sees the forward taken" ); - let mut after_the_forward = at_hook; - after_the_forward.set_reservoir(0); assert_eq!( *gas.tracker(), - after_the_forward, - "{name}: nothing is charged after the hook; the whole reservoir is forwarded" + at_hook, + "{name}: nothing is charged or taken after the hook" ); let stipend = if matches!(op, CALL | CALLCODE) { params.call_stipend() @@ -1050,10 +1048,11 @@ fn test_the_value_stipend_is_not_part_of_the_forward() { } } -/// The frame's input takes the reservoir as the hook left it, for every kind of start, out of the -/// caller's, which forwards the whole of it by default. A charge the reservoir covers leaves the -/// forward and the caller's regular gas alone; one that spills draws the caller's regular gas and -/// empties the reservoir, and the forward is still what was taken before. +/// The frame's input copies the caller's reservoir as the hook left it, for every kind of start, +/// and the caller keeps it while the child runs, as upstream's instructions do. A charge the +/// reservoir covers leaves the forward and the caller's regular gas alone; one that spills draws +/// the caller's regular gas and empties the reservoir, and the forward is still what was taken +/// before. #[test] fn test_the_input_copies_the_reservoir_the_hook_left() { let spec = SpecId::AMSTERDAM; @@ -1071,8 +1070,8 @@ fn test_the_input_copies_the_reservoir_the_hook_left() { assert_eq!(input_reservoir, reservoir, "{name}, charge {charge}"); assert_eq!( gas.reservoir(), - 0, - "{name}, charge {charge}: the caller forwarded the whole reservoir" + reservoir, + "{name}, charge {charge}: the caller keeps the reservoir it copied" ); assert_eq!( gas_limit, quiet_limit, @@ -1088,8 +1087,8 @@ fn test_the_input_copies_the_reservoir_the_hook_left() { } /// A hook that takes the child's reservoir out of the caller's itself names it on the start -/// ([`FrameStart::reservoir`]): the frame's input carries it, and the instruction takes no -/// reservoir share of its own, so the caller keeps what the hook left. +/// ([`FrameStart::reservoir`]): the frame's input carries it in place of the caller's reservoir, +/// and the caller keeps what the hook left. #[test] fn test_the_input_carries_the_child_reservoir_the_hook_names() { let spec = SpecId::AMSTERDAM; From 72cdbf1c6376e12dc4a148322e6e10bdb21c2ddf Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 19:01:09 +0800 Subject: [PATCH 101/110] test(handler): a frame result is 208 bytes on a 64-bit target --- crates/handler/src/frame_data.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index cfda9f3844..536cf43c12 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -202,3 +202,23 @@ impl FrameData { } } } + +#[cfg(test)] +mod tests { + use super::*; + use core::mem::size_of; + + /// A frame result is 208 bytes on a 64-bit target, and the values it is built from are what + /// that takes. The handler moves frame results through its wrappers several times per frame, + /// and past about 256 bytes each move is a library copy rather than an inline one, so a field + /// added to any of them is measured before this changes. + #[cfg(target_pointer_width = "64")] + #[test] + fn test_a_frame_result_is_208_bytes() { + assert_eq!(size_of::<Gas>(), 104); + assert_eq!(size_of::<InterpreterResult>(), 144); + assert_eq!(size_of::<CallOutcome>(), 208); + assert_eq!(size_of::<CreateOutcome>(), 192); + assert_eq!(size_of::<FrameResult>(), 208); + } +} From b86f16049e691916534f38afbf1d5d233de6944c Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 19:03:03 +0800 Subject: [PATCH 102/110] docs: MEGAETH-FORK.md drops the pools, the reservoir share, the start charge and the history allowance Rule 1 no longer carries the additive reservoir settlement as an exception, rule 2's set is withheld gas and the history dimension, and the entries for the four figures go. The frame-start hook and the start lifecycle say how revm forwards and settles the reservoir now and how a consumer that keeps part of it adds it back; the code-deposit admission entry is the hook's original one; the sizes are the frame values' without the figures. --- MEGAETH-FORK.md | 190 +++++++----------------------------------------- 1 file changed, 28 insertions(+), 162 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index f84162ef0f..7a42f49664 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -37,33 +37,20 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T The `Semver` workflow checks every pull request against its base; a deviation passes only with the `api:exception` label, and the pull request body lists every deviating item with the consumers it was checked against. Each consumer's own CI builds against the tagged fork. The fork carries accepted exceptions, and each entry under Hooks names its own. - One of them changes what upstream functions do without changing a signature, so neither the compiler nor the `Semver` workflow finds it: the reservoir settlement adds. - `handle_reservoir_remaining_gas` and `GasTracker::absorb_returned_reservoir` add the reservoir a frame returns to what its caller kept, where upstream's replace the caller's reservoir with it, and the forward takes the reservoir out of the caller where upstream's left it there (see The reservoir share). - A consumer that starts and settles frames only through revm's instructions and handler, on a schedule that keeps none of the reservoir, gets upstream's results, since the caller then holds nothing when the child returns. - It affects three kinds of consumer: - - code that hands a frame a reservoir or a pool without taking it from the caller, such as a child's input or a first-frame result built by hand, an override of `Handler::first_frame_input` or `Handler::runtime_oog_result`, or a runner that settles its own first frame: it compiles and counts the reservoir twice (see The settlement adds); - - an inspector that reads a caller's gas while its child runs, at a `CALL` or `CREATE` instruction's `step_end`: it sees the part the caller kept, zero by default, where upstream's showed the forwarded reservoir; - - a consumer whose schedule keeps part of the reservoir (`GasId::reservoir_kept_percent`), whose results differ from upstream's by design. - - Another changes the signature of an upstream function the fork picked with the EIP-8037 / EIP-2780 gas core: `pre_execution::apply_auth_list_eip2780`. + One changes the signature of an upstream function the fork picked with the EIP-8037 / EIP-2780 gas core: `pre_execution::apply_auth_list_eip2780`. The fork's takes the context, the authorization list as `&[Eip7702AuthFacts]` and whether EIP-8037 is on, where upstream's takes the journal, an iterator of authorizations and the two state-gas prices, so that every authorization's charge is priced through `Host::state_gas_price` (see State-gas price). The base line has no such function, so the change breaks no code written for it. A consumer that runs the authorization phase through `pre_execution::apply_eip7702_auth_list` or `Handler::apply_eip7702_auth_list`, whose signatures are upstream's, is unaffected. It affects code that calls `apply_auth_list_eip2780` itself, written for upstream's signature: it does not compile against the fork until it passes the context and the list `Eip7702AuthFacts::collect` builds. 2. **Hooks and data, and a bounded set of MegaETH accounting.** The fork adds hooks and data. - It also carries, today, a named, bounded set of MegaETH accounting inside revm's forwarding and settlement; the set is what the fork carries now, and the test for an addition (below) is stricter: + It also carries a named, bounded set of MegaETH accounting inside revm's charges and settlement: - withheld regular gas and its crossing record, which every regular charge reads; - - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`; - - the resource pools, per-frame budgets forwarded to a child, given back by a failed one and settled with the reservoir; - - the reservoir kept share, and the additive settlement it needs (rule 1); - - the start charge, and its refund when the frame fails; - - the history allowance. + - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`. - Some of these a consumer could keep beside revm's gas through the hooks, at a cost in code and in the gas figures it has to restore; the next base-line move may take them out (see What the fork carries). Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing. Nothing else that implements MegaETH semantics enters the fork. - The start lifecycle carries no MegaETH figure, so it is a generic hook and the set does not grow with it (see Start lifecycle). + What a consumer decides per frame start, such as a budget, a charge the frame's failure gives back, an allowance or a part of the caller's reservoir it keeps, it keeps beside revm's gas, driven by the start lifecycle's hooks; the lifecycle carries no MegaETH figure, so it is a generic hook and the set does not grow with it (see Start lifecycle). An addition to the set needs all of these, argued in its pull request: - no hook that sees only the state revm exposes at that point can make the same decision, because the figure is read or written inside a charge, or has to be ordered with revm's own settlement; the pull request says why the consumer cannot keep it beside revm's gas; - it is mechanism, not policy: every amount, share, price and limit comes from the consumer, through the gas schedule or a hook, and a detail the fork has to fix itself, such as a rounding, is named in its entry; @@ -101,11 +88,11 @@ The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fo | Class | What | Size | At the next base-line move | |---|---|---|---| -| Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `EthFrame::return_result`, `create_init_frame`, `last_frame_result`), so that accounting is re-applied to the new base's versions of it. | +| Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `rollback_state_gas`, `return_create`), so that accounting is re-applied to the new base's versions of it. | | Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | -| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | not counted | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types (`FrameStart::charge` leaves `FrameStart` first), as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | +| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | not counted | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types, as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | | Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. | -| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, the resource pools, the reservoir kept share, the start charge, the history allowance | about 2,150 lines, of which the pools, the kept share, the start charge and the allowance are about 1,450 | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. The items that ride on the frame results (the pools, the start charge, the allowance) are the first candidates, since every consumer pays their size. | +| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension | about 700 lines | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. | ## Hooks @@ -119,7 +106,7 @@ A format that encodes a struct by position, such as bincode, cannot read such an A gas schedule (`GasParams`) is a table of 256 entries, not named fields, so `serde(default)` cannot reach an entry: a table built raw (`GasParams::new`) or decoded from an encoding made before an entry existed holds zero there. Every entry the fork adds is therefore zero by default, and zero is upstream's behaviour: such a table behaves as the default schedule does. -An id the fork once used for an entry with another default is left unused rather than given a new meaning, so a table encoded then does not read as a setting. +An id the fork once used for an entry is left unused rather than given a new meaning, so a table encoded then does not read as a setting: ids 246 to 254 are such ids. ### State-gas price @@ -138,6 +125,7 @@ An id the fork once used for an entry with another default is left unused rather With the nonce check off and a transaction nonce that differs from the caller's account nonce, as for an OP deposit, upstream's checks, charges and warms an address the transaction does not deploy at, and the fork's the address it deploys at. There, whether the creation pays `create_state_gas` can differ from upstream's, and so can the gas of a later access to the other address, which upstream's leaves warm and the fork's leaves cold. The refund carries one address more in the frame inputs and outcomes, and under EIP-2780 an EIP-7702 transaction's authorization list is buffered before the authorization phase, one 88-byte entry per authorization that can apply. + `CallOutcome` and `CreateOutcome` are constructible by literal and carry `charged_state_gas_address`, which upstream's do not, so an outcome literal written for upstream's fields does not compile against the fork until it names it (`Address::ZERO` with nothing charged). ### History gas @@ -208,7 +196,7 @@ An id the fork once used for an entry with another default is left unused rather - **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns. - **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned. - **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code. - It takes two words of the tracker, a number and a flag, and the flag's word also holds the pools' crossings (see Resource pools); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words. + It takes two words of the tracker, a number and a flag, and the flag's word also holds the start mark (see Start lifecycle); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words. Encoded, the record is an optional number in the field's place. Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable. @@ -236,28 +224,22 @@ An id the fork once used for an entry with another default is left unused rather ### Code-deposit admission -- **API.** `ContextTr::admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>, gas: &mut GasTracker) -> Result<(), Bytes>`, whose default admits and leaves `gas` alone. +- **API.** `ContextTr::admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes>`, whose default admits. `CodeDeposit` carries `address`, `code`, `gas_before` and `gas_after`; `regular_gas`, `state_gas` and `history_gas` read the deposit's charges off the two trackers. It is `#[non_exhaustive]` and built with `CodeDeposit::new`, so a later field is not a breaking change. - **Contract.** `return_create` calls it once for every creation it deploys, on the plain and the inspected path: after the code passed every check and every deposit charge is recorded, before the journal checkpoint is committed. A creation `return_create` fails itself, out of gas on a deposit charge included, is never offered. Before Homestead a deposit the frame cannot pay does not fail: `return_create` deploys empty code instead, and offers that deposit with empty code and no charge. If the failed charge was a crossing of the frame's withheld gas, `gas_after` carries its crossing record and `gas_before` does not, so an admitted deposit keeps the record and a refusal discards it. - `gas` is the creating frame's tracker, which `gas_after` reads a copy of: the hook may debit and credit it, for instance draw the deployed code from one of the frame's pools (see Resource pools), and a charge it makes that fails records as any failed charge does. - `Ok(())` admits, and the frame returns with `gas` as the hook left it. - `Err(output)` refuses: the checkpoint is reverted, the frame's gas is put back to `gas_before`, which undoes whatever the hook did to `gas`, a crossing its failed draw recorded included, and the creation ends as a `Revert` with `output`, settling as a creation whose init code reverted. + `Err(output)` refuses: the checkpoint is reverted, the frame's gas is put back to `gas_before`, and the creation ends as a `Revert` with `output`, settling as a creation whose init code reverted. A hook that fails fatally records the cause in the context error and refuses; the transaction returns the error. The deposit's charges, and with them its state-gas price lookup through `Host::state_gas_price`, are made before it is offered, so that lookup is made whether or not the deposit is admitted; a refusal does not undo what the lookup recorded. - **Reach.** The hook is on the context `return_create` is called with, so a consumer that wraps `EthFrame`, runs `process_next_action` from its own `frame_run`, or customises `Handler` reaches it by implementing `ContextTr` for its context. A context that wraps another and implements `ContextTr` by hand must forward the method, or it gets the admitting default. -- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits, and holds the deployed code to the creating frame's byte budget there. That point is inside `return_create`, between its last charge and the checkpoint commit, and no other hook is lent the frame's gas between the two. +- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits, and counts the deployed code against the creating frame's budget there. That point is inside `return_create`, between its last charge and the checkpoint commit. - **Removal.** When upstream has an equivalent admission point, or when mega-evm stops refusing deposits. - **Default.** `return_create` compiles to the same code, on its own and inlined into the handler on the plain and the inspected path. Inlined into a consumer's own function, the admitting default may shift its block layout; where measured, that cost one unconditional branch on one out-of-gas path and changed no success path. - Where measured (callgrind, the fork's release profile), lending `gas` costs nothing: a top-level creation runs the same instruction count as without it, and a nested `CREATE` 0.06 fewer. - The `gas` parameter is an exception to rule 1 (`api:exception`): an override written for the signature without it does not compile until it takes `gas: &mut GasTracker`, and an override that leaves `gas` alone behaves as it did without it. - A context that forwards the method to another forwards `gas` with it. - Nothing built against upstream revm overrides the hook, since the hook is the fork's. ### revm 40.0.3's journal semantics @@ -289,7 +271,7 @@ An id the fork once used for an entry with another default is left unused rather ### Frame-start hook - **API.** `Host::frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`. - `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, `charge`, which `new` leaves empty, and `reservoir`, which `new` leaves `None`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. + `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, and `reservoir`, which `new` leaves `None`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`. `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change. - **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path. `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`. @@ -298,10 +280,10 @@ An id the fork once used for an entry with another default is left unused rather A creation's address is computed once, into the creation's input, and the handler builds the frame at it without computing it again. With EIP-8037 on, the instruction's EIP-8037 branch computes it. With EIP-8037 off, the instruction computes it after the same checks, reading the caller's balance and nonce from the journal. It is `None` only for a creation the handler fails before it takes an address: an endowment above the caller's balance, a caller's nonce at its maximum, or a creating frame at the depth limit. Such a creation reaches the hook only with EIP-8037 off; with it on, the instruction ends the creation before the hook. The address is fixed when the hook sees it. Something that changes the caller's nonce between the instruction and the frame does not move it, as on upstream's EIP-8037 path. An inspector that changes the creation's caller, scheme or init code (`CreateInputs::set_call`, `set_scheme`, `set_init_code`) clears it, and the handler computes the new one. - `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input takes its share of the reservoir from it, so a frame the handler runs and one it answers without running (a precompile) both start from a share of the reservoir the hook left (see The reservoir share). A charge the hook makes that fails records as any failed charge does, whatever the answer. - `start` is the hook's to declare the start charge on (`charge`, see The start charge) and, if it takes the child's reservoir itself, the child's reservoir (`reservoir`); the instruction reads nothing else back from it. - `FrameStart::reservoir` is `None` when the hook is called. `Some(r)` means the hook took the child's reservoir out of `gas` itself: the instruction takes no reservoir share, the frame's input carries `r`, and the caller keeps what the hook left it. `None` keeps the schedule's share (see The reservoir share). The instruction does not check `r` against what the hook took. The pools are forwarded by the schedule either way. - After the hook the instruction copies that charge onto the frame's input and takes the child's shares of the reservoir (unless the hook named it) and of each pool off `gas` for it (`GasTracker::forward_to_child_with_reservoir`, which `forward_to_child` calls with `None`, see The reservoir share and Resource pools); the shares are of the reservoir and the pools as the hook left them. + `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies the reservoir the hook left in it, so a frame the handler runs and one it answers without running (a precompile) both start from that reservoir. A charge the hook makes that fails records as any failed charge does, whatever the answer. + `start` is the hook's to name the child's reservoir on (`reservoir`), if it takes that out of `gas` itself; the instruction reads nothing else back from it. + `FrameStart::reservoir` is `None` when the hook is called. `None` leaves the frame's input a copy of the reservoir in `gas`, which the caller keeps while the child runs, as upstream's instructions do. `Some(r)` means the hook took the child's reservoir out of `gas` itself: the frame's input carries `r` instead, and the caller keeps what the hook left it. The instruction does not check `r` against what the hook took. + Either way the child's settlement replaces the caller's reservoir with the one the child returns, as upstream's does; a consumer that kept part of the caller's reservoir adds it back when revm settles the child (`FrameSettle::held_reservoir`, see Start lifecycle). `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did. A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered. - **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails. @@ -309,7 +291,7 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts. - **Default.** Returns `true` and touches nothing. Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops. - For `CREATE` and `CREATE2` the hook's only cost is the start's address; the resource pools' forward is counted under Resource pools. + For `CREATE` and `CREATE2` the hook's only cost is the start's address. With EIP-8037 off, the default spec's path, the address costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per creation. The instruction computes the address and a `CREATE2`'s init-code hash, and the handler reuses them, so a creation the handler builds or fails computes the same hashes as upstream's. A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way. @@ -317,127 +299,6 @@ An id the fork once used for an entry with another default is left unused rather `CreateInputs`' derived `PartialEq` compares the cached address and hash, which the input of a creation the instruction starts holds with EIP-8037 on and off, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache. A consumer tells a creation from a call by `kind`, not by `target`: `target` is `None` only for the creations the Contract names, and for every other start an address, which for a creation is the one it would take. -### Resource pools - -- **API.** `PoolId` (`new(index)`, `index`, `COUNT` = 3, `ALL`) and `PoolAmounts` (an amount per pool: `ZERO`, `UNLIMITED`, `get`, `set`, `with`, `is_zero`), in `revm_context_interface::cfg::gas`, re-exported from `revm_interpreter`. - On `GasTracker`, forwarded on `Gas`: `pool_remaining`, `set_pool_remaining`, `pool_spent`, `set_pool_spent`, `record_pool`, `refill_pool`, `pool_crossing`, `clear_pool_crossing`, `set_pool_crossing`, each taking the `PoolId`. - On `GasTracker` alone, the fork's own plumbing: `pools_remaining`, `set_pools_remaining`, `add_pool_spent`, `forward_pool`, `absorb_returned_pool`, `absorb_returned_pools`, `adopt_pool_share`, `adopt_pool_shares`, and `forward_to_child` and `forward_all_to_child` with their `ChildShares` (see The reservoir share). - `GasId::pool_kept_percent(pool)` (ids 248, 247 and 246) and `GasParams::pool_forward_share(pool, remaining)`. - `pool_shares` on `CallInputs` (a field) and `CreateInputs` (`pool_shares`, `set_pool_shares`). -- **Contract.** A tracker carries `PoolId::COUNT` pools, budgets beside its gas whose meaning the consumer gives (bytes a frame may append, records it may write, entries it may create); the fork knows them by index only. - For each pool, `pool_remaining` is what the frame may still draw and `pool_spent` its net draw, signed as `history_gas_spent` is. - `record_pool(pool, n)` draws; a draw the pool cannot pay takes nothing, returns `false` and sets the pool's crossing (`pool_crossing(pool)` is `true`), which survives `spend_all`, starts clear in every child, is not taken over by a caller, and stays until cleared; a consumer marks a result it produced itself with `set_pool_crossing`. - A crossing is a bit per pool: it says that a draw failed, not what the draw asked for, which the hook that drew knows when it fails. - No halt touches a pool, so a halted frame's result still reads each pool as the failed draw found it, until its caller settles it. - `refill_pool(pool, n)` gives back and lowers the net, below zero when the draw was a caller's. - Amounts are bounded as the tracker bounds gas amounts: every draw and refill is at most `i64::MAX`, and each net with its children's nets merged in stays within `±i64::MAX`, so it can be negated; a debug build asserts it where a net moves, and past it a release build saturates the net, so a rollback no longer restores the pool exactly. - Each pool is a figure of its own: nothing the fork does to one moves another, and a consumer that draws several for one write draws them one by one, in the order its rules give. - A consumer draws deployed code where the deposit is admitted: `ContextTr::admit_code_deposit` is lent the creating frame's tracker (see Code-deposit admission). - The transaction's frame gets every whole pool of the transaction's tracker, set by a consumer at `tx_gas` or in pre-execution (`forward_all_to_child`, from `create_init_frame` and from the stand-in `Handler::runtime_oog_result` builds when the EIP-2780 runtime phase runs out of gas). - At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `pool_forward_share(pool, …)` of each of the caller's pools out of it and puts the shares on the frame's input as `pool_shares`: the child's pools when it starts, on the frame the handler runs and on an answer it gives without one (a precompile, a refused start). - `pool_forward_share` is `100 − pool_kept_percent` per cent of what the caller has left of the pool, rounded down, and the caller keeps the rest: zero kept forwards the whole pool, a hundred or more none. - A forward is not a draw. - The settlement is in `handle_reservoir_remaining_gas` (`absorb_returned_pools`) and follows the reservoir, not regular gas: a child that reverts or halts has its draws on every pool undone by `rollback_state_gas`, which gives each pool's net back to it, so what the caller absorbs of each pool is the child's remaining pool on success and the whole share on revert *and on halt*, since a halted frame draws nothing; the caller kept what it did not forward. - The child's nets merge into the caller's on success only, as the history net does, so a caller's rollback undoes its children's draws too. - `rollback_state_gas` rolls every pool back with state and history gas, so a consumer that rolls a frame back by hand rolls the pools back with it. - The first frame's return settles into the transaction's tracker the same way (`last_frame_result`, through `execution::settle_first_frame`, see The start charge), whose `pool_spent` of each pool is then the transaction's net draw. - A precompile's answer adopts the shares as the pools it started with (`adopt_pool_shares`): each pool is the share less what its provider drew on it, so its pools and nets add up to the shares as a frame's do; a provider that draws on its answer starts the answer's pools at the input's `pool_shares` first, so a draw a share cannot pay fails. - A provider that drew more than a share anyway, on pools it did not start at the shares, fails closed on that pool: the adoption empties the pool, caps its net at the share and sets its crossing, so the caller gets back no more than it forwarded whether the answer succeeds or fails, and the consumer classifies the crossing as it classifies a refused draw. The answer's result is the provider's, so a successful answer can carry a crossing. - An outcome an inspector builds to answer a start carries whatever pools its gas was built with, unlimited ones with `CallOutcome::new` and `CreateOutcome::new`, and the settlement absorbs them as they are. - A consumer that answers a start itself, without a frame or a provider, sets the answer's pools to the shares it was given (`set_pools_remaining(inputs.pool_shares)`), and a consumer that builds a child's input itself takes the child's shares with `forward_to_child`. - The pools are not reported on `ResultGas`. -- **Consumer.** mega-evm keeps per-frame budgets of what a transaction adds to the chain: the bytes it appends to the state and the history, the write records it makes and the state entries it creates, each forwarded to a child at 98/100 of what its caller has left, each given back by a failed frame and handed to its caller by a successful one, and each held to a per-transaction and a per-block limit. That is what the tracker does for the reservoir, and only the tracker's forward and settlement can carry figures that move with a frame's gas. -- **Removal.** When upstream carries equivalent per-frame budgets on its gas, or when mega-evm stops limiting these per frame. -- **Default.** Every tracker starts with every pool unlimited (`u64::MAX`), every schedule keeps none of a pool and so forwards every whole pool, and nothing in the workspace draws one, so every figure of the pools is the unlimited pool going out and coming back and every result is upstream's. - A table without the entries, built raw or decoded from an encoding that predates them, keeps none too (see Hooks). - Three pools, because mega-evm limits three figures per frame: data size, write records and state growth. A fourth would carry one more figure the engine keeps beside the pools today (the transfer-log bytes it subtracts from the history bytes), but the engine's per-start entry stays for the take-back credit and the creator-record overdraft in any case, and the pool would cost every consumer 16 bytes more on every frame result. A later pool is a size change, not an API change: it moves `PoolId::COUNT` and `PoolId::ALL`, gives the pool's kept percentage the next id below the pools' (245) and a name, and changes the tests that count them. - The tracker is 144 bytes (88 without the fork's figures, 112 with one pool): two words per pool, the pool and its net, a word for the allowance (see The history allowance), and the crossings, a bit per pool, in the word the failed-charge record's flag takes (see The failed-charge record). In a format that carries field names, encodings that predate the fields decode with unlimited pools, no crossing and zero for the rest, and a positional format cannot read them (see Hooks). - `Gas` is 160 bytes (104 at the base without the fork's figures), `InterpreterResult` 200 (144), `CallOutcome` and `FrameResult` 296 (208), `CreateOutcome` 280 (192), the outcomes with the start charge's four words (see The start charge). - Where measured (callgrind, aarch64, the fork's release profile), against the single byte pool before these pools: a transfer costs 215 instructions more (+3.9%), each `CALL` about 258 more (+10.9% on a transaction of 64 calls), a top-level creation 273 more (+1.5%), a nested `CREATE` 331 more (+2.1%) and a `SELFDESTRUCT` transaction 285 more (+3.5%). - Nearly all of it is the size: the same code with one pool, at the earlier sizes, cost 2, 8, 7, 10 and 1 instructions on the same workloads. At 296 bytes the frame result passes what the compiler copies inline, and the moves of the frame results through the handler's `Result` and `ItemOrResult` wrappers (about seven per `CALL`) become library `memcpy` calls. - Against the base without any of the fork's figures, a transfer costs 336 more (+6.2%) and each `CALL` about 398 more (+17.9% on a transaction of 64 calls). - A precompile's answer runs 11 instructions more than with an adoption that does not check each pool's net against its share (see Contract); measured against the head before the check, a transfer runs 1 instruction less, each `CALL` 1.9 less, a top-level creation 3 less and a nested `CREATE` 7.75 less, and a `SELFDESTRUCT` transaction 4 more, from code layout, not from the check. - -### The reservoir share - -- **API.** `GasId::reservoir_kept_percent` (id 249) and `GasParams::reservoir_forward_share(reservoir)`. - On `GasTracker`: `forward_reservoir(share)`, `forward_to_child(&GasParams)`, `forward_to_child_with_reservoir(&GasParams, Option<u64>)` (the first with `None`) and `forward_all_to_child()`, which take the reservoir's share and every pool's share at once and return them as `ChildShares { reservoir, pools }` (`#[non_exhaustive]`). -- **Contract.** At every `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, after `frame_starting` has answered, the instruction takes `reservoir_forward_share` of the caller's EIP-8037 reservoir (unless the frame-start hook named the child's reservoir, `FrameStart::reservoir`, in which case it takes none and the input carries the hook's) out of the caller's tracker and puts it on the frame's input as `reservoir`, the child's reservoir when it starts, on a frame and on an answer alike. - `reservoir_forward_share` is the reservoir less the caller's part, `reservoir_kept_percent` per cent of it rounded down, taken away as `call_stipend_reduction` takes regular gas: at 2 kept the child receives `reservoir − reservoir × 2 / 100`, so a reservoir of 99 forwards 98, where a pool keeping 2 forwards 97 (its share is rounded down). Zero kept forwards the whole reservoir, as EIP-8037 does; a hundred or more forwards none. - The two roundings are the fork's, not the schedule's: the reservoir's share takes the caller's part away as regular gas's forward does, and a pool's share is rounded down. A chain that needs the floor for the reservoir, or the subtraction for a pool, has no entry for it. - The caller keeps the rest while the child runs; the share is all the child has, so a child whose state and history charges pass it spills onto its own regular gas, as a frame with an empty reservoir does, and one that cannot pay that fails out of gas. - On the child's return, `GasTracker::absorb_returned_reservoir` adds the reservoir the child left to the part the caller kept, where upstream's replaced the caller's reservoir with the child's; as before, the returned reservoir first unwinds the caller's outstanding spill, last in first out, and the part the caller kept stays in its reservoir. - A child that fails rolls its charges back and returns its whole share; one that succeeds returns what it left, its own refills (EIP-8037 restorations) included, which land in its reservoir as before. - A caller that keeps part of its reservoir can therefore hold it beside an outstanding spill: a child that succeeded after spending past its share spilled onto its regular gas, and the spill merges into the caller's. A whole forward cannot produce this, since the caller then keeps none. - A refill in such a caller (an EIP-8037 restoration, `refill_history`, the refund of an upfront or a start charge) keeps EIP-8037's order: regular gas up to the outstanding spill first, the reservoir after, whichever of the two paid the charge the refill undoes. So a charge the caller paid from its kept reservoir comes back as regular gas while a child's spill is outstanding. - For example, a caller with a reservoir of 1,000 that keeps 2 per cent keeps 20 and forwards 980; a child that charges 1,000 spills 20; the caller then charges 10 from its reservoir (reservoir 10, spill 20) and refills 10, which leaves its reservoir at 10, its spill at 10 and its regular gas 10 higher. - The sum of the two is conserved, a rollback still restores the reservoir the frame started with, and the reimbursement and `gas_used` read the sum, so no final figure moves; `GAS` in the caller reads the credited regular gas. - The transaction's frame takes the whole reservoir of the transaction's tracker (`forward_all_to_child`, from `create_init_frame`), and settles back into it the same way, so a system call's frame does too; so does the stand-in result `Handler::runtime_oog_result` builds for a transaction whose EIP-2780 runtime phase ran out of gas, which carries the whole reservoir and every pool and settles them back once. - A precompile's answer carries the share the input gave it, as the provider builds the answer's gas from the input's reservoir (the standard providers do, and a provider must); the fork does not check an answer's reservoir, state-gas net or spill against what the input forwarded, and takes the provider's answer as the provider reports it, as upstream does, so only the pools are adopted fail-closed; a start the handler refuses (call depth, balance) and a creation it fails early carry it too. - An outcome an inspector builds to answer a start carries whatever reservoir its gas was built with, none with `Gas::new`, and the settlement adds it to what the caller kept: with the whole reservoir forwarded the caller is left with none, as with upstream's settlement. - **The settlement adds.** `handle_reservoir_remaining_gas` (with the `GasTracker::absorb_returned_reservoir` and `absorb_returned_pools` it calls) and `execution::settle_first_frame` add what a frame returns to what its caller holds, so the caller must no longer hold what it handed the frame. - Code that hands a frame the caller's reservoir or a pool without taking it from the caller compiles, and the caller ends with it twice. The shapes: - - a child's input built by hand from the caller's `reservoir()` or `pools_remaining()`, while the caller keeps them; - - the transaction's frame, or a stand-in result for it, built from the transaction's gas without taking from it, in an override of `Handler::first_frame_input` or `Handler::runtime_oog_result` or in a runner of its own; - - a runner that settles the transaction's frame into gas it seeds from the frame's own figures (`GasTracker::new(limit, frame.remaining(), frame.reservoir())`) and then calls `last_frame_result` or `settle_first_frame`. - - A consumer takes what it hands over: `forward_to_child` takes the schedule's shares, as the instructions do; `forward_all_to_child` takes everything, as the transaction's frame does; `forward_reservoir` and `forward_pool` take a share the consumer computed. - A consumer that lowers a child's share after the forward and gives the excess back to the caller keeps the sum, and is right; so is code that settles with arithmetic of its own that replaces the caller's reservoir and calls none of these functions. - A debug build asserts on entry to `settle_first_frame` that the transaction's gas holds no reservoir and no limited pool; an unlimited pool is exempt, since what comes back saturates at it. A frame below the transaction's has no such check: its caller may hold a kept part, or an excess given back, beside the share, and only the code that built the input knows which. -- **Consumer.** mega-evm keeps the caller's part of the reservoir from a callee that could exhaust it: a child receives 98/100 of what its caller has left, as with every other resource a callee could exhaust. The instruction takes the forwarded share from the reservoir as the frame-start hook left it, so the kept part stays in the caller's tracker while the child runs, and the child's returned reservoir is added to it at settlement, after it has unwound the caller's outstanding spill. -- **Removal.** When upstream forwards a share of the reservoir through an equivalent setting, or when mega-evm forwards the whole reservoir. -- **Default.** Every schedule keeps none of the reservoir and so forwards it whole, the child's return gives the caller what the child left, and every result is upstream's: EEST, the default-path figures pinned to upstream and the handler suites pass unchanged. - A table without the entry, built raw or decoded from an encoding that predates it, keeps none too (see Hooks). - What a frame's tracker reads while its child runs differs: its reservoir is the part it kept, zero by default, where upstream's left the forwarded reservoir in it until the child returned; an inspector that reads the caller's gas at the `CALL` or `CREATE` instruction's `step_end` sees it. - Where measured with the pools' figures (above), the share and the generalised forward cost 8 instructions per `CALL` with one pool. - `handle_reservoir_remaining_gas` (upstream's, public) and `GasTracker::absorb_returned_reservoir` (upstream's, picked) change meaning: they add the child's reservoir to the caller's. A consumer that calls them, or builds a child's input, without taking the share from the caller does not fail to compile; it counts the reservoir twice. The pull request that makes the change lists it with the `api:exception` items. - A consumer that builds a child's input by hand with the caller's reservoir, without taking the child's shares with `forward_to_child`, counts that reservoir twice, and must take them. A first-frame settlement written outside the handler does the same. A consumer that runs before the reservoir exists, or settles its first frame without `handle_reservoir_remaining_gas` or `GasTracker::absorb_returned_reservoir`, calls neither function and is unaffected. - Upstream's own builders of a first-frame result take the reservoir and the pools out of the transaction's tracker: `create_init_frame` and `Handler::runtime_oog_result`, whose default body changes so, which an override that builds its own stand-in must do too (see The settlement adds). - The entries are kept parts, not forwarded ones, so that zero, which a table without them holds, forwards everything. Ids 254 and 250 to 252 are left unused. A consumer names the entries by function, and a chain that forwards 98 per cent keeps 2. - -### The start charge - -- **API.** The type `StartCharge` (`new(history, pools)`, `history`, `pools`, `is_zero`; `#[non_exhaustive]`), re-exported from `revm_interpreter`, and `GasTracker::refill_start_charge`. - `FrameStart::charge` (see Frame-start hook). - `charged_start` on `CallInputs`, `CallOutcome` and `CreateOutcome` (fields) and on `CreateInputs` (`charged_start`, `set_charged_start`); `FrameResult::refundable_start_charge`. - `revm_handler::execution::settle_first_frame`, the settlement of the first frame. -- **Contract.** The start charge is what a frame start charged its caller and the frame's failure gives back: history gas and an amount of each pool (`PoolAmounts`). - The `frame_starting` hook charges the caller's tracker and declares the refundable part on the start it is handed (`start.charge`); the instruction copies it onto the frame's input when the hook admits the start; a start the hook refuses discards the charge with the start, and what the hook charged stands. - The transaction's frame has no start hook: a consumer that charges the transaction's tracker for it in pre-execution puts the refundable part on the first frame's input (`charged_start`), from `Handler::first_frame_input`. - The charge rides from the input to the outcome, and `return_result` refunds it to the caller whole, with `refill_start_charge` (`refill_history`, and `refill_pool` for each pool), on the condition `refundable_state_gas_charge` uses: a call that did not succeed, a creation that did not succeed or deployed no address; `last_frame_result` refunds the first frame's the same way, and after a halt consumes the regular gas the refill credited, as it does for the state refund. - `last_frame_result` settles the first frame through `execution::settle_first_frame`, which is all of mainnet's settlement but the copy of the transaction's gas into the frame's result: the spend and the settlement of the frame, the EIP-2780 state-gas refund and the start-charge refund, each with its halt rule. - A chain whose handler overrides `last_frame_result` calls it rather than copying the mainnet body, so the start-charge refund and any later step reach it too, and applies its own rules between it and the copy, such as the op-revm fork's pre-Regolith deposit rule. - Upstream's own steps of the settlement (the spend, `handle_reservoir_remaining_gas` and the EIP-2780 refund) live in `crates/handler/src/execution/first_frame.rs`, not in `handler.rs`: a pick or a base-line merge that changes upstream's `last_frame_result` body lands there, and records the move as its conflict resolution. - A frame that succeeds keeps the charge. - A precompile's answer and a start the handler refuses before any frame (call depth, balance) carry the input's charge, so they refund as a frame does. - An outcome an inspector builds to answer a start carries no charge unless the inspector copies the input's (`CallOutcome::new` and `CreateOutcome::new` carry none), so the caller keeps the charge, as revm keeps its own upfront state charge on an outcome a tool builds; an outcome the inspector rewrites at `call_end` or `create_end` keeps the frame's charge, so a success rewritten into a failure is refunded. - An answer a consumer builds itself, such as an interceptor's, is refunded by the same rule: it carries the charge the consumer puts on it, and none when built with `new`. - A consumer that settles a result into a caller's tracker itself refunds the charge with `refill_start_charge` on the same condition, so a pool added to the charge reaches it. -- **Consumer.** mega-evm charges a start's write records to the caller at the hook, after the forward and before the frame's input takes its share of the reservoir, and must give them back when the frame fails. Its hook charges history only and declares `StartCharge::new(charge, PoolAmounts::ZERO)`: the records a start draws on the child's pools are counted in the child, and a creation's creator record is counted on the creator's pools after the creation returns, once the engine sees the creator's nonce was bumped, whether the creation succeeded or not, so no pool amount rides on the charge. The refund belongs where the fork refunds the upfront state charge. -- **Removal.** When upstream carries an equivalent refundable start charge, or when mega-evm stops charging frame starts. -- **Default.** The hook declares nothing, so the fields and the refund are zero. - The charge is four words, history and one per pool, on every input and outcome; its size is part of the outcomes' measured above (see Resource pools). - `settle_first_frame` is inlined: where measured (callgrind, the fork's release profile), a transfer and a transaction of 64 calls run the same instruction count as with its steps written out in `last_frame_result`. - A handler that overrides `last_frame_result` with a copy of mainnet's settlement instead of calling `settle_first_frame` compiles, but does not refund the first frame's start charge; that matters only to a consumer that declares one. - This entry is an exception to rule 1 (`api:exception`): `CallInputs`, `CallOutcome` and `CreateOutcome` are constructible by literal and carry fields upstream's do not (`charged_start`, and on `CallInputs` also `pool_shares` and `history_allowance`), so a literal written for upstream's fields does not compile until it names them. - A consumer that uses none of the figures names them at their defaults, no charge (`StartCharge::default()`), unlimited shares (`PoolAmounts::UNLIMITED`) and no allowance (`0`), and keeps upstream's behaviour. - A consumer that answers a start with an outcome it builds itself sets the answer's charge as the Contract says and its pools as Resource pools says. - The outcomes also carry the state-gas refund's `charged_state_gas_address` (see State-gas price), which upstream's do not, so an outcome literal written for upstream's fields does not compile against the fork whatever this entry adds; `CallInputs` has upstream's fields apart from this entry's, so this entry is what breaks its literals. - `CreateInputs` has private fields and is built with `CreateInputs::new`, so its new fields break no literal. - -### The history allowance - -- **API.** On `GasTracker`, forwarded on `Gas`: `history_allowance`, `set_history_allowance`, `draw_history_allowance`. - `GasId::call_history_allowance` and `GasParams::call_history_allowance()`; `history_allowance` on `CallInputs`. -- **Contract.** The allowance is history gas a frame may spend before it charges its budget. - A call that transfers value gives its child the schedule's `call_history_allowance`, decided where the call instruction adds the call stipend, carried on the input and set on the child's tracker when it starts, on the frame and on an answer alike; no other start gives one, and the transaction's frame has none. - Only a consumer draws it: `draw_history_allowance(cost)` takes `min(cost, allowance)` and returns the part of `cost` the allowance did not cover, which the consumer charges as history. - A precompile's answer is given the input's allowance after its provider ran, so the allowance it carries back is the input's, whatever the provider drew. - The allowance is the frame's alone: it is not returned, merged or rolled back. -- **Consumer.** mega-evm lets a value call's child log a bounded number of bytes without charging history, as the call stipend lets it run. The call instruction decides which starts get the stipend; a start's `kind` and `value` are public on `FrameStart`. -- **Removal.** When upstream carries an equivalent allowance, or when mega-evm drops the rule. -- **Default.** Zero on every schedule, so every child starts with none and a draw returns the whole cost; nothing in the workspace draws it. - ### The pending action - **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction, and which `InspectorEvmTr::inspect_frame_init` reads before it hands a new frame to `Inspector::initialize_interp`. @@ -483,7 +344,7 @@ An id the fork once used for an entry with another default is left unused rather `revm_handler::lifecycle`: `open_frame_start`, `open_transaction_start`, `Returning` and `close_frame_start`, `close_transaction_start`, `finish_transaction`, `discard_transaction`, `mark_for_end_callbacks` and `check_end_callbacks`. On `FrameStack`, the record: `open_start`, `close_start`, `pending_start`, `running_start`, `lifecycle_active`, `lifecycle_settled`, and its two boundaries `settle_lifecycle` and `discard_lifecycle`. `StartLifecycleError` (`Exhausted`, `Stale`, `NotOpen`, `NoParent`, `Unsettled`; `#[non_exhaustive]`), `PendingStart` (its fields are private: the identity can be read and not written, and only the three flags can be set), `StartMark` and `OutcomeMark`. - `GasTracker::start_mark` and `set_start_mark`, `GasTracker::forward_to_child_with_reservoir`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field). + `GasTracker::start_mark` and `set_start_mark`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field). `LocalContextTr::lifecycle_mirror`, `LifecycleMirror` and `LifecycleEvent` (`Split`, `Settle`, `End`), the debug mirror (below). The types and the method exist in every profile. - **Contract.** A *start* is one frame's beginning with the identity revm gave it; revm pairs every start it opens with exactly one settlement, last in first out, and the consumer does not pair them. *Where revm opens one.* @@ -503,8 +364,13 @@ An id the fork once used for an entry with another default is left unused rather `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input. Whether the consumer's `frame_init` is handed that input after the split is conditional: when initialisation reaches it, it receives the input as an inspector's `frame_start`, `call` or `create` left it; an inspector that answers the start does so before `frame_init` is called, and the stand-in for a runtime out-of-gas transaction has no init at all, so a start can split and settle with no `frame_init` between. - What an instruction's start owes (its shares, its charge, its allowance) is parked at `frame_starting`; the transaction's start does not pass through `frame_starting`. + What a consumer charges or keeps for an instruction's start it does at `frame_starting`, before the split; the transaction's start does not pass through `frame_starting`. `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. + + *The reservoir.* revm forwards and settles the reservoir as upstream does: the child's input copies the caller's reservoir, or carries the reservoir the frame-start hook named (`FrameStart::reservoir`), and the settlement replaces the caller's reservoir with the one the child returns, once that has unwound the caller's outstanding spill. + A consumer that keeps part of the caller's reservoir for it takes that part in `frame_starting` and names the rest as the child's, and adds `held_reservoir` back to the caller's reservoir in `frame_settle`. + The caller then holds what the child returned on top of the part it kept, whatever refills the settlement made, since the unwinding and every refill read the spill and their own amount, never the reservoir. + The transaction's frame, and the stand-in for a runtime out-of-gas transaction, are handed a copy of the transaction's reservoir, which the transaction's gas keeps until the settlement replaces it, so there `held_reservoir` is that copy: a consumer adds back only what it kept. `frame_lifecycle_end` is called once at the end of a transaction's lifecycle: `Settled` at the successful boundary, with every start settled, and `Discarded` when a fatal error ends the transaction and the open starts are dropped unsettled. A transaction that ends before any start opened emits neither. @@ -569,14 +435,14 @@ An id the fork once used for an entry with another default is left unused rather - **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. - **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk: a boundary neither resizes nor frees the slots, a successful end does not scan them, and discarding open children clears the retained slots, at a cost proportional to their retained length. - The marks sit in the padding of the values they ride on, so `GasTracker` stays 144 bytes, `Gas` 160, `InterpreterResult` 200, `CallOutcome` and `FrameResult` 296 and `CreateOutcome` 280 (aarch64, the fork's release profile), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. + The marks sit in the padding of the values they ride on, so `GasTracker` stays 88 bytes, `Gas` 104, `InterpreterResult` 144, `CallOutcome` and `FrameResult` 208 and `CreateOutcome` 192 (64-bit targets), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary (and, after a discard with open children, one clear of the retained slots), and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's. Three exceptions to that compatibility are carried, each an `api:exception` item. A pull request that introduces such an exception lists it and checks the consumers against it. What a consumer does for each: - - The outcomes' public `start_mark` field (`CallOutcome` and `CreateOutcome`): a consumer that builds an outcome by literal names it as `start_mark: Default::default()`, or builds it with the constructors. It extends the exception the outcome literals already carry (see The start charge). + - The outcomes' public `start_mark` field (`CallOutcome` and `CreateOutcome`): a consumer that builds an outcome by literal names it as `start_mark: Default::default()`, or builds it with the constructors. It extends the exception the outcome literals already carry for the state-gas refund's address (see State-gas price). - `LocalContext` gains a private field in a debug build, so a debug build cannot build it with a struct literal; a consumer builds it with `LocalContext::default()` or `new`. A release build's is unchanged. - A behaviour change no compiler finds: a runner that drives the transaction's frame, or settles it, without `Handler::execution` and `Handler::last_frame_result` must open and close the transaction's start (see A hand-driven first frame); otherwise the record refuses it with `NoParent` or `NotOpen`. From 87ded5c7c7ac009edc48033772e2e51bc6708aed Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 19:03:34 +0800 Subject: [PATCH 103/110] test: the reservoir settlement tests' doc comments wrap at the line width --- crates/handler/tests/reservoir_settlement.rs | 5 +++-- crates/inspector/tests/reservoir_settlement.rs | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/handler/tests/reservoir_settlement.rs b/crates/handler/tests/reservoir_settlement.rs index 77bcd7b5ef..7af0a7c56b 100644 --- a/crates/handler/tests/reservoir_settlement.rs +++ b/crates/handler/tests/reservoir_settlement.rs @@ -855,8 +855,9 @@ fn test_a_child_that_cannot_pay_past_its_share_runs_out_of_gas() { /// A child that clears a slot its caller created gets the slot's state gas back as an EIP-8037 /// restoration, into its own reservoir; when it succeeds, the caller gets it back with the rest of -/// the share and the part the consumer kept, and is back where it was before it created the slot. When it reverts, -/// the restoration is undone with the rest of its frame and the caller gets the share back. +/// the share and the part the consumer kept, and is back where it was before it created the slot. +/// When it reverts, the restoration is undone with the rest of its frame and the caller gets the +/// share back. #[test] fn test_a_restoration_in_the_child_comes_back_to_its_caller() { for (restorer, kept) in [(RESTORER, true), (RESTORER_REVERTS, false)] { diff --git a/crates/inspector/tests/reservoir_settlement.rs b/crates/inspector/tests/reservoir_settlement.rs index d9ebe5108d..32546ef06b 100644 --- a/crates/inspector/tests/reservoir_settlement.rs +++ b/crates/inspector/tests/reservoir_settlement.rs @@ -452,8 +452,8 @@ fn test_an_answer_the_inspector_builds_settles_its_reservoir_as_built() { } /// A creation's answer settles as a call's: as built, the caller gets back the part the consumer -/// kept, and keeps the creation's charge; with the shares and the input's charges, the caller gets back what it held -/// before the creation's start. +/// kept, and keeps the creation's charge; with the share and the input's charges, the caller gets +/// back what it held before the creation's start. #[test] fn test_an_answer_the_inspector_builds_for_a_creation_settles_its_reservoir_as_built() { for (answer, whole, kept_98) in [ From c71d578b5e2bc2ee980f36e622ef814235b35601 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 20:14:05 +0800 Subject: [PATCH 104/110] refactor(interpreter): the frame-start hook's helper answers the reservoir the frame's input carries --- crates/context/interface/src/host.rs | 4 ++-- crates/context/interface/src/host/instruction_hooks.rs | 7 ++++--- crates/interpreter/src/instructions/contract.rs | 4 ++-- .../interpreter/src/instructions/instruction_hooks.rs | 10 +++++----- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/crates/context/interface/src/host.rs b/crates/context/interface/src/host.rs index 45e533c164..ad89af4623 100644 --- a/crates/context/interface/src/host.rs +++ b/crates/context/interface/src/host.rs @@ -130,8 +130,8 @@ pub trait Host { /// The hook may debit and credit `gas`, and the instruction uses it as the hook left it, /// charging nothing after the hook: the frame's input copies the reservoir in `gas`, or /// carries the child's reservoir the hook names on `start` if it took that out of `gas` itself - /// ([`FrameStart::reservoir`]). A charge the hook makes that fails records as - /// any failed charge does ([`GasTracker::failed_charge_remaining`]), whatever the answer. + /// ([`FrameStart::reservoir`]). A charge the hook makes that fails records as any failed + /// charge does ([`GasTracker::failed_charge_remaining`]), whatever the answer. /// `true` goes on to start the frame, which the handler may still refuse or answer without /// running it. `false` fails the instruction out of gas and starts no frame: the forward stays /// taken unless the hook gave it back, and the halt records the regular gas the hook left diff --git a/crates/context/interface/src/host/instruction_hooks.rs b/crates/context/interface/src/host/instruction_hooks.rs index aa3d321766..35cb0a235e 100644 --- a/crates/context/interface/src/host/instruction_hooks.rs +++ b/crates/context/interface/src/host/instruction_hooks.rs @@ -124,9 +124,10 @@ pub struct FrameStart { /// when the hook is called. /// /// `None` leaves the forward to the instruction, whose frame's input copies the caller's - /// reservoir as the hook left it, and the caller keeps it, as upstream's instructions do. `Some` - /// is the reservoir the frame's input carries in its place, and the caller keeps the reservoir - /// the hook left it. The instruction does not check the amount against what the hook took. + /// reservoir as the hook left it, and the caller keeps it, as upstream's instructions do. + /// `Some` is the reservoir the frame's input carries in its place, and the caller keeps the + /// reservoir the hook left it. The instruction does not check the amount against what the hook + /// took. /// /// Either way the child's settlement replaces the caller's reservoir with the one the child /// returns. A hook that kept part of the caller's reservoir for it adds that back when the diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index 8bd8804df2..bd33affeeb 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -197,7 +197,7 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( let reservoir = frame_starting(&mut context.interpreter.gas, context.host, start)?; create_inputs.set_gas_limit(gas_limit); - create_inputs.set_reservoir(reservoir.unwrap_or(context.interpreter.gas.reservoir())); + create_inputs.set_reservoir(reservoir); context .interpreter .bytecode @@ -294,7 +294,7 @@ pub fn call<const KIND: u8, IT: ITy, H: Host + ?Sized>(mut context: Ictx<'_, H, scheme, is_static, return_memory_offset, - reservoir: reservoir.unwrap_or(context.interpreter.gas.reservoir()), + reservoir, charged_new_account_state_gas, }, )))); diff --git a/crates/interpreter/src/instructions/instruction_hooks.rs b/crates/interpreter/src/instructions/instruction_hooks.rs index eeb97df459..e292b652ef 100644 --- a/crates/interpreter/src/instructions/instruction_hooks.rs +++ b/crates/interpreter/src/instructions/instruction_hooks.rs @@ -44,17 +44,17 @@ fn revert<IT: ITy>(interpreter: &mut Interpreter<IT>, output: Bytes) -> Result { } /// Hands `start`, whose forward the running instruction has taken from `gas`, to -/// [`Host::frame_starting`]. `true` returns the child's reservoir if the hook took it itself and -/// named it on `start`, which the frame's input carries in place of the caller's reservoir; -/// `false` fails the instruction out of gas. +/// [`Host::frame_starting`]. `true` returns the reservoir the frame's input carries: the child's +/// reservoir if the hook took it itself and named it on `start`, or else a copy of the reservoir +/// the hook left in `gas`. `false` fails the instruction out of gas. #[inline] pub(crate) fn frame_starting<H: Host + ?Sized>( gas: &mut Gas, host: &mut H, mut start: FrameStart, -) -> core::result::Result<Option<u64>, InstructionResult> { +) -> core::result::Result<u64, InstructionResult> { if host.frame_starting(&mut start, gas.tracker_mut()) { - Ok(start.reservoir) + Ok(start.reservoir.unwrap_or(gas.reservoir())) } else { cold_path(); Err(InstructionResult::OutOfGas) From 4c8f0d43b70f2175f9ce0132cc343283f9a29548 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Tue, 27 Oct 2026 20:14:05 +0800 Subject: [PATCH 105/110] test(handler): the frame-result size test is a test file of its own --- crates/handler/src/frame_data.rs | 20 -------------------- crates/handler/tests/frame_result_size.rs | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 20 deletions(-) create mode 100644 crates/handler/tests/frame_result_size.rs diff --git a/crates/handler/src/frame_data.rs b/crates/handler/src/frame_data.rs index 536cf43c12..cfda9f3844 100644 --- a/crates/handler/src/frame_data.rs +++ b/crates/handler/src/frame_data.rs @@ -202,23 +202,3 @@ impl FrameData { } } } - -#[cfg(test)] -mod tests { - use super::*; - use core::mem::size_of; - - /// A frame result is 208 bytes on a 64-bit target, and the values it is built from are what - /// that takes. The handler moves frame results through its wrappers several times per frame, - /// and past about 256 bytes each move is a library copy rather than an inline one, so a field - /// added to any of them is measured before this changes. - #[cfg(target_pointer_width = "64")] - #[test] - fn test_a_frame_result_is_208_bytes() { - assert_eq!(size_of::<Gas>(), 104); - assert_eq!(size_of::<InterpreterResult>(), 144); - assert_eq!(size_of::<CallOutcome>(), 208); - assert_eq!(size_of::<CreateOutcome>(), 192); - assert_eq!(size_of::<FrameResult>(), 208); - } -} diff --git a/crates/handler/tests/frame_result_size.rs b/crates/handler/tests/frame_result_size.rs new file mode 100644 index 0000000000..3532791001 --- /dev/null +++ b/crates/handler/tests/frame_result_size.rs @@ -0,0 +1,19 @@ +//! The size of a frame result and of the values it is built from. + +use interpreter::{CallOutcome, CreateOutcome, Gas, InterpreterResult}; +use revm_handler::FrameResult; + +/// A frame result is 208 bytes on a 64-bit target, and the values it is built from are what that +/// takes. The handler moves frame results through its wrappers several times per frame, and past +/// about 256 bytes each move is a library copy rather than an inline one, so a field added to any +/// of them is measured before this changes. +#[cfg(target_pointer_width = "64")] +#[test] +fn test_a_frame_result_is_208_bytes() { + use core::mem::size_of; + assert_eq!(size_of::<Gas>(), 104); + assert_eq!(size_of::<InterpreterResult>(), 144); + assert_eq!(size_of::<CallOutcome>(), 208); + assert_eq!(size_of::<CreateOutcome>(), 192); + assert_eq!(size_of::<FrameResult>(), 208); +} From 236f6d9558e627c181f220d91a57ed2ee9b36e69 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 12 Nov 2026 15:54:35 +0800 Subject: [PATCH 106/110] fix(precompile): charge modexp before the Osaka size bound --- crates/precompile/src/modexp.rs | 149 +++++++++++++++++++++--- crates/precompile/src/required_gas.rs | 30 +++-- crates/precompile/tests/required_gas.rs | 10 +- 3 files changed, 154 insertions(+), 35 deletions(-) diff --git a/crates/precompile/src/modexp.rs b/crates/precompile/src/modexp.rs index ae026f90de..d6fc39a288 100644 --- a/crates/precompile/src/modexp.rs +++ b/crates/precompile/src/modexp.rs @@ -210,20 +210,20 @@ where let exp_len = U256::from_be_bytes(right_pad_with_offset::<32>(input, 32).into_owned()); let mod_len = U256::from_be_bytes(right_pad_with_offset::<32>(input, 64).into_owned()); - // Cast base and modulus to usize, it does not make sense to handle larger values - let base_len = usize::try_from(base_len).map_err(|_| PrecompileHalt::ModexpEip7823LimitSize)?; - let mod_len = usize::try_from(mod_len).map_err(|_| PrecompileHalt::ModexpEip7823LimitSize)?; - // cast exp len to the max size, it will fail later in gas calculation if it is too large. - let exp_len = usize::try_from(exp_len).unwrap_or(usize::MAX); - - // for EIP-7823 we need to check size of inputs - if OSAKA - && (base_len > eip7823::INPUT_SIZE_LIMIT - || mod_len > eip7823::INPUT_SIZE_LIMIT - || exp_len > eip7823::INPUT_SIZE_LIMIT) - { - return Err(PrecompileHalt::ModexpEip7823LimitSize); - } + let [base_len64, exp_len64, mod_len64] = if OSAKA { + // Osaka prices oversized lengths before rejecting them, independently of pointer width. + [base_len, exp_len, mod_len].map(|len| u64::try_from(len).unwrap_or(u64::MAX)) + } else { + // Earlier forks keep their original length checks and exponent saturation. + let base_len = + usize::try_from(base_len).map_err(|_| PrecompileHalt::ModexpEip7823LimitSize)?; + let mod_len = + usize::try_from(mod_len).map_err(|_| PrecompileHalt::ModexpEip7823LimitSize)?; + let exp_len = usize::try_from(exp_len).unwrap_or(usize::MAX); + [base_len as u64, exp_len as u64, mod_len as u64] + }; + let [base_len, exp_len, mod_len] = + [base_len64, exp_len64, mod_len64].map(|len| usize::try_from(len).unwrap_or(usize::MAX)); // Used to extract ADJUSTED_EXPONENT_LENGTH. let exp_highp_len = min(exp_len, 32); @@ -239,12 +239,21 @@ where U256::from_be_bytes(out.into_owned()) }; - // Check if we have enough gas. - let gas_cost = calc_gas(base_len as u64, exp_len as u64, mod_len as u64, &exp_highp); - if gas_cost > gas_limit { + // Osaka's formula is even above its minimum, so u64::MAX can only mean a saturated price. + let gas_cost = calc_gas(base_len64, exp_len64, mod_len64, &exp_highp); + if gas_cost > gas_limit || (OSAKA && gas_cost == u64::MAX) { return Err(PrecompileHalt::OutOfGas); } + // EIP-7823 checks the bound only after the formula's gas charge. + if OSAKA + && [base_len64, exp_len64, mod_len64] + .into_iter() + .any(|len| len > eip7823::INPUT_SIZE_LIMIT as u64) + { + return Err(PrecompileHalt::ModexpEip7823LimitSize); + } + if base_len == 0 && mod_len == 0 { return Ok(EthPrecompileOutput::new(gas_cost, Bytes::new())); } @@ -567,6 +576,103 @@ mod tests { assert_eq!(res.bytes, expected) } + #[test] + fn test_osaka_modexp_charges_before_the_size_bound() { + let input: Vec<u8> = [U256::from(1_025), U256::from(1), U256::from(1)] + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + // EIP-7883: 2 * ceil(1025 / 8)^2 * 1 = 33,282, with a zero exponent. + for (gas, expected) in [ + (499, PrecompileHalt::OutOfGas), + (500, PrecompileHalt::OutOfGas), + (33_281, PrecompileHalt::OutOfGas), + (33_282, PrecompileHalt::ModexpEip7823LimitSize), + (33_283, PrecompileHalt::ModexpEip7823LimitSize), + ] { + assert_eq!(osaka_run(&input, gas), Err(expected), "gas={gas}"); + } + } + + #[test] + fn test_osaka_modexp_over_bound_input_has_its_formula_price() { + for (lengths, price) in [ + ([1_025, 1, 1], 33_282), + ([1, 1_025, 1], 254_208), + ([1, 1, 1_025], 33_282), + ] { + let input: Vec<u8> = lengths + .map(U256::from) + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + assert_eq!( + OSAKA.required_gas(&input), + Some(price), + "lengths={lengths:?}" + ); + assert_eq!(osaka_run(&input, price - 1), Err(PrecompileHalt::OutOfGas)); + assert_eq!( + osaka_run(&input, price), + Err(PrecompileHalt::ModexpEip7823LimitSize) + ); + } + } + + #[test] + fn test_modexp_earlier_forks_keep_their_length_rules() { + let input: Vec<u8> = [U256::from(1_025), U256::from(1), U256::from(1)] + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + for (run, entry, price) in [ + ( + byzantium_run as fn(&[u8], u64) -> EthPrecompileResult, + BYZANTIUM, + 17_899, + ), + (berlin_run, BERLIN, 5_547), + ] { + let output = run(&input, price).unwrap(); + assert_eq!(output.gas_used, price); + assert_eq!(output.bytes.as_ref(), &[0]); + assert_eq!(entry.required_gas(&input), Some(price)); + + for position in [0, 2] { + let mut oversized = input.clone(); + oversized[position * 32..(position + 1) * 32] + .copy_from_slice(&(U256::from(1) << 64_usize).to_be_bytes::<32>()); + assert_eq!( + run(&oversized, 100_000), + Err(PrecompileHalt::ModexpEip7823LimitSize), + "price={price}, position={position}" + ); + } + } + } + + #[test] + fn test_osaka_modexp_unpayable_lengths_run_out_of_gas() { + for position in 0..3 { + for length in [U256::from(u64::MAX), U256::from(1) << 64, U256::MAX] { + let mut lengths = [U256::from(1); 3]; + lengths[position] = length; + let input: Vec<u8> = lengths + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + for gas in [0, 499, 500, 100_000, u64::MAX - 1, u64::MAX] { + assert_eq!( + osaka_run(&input, gas), + Err(PrecompileHalt::OutOfGas), + "position={position}, length={length}, gas={gas}" + ); + } + assert_eq!(OSAKA.required_gas(&input), Some(u64::MAX)); + } + } + } + #[test] fn test_osaka_modexp_input_len() { #[derive(Debug)] @@ -574,6 +680,7 @@ mod tests { base_len: U256, exp_len: U256, mod_len: U256, + gas: u64, expected: Option<PrecompileHalt>, } @@ -592,42 +699,48 @@ mod tests { base_len: U256::from(1025), exp_len: U256::from(1024), mod_len: U256::from(1024), + gas: u64::MAX, expected: Some(PrecompileHalt::ModexpEip7823LimitSize), }, TestInput { base_len: U256::from(1024), exp_len: U256::from(1025), mod_len: U256::from(1024), + gas: u64::MAX, expected: Some(PrecompileHalt::ModexpEip7823LimitSize), }, TestInput { base_len: U256::from(1024), exp_len: U256::from(1024), mod_len: U256::from(1025), + gas: u64::MAX, expected: Some(PrecompileHalt::ModexpEip7823LimitSize), }, TestInput { base_len: U256::from(0), exp_len: U256::from(0), mod_len: U256::from(1025), + gas: u64::MAX, expected: Some(PrecompileHalt::ModexpEip7823LimitSize), }, TestInput { base_len: U256::from(1024), exp_len: U256::from(1024), mod_len: U256::from(1024), + gas: 100_000_000, expected: Some(PrecompileHalt::OutOfGas), }, TestInput { base_len: U256::from(0), exp_len: U256::from(0), mod_len: U256::from(0), + gas: 100_000_000, expected: None, }, ]; for test in test_inputs { let input = test.input(); - let res = osaka_run(&input, 100_000_000).err(); + let res = osaka_run(&input, test.gas).err(); if res != test.expected { panic!("test failed: {test:?} result: {res:?}"); } diff --git a/crates/precompile/src/required_gas.rs b/crates/precompile/src/required_gas.rs index 9cf092ba44..5e669e8f51 100644 --- a/crates/precompile/src/required_gas.rs +++ b/crates/precompile/src/required_gas.rs @@ -7,7 +7,7 @@ //! //! # Contract //! -//! `required_gas(input) == Some(price)` guarantees, for every gas limit `g`: +//! `required_gas(input) == Some(price)` with `price < u64::MAX` guarantees, for every gas limit `g`: //! //! - [`Precompile::execute`] with `g` halts with //! [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if @@ -15,6 +15,9 @@ //! - with `g >= price` the run's result is the same for every `g`, and a run that succeeds or //! reverts uses exactly `price`. //! +//! A price saturated to `u64::MAX` can represent a charge beyond any gas limit. Osaka `MODEXP` +//! halts out of gas for such a price even when given `u64::MAX` gas. +//! //! So `price` is both what the call charges and the least gas limit it runs on. An input that //! fails a check, a malformed one, keeps the contract too: //! @@ -26,9 +29,10 @@ //! input's price is the gas that check asks for: every precompile with a flat price, the //! BN254 pairing on a length that is not a multiple of 192 bytes, KZG point evaluation on any //! malformed input, a `BLAKE2F` final-block flag other than 0 or 1; -//! - `MODEXP` checks the sizes in its header between its two gas checks: a header whose sizes -//! do not fit (EIP-7823 under Osaka, or `usize` everywhere) prices at the minimum the first -//! gas check asks for, 0, 200 or 500 by schedule. +//! - Osaka `MODEXP` prices every header by its formula before checking EIP-7823's bound, with +//! each length saturated to 64 bits. Earlier schedules refuse a base or modulus length that +//! does not fit `usize` between the two gas checks, so those inputs keep the first check's +//! minimum price, 0 under Byzantium or 200 under Berlin. //! //! The price never tells whether a call with enough gas succeeds: an input that fails a check //! after the gas check is only told apart from one that succeeds by running it. @@ -168,10 +172,12 @@ impl Precompile { /// Returns the gas a call with `input` needs, without running the precompile, or `None` when /// the precompile has no price function. /// - /// `Some(price)` guarantees, for every gas limit `g`: [`execute`](Self::execute) with `g` - /// halts with [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if - /// `g < price`, and with `g >= price` its result is the same for every `g`, a success or a - /// revert using exactly `price`. An input a check refuses before any gas check prices at `0`. + /// `Some(price)` with `price < u64::MAX` guarantees, for every gas limit `g`: + /// [`execute`](Self::execute) with `g` halts with + /// [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if `g < price`, + /// and with `g >= price` its result is the same for every `g`, a success or a revert using + /// exactly `price`. A saturated `u64::MAX` price can exceed every gas limit. + /// An input a check refuses before any gas check prices at `0`. /// See the [module documentation](self) for the malformed inputs of each precompile. #[inline] pub fn required_gas(&self, input: &[u8]) -> Option<u64> { @@ -215,10 +221,10 @@ pub fn modexp_osaka(input: &[u8]) -> u64 { } /// Prices a `MODEXP` call with the run's own header parsing: [`modexp::run_inner`] reads the -/// header, checks the sizes and prices the call exactly as a run does, and `gas_calc` is handed -/// to it as the price, recorded and then refused, so the run stops at its gas check before any -/// exponentiation. A header refused between the two gas checks never reaches `gas_calc`, and -/// prices at `min_gas`. +/// header and prices the call exactly as a run does, and `gas_calc` is handed to it as the price, +/// recorded and then refused, so the run stops at its gas check before any exponentiation. +/// Osaka prices every header before checking its size bound. Earlier forks still price a +/// header refused between the two gas checks at `min_gas`. fn modexp_price<const OSAKA: bool>( input: &[u8], min_gas: u64, diff --git a/crates/precompile/tests/required_gas.rs b/crates/precompile/tests/required_gas.rs index 15b74ca179..1a0f5f8202 100644 --- a/crates/precompile/tests/required_gas.rs +++ b/crates/precompile/tests/required_gas.rs @@ -250,7 +250,7 @@ fn made_inputs(id: &PrecompileId, rng: &mut StdRng) -> Vec<Vec<u8>> { let mut high_exp = modexp_input(rng, small(1), small(40), small(1), 42); high_exp[96 + 1] = 0xff; inputs.push(high_exp); - // Sizes EIP-7823 refuses under Osaka, between the two gas checks. + // Sizes EIP-7823 refuses under Osaka, after the formula price is charged. for (base, exp, modulus) in [(1_025, 1, 1), (1, 1_025, 1), (1, 1, 1_025)] { inputs.push(modexp_input( rng, @@ -452,12 +452,12 @@ fn malformed_inputs_price_as_documented() { Some(7) ); - // `MODEXP` sizes refused between its two gas checks: the first gas check's minimum. + // `MODEXP` under Osaka prices oversized lengths before checking its size bound. let mut rng = StdRng::seed_from_u64(2); let too_big = modexp_input(&mut rng, U256::from(1_025), U256::from(1), U256::from(1), 8); - assert_eq!(modexp::OSAKA.required_gas(&too_big), Some(500)); + assert_eq!(modexp::OSAKA.required_gas(&too_big), Some(33_282)); let unaddressable = modexp_input(&mut rng, U256::MAX, U256::from(1), U256::from(1), 8); - assert_eq!(modexp::OSAKA.required_gas(&unaddressable), Some(500)); + assert_eq!(modexp::OSAKA.required_gas(&unaddressable), Some(u64::MAX)); assert_eq!(modexp::BERLIN.required_gas(&unaddressable), Some(200)); assert_eq!(modexp::BYZANTIUM.required_gas(&unaddressable), Some(0)); } @@ -490,7 +490,7 @@ fn every_set_prices_with_its_own_schedule() { assert_eq!(modexp_price(PrecompileSpecId::BYZANTIUM), Some(0)); assert_eq!(modexp_price(PrecompileSpecId::BERLIN), Some(200)); assert_eq!(modexp_price(PrecompileSpecId::PRAGUE), Some(200)); - assert_eq!(modexp_price(PrecompileSpecId::OSAKA), Some(500)); + assert_eq!(modexp_price(PrecompileSpecId::OSAKA), Some(u64::MAX)); let p256 = |spec| { Precompiles::new(spec) From a125b2c45bef8476e2c1b72dac315c1d05f94f61 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Thu, 12 Nov 2026 16:14:15 +0800 Subject: [PATCH 107/110] fix(precompile): match modexp saturated gas boundary --- crates/precompile/src/modexp.rs | 11 ++++++++--- crates/precompile/src/required_gas.rs | 19 ++++++++----------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/precompile/src/modexp.rs b/crates/precompile/src/modexp.rs index d6fc39a288..d132c442b9 100644 --- a/crates/precompile/src/modexp.rs +++ b/crates/precompile/src/modexp.rs @@ -239,9 +239,8 @@ where U256::from_be_bytes(out.into_owned()) }; - // Osaka's formula is even above its minimum, so u64::MAX can only mean a saturated price. let gas_cost = calc_gas(base_len64, exp_len64, mod_len64, &exp_highp); - if gas_cost > gas_limit || (OSAKA && gas_cost == u64::MAX) { + if gas_cost > gas_limit { return Err(PrecompileHalt::OutOfGas); } @@ -661,13 +660,19 @@ mod tests { .into_iter() .flat_map(|len| len.to_be_bytes::<32>()) .collect(); - for gas in [0, 499, 500, 100_000, u64::MAX - 1, u64::MAX] { + for gas in [0, 499, 500, 100_000, u64::MAX - 1] { assert_eq!( osaka_run(&input, gas), Err(PrecompileHalt::OutOfGas), "position={position}, length={length}, gas={gas}" ); } + // Like go-ethereum, a u64::MAX gas limit pays the saturated price before the bound. + assert_eq!( + osaka_run(&input, u64::MAX), + Err(PrecompileHalt::ModexpEip7823LimitSize), + "position={position}, length={length}" + ); assert_eq!(OSAKA.required_gas(&input), Some(u64::MAX)); } } diff --git a/crates/precompile/src/required_gas.rs b/crates/precompile/src/required_gas.rs index 5e669e8f51..b0290ee3d8 100644 --- a/crates/precompile/src/required_gas.rs +++ b/crates/precompile/src/required_gas.rs @@ -7,7 +7,7 @@ //! //! # Contract //! -//! `required_gas(input) == Some(price)` with `price < u64::MAX` guarantees, for every gas limit `g`: +//! `required_gas(input) == Some(price)` guarantees, for every gas limit `g`: //! //! - [`Precompile::execute`] with `g` halts with //! [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if @@ -15,9 +15,6 @@ //! - with `g >= price` the run's result is the same for every `g`, and a run that succeeds or //! reverts uses exactly `price`. //! -//! A price saturated to `u64::MAX` can represent a charge beyond any gas limit. Osaka `MODEXP` -//! halts out of gas for such a price even when given `u64::MAX` gas. -//! //! So `price` is both what the call charges and the least gas limit it runs on. An input that //! fails a check, a malformed one, keeps the contract too: //! @@ -30,7 +27,9 @@ //! BN254 pairing on a length that is not a multiple of 192 bytes, KZG point evaluation on any //! malformed input, a `BLAKE2F` final-block flag other than 0 or 1; //! - Osaka `MODEXP` prices every header by its formula before checking EIP-7823's bound, with -//! each length saturated to 64 bits. Earlier schedules refuse a base or modulus length that +//! each length saturated to 64 bits. A formula price saturated to `u64::MAX` passes the gas +//! check at that exact gas limit and then fails the size bound. +//! Earlier schedules refuse a base or modulus length that //! does not fit `usize` between the two gas checks, so those inputs keep the first check's //! minimum price, 0 under Byzantium or 200 under Berlin. //! @@ -172,12 +171,10 @@ impl Precompile { /// Returns the gas a call with `input` needs, without running the precompile, or `None` when /// the precompile has no price function. /// - /// `Some(price)` with `price < u64::MAX` guarantees, for every gas limit `g`: - /// [`execute`](Self::execute) with `g` halts with - /// [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if `g < price`, - /// and with `g >= price` its result is the same for every `g`, a success or a revert using - /// exactly `price`. A saturated `u64::MAX` price can exceed every gas limit. - /// An input a check refuses before any gas check prices at `0`. + /// `Some(price)` guarantees, for every gas limit `g`: [`execute`](Self::execute) with `g` + /// halts with [`PrecompileHalt::OutOfGas`](crate::PrecompileHalt::OutOfGas) if and only if + /// `g < price`, and with `g >= price` its result is the same for every `g`, a success or a + /// revert using exactly `price`. An input a check refuses before any gas check prices at `0`. /// See the [module documentation](self) for the malformed inputs of each precompile. #[inline] pub fn required_gas(&self, input: &[u8]) -> Option<u64> { From df02eaa390952ff4e989372ae16c03ef800a5163 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 13 Nov 2026 12:25:27 +0800 Subject: [PATCH 108/110] feat(gas): give-backs to the reservoir alone behind a switch, and a legacy share of state charges A configuration switch, off by default, makes every refill, rollback and returned reservoir credit the reservoir and never regular gas, and counts what regular gas paid for state and history so a halt restores the reservoir a frame received. Four schedule entries, zero by default, give an opcode's state charge a share regular gas pays before the reservoir. --- MEGAETH-FORK.md | 29 +- crates/context/interface/src/cfg.rs | 9 + crates/context/interface/src/cfg/gas.rs | 72 ++- .../context/interface/src/cfg/gas/encoding.rs | 15 +- .../interface/src/cfg/gas/give_backs.rs | 304 ++++++++++ .../context/interface/src/cfg/gas_params.rs | 96 ++- crates/context/src/cfg.rs | 21 + crates/handler/src/execution/first_frame.rs | 17 +- crates/handler/src/frame.rs | 147 ++++- crates/handler/src/handler.rs | 8 +- .../tests/reservoir_only_give_backs.rs | 547 ++++++++++++++++++ crates/interpreter/src/gas.rs | 35 ++ .../interpreter/src/instructions/contract.rs | 3 +- .../src/instructions/contract/call_helpers.rs | 14 +- crates/interpreter/src/instructions/host.rs | 12 +- crates/interpreter/src/instructions/macros.rs | 17 + crates/interpreter/tests/start_marks.rs | 6 +- 17 files changed, 1316 insertions(+), 36 deletions(-) create mode 100644 crates/context/interface/src/cfg/gas/give_backs.rs create mode 100644 crates/handler/tests/reservoir_only_give_backs.rs diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 7a42f49664..0a9af9eee6 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -46,7 +46,8 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T The fork adds hooks and data. It also carries a named, bounded set of MegaETH accounting inside revm's charges and settlement: - withheld regular gas and its crossing record, which every regular charge reads; - - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`. + - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`; + - give-backs to the reservoir alone, which change where revm's refills, rollbacks and reservoir merges credit a give-back, and the legacy share of an opcode's state charge. Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing. Nothing else that implements MegaETH semantics enters the fork. @@ -92,7 +93,7 @@ The sizes are the lines of `crates/`, without tests, that `git blame <base>..<fo | Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). | | Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | not counted | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types, as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). | | Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. | -| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension | about 700 lines | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. | +| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, give-backs to the reservoir alone and the legacy share | about 800 lines | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. | ## Hooks @@ -133,7 +134,7 @@ An id the fork once used for an entry is left unused rather than given a new mea `GasId::code_deposit_history_gas` and `GasParams::code_deposit_history_gas(len)`. - **Contract.** A history charge draws the same reservoir-first budget as a state-gas charge: the reservoir, then regular gas, withheld part first. It is booked on its own counter, so history gas can be reported and limited apart from state gas. - It unwinds with state gas: a frame that reverts or halts refills both in last-in-first-out order, and `refill_history` returns a spill before it tops up the reservoir. + It unwinds with state gas: a frame that reverts or halts refills both in last-in-first-out order, and `refill_history` returns a spill before it tops up the reservoir, unless give-backs go to the reservoir alone (see Give-backs to the reservoir alone and the legacy share). `return_create` charges `code_deposit_history_gas` for the deployed bytes after their state-gas charge. `ResultGas` has no field for it: `total_gas_spent` and `block_regular_gas_used` include it, and the `ResultGas` documentation says how a block-level consumer separates it. - **Consumer.** mega-evm charges history gas for the bytes a transaction appends to the chain's history. The code deposit is charged inside `return_create`, and only the tracker can unwind a frame's history charges with its state charges. @@ -141,6 +142,26 @@ An id the fork once used for an entry is left unused rather than given a new mea - **Default.** No schedule prices `code_deposit_history_gas`, and nothing else in the workspace charges history gas, so the counter stays zero and every result is upstream's. In a format that carries field names, the counter decodes as zero from encodings that predate it. +### Give-backs to the reservoir alone and the legacy share + +- **API.** `CfgEnv::reservoir_only_give_backs` with `with_reservoir_only_give_backs`, and `Cfg::reservoir_only_give_backs` (default `false`). + On `GasTracker`, forwarded on `Gas`: `reservoir_only_give_backs`, `set_reservoir_only_give_backs`, `record_state_cost_with_legacy_share` and `consume_regular_paid_charges`. + `GasId::sstore_set_state_gas_legacy_share`, `new_account_state_gas_legacy_share`, `selfdestruct_new_account_state_gas_legacy_share` and `create_state_gas_legacy_share` (ids 245 to 242), with their `GasParams` accessors, and the `state_gas_with_legacy_share!` instruction macro. +- **Contract.** revm sets the switch on the transaction's gas (`Handler::tx_gas`) and on every frame's gas, and on the results it builds for a call or creation it answers without running a frame (`EthFrame::make_call_frame`, `make_create_frame`), from the configuration. + With it on, no give-back of state or history gas credits regular gas: `refill_reservoir` and `refill_history` top up the reservoir alone, `rollback_state_gas` sets the reservoir to `reservoir + state_gas_spent + history_gas_spent` and leaves regular gas as it was, and `absorb_returned_reservoir` takes the returned reservoir as the caller's without unwinding anything. + A frame's regular gas then rises within the frame only by the regular gas a child returns. + `state_gas_spilled` counts every part of a state or history charge regular gas paid, and no give-back lowers it: a child that succeeds or reverts adds its count to its caller's (`handle_reservoir_remaining_gas`), and a halt takes it out of the reservoir the rollback set, which leaves the reservoir the frame received (`consume_regular_paid_charges`), before it spends the regular gas. + After a halt of the transaction's frame, `settle_first_frame` gives back only the part of the EIP-2780 first-frame charge the reservoir paid: that charge is the last made before the frame, and every charge there draws the reservoir first, so the part regular gas paid is the last `min(charge, state_gas_spilled)` of the transaction's count. + The legacy share is the part of an opcode's state charge regular gas pays before the reservoir pays any of it: `SSTORE`'s fresh slot, a value `CALL`'s new account, a `SELFDESTRUCT`'s new beneficiary and a `CREATE`'s or `CREATE2`'s created account each take `min(charge, entry)` of their schedule entry from regular gas, withheld part first, before the reservoir; a value call's and a creation's before the forward is computed. + A frame whose regular gas cannot pay the share and what the reservoir cannot pay runs out of gas, whatever the reservoir holds. + The share is state gas, counted with its charge and given back with it, and the switch and the shares are independent: with the switch off a share is part of the spill a give-back unwinds. +- **Consumer.** mega-evm keeps a frame's regular gas from rising within the frame by gas spent on state and history, and keeps creating state at its pre-Amsterdam price in regular gas when a transaction carries a reservoir. + Every refill, rollback and reservoir merge that credits regular gas is inside revm: an `SSTORE` that writes a slot back refills inside its instruction, and a frame's rollback and the merge of its reservoir into its caller's are revm's settlement, so no hook that sees the gas afterwards can tell what revm credited; and a value call's and a creation's share must come off regular gas before the opcode computes its forward. +- **Removal.** When upstream's EIP-8037 credits every give-back to the reservoir and takes a legacy share from regular gas, as ethereum/EIPs#12581 proposes, or when mega-evm stops doing either. +- **Default.** The switch is off and every share entry is zero, so every result is upstream's: `record_state_cost_with_legacy_share` with a share of zero is `record_state_cost`, `consume_regular_paid_charges` finds nothing after an upstream rollback, which zeroed the spill, and the count a revert adds to its caller is zero for the same reason. + The switch is a `bool` in a word the tracker already had, so `GasTracker` stays 88 bytes and every frame result its size; in a format that carries field names it decodes as `false` from encodings that predate it. + In instructions, a give-back, a rollback and a merge read one `bool`, a value call that creates an account and the three other share sites read one schedule entry, and every frame's construction reads the switch from the configuration once. + ### Amsterdam opcodes and transfer logs below Amsterdam - **API.** `revm_interpreter::enable_amsterdam_opcodes(&mut InstructionTable)` and the ungated instructions it installs (`dupn_enabled`, `swapn_enabled`, `exchange_enabled`, `slot_num_enabled`); `DummyHost::with_slot_num`. @@ -367,7 +388,7 @@ An id the fork once used for an entry is left unused rather than given a new mea What a consumer charges or keeps for an instruction's start it does at `frame_starting`, before the split; the transaction's start does not pass through `frame_starting`. `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it. - *The reservoir.* revm forwards and settles the reservoir as upstream does: the child's input copies the caller's reservoir, or carries the reservoir the frame-start hook named (`FrameStart::reservoir`), and the settlement replaces the caller's reservoir with the one the child returns, once that has unwound the caller's outstanding spill. + *The reservoir.* revm forwards and settles the reservoir as upstream does: the child's input copies the caller's reservoir, or carries the reservoir the frame-start hook named (`FrameStart::reservoir`), and the settlement replaces the caller's reservoir with the one the child returns, once that has unwound the caller's outstanding spill, or as it is when give-backs go to the reservoir alone. A consumer that keeps part of the caller's reservoir for it takes that part in `frame_starting` and names the rest as the child's, and adds `held_reservoir` back to the caller's reservoir in `frame_settle`. The caller then holds what the child returned on top of the part it kept, whatever refills the settlement made, since the unwinding and every refill read the spill and their own amount, never the reservoir. The transaction's frame, and the stand-in for a runtime out-of-gas transaction, are handed a copy of the transaction's reservoir, which the transaction's gas keeps until the settlement replaces it, so there `held_reservoir` is that copy: a consumer adds back only what it kept. diff --git a/crates/context/interface/src/cfg.rs b/crates/context/interface/src/cfg.rs index 9c9effe5e6..dd2ac171d2 100644 --- a/crates/context/interface/src/cfg.rs +++ b/crates/context/interface/src/cfg.rs @@ -124,6 +124,14 @@ pub trait Cfg { fn legacy_journal_semantics(&self) -> bool { false } + + /// Returns whether every give-back of state or history gas credits the reservoir alone + /// (`GasTracker::reservoir_only_give_backs`), which revm sets on the transaction's gas and on + /// every frame's. Default is `false`, EIP-8037's tracker. + #[inline] + fn reservoir_only_give_backs(&self) -> bool { + false + } } /// What bytecode analysis to perform @@ -264,5 +272,6 @@ mod tests { let cfg = RequiredOnly(GasParams::default()); assert!(!cfg.legacy_journal_semantics()); assert!(!cfg.enable_amsterdam_eip7708()); + assert!(!cfg.reservoir_only_give_backs()); } } diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 949081c101..3c09b15e1f 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -6,6 +6,7 @@ use primitives::hardfork::SpecId; #[cfg(feature = "serde")] mod encoding; mod failed_charge; +mod give_backs; mod mark; mod withheld; @@ -42,7 +43,8 @@ pub use withheld::WithheldCrossing; /// of them lands inside a frame rather than at a frame boundary: `SSTORE`'s refill when it /// restores a slot to its original zero (0→x→0). A consumer that holds the spendable part at an /// allowance limits it at a frame's start and again after each credit: when a child returns, and -/// after `SSTORE`. +/// after `SSTORE`. With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set only the +/// first of them credits regular gas. /// /// Releasing the withheld part ([`release_withheld`](Self::release_withheld)) is not needed to /// conserve gas: the gas a child returns is its [`remaining`](Self::remaining), withheld part @@ -60,6 +62,17 @@ pub use withheld::WithheldCrossing; /// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX` /// (about 9.2 × 10^18). /// +/// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set, which is off by +/// default, no give-back of state or history gas credits regular gas: a refill, the rollback of a +/// failed frame and a reservoir a child returns all land in the reservoir, so `remaining` rises +/// only by the regular gas a child returns. `state_gas_spilled` then counts every part of a state +/// or history charge that regular gas paid, and no give-back lowers it; a halt reads it to give the +/// frame back the reservoir it received. +/// +/// A state charge can take a legacy share from regular gas before it draws the reservoir +/// ([`record_state_cost_with_legacy_share`](Self::record_state_cost_with_legacy_share)); a share of +/// zero, the default schedule's for every charge, is [`record_state_cost`](Self::record_state_cost). +/// /// Encoded, the tracker has a field per figure, in the order below; the failed-charge record, /// a number and a flag in memory, is encoded as an optional number in its place. /// @@ -108,6 +121,12 @@ pub struct GasTracker { /// halt) the spilled portion is credited back to `remaining` in last-in- /// first-out order by [`Self::rollback_state_gas`]; on success it is /// propagated to the parent frame so a later parent rollback can return it. + /// + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set it is the state and + /// history gas regular gas paid, a legacy share included: no give-back lowers it, and a child + /// that succeeds or reverts adds its own to its caller's, its reverted charges having gone into + /// the reservoir it returns. A halt takes it out of the reservoir and then zeroes it + /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)). state_gas_spilled: u64, /// Net history gas spent so far. /// @@ -165,6 +184,13 @@ pub struct GasTracker { /// an `Option`, whose tag would take a word of its own, so it shares a word with /// `start_mark`. failed_charge_recorded: bool, + /// Whether every give-back of state or history gas credits the reservoir alone + /// ([`reservoir_only_give_backs`](Self::reservoir_only_give_backs)). A flag that shares the word + /// of `failed_charge_recorded` and `start_mark`, so the tracker's size is unchanged. + /// + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as `false`. + reservoir_only_give_backs: bool, /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)). It fits padding /// the tracker already had, in the word `failed_charge_recorded` takes, so the tracker's size /// is unchanged. No part of the tracker's value, and not encoded. @@ -186,6 +212,7 @@ impl core::fmt::Debug for GasTracker { .field("withheld_crossing", &self.withheld_crossing) .field("failed_charge_remaining", &self.failed_charge_remaining) .field("failed_charge_recorded", &self.failed_charge_recorded) + .field("reservoir_only_give_backs", &self.reservoir_only_give_backs) .finish() } } @@ -206,6 +233,7 @@ impl GasTracker { withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, + reservoir_only_give_backs: false, start_mark: StartMark::NONE, } } @@ -297,8 +325,16 @@ impl GasTracker { /// This only reconciles the funding pools. The child's signed /// `state_gas_spent` has already accounted for the refill and is merged /// separately by the frame handler. + /// + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set nothing is + /// unwound: the returned reservoir becomes this frame's reservoir as it is, and regular gas is + /// left as it was. #[inline] pub const fn absorb_returned_reservoir(&mut self, reservoir: u64) { + if self.reservoir_only_give_backs { + self.reservoir = reservoir; + return; + } let to_remaining = if reservoir < self.state_gas_spilled { reservoir } else { @@ -480,8 +516,18 @@ impl GasTracker { /// last-in-first-out order: `remaining` is credited up to `state_gas_spilled`, the rest tops up /// the reservoir, and the net history gas falls by the full `amount` — below zero when the /// matching charge was made by a parent frame, which the merge on return reconciles. + /// + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set the whole `amount` + /// tops up the reservoir, and `remaining` and `state_gas_spilled` are left as they were. #[inline] pub const fn refill_history(&mut self, amount: u64) { + if self.reservoir_only_give_backs { + self.reservoir = self.reservoir.saturating_add(amount); + self.history_gas_spent = self + .history_gas_spent + .saturating_sub(saturating_signed(amount)); + return; + } let to_remaining = if amount < self.state_gas_spilled { amount } else { @@ -512,12 +558,26 @@ impl GasTracker { /// On revert the resulting `remaining` (including the refilled spill) is /// returned to the parent; on halt the caller additionally zeroes `remaining` /// so the spilled gas is consumed while the reservoir is left untouched. + /// + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set every charge the + /// frame made, net of the give-backs it received, goes into the reservoir, whichever pool + /// paid it: the reservoir becomes `reservoir + state_gas_spent + history_gas_spent`, and + /// `remaining` and `state_gas_spilled` are left as they were. That is a reverted frame's + /// reservoir; a halting frame's caller then consumes the part regular gas paid + /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)), which leaves the + /// reservoir the frame received. #[inline] pub const fn rollback_state_gas(&mut self) { // The two nets are summed before they meet the reservoir: a frame that took back a parent's // state charge after its own history charge spilled holds less reservoir than its state // net is negative, and adding the terms one at a time would clamp at zero part-way. let charged = self.state_gas_spent.saturating_add(self.history_gas_spent); + if self.reservoir_only_give_backs { + self.reservoir = self.reservoir.saturating_add_signed(charged); + self.state_gas_spent = 0; + self.history_gas_spent = 0; + return; + } self.reservoir = self .reservoir .saturating_add_signed(charged) @@ -545,8 +605,18 @@ impl GasTracker { /// (`remaining`) last, the refill credits the pool charged last first: /// `remaining` is credited up to `state_gas_spilled` and any remainder tops /// up the reservoir. + /// + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set the whole `amount` + /// tops up the reservoir, and `remaining` and `state_gas_spilled` are left as they were. #[inline] pub const fn refill_reservoir(&mut self, amount: u64) { + if self.reservoir_only_give_backs { + self.reservoir = self.reservoir.saturating_add(amount); + self.state_gas_spent = self + .state_gas_spent + .saturating_sub(saturating_signed(amount)); + return; + } let to_remaining = if amount < self.state_gas_spilled { amount } else { diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index 9fc1f0d025..3d359107c1 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -30,6 +30,8 @@ pub(super) struct Encoded { withheld_crossing: Option<WithheldCrossing>, #[serde(default)] failed_charge_remaining: Option<u64>, + #[serde(default)] + reservoir_only_give_backs: bool, } impl From<GasTracker> for Encoded { @@ -45,6 +47,7 @@ impl From<GasTracker> for Encoded { withheld: tracker.withheld, withheld_crossing: tracker.withheld_crossing, failed_charge_remaining: tracker.failed_charge_remaining(), + reservoir_only_give_backs: tracker.reservoir_only_give_backs, } } } @@ -63,6 +66,7 @@ impl From<Encoded> for GasTracker { withheld_crossing: encoded.withheld_crossing, failed_charge_remaining: 0, failed_charge_recorded: false, + reservoir_only_give_backs: encoded.reservoir_only_give_backs, start_mark: super::StartMark::NONE, }; tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); @@ -75,10 +79,11 @@ mod tests { use super::super::GasTracker; /// A tracker with every field away from its default: part of its regular gas withheld, a - /// crossing and a failed charge recorded, a state charge spilled past the reservoir and a - /// refund. + /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a + /// refund, and give-backs that credit the reservoir alone. fn every_field_set() -> GasTracker { let mut tracker = GasTracker::new(1_000, 400, 300); + tracker.set_reservoir_only_give_backs(true); tracker.withhold(100); assert!(!tracker.record_regular_cost(350)); assert!(tracker.record_state_cost(500)); @@ -96,7 +101,8 @@ mod tests { concat!( r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#, r#""state_gas_spilled":200,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, - r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400}"#, + r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#, + r#""reservoir_only_give_backs":true}"#, ) ); assert_eq!( @@ -104,7 +110,8 @@ mod tests { concat!( r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#, r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#, - r#""withheld_crossing":null,"failed_charge_remaining":null}"#, + r#""withheld_crossing":null,"failed_charge_remaining":null,"#, + r#""reservoir_only_give_backs":false}"#, ) ); } diff --git a/crates/context/interface/src/cfg/gas/give_backs.rs b/crates/context/interface/src/cfg/gas/give_backs.rs new file mode 100644 index 0000000000..c6e43cc81d --- /dev/null +++ b/crates/context/interface/src/cfg/gas/give_backs.rs @@ -0,0 +1,304 @@ +//! Give-backs to the reservoir alone, and the legacy share of a state charge. +//! +//! The switch that makes every give-back of state or history gas credit a [`GasTracker`]'s +//! reservoir and never its regular gas, the count of what regular gas paid for state and history +//! that a halt consumes, and the charge that takes a legacy share from regular gas before the +//! reservoir. The tracker's own documentation describes how each give-back is credited with the +//! switch on and off. + +use super::GasTracker; + +impl GasTracker { + /// Whether every give-back of state or history gas credits the reservoir alone. Off by + /// default, which is EIP-8037's tracker. + /// + /// With it on, no give-back credits regular gas, whichever pool paid the charge it gives back: + /// a refill ([`refill_reservoir`](Self::refill_reservoir), + /// [`refill_history`](Self::refill_history)), a failed frame's rollback + /// ([`rollback_state_gas`](Self::rollback_state_gas)) and a reservoir a child returns + /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)) land in the reservoir, so a + /// frame's `remaining` rises within the frame only by the regular gas a child returns. + /// [`state_gas_spilled`](Self::state_gas_spilled) counts what regular gas paid of state and + /// history charges and no give-back lowers it. A halt consumes the frame's regular gas and + /// the part of its charges regular gas paid, and gives it back the reservoir it received + /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)). + #[inline] + pub const fn reservoir_only_give_backs(&self) -> bool { + self.reservoir_only_give_backs + } + + /// Sets whether every give-back of state or history gas credits the reservoir alone; see + /// [`reservoir_only_give_backs`](Self::reservoir_only_give_backs). revm sets it on the + /// transaction's gas and on every frame's from `Cfg::reservoir_only_give_backs`. + #[inline] + pub const fn set_reservoir_only_give_backs(&mut self, on: bool) { + self.reservoir_only_give_backs = on; + } + + /// Records a state gas cost that takes a legacy share from regular gas before it draws the + /// reservoir. + /// + /// The share is `min(cost, legacy_share)`: it is drawn from `remaining` first, withheld part + /// first ([`record_withheld_first_cost`](Self::record_withheld_first_cost)); the rest of the + /// charge is then paid as [`record_state_cost`](Self::record_state_cost) pays it, from the + /// reservoir and, past it, from `remaining` again. The share and that spill are one deduction + /// from `remaining`, booked on [`state_gas_spilled`](Self::state_gas_spilled), and the whole + /// charge is state gas. + /// + /// Returns `false` if `remaining` cannot pay the share and the spill together, whatever the + /// reservoir holds, leaving the tracker's gas untouched and recording the regular gas left + /// ([`failed_charge_remaining`](Self::failed_charge_remaining)). A share of zero is + /// [`record_state_cost`](Self::record_state_cost). + #[inline] + #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"] + pub const fn record_state_cost_with_legacy_share( + &mut self, + cost: u64, + legacy_share: u64, + ) -> bool { + let share = if legacy_share < cost { + legacy_share + } else { + cost + }; + let rest = cost - share; + let from_reservoir = if self.reservoir < rest { + self.reservoir + } else { + rest + }; + let from_regular = cost - from_reservoir; + if from_regular != 0 && !self.record_withheld_first_cost(from_regular) { + return false; + } + self.reservoir -= from_reservoir; + self.state_gas_spent = self + .state_gas_spent + .saturating_add(super::saturating_signed(cost)); + self.state_gas_spilled = self.state_gas_spilled.saturating_add(from_regular); + true + } + + /// Consumes, after [`rollback_state_gas`](Self::rollback_state_gas) of a frame that halts, the + /// part of its state and history charges regular gas paid: the reservoir gives up + /// `state_gas_spilled`, which is then zero, so it holds the reservoir the frame received, and + /// what regular gas paid is consumed with the regular gas the halt spends. + /// + /// The rollback put every charge into the reservoir only with + /// [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set. With it off the rollback + /// credited the spill to `remaining` and zeroed it, so there is nothing left to take and this + /// changes nothing. + #[inline] + pub const fn consume_regular_paid_charges(&mut self) { + self.reservoir = self.reservoir.saturating_sub(self.state_gas_spilled); + self.state_gas_spilled = 0; + } +} + +#[cfg(test)] +mod tests { + use super::GasTracker; + + /// A tracker with `remaining` regular gas and `reservoir`, its give-backs to the reservoir + /// alone when `on`. + fn tracker(remaining: u64, reservoir: u64, on: bool) -> GasTracker { + let mut tracker = GasTracker::new(remaining, remaining, reservoir); + tracker.set_reservoir_only_give_backs(on); + tracker + } + + /// `(remaining, reservoir, state_spent, history_spent, spilled)`. + const fn figures(tracker: &GasTracker) -> (u64, u64, i64, i64, u64) { + ( + tracker.remaining(), + tracker.reservoir(), + tracker.state_gas_spent(), + tracker.history_gas_spent(), + tracker.state_gas_spilled(), + ) + } + + /// The switch is off on every tracker built, and is no part of a tracker that has it off. + #[test] + fn test_the_switch_is_off_by_default() { + assert!(!GasTracker::new(1_000, 1_000, 0).reservoir_only_give_backs()); + assert!(!GasTracker::default().reservoir_only_give_backs()); + let mut on = GasTracker::default(); + on.set_reservoir_only_give_backs(true); + assert!(on.reservoir_only_give_backs()); + assert_ne!( + on, + GasTracker::default(), + "the switch is part of the tracker's value" + ); + } + + /// A refill of state gas regular gas paid credits regular gas first with the switch off, and + /// the reservoir alone with it on, the spill count standing. + #[test] + fn test_a_state_refill_credits_the_reservoir_alone_with_the_switch_on() { + for on in [false, true] { + let mut gas = tracker(1_000, 100, on); + assert!(gas.record_state_cost(300)); + assert_eq!(figures(&gas), (800, 0, 300, 0, 200)); + gas.refill_reservoir(300); + let expected = if on { + (800, 300, 0, 0, 200) + } else { + (1_000, 100, 0, 0, 0) + }; + assert_eq!(figures(&gas), expected, "switch on: {on}"); + } + } + + /// A refill of history gas follows the same rule as a refill of state gas. + #[test] + fn test_a_history_refill_credits_the_reservoir_alone_with_the_switch_on() { + for on in [false, true] { + let mut gas = tracker(1_000, 100, on); + assert!(gas.record_history_cost(300)); + gas.refill_history(300); + let expected = if on { + (800, 300, 0, 0, 200) + } else { + (1_000, 100, 0, 0, 0) + }; + assert_eq!(figures(&gas), expected, "switch on: {on}"); + } + } + + /// A reservoir a child returns unwinds the caller's spill with the switch off, and becomes the + /// caller's reservoir as it is with it on. + #[test] + fn test_a_returned_reservoir_unwinds_nothing_with_the_switch_on() { + for on in [false, true] { + let mut gas = tracker(1_000, 0, on); + assert!(gas.record_state_cost(300)); + gas.absorb_returned_reservoir(500); + let expected = if on { + (700, 500, 300, 0, 300) + } else { + (1_000, 200, 300, 0, 0) + }; + assert_eq!(figures(&gas), expected, "switch on: {on}"); + } + } + + /// With the switch on a revert puts every charge the frame made, net of what it was given + /// back, into the reservoir, whichever pool paid it, and keeps the count of what regular gas + /// paid; regular gas is left as it was. With it off the spill goes back to regular gas. + #[test] + fn test_a_rollback_puts_every_charge_into_the_reservoir_with_the_switch_on() { + for on in [false, true] { + let mut gas = tracker(1_000, 100, on); + assert!(gas.record_state_cost(300)); + assert!(gas.record_history_cost(50)); + gas.refill_reservoir(20); + gas.rollback_state_gas(); + let expected = if on { + // 100 − 100 − 0 + 20 (refill) + 330 (net) = 350 of reservoir; 750 regular left. + (750, 350, 0, 0, 250) + } else { + (1_000, 100, 0, 0, 0) + }; + assert_eq!(figures(&gas), expected, "switch on: {on}"); + } + } + + /// After a halting frame's rollback, consuming what regular gas paid leaves the reservoir the + /// frame received with the switch on, and changes nothing with it off, where the rollback + /// already credited it to regular gas. + #[test] + fn test_a_halt_gives_back_the_reservoir_the_frame_received() { + for on in [false, true] { + let mut gas = tracker(1_000, 100, on); + assert!(gas.record_state_cost(300)); + assert!(gas.record_history_cost(50)); + gas.refill_reservoir(300); + assert!(gas.record_state_cost_with_legacy_share(200, 80)); + gas.rollback_state_gas(); + gas.consume_regular_paid_charges(); + gas.spend_all(); + assert_eq!(gas.reservoir(), 100, "switch on: {on}"); + assert_eq!(gas.state_gas_spilled(), 0, "switch on: {on}"); + assert_eq!(gas.remaining(), 0, "switch on: {on}"); + } + } + + /// A legacy share is paid from regular gas before the reservoir, which pays the rest; the + /// regular part is counted as paid by regular gas, and the whole charge is state gas. + #[test] + fn test_a_legacy_share_comes_from_regular_gas_before_the_reservoir() { + let mut gas = tracker(1_000, 500, true); + assert!(gas.record_state_cost_with_legacy_share(300, 100)); + assert_eq!(figures(&gas), (900, 300, 300, 0, 100)); + + // The share is capped at the charge. + let mut gas = tracker(1_000, 500, true); + assert!(gas.record_state_cost_with_legacy_share(60, 100)); + assert_eq!(figures(&gas), (940, 500, 60, 0, 60)); + + // What the reservoir cannot pay after the share spills onto regular gas too. + let mut gas = tracker(1_000, 150, true); + assert!(gas.record_state_cost_with_legacy_share(300, 100)); + assert_eq!(figures(&gas), (850, 0, 300, 0, 150)); + } + + /// A share regular gas cannot pay is an out-of-gas whatever the reservoir holds, and leaves the + /// tracker's gas untouched with the failure recorded; so is a share and a spill it cannot pay + /// together. + #[test] + fn test_a_legacy_share_regular_gas_cannot_pay_runs_out_of_gas() { + let mut gas = tracker(99, 1_000, true); + let before = figures(&gas); + assert!(!gas.record_state_cost_with_legacy_share(300, 100)); + assert_eq!(figures(&gas), before); + assert_eq!(gas.failed_charge_remaining(), Some(99)); + + let mut gas = tracker(149, 150, true); + assert!(!gas.record_state_cost_with_legacy_share(300, 100)); + assert_eq!(gas.failed_charge_remaining(), Some(149)); + } + + /// The share draws the withheld part first, as a spill does. + #[test] + fn test_a_legacy_share_draws_the_withheld_part_first() { + let mut gas = tracker(1_000, 500, true); + gas.withhold(300); + assert!(gas.record_state_cost_with_legacy_share(300, 100)); + assert_eq!(gas.withheld(), 200); + assert_eq!(gas.spendable(), 700); + } + + /// A share of zero is the charge EIP-8037 makes, with the switch on or off. + #[test] + fn test_a_legacy_share_of_zero_is_the_plain_state_charge() { + for on in [false, true] { + for (remaining, reservoir, cost) in + [(1_000, 500, 300), (1_000, 100, 300), (200, 50, 300)] + { + let mut plain = tracker(remaining, reservoir, on); + let mut shared = plain; + assert_eq!( + plain.record_state_cost(cost), + shared.record_state_cost_with_legacy_share(cost, 0) + ); + assert_eq!(plain, shared, "{remaining} {reservoir} {cost} {on}"); + } + } + } + + /// A give-back never lowers the count of what regular gas paid with the switch on, so a frame + /// that paid a slot from regular gas and wrote it back still counts what it paid. + #[test] + fn test_no_give_back_lowers_the_count_of_what_regular_gas_paid() { + let mut gas = tracker(1_000, 0, true); + assert!(gas.record_state_cost_with_legacy_share(300, 100)); + assert!(gas.record_history_cost(40)); + gas.refill_reservoir(300); + gas.refill_history(40); + gas.absorb_returned_reservoir(500); + assert_eq!(gas.state_gas_spilled(), 340); + assert_eq!(gas.remaining(), 660); + } +} diff --git a/crates/context/interface/src/cfg/gas_params.rs b/crates/context/interface/src/cfg/gas_params.rs index c78d277f99..7c4c0d856f 100644 --- a/crates/context/interface/src/cfg/gas_params.rs +++ b/crates/context/interface/src/cfg/gas_params.rs @@ -814,6 +814,38 @@ impl GasParams { .saturating_mul(len as u64) } + /// The most of the state gas of a slot an `SSTORE` fills that regular gas pays before the + /// reservoir ([`GasId::sstore_set_state_gas_legacy_share`]). Zero unless the schedule sets it. + #[inline] + pub fn sstore_set_state_gas_legacy_share(&self) -> u64 { + self.get(GasId::sstore_set_state_gas_legacy_share()) + } + + /// The most of the state gas of the account a value `CALL` creates that regular gas pays + /// before the reservoir ([`GasId::new_account_state_gas_legacy_share`]). Zero unless the + /// schedule sets it. + #[inline] + pub fn new_account_state_gas_legacy_share(&self) -> u64 { + self.get(GasId::new_account_state_gas_legacy_share()) + } + + /// The most of the state gas of the account a `SELFDESTRUCT` creates for its beneficiary that + /// regular gas pays before the reservoir + /// ([`GasId::selfdestruct_new_account_state_gas_legacy_share`]). Zero unless the schedule sets + /// it. + #[inline] + pub fn selfdestruct_new_account_state_gas_legacy_share(&self) -> u64 { + self.get(GasId::selfdestruct_new_account_state_gas_legacy_share()) + } + + /// The most of the state gas of the account a `CREATE` or `CREATE2` creates that regular gas + /// pays before the reservoir ([`GasId::create_state_gas_legacy_share`]). Zero unless the + /// schedule sets it. + #[inline] + pub fn create_state_gas_legacy_share(&self) -> u64 { + self.get(GasId::create_state_gas_legacy_share()) + } + /// Used in [GasParams::initial_tx_gas] to calculate the eip7702 per-auth cost. /// /// Pre-Amsterdam this is the pessimistic bundled `PER_EMPTY_ACCOUNT_COST` @@ -1276,6 +1308,18 @@ impl GasId { x if x == Self::tx_account_write_cost().as_u8() => "tx_account_write_cost", x if x == Self::tx_create_access_cost().as_u8() => "tx_create_access_cost", x if x == Self::code_deposit_history_gas().as_u8() => "code_deposit_history_gas", + x if x == Self::sstore_set_state_gas_legacy_share().as_u8() => { + "sstore_set_state_gas_legacy_share" + } + x if x == Self::new_account_state_gas_legacy_share().as_u8() => { + "new_account_state_gas_legacy_share" + } + x if x == Self::selfdestruct_new_account_state_gas_legacy_share().as_u8() => { + "selfdestruct_new_account_state_gas_legacy_share" + } + x if x == Self::create_state_gas_legacy_share().as_u8() => { + "create_state_gas_legacy_share" + } _ => "unknown", } } @@ -1351,6 +1395,14 @@ impl GasId { "tx_account_write_cost" => Some(Self::tx_account_write_cost()), "tx_create_access_cost" => Some(Self::tx_create_access_cost()), "code_deposit_history_gas" => Some(Self::code_deposit_history_gas()), + "sstore_set_state_gas_legacy_share" => Some(Self::sstore_set_state_gas_legacy_share()), + "new_account_state_gas_legacy_share" => { + Some(Self::new_account_state_gas_legacy_share()) + } + "selfdestruct_new_account_state_gas_legacy_share" => { + Some(Self::selfdestruct_new_account_state_gas_legacy_share()) + } + "create_state_gas_legacy_share" => Some(Self::create_state_gas_legacy_share()), _ => None, } } @@ -1641,6 +1693,39 @@ impl GasId { pub const fn code_deposit_history_gas() -> GasId { Self::new(255) } + + /// The legacy share of the state gas of a slot an `SSTORE` fills: the most of that charge + /// regular gas pays before the reservoir pays any of it + /// ([`GasTracker::record_state_cost_with_legacy_share`](crate::cfg::gas::GasTracker::record_state_cost_with_legacy_share)). + /// + /// Zero on every schedule defined here, which makes the charge the one EIP-8037 makes. A chain + /// that keeps what creating state costs in regular gas when a transaction carries a reservoir + /// sets it. A fork id, allocated down from the top of the table below the ids the fork retired. + pub const fn sstore_set_state_gas_legacy_share() -> GasId { + Self::new(245) + } + + /// The legacy share of the state gas of the account a value `CALL` creates for its target: + /// the most of that charge regular gas pays before the reservoir pays any of it, as + /// [`sstore_set_state_gas_legacy_share`](Self::sstore_set_state_gas_legacy_share) is for a + /// slot. Zero on every schedule defined here. + pub const fn new_account_state_gas_legacy_share() -> GasId { + Self::new(244) + } + + /// The legacy share of the state gas of the account a `SELFDESTRUCT` creates for its + /// beneficiary, as [`sstore_set_state_gas_legacy_share`](Self::sstore_set_state_gas_legacy_share) + /// is for a slot. Zero on every schedule defined here. + pub const fn selfdestruct_new_account_state_gas_legacy_share() -> GasId { + Self::new(243) + } + + /// The legacy share of the state gas of the account a `CREATE` or `CREATE2` creates, as + /// [`sstore_set_state_gas_legacy_share`](Self::sstore_set_state_gas_legacy_share) is for a + /// slot. Zero on every schedule defined here. + pub const fn create_state_gas_legacy_share() -> GasId { + Self::new(242) + } } #[cfg(test)] @@ -1714,14 +1799,15 @@ mod tests { ); // The known GasIds are upstream's indices 1-49 (0 is unused) plus the fork's - // `code_deposit_history_gas` at 255, allocated from the top of the table so upstream's - // next sequential id does not collide with it. Every one of them has a name. - let expected_ids: HashSet<u8> = (1..=49).chain([255]).collect(); + // `code_deposit_history_gas` at 255 and the four legacy shares at 242-245, allocated from + // the top of the table so upstream's next sequential id does not collide with them. Every + // one of them has a name. + let expected_ids: HashSet<u8> = (1..=49).chain(242..=245).chain([255]).collect(); assert_eq!(named_ids, expected_ids); assert_eq!( unique_names.len(), - 50, - "Expected 50 unique GasIds, found {}", + 54, + "Expected 54 unique GasIds, found {}", unique_names.len() ); } diff --git a/crates/context/src/cfg.rs b/crates/context/src/cfg.rs index 09a1ba63f1..1b2c1da3c3 100644 --- a/crates/context/src/cfg.rs +++ b/crates/context/src/cfg.rs @@ -186,6 +186,13 @@ pub struct CfgEnv<SPEC = SpecId> { /// [`CfgEnv::enable_amsterdam_eip7708`] does. #[cfg_attr(feature = "serde", serde(default))] pub legacy_journal_semantics: bool, + /// Credits every give-back of state or history gas to the reservoir alone, never to regular + /// gas: a refill, a failed frame's rollback and a reservoir a child returns. revm sets it on + /// the transaction's gas and on every frame's (`GasTracker::reservoir_only_give_backs`). For a + /// chain that keeps a frame's regular gas from rising within the frame; `false`, EIP-8037's + /// tracker, by default. + #[cfg_attr(feature = "serde", serde(default))] + pub reservoir_only_give_backs: bool, } impl CfgEnv { @@ -307,6 +314,7 @@ impl<SPEC> CfgEnv<SPEC> { amsterdam_eip7708_disabled: self.amsterdam_eip7708_disabled, amsterdam_eip8246_delayed_clear_disabled: self.amsterdam_eip8246_delayed_clear_disabled, legacy_journal_semantics: self.legacy_journal_semantics, + reservoir_only_give_backs: self.reservoir_only_give_backs, } } @@ -372,6 +380,13 @@ impl<SPEC> CfgEnv<SPEC> { self.legacy_journal_semantics = enable; self } + + /// Credits every give-back of state or history gas to the reservoir alone; see + /// [`CfgEnv::reservoir_only_give_backs`]. + pub const fn with_reservoir_only_give_backs(mut self, enable: bool) -> Self { + self.reservoir_only_give_backs = enable; + self + } } impl<SPEC: Into<SpecId> + Clone> CfgEnv<SPEC> { @@ -413,6 +428,7 @@ impl<SPEC: Into<SpecId> + Clone> CfgEnv<SPEC> { amsterdam_eip7708_disabled: false, amsterdam_eip8246_delayed_clear_disabled: false, legacy_journal_semantics: false, + reservoir_only_give_backs: false, } } @@ -647,6 +663,11 @@ impl<SPEC: Into<SpecId> + Clone> Cfg for CfgEnv<SPEC> { fn legacy_journal_semantics(&self) -> bool { self.legacy_journal_semantics } + + #[inline] + fn reservoir_only_give_backs(&self) -> bool { + self.reservoir_only_give_backs + } } impl<SPEC: Default + Into<SpecId> + Clone> Default for CfgEnv<SPEC> { diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index 6da838f3b5..f68c1a2dbd 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -19,7 +19,10 @@ use std::string::ToString; /// the frame left returns to `gas`, its reservoir in place of the one `gas` gave it; /// - the EIP-2780 refundable first-frame charge is refunded when no account leaf was created, /// priced through [`Host::state_gas_charge`](context_interface::Host::state_gas_charge) as it -/// was charged; after a halt the regular gas the refund credited is consumed. +/// was charged; after a halt the regular gas the refund credited is consumed. With give-backs +/// to the reservoir alone ([`GasTracker::reservoir_only_give_backs`]) a refund credits no regular +/// gas, so after a halt only the part of the charge the reservoir paid returns, into the +/// reservoir, and the part regular gas paid is consumed with the regular gas. /// /// A chain whose handler overrides `last_frame_result` calls this rather than copying the mainnet /// body, so a step the fork adds here reaches its handler too. It applies its own rules to `gas` @@ -73,12 +76,24 @@ where "state gas price lookup failed".to_string(), )); }; + // With give-backs to the reservoir alone, the part of the charge regular gas paid stays + // spent after a halt. The charge is the last one made before the frame, and every charge + // made there draws the reservoir first, so that part is the last of what the + // transaction's regular gas paid for state and history, which the halted frame added + // nothing to. Without the switch the refill below credits that part to `remaining`, which + // the halt consumes. + let consumed = if instruction_result.is_halt() && gas.reservoir_only_give_backs() { + core::cmp::min(charge, gas.state_gas_spilled()) + } else { + 0 + }; gas.refill_reservoir(charge); // Unlike an inner frame's caller, the transaction ends here: an // exceptional halt consumes all regular gas, including the // spilled portion the refill just credited back to `remaining`. if instruction_result.is_halt() { gas.spend_all(); + gas.set_reservoir(gas.reservoir().saturating_sub(consumed)); } } diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index 64991f508a..dd77209afc 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -159,8 +159,10 @@ impl EthFrame<EthInterpreter> { let reservoir_remaining_gas = inputs.reservoir; let charged_new_account_state_gas = inputs.charged_new_account_state_gas; let charged_state_gas_address = inputs.target_address; - let gas = + let reservoir_only_give_backs = ctx.cfg().reservoir_only_give_backs(); + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas); + gas.set_reservoir_only_give_backs(reservoir_only_give_backs); let return_result = |instruction_result: InstructionResult| { Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome { @@ -210,7 +212,10 @@ impl EthFrame<EthInterpreter> { let is_static = inputs.is_static; let gas_limit = inputs.gas_limit; - if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { + if let Some(mut result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? { + result + .gas + .set_reservoir_only_give_backs(reservoir_only_give_backs); let mut logs = Vec::new(); if result.result.is_ok() { // Preserve the reservoir on the result gas so it can be reimbursed. @@ -243,7 +248,8 @@ impl EthFrame<EthInterpreter> { } // Create interpreter and executes call and push new CallStackFrame. - this.get(EthFrame::invalid).clear( + let frame = this.get(EthFrame::invalid); + frame.clear( FrameData::Call(CallFrame { return_memory_range: inputs.return_memory_offset.clone(), }), @@ -258,6 +264,10 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); + frame + .interpreter + .gas + .set_reservoir_only_give_backs(reservoir_only_give_backs); Ok(ItemOrResult::Item(this.consume())) } @@ -276,6 +286,7 @@ impl EthFrame<EthInterpreter> { ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> { let reservoir_remaining_gas = inputs.reservoir(); let spec = context.cfg().spec().into(); + let reservoir_only_give_backs = context.cfg().reservoir_only_give_backs(); // EIP-8037 refund for the CREATE opcode's upfront `create_state_gas` is // applied uniformly in `return_result` when the create fails (revert, // halt, or early-fail with `address == None`), so early-fail results @@ -285,13 +296,15 @@ impl EthFrame<EthInterpreter> { // — because the created address is not derivable here on the early-fail paths. let charged_state_gas_address = inputs.charged_state_gas_address(); let return_error = |e| { + let mut gas = Gas::new_with_regular_gas_and_reservoir( + inputs.gas_limit(), + reservoir_remaining_gas, + ); + gas.set_reservoir_only_give_backs(reservoir_only_give_backs); Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome { result: InterpreterResult { result: e, - gas: Gas::new_with_regular_gas_and_reservoir( - inputs.gas_limit(), - reservoir_remaining_gas, - ), + gas, output: Bytes::new(), }, address: None, @@ -359,7 +372,8 @@ impl EthFrame<EthInterpreter> { }; let gas_limit = inputs.gas_limit(); - this.get(EthFrame::invalid).clear( + let frame = this.get(EthFrame::invalid); + frame.clear( FrameData::Create(CreateFrame { created_address }), FrameInput::Create(inputs), depth, @@ -372,6 +386,10 @@ impl EthFrame<EthInterpreter> { reservoir_remaining_gas, checkpoint, ); + frame + .interpreter + .gas + .set_reservoir_only_give_backs(reservoir_only_give_backs); Ok(ItemOrResult::Item(this.consume())) } @@ -629,6 +647,14 @@ impl EthFrame<EthInterpreter> { /// - net state gas, net history gas, the spilled portion, and the refund counter /// persist only on success; on revert/halt the child's state changes roll back /// and contribute nothing. +/// +/// With [`GasTracker::reservoir_only_give_backs`] set, a failing child's rollback puts every +/// charge it made into its reservoir, and none into its regular gas: a revert returns the unspent +/// regular gas and a reservoir that holds those charges, and a halt consumes the regular gas with +/// what it paid of the charges ([`GasTracker::consume_regular_paid_charges`]) and returns the +/// reservoir the child received. The parent adopts the returned reservoir without unwinding +/// anything, and adds the regular gas the child paid for state and history to its own count on a +/// revert as on a success, since that gas is not given back to regular gas. #[inline] pub const fn handle_reservoir_remaining_gas( instruction_result: InstructionResult, @@ -643,13 +669,21 @@ pub const fn handle_reservoir_remaining_gas( if instruction_result.is_halt() { // Exceptional halt consumes the child's regular gas (including the spill // just credited back by `rollback_state_gas`); the reservoir is left - // restored to the inherited value for the parent. + // restored to the inherited value for the parent. With give-backs to the reservoir + // alone, the rollback put what regular gas paid into the reservoir, which the halt takes + // out again; otherwise nothing is left to take. + child_gas.consume_regular_paid_charges(); child_gas.spend_all(); } // Merge the settled child into the parent. if instruction_result.is_ok_or_revert() { parent_gas.erase_cost(child_gas.remaining()); + // What the child's regular gas paid for state and history: on a success, so a later + // rollback of the parent can return it; on a revert, only with give-backs to the + // reservoir alone, where the rollback kept the count and returned the charges in the + // reservoir. A revert's rollback zeroes it otherwise, and a halt's consumption always. + parent_gas.add_state_gas_spilled(child_gas.state_gas_spilled()); } if instruction_result.is_ok() { // Parent may have already charged state gas (e.g. new_account + create) @@ -662,7 +696,6 @@ pub const fn handle_reservoir_remaining_gas( .state_gas_spent() .saturating_add(child_gas.state_gas_spent()), ); - parent_gas.add_state_gas_spilled(child_gas.state_gas_spilled()); // History gas rides the same success-only merge, signed for the same reason: a // failing child rolled it back along with its state gas, so it contributes // nothing. Zero on any chain that never charges history gas. @@ -1022,4 +1055,98 @@ mod tests { ); } } + /// A tracker with give-backs to the reservoir alone. + fn reservoir_only(limit: u64, reservoir: u64) -> GasTracker { + let mut gas = GasTracker::new(limit, limit, reservoir); + gas.set_reservoir_only_give_backs(true); + gas + } + + /// `(remaining, reservoir, state_spent, spilled)` of a tracker. + const fn figures(gas: &GasTracker) -> (u64, u64, i64, u64) { + ( + gas.remaining(), + gas.reservoir(), + gas.state_gas_spent(), + gas.state_gas_spilled(), + ) + } + + /// With give-backs to the reservoir alone, the sibling refill of the first test lands in the + /// reservoir the sibling returns, and its caller's regular gas stays what the first child left + /// it: the reservoir is adopted without unwinding the regular gas the first child paid. + #[test] + fn test_with_give_backs_to_the_reservoir_a_sibling_refill_leaves_regular_gas_spent() { + const STATE_GAS: u64 = 200; + const CHILD_GAS: u64 = 500; + + let mut parent = reservoir_only(1_000, 0); + assert!(parent.record_regular_cost(CHILD_GAS)); + let mut child_a = reservoir_only(CHILD_GAS, 0); + assert!(child_a.record_state_cost(STATE_GAS)); + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut parent, &mut child_a); + assert_eq!(figures(&parent), (800, 0, 200, 200)); + + assert!(parent.record_regular_cost(CHILD_GAS)); + let mut child_b = reservoir_only(CHILD_GAS, parent.reservoir()); + child_b.refill_reservoir(STATE_GAS); + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut parent, &mut child_b); + assert_eq!( + figures(&parent), + (800, 200, 0, 200), + "the refill is reservoir, and what regular gas paid stays counted" + ); + } + + /// With give-backs to the reservoir alone a child that succeeds hands back what it left of + /// both pools; one that reverts puts every charge it made, net of the give-backs it received, + /// into the reservoir it returns, and its caller counts what the child's regular gas paid as + /// its own; one that halts returns the reservoir it received and consumes its regular gas with + /// what it paid of the charges. + #[test] + fn test_with_give_backs_to_the_reservoir_a_failed_child_returns_its_charges_as_reservoir() { + for (result, expected) in [ + (InstructionResult::Stop, (9_700, 50, 1_250, 300)), + (InstructionResult::Revert, (9_700, 1_300, 0, 300)), + (InstructionResult::OutOfGas, (5_000, 1_000, 0, 0)), + ] { + let mut parent = reservoir_only(10_000, 1_000); + assert!(parent.record_regular_cost(5_000)); + let mut child = reservoir_only(5_000, parent.reservoir()); + // 1,000 of the charge from the reservoir and 300 from regular gas; 50 given back. + assert!(child.record_state_cost(1_300)); + child.refill_reservoir(50); + + handle_reservoir_remaining_gas(result, &mut parent, &mut child); + + assert_eq!(figures(&parent), expected, "{result:?}"); + } + } + + /// A reverted grandchild's reservoir, which holds what its regular gas paid, stays in the + /// reservoir of the frame it returned into: when that frame reverts too, it returns its own + /// charges and the grandchild's on top of the reservoir it received; when it halts, it returns + /// the reservoir it received and nothing more. + #[test] + fn test_with_give_backs_to_the_reservoir_a_failed_frame_keeps_a_failed_childs_reservoir() { + for (result, reservoir) in [ + (InstructionResult::Revert, 1_200), + (InstructionResult::OutOfGas, 1_000), + ] { + let mut a = reservoir_only(10_000, 1_000); + assert!(a.record_regular_cost(5_000)); + let mut b = reservoir_only(5_000, a.reservoir()); + assert!(b.record_state_cost(200)); + assert!(b.record_regular_cost(2_000)); + let mut c = reservoir_only(2_000, b.reservoir()); + // 800 from the reservoir C received, 200 from its regular gas. + assert!(c.record_state_cost(1_000)); + handle_reservoir_remaining_gas(InstructionResult::Revert, &mut b, &mut c); + assert_eq!(figures(&b), (4_800, 1_000, 200, 200)); + + handle_reservoir_remaining_gas(result, &mut a, &mut b); + + assert_eq!(a.reservoir(), reservoir, "{result:?}"); + } + } } diff --git a/crates/handler/src/handler.rs b/crates/handler/src/handler.rs index 8892b6e6ac..805b6f3f08 100644 --- a/crates/handler/src/handler.rs +++ b/crates/handler/src/handler.rs @@ -212,14 +212,18 @@ pub trait Handler { /// The gas limit is the transaction gas limit, `remaining` is the regular /// gas budget left after the intrinsic gas (constrained by the EIP-8037 /// `TX_MAX_GAS_LIMIT` cap) and `reservoir` is the state gas pool, so the - /// intrinsic gas is accounted as already spent. + /// intrinsic gas is accounted as already spent. Whether its give-backs credit the reservoir + /// alone is the configuration's (`Cfg::reservoir_only_give_backs`), as it is for every frame's + /// gas. #[inline] fn tx_gas(&self, evm: &mut Self::Evm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { let ctx = evm.ctx_ref(); let tx_gas_limit = ctx.tx().gas_limit(); let (remaining, reservoir) = init_and_floor_gas .initial_gas_and_reservoir(tx_gas_limit, ctx.cfg().tx_gas_limit_cap()); - GasTracker::new(tx_gas_limit, remaining, reservoir) + let mut gas = GasTracker::new(tx_gas_limit, remaining, reservoir); + gas.set_reservoir_only_give_backs(ctx.cfg().reservoir_only_give_backs()); + gas } /// Prepares the EVM state for execution. diff --git a/crates/handler/tests/reservoir_only_give_backs.rs b/crates/handler/tests/reservoir_only_give_backs.rs new file mode 100644 index 0000000000..5b431963a8 --- /dev/null +++ b/crates/handler/tests/reservoir_only_give_backs.rs @@ -0,0 +1,547 @@ +//! Give-backs to the reservoir alone (`Cfg::reservoir_only_give_backs`) and the legacy share of a +//! state charge, through the mainnet handler on Amsterdam. +//! +//! With the switch off and every legacy share zero, which is the default, the handler is +//! EIP-8037's: the rest of this crate's tests run that way. These pin what the switch and the +//! shares change, each against the same transaction without them. + +use bytecode::opcode::{ + CALL, CODECOPY, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH32, PUSH4, RETURN, + REVERT, SELFDESTRUCT, SSTORE, STOP, +}; +use context::{ + result::{EVMError, ExecutionResult, HaltReason}, + Context, ContextSetters, Evm, TxEnv, +}; +use context_interface::{cfg::GasId, Cfg, ContextTr, Database}; +use database::{CacheDB, EmptyDB, BENCH_CALLER}; +use interpreter::{interpreter_action::FrameInit, GasTracker, InstructionResult}; +use primitives::{address, eip8037, hardfork::SpecId, Address, Bytes, TxKind, U256}; +use revm_handler::{ + instructions::EthInstructions, post_execution, EthPrecompiles, EvmTr, FrameResult, Handler, + ItemOrResult, MainContext, MainnetContext, MainnetEvm, +}; +use state::{AccountInfo, Bytecode}; +use std::cell::Cell; + +type Db = CacheDB<EmptyDB>; +type DbError = <Db as Database>::Error; +type TestContext = MainnetContext<Db>; +type TestEvm = MainnetEvm<TestContext>; +type TestError = EVMError<DbError>; + +/// Contract the transaction calls. +const CONTRACT: Address = address!("0x000000000000000000000000000000000000c0de"); +/// Contract [`CONTRACT`] calls. +const CHILD: Address = address!("0x000000000000000000000000000000000000c41d"); +/// An address the state holds no account for. +const EMPTY: Address = address!("0x000000000000000000000000000000000000e3e3"); + +/// Regular gas budget of a transaction; the gas limit above it is the reservoir. +const REGULAR_CAP: u64 = 2_000_000; +/// A reservoir that pays every state charge here. +const RESERVOIR: u64 = 1_000_000; + +/// State gas of a fresh slot. +const SSTORE_SET: u64 = eip8037::SSTORE_SET_BYTES * eip8037::CPSB_GLAMSTERDAM; +/// State gas of a new or created account. +const NEW_ACCOUNT: u64 = eip8037::NEW_ACCOUNT_BYTES * eip8037::CPSB_GLAMSTERDAM; + +/// The legacy shares a chain that keeps its pre-Amsterdam prices in regular gas would set. +const SLOT_SHARE: u64 = 10_000; +const CALL_SHARE: u64 = 25_000; +const SELFDESTRUCT_SHARE: u64 = 16_000; +const CREATE_SHARE: u64 = 20_000; + +/// Bytecode under construction. +#[derive(Default)] +struct Code(Vec<u8>); + +impl Code { + fn op(mut self, op: u8) -> Self { + self.0.push(op); + self + } + + /// Pushes `value` as a four-byte word, so the gas the code costs does not depend on it. + fn push(mut self, value: u64) -> Self { + let value = u32::try_from(value).expect("test amounts fit in four bytes"); + self.0.push(PUSH4); + self.0.extend_from_slice(&value.to_be_bytes()); + self + } + + fn push_address(mut self, address: Address) -> Self { + self.0.push(PUSH20); + self.0.extend_from_slice(address.as_slice()); + self + } + + /// Writes `value` to slot zero. + fn sstore(self, value: u64) -> Self { + self.push(value).push(0).op(SSTORE) + } + + /// `CALL(gas, to, value, 0, 0, 0, 0)`, dropping the success flag; `gas` of `None` forwards + /// all the call may. + fn call(self, gas: Option<u64>, to: Address, value: u64) -> Self { + let code = self + .op(PUSH0) + .op(PUSH0) + .op(PUSH0) + .op(PUSH0) + .push(value) + .push_address(to); + let code = match gas { + Some(gas) => code.push(gas), + None => code.op(GAS), + }; + code.op(CALL).op(POP) + } + + /// `CREATE` with [`initcode`], which this code carries after its last instruction. + fn create_and_stop(self) -> Self { + let initcode = initcode(); + let len = initcode.len() as u64; + let with_offset = |offset| { + Code(self.0.clone()) + .push(len) + .push(offset) + .op(PUSH0) + .op(CODECOPY) + .push(len) + .op(PUSH0) + .op(PUSH0) + .op(CREATE) + .op(POP) + .op(STOP) + }; + // Four-byte pushes keep the prefix length independent of the offset it carries. + let offset = with_offset(0).0.len() as u64; + let mut code = with_offset(offset); + code.0.extend_from_slice(&initcode); + code + } + + fn revert(self) -> Self { + self.op(PUSH0).op(PUSH0).op(REVERT) + } + + fn build(self) -> Bytecode { + Bytecode::new_raw(Bytes::from(self.0)) + } +} + +/// Initcode that deploys one `STOP` byte. +fn initcode() -> Vec<u8> { + vec![PUSH1, STOP, PUSH0, MSTORE, PUSH1, 1, PUSH1, 31, RETURN] +} + +/// A frame's gas as it returned, before its caller settled it. +#[derive(Clone, Copy, Debug)] +struct Returned { + result: InstructionResult, + gas: GasTracker, +} + +/// The mainnet handler, recording gas as frames return and settle. +#[derive(Default)] +struct Observer { + returned: Vec<Returned>, + settled: Cell<Option<GasTracker>>, +} + +impl Observer { + fn record(&mut self, result: &FrameResult) { + self.returned.push(Returned { + result: result.instruction_result(), + gas: *result.gas().tracker(), + }); + } +} + +impl Handler for Observer { + type Evm = TestEvm; + type Error = TestError; + type HaltReason = HaltReason; + + /// The default loop, recording each frame result before it goes back to its caller. + fn run_exec_loop( + &mut self, + evm: &mut TestEvm, + first_frame_input: FrameInit, + ) -> Result<FrameResult, TestError> { + if let ItemOrResult::Result(result) = evm.frame_init(first_frame_input)? { + self.record(&result); + return Ok(result); + } + loop { + let result = match evm.frame_run()? { + ItemOrResult::Item(init) => match evm.frame_init(init)? { + ItemOrResult::Item(_) => continue, + ItemOrResult::Result(result) => result, + }, + ItemOrResult::Result(mut result) => { + evm.frame_run_result(&mut result)?; + result + } + }; + self.record(&result); + if let Some(result) = evm.frame_return_result(result)? { + return Ok(result); + } + } + } + + /// Records the settled transaction-level gas, then refunds as the default does. + fn refund( + &self, + evm: &mut TestEvm, + exec_result: &mut FrameResult, + eip7702_refund: i64, + ) -> Result<(), TestError> { + self.settled.set(Some(*exec_result.gas().tracker())); + post_execution::refund( + evm.ctx().cfg().gas_params(), + exec_result.gas_mut(), + eip7702_refund, + ); + Ok(()) + } +} + +/// What the observed handler saw of one transaction. +struct Run { + result: ExecutionResult, + /// Every frame's gas as it returned, innermost first. + returned: Vec<Returned>, + /// The transaction-level gas once the first frame settled into it. + settled: GasTracker, +} + +impl Run { + /// The transaction's own frame, as it returned. + fn top(&self) -> Returned { + *self.returned.last().expect("the transaction ran a frame") + } + + /// The one frame [`CONTRACT`] started, as it returned. + fn child(&self) -> Returned { + assert_eq!(self.returned.len(), 2, "one child and the top frame"); + self.returned[0] + } +} + +/// How a run is configured: the switch, and whether the schedule sets the legacy shares. +#[derive(Clone, Copy, Debug)] +struct Setting { + reservoir_only: bool, + shares: bool, +} + +const UPSTREAM: Setting = Setting { + reservoir_only: false, + shares: false, +}; +const SATIN: Setting = Setting { + reservoir_only: true, + shares: true, +}; +const RESERVOIR_ONLY: Setting = Setting { + reservoir_only: true, + shares: false, +}; + +fn context(db: Db, setting: Setting) -> TestContext { + Context::mainnet().with_db(db).modify_cfg_chained(|cfg| { + cfg.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM); + cfg.tx_gas_limit_cap = Some(REGULAR_CAP); + cfg.reservoir_only_give_backs = setting.reservoir_only; + if setting.shares { + cfg.gas_params.override_gas([ + (GasId::sstore_set_state_gas_legacy_share(), SLOT_SHARE), + (GasId::new_account_state_gas_legacy_share(), CALL_SHARE), + ( + GasId::selfdestruct_new_account_state_gas_legacy_share(), + SELFDESTRUCT_SHARE, + ), + (GasId::create_state_gas_legacy_share(), CREATE_SHARE), + ]); + } + }) +} + +fn run(ctx: TestContext, tx: TxEnv) -> Run { + let spec = ctx.cfg.spec; + let instructions = EthInstructions::new_mainnet_with_spec(spec); + let mut evm: TestEvm = Evm::new(ctx, instructions, EthPrecompiles::new(spec)); + evm.ctx.set_tx(tx); + + let mut observer = Observer::default(); + let result = observer.run(&mut evm).expect("transaction runs"); + Run { + result, + returned: observer.returned, + settled: observer.settled.get().expect("post-execution ran"), + } +} + +/// A funded sender, [`CONTRACT`] holding `contract` and a balance of `balance`, and [`CHILD`] +/// holding `child`. +fn db(contract: Code, balance: u64, child: Code) -> Db { + let mut db = Db::default(); + db.insert_account_info( + BENCH_CALLER, + AccountInfo::from_balance(U256::from(10u128.pow(21))), + ); + for (address, code, balance) in [(CONTRACT, contract, balance), (CHILD, child, 0)] { + let code = code.build(); + db.insert_account_info( + address, + AccountInfo::new(U256::from(balance), 1, code.hash_slow(), code), + ); + } + db +} + +fn tx(kind: TxKind, data: Vec<u8>, gas_limit: u64) -> TxEnv { + TxEnv::builder_for_bench() + .kind(kind) + .data(Bytes::from(data)) + .gas_price(0) + .gas_limit(gas_limit) + .build_fill() +} + +/// Runs a call to [`CONTRACT`] with `reservoir` above the regular budget. +fn call(setting: Setting, contract: Code, balance: u64, child: Code, reservoir: u64) -> Run { + run( + context(db(contract, balance, child), setting), + tx(TxKind::Call(CONTRACT), Vec::new(), REGULAR_CAP + reservoir), + ) +} + +/// `(regular gas left, reservoir)` of a tracker. +const fn pools(gas: &GasTracker) -> (u64, u64) { + (gas.remaining(), gas.reservoir()) +} + +/// The handler gives the transaction's gas and every frame's the switch the configuration sets. +#[test] +fn test_every_frames_gas_carries_the_configured_switch() { + for setting in [UPSTREAM, RESERVOIR_ONLY] { + let run = call( + setting, + Code::default().call(Some(100_000), CHILD, 0).op(STOP), + 0, + Code::default().op(STOP), + RESERVOIR, + ); + assert_eq!(run.returned.len(), 2); + for returned in &run.returned { + assert_eq!( + returned.gas.reservoir_only_give_backs(), + setting.reservoir_only, + "{setting:?}" + ); + } + assert_eq!( + run.settled.reservoir_only_give_backs(), + setting.reservoir_only + ); + } +} + +/// A fresh slot's legacy share comes from regular gas before the reservoir pays the rest: the +/// frame ends with the share less regular gas and the share more reservoir, the charge and the +/// total the same. +#[test] +fn test_a_fresh_slot_takes_its_legacy_share_from_regular_gas_first() { + let code = || Code::default().sstore(1).op(STOP); + let plain = call(RESERVOIR_ONLY, code(), 0, Code::default(), RESERVOIR); + let shared = call(SATIN, code(), 0, Code::default(), RESERVOIR); + + let (regular, reservoir) = pools(&plain.top().gas); + assert_eq!(reservoir, RESERVOIR - SSTORE_SET); + assert_eq!( + pools(&shared.top().gas), + (regular - SLOT_SHARE, reservoir + SLOT_SHARE) + ); + assert_eq!(shared.top().gas.state_gas_spent(), SSTORE_SET as i64); + assert_eq!( + shared.result.gas().total_gas_spent(), + plain.result.gas().total_gas_spent() + ); +} + +/// A frame whose regular gas cannot pay a fresh slot's legacy share runs out of gas, whatever +/// its reservoir holds; one regular gas more pays it. +#[test] +fn test_a_legacy_share_regular_gas_cannot_pay_is_an_out_of_gas() { + let child = || Code::default().sstore(1).op(STOP); + // What the child spends of its regular gas without a share. + let measured = call( + RESERVOIR_ONLY, + Code::default().call(Some(100_000), CHILD, 0).op(STOP), + 0, + child(), + RESERVOIR, + ); + let returned = measured.child(); + assert_eq!(returned.result, InstructionResult::Stop); + let regular = returned.gas.limit() - returned.gas.remaining(); + + for (forward, result) in [ + (regular + SLOT_SHARE - 1, InstructionResult::OutOfGas), + (regular + SLOT_SHARE, InstructionResult::Stop), + ] { + let run = call( + SATIN, + Code::default().call(Some(forward), CHILD, 0).op(STOP), + 0, + child(), + RESERVOIR, + ); + assert_eq!(run.child().result, result, "forward {forward}"); + } +} + +/// The share of a value call's new account is taken before the forward is computed, so the +/// child is forwarded 63/64 of what the share left. +#[test] +fn test_a_value_calls_new_account_share_is_taken_before_the_forward() { + let contract = || Code::default().call(None, EMPTY, 1).op(STOP); + let plain = call(RESERVOIR_ONLY, contract(), 1, Code::default(), RESERVOIR); + let shared = call(SATIN, contract(), 1, Code::default(), RESERVOIR); + + let forward = |remaining: u64| remaining - remaining / 64; + let plain_limit = plain.child().gas.limit(); + let shared_limit = shared.child().gas.limit(); + let stipend = 2_300; + // Invert the plain forward to the regular gas the caller held before it. + let held = (0..64) + .map(|r| (plain_limit - stipend) * 64 / 63 + r) + .find(|held| forward(*held) == plain_limit - stipend) + .expect("the forward inverts"); + assert_eq!(shared_limit - stipend, forward(held - CALL_SHARE)); + assert_eq!( + shared.top().gas.reservoir() - plain.top().gas.reservoir(), + CALL_SHARE, + "regular gas paid the share, and the reservoir the rest" + ); +} + +/// The share of a creation's account is taken before the forward is computed. +#[test] +fn test_a_creations_account_share_is_taken_before_the_forward() { + let contract = || Code::default().create_and_stop(); + let plain = call(RESERVOIR_ONLY, contract(), 0, Code::default(), RESERVOIR); + let shared = call(SATIN, contract(), 0, Code::default(), RESERVOIR); + let forward = |remaining: u64| remaining - remaining / 64; + + let plain_limit = plain.child().gas.limit(); + let held = (0..64) + .map(|r| plain_limit * 64 / 63 + r) + .find(|held| forward(*held) == plain_limit) + .expect("the forward inverts"); + assert_eq!(shared.child().gas.limit(), forward(held - CREATE_SHARE)); +} + +/// A `SELFDESTRUCT` that creates its beneficiary takes that account's share from regular gas +/// before the reservoir. +#[test] +fn test_a_selfdestructs_new_beneficiary_takes_its_share_from_regular_gas_first() { + let contract = || Code::default().push_address(EMPTY).op(SELFDESTRUCT); + let plain = call(RESERVOIR_ONLY, contract(), 1, Code::default(), RESERVOIR); + let shared = call(SATIN, contract(), 1, Code::default(), RESERVOIR); + + let (regular, reservoir) = pools(&plain.top().gas); + assert_eq!(reservoir, RESERVOIR - NEW_ACCOUNT); + assert_eq!( + pools(&shared.top().gas), + (regular - SELFDESTRUCT_SHARE, reservoir + SELFDESTRUCT_SHARE) + ); +} + +/// A slot written and written back gives its state gas back into the reservoir with the switch +/// on, though regular gas paid it, and to regular gas with the switch off. +#[test] +fn test_a_slot_written_back_gives_its_state_gas_to_the_reservoir() { + let code = || Code::default().sstore(1).sstore(0).op(STOP); + let upstream = call(UPSTREAM, code(), 0, Code::default(), 0); + let reservoir_only = call(RESERVOIR_ONLY, code(), 0, Code::default(), 0); + + let (regular, reservoir) = pools(&upstream.top().gas); + assert_eq!(reservoir, 0); + assert_eq!( + pools(&reservoir_only.top().gas), + (regular - SSTORE_SET, SSTORE_SET) + ); + assert_eq!( + reservoir_only.top().gas.state_gas_spilled(), + SSTORE_SET, + "what regular gas paid stays counted" + ); + assert_eq!( + reservoir_only.result.gas().total_gas_spent(), + upstream.result.gas().total_gas_spent(), + "the reservoir returns to the sender with the regular gas" + ); +} + +/// A child that pays a fresh slot from regular gas and reverts returns that charge in its +/// reservoir with the switch on, and as regular gas with it off: its caller holds the charge's +/// less regular gas and the charge more reservoir. +#[test] +fn test_a_reverting_child_returns_its_regular_paid_charge_as_reservoir() { + let contract = || Code::default().call(Some(500_000), CHILD, 0).op(STOP); + let child = || Code::default().sstore(1).revert(); + let upstream = call(UPSTREAM, contract(), 0, child(), 0); + let reservoir_only = call(RESERVOIR_ONLY, contract(), 0, child(), 0); + + assert_eq!(upstream.child().result, InstructionResult::Revert); + let (regular, reservoir) = pools(&upstream.top().gas); + assert_eq!(reservoir, 0); + assert_eq!( + pools(&reservoir_only.top().gas), + (regular - SSTORE_SET, SSTORE_SET) + ); + assert_eq!( + reservoir_only.top().gas.state_gas_spilled(), + SSTORE_SET, + "the caller counts what the child's regular gas paid" + ); +} + +/// A child that pays a fresh slot from regular gas and halts returns the reservoir it received, +/// with the switch on as with it off: what regular gas paid is consumed with its regular gas, and +/// its caller ends as it does without the switch. +#[test] +fn test_a_halting_child_returns_the_reservoir_it_received() { + let contract = || Code::default().call(Some(500_000), CHILD, 0).op(STOP); + let child = || Code::default().sstore(1).op(INVALID); + let upstream = call(UPSTREAM, contract(), 0, child(), 0); + let reservoir_only = call(RESERVOIR_ONLY, contract(), 0, child(), 0); + + assert_eq!(upstream.child().result, InstructionResult::InvalidFEOpcode); + assert_eq!(upstream.top().gas.reservoir(), 0); + assert_eq!(pools(&reservoir_only.top().gas), pools(&upstream.top().gas)); + assert_eq!(reservoir_only.top().gas.state_gas_spilled(), 0); +} + +/// A creation transaction whose frame halts gives back, with the switch on, the part of its +/// created account's state gas the reservoir paid, and consumes the part regular gas paid, as the +/// tracker without the switch does. +#[test] +fn test_a_halting_first_frame_gives_back_only_what_the_reservoir_paid_of_its_charge() { + let reservoir = NEW_ACCOUNT / 3; + for setting in [UPSTREAM, RESERVOIR_ONLY] { + let run = run( + context(db(Code::default(), 0, Code::default()), setting), + tx(TxKind::Create, vec![INVALID], REGULAR_CAP + reservoir), + ); + assert_eq!(run.top().result, InstructionResult::InvalidFEOpcode); + assert_eq!(pools(&run.settled), (0, reservoir), "{setting:?}"); + assert!(matches!(run.result, ExecutionResult::Halt { .. })); + } +} diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index 796eeaed50..e5781e8afa 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -236,6 +236,27 @@ impl Gas { self.tracker.refill_reservoir(amount); } + /// Consumes, after the rollback of a frame that halts, the part of its charges regular gas + /// paid. See [`GasTracker::consume_regular_paid_charges`]. + #[inline] + pub const fn consume_regular_paid_charges(&mut self) { + self.tracker.consume_regular_paid_charges(); + } + + /// Whether every give-back of state or history gas credits the reservoir alone. See + /// [`GasTracker::reservoir_only_give_backs`]. + #[inline] + pub const fn reservoir_only_give_backs(&self) -> bool { + self.tracker.reservoir_only_give_backs() + } + + /// Sets whether every give-back of state or history gas credits the reservoir alone. See + /// [`GasTracker::set_reservoir_only_give_backs`]. + #[inline] + pub const fn set_reservoir_only_give_backs(&mut self, on: bool) { + self.tracker.set_reservoir_only_give_backs(on); + } + /// Erases a gas cost from remaining (returns gas from child frame). #[inline] pub const fn erase_cost(&mut self, returned: u64) { @@ -353,6 +374,20 @@ impl Gas { self.tracker.record_history_cost(cost) } + /// Records a state gas cost that takes its legacy share, `min(cost, legacy_share)`, from + /// `gas_left` before it draws the reservoir. See + /// [`GasTracker::record_state_cost_with_legacy_share`]. + #[inline] + #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"] + pub const fn record_state_cost_with_legacy_share( + &mut self, + cost: u64, + legacy_share: u64, + ) -> bool { + self.tracker + .record_state_cost_with_legacy_share(cost, legacy_share) + } + /// Records a regular gas cost: deducts from the spendable part of `remaining` only. /// Does not affect the reservoir. /// diff --git a/crates/interpreter/src/instructions/contract.rs b/crates/interpreter/src/instructions/contract.rs index bd33affeeb..eeb8c8e8ea 100644 --- a/crates/interpreter/src/instructions/contract.rs +++ b/crates/interpreter/src/instructions/contract.rs @@ -148,7 +148,8 @@ pub fn create<const IS_CREATE2: bool, IT: ITy, H: Host + ?Sized>( .host .state_gas_charge(charge) .ok_or(InstructionResult::FatalExternalError)?; - state_gas!(context.interpreter, price); + let share = context.host.gas_params().create_state_gas_legacy_share(); + state_gas_with_legacy_share!(context.interpreter, price, share); create_inputs.set_charged_create_state_gas(true); create_inputs.set_charged_state_gas_address(created_address); } diff --git a/crates/interpreter/src/instructions/contract/call_helpers.rs b/crates/interpreter/src/instructions/contract/call_helpers.rs index 78f67d1a34..5e7c6d8744 100644 --- a/crates/interpreter/src/instructions/contract/call_helpers.rs +++ b/crates/interpreter/src/instructions/contract/call_helpers.rs @@ -106,13 +106,19 @@ pub(super) fn load_acc_and_calc_forward<H: Host + ?Sized>( let (gas, state_gas_cost, bytecode, code_hash) = load_account_delegated_handle_error(context, to, transfers_value, create_empty_account)?; let charged_new_account_state_gas = state_gas_cost > 0; - let interpreter = &mut context.interpreter; // deduct dynamic gas. - gas!(interpreter, gas); + gas!(context.interpreter, gas); - // deduct state gas (EIP-8037) if any. - state_gas!(interpreter, state_gas_cost); + // deduct state gas (EIP-8037) if any, its legacy share first from regular gas, before the + // forward is computed. + if charged_new_account_state_gas { + let legacy_share = context + .host + .gas_params() + .new_account_state_gas_legacy_share(); + state_gas_with_legacy_share!(context.interpreter, state_gas_cost, legacy_share); + } let interpreter = &mut context.interpreter; let host = &mut context.host; diff --git a/crates/interpreter/src/instructions/host.rs b/crates/interpreter/src/instructions/host.rs index 11bfca24eb..532822fa01 100644 --- a/crates/interpreter/src/instructions/host.rs +++ b/crates/interpreter/src/instructions/host.rs @@ -259,7 +259,11 @@ pub fn sstore<IT: ITy, H: Host + ?Sized>(context: Ictx<'_, H, IT>) -> Result { .state_gas_charge(charge) .ok_or(InstructionResult::FatalExternalError)?; if charges_state_gas { - state_gas!(context.interpreter, price); + let share = context + .host + .gas_params() + .sstore_set_state_gas_legacy_share(); + state_gas_with_legacy_share!(context.interpreter, price, share); } // EIP-8037 issue #2: 0→x→0 storage restoration refills the reservoir // directly rather than routing the state gas through the capped refund @@ -397,7 +401,11 @@ pub fn selfdestruct<IT: ITy, H: Host + ?Sized>(context: Ictx<'_, H, IT>) -> Resu .host .state_gas_charge(charge) .ok_or(InstructionResult::FatalExternalError)?; - state_gas!(context.interpreter, price); + let share = context + .host + .gas_params() + .selfdestruct_new_account_state_gas_legacy_share(); + state_gas_with_legacy_share!(context.interpreter, price, share); } if !res.previously_destroyed { diff --git a/crates/interpreter/src/instructions/macros.rs b/crates/interpreter/src/instructions/macros.rs index a5f5503141..96ce92adc1 100644 --- a/crates/interpreter/src/instructions/macros.rs +++ b/crates/interpreter/src/instructions/macros.rs @@ -41,6 +41,23 @@ macro_rules! state_gas { }}; } +/// Records a state gas cost (EIP-8037) that takes its legacy share, `min(gas, share)`, from +/// regular gas before it draws the reservoir, and fails the instruction if the frame's regular gas +/// cannot pay the share and what the reservoir cannot. A share of zero is [`state_gas!`]. +#[macro_export] +#[collapse_debuginfo(yes)] +macro_rules! state_gas_with_legacy_share { + ($interpreter:expr, $gas:expr, $share:expr) => {{ + if !$interpreter + .gas + .record_state_cost_with_legacy_share($gas, $share) + { + $crate::primitives::hints_util::cold_path(); + return Err($crate::InstructionResult::OutOfGas); + } + }}; +} + /// Records a `gas` cost and fails the instruction if it would exceed the available gas. #[macro_export] #[collapse_debuginfo(yes)] diff --git a/crates/interpreter/tests/start_marks.rs b/crates/interpreter/tests/start_marks.rs index 83bdce5a7b..22c4570134 100644 --- a/crates/interpreter/tests/start_marks.rs +++ b/crates/interpreter/tests/start_marks.rs @@ -10,11 +10,13 @@ use revm_interpreter::{ /// The derived debug output of these values before the marks existed. const TRACKER: &str = "GasTracker { gas_limit: 100, remaining: 90, reservoir: 5, \ state_gas_spent: 0, state_gas_spilled: 0, history_gas_spent: 0, refunded: 3, withheld: 0, \ - withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false }"; + withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, \ + reservoir_only_give_backs: false }"; const RESULT: &str = "InterpreterResult { result: Stop, output: 0x, gas: Gas { tracker: \ GasTracker { gas_limit: 10, remaining: 10, reservoir: 0, state_gas_spent: 0, \ state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, withheld_crossing: \ - None, failed_charge_remaining: 0, failed_charge_recorded: false }, memory: MemoryGas { \ + None, failed_charge_remaining: 0, failed_charge_recorded: false, \ + reservoir_only_give_backs: false }, memory: MemoryGas { \ words_num: 0, expansion_cost: 0 } } }"; const fn tracker() -> GasTracker { From 41097153bafb0b4e3e10cbe55fc6b57cfcff81f1 Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 13 Nov 2026 12:31:32 +0800 Subject: [PATCH 109/110] test(handler): drop an unused import from the give-back tests --- crates/handler/tests/reservoir_only_give_backs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/handler/tests/reservoir_only_give_backs.rs b/crates/handler/tests/reservoir_only_give_backs.rs index 5b431963a8..0a871a5666 100644 --- a/crates/handler/tests/reservoir_only_give_backs.rs +++ b/crates/handler/tests/reservoir_only_give_backs.rs @@ -6,8 +6,8 @@ //! shares change, each against the same transaction without them. use bytecode::opcode::{ - CALL, CODECOPY, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH32, PUSH4, RETURN, - REVERT, SELFDESTRUCT, SSTORE, STOP, + CALL, CODECOPY, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH20, PUSH4, RETURN, REVERT, + SELFDESTRUCT, SSTORE, STOP, }; use context::{ result::{EVMError, ExecutionResult, HaltReason}, From 2b71cb617f9cb401cf62f78df48e142d13eaf7de Mon Sep 17 00:00:00 2001 From: RealiCZ <wylbzc4928@gmail.com> Date: Fri, 13 Nov 2026 14:33:41 +0800 Subject: [PATCH 110/110] fix(gas): count what a halted child paid from regular gas on its caller, and consume it once --- MEGAETH-FORK.md | 13 +-- crates/context/interface/src/cfg/gas.rs | 19 +++- .../context/interface/src/cfg/gas/encoding.rs | 18 +++- .../interface/src/cfg/gas/give_backs.rs | 94 ++++++++++++++++--- .../context/interface/src/cfg/gas/withheld.rs | 15 +-- crates/handler/src/execution/first_frame.rs | 11 ++- crates/handler/src/frame.rs | 22 +++-- crates/handler/tests/frame_result_size.rs | 14 +-- .../tests/reservoir_only_give_backs.rs | 25 ++++- crates/interpreter/src/gas.rs | 7 ++ crates/interpreter/tests/start_marks.rs | 4 +- 11 files changed, 187 insertions(+), 55 deletions(-) diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md index 0a9af9eee6..341d1e90bb 100644 --- a/MEGAETH-FORK.md +++ b/MEGAETH-FORK.md @@ -145,21 +145,22 @@ An id the fork once used for an entry is left unused rather than given a new mea ### Give-backs to the reservoir alone and the legacy share - **API.** `CfgEnv::reservoir_only_give_backs` with `with_reservoir_only_give_backs`, and `Cfg::reservoir_only_give_backs` (default `false`). - On `GasTracker`, forwarded on `Gas`: `reservoir_only_give_backs`, `set_reservoir_only_give_backs`, `record_state_cost_with_legacy_share` and `consume_regular_paid_charges`. + On `GasTracker`, forwarded on `Gas`: `reservoir_only_give_backs`, `set_reservoir_only_give_backs`, `record_state_cost_with_legacy_share`, `consume_regular_paid_charges` and `halted_regular_paid`; on `GasTracker` alone, `add_regular_paid_of`. `GasId::sstore_set_state_gas_legacy_share`, `new_account_state_gas_legacy_share`, `selfdestruct_new_account_state_gas_legacy_share` and `create_state_gas_legacy_share` (ids 245 to 242), with their `GasParams` accessors, and the `state_gas_with_legacy_share!` instruction macro. - **Contract.** revm sets the switch on the transaction's gas (`Handler::tx_gas`) and on every frame's gas, and on the results it builds for a call or creation it answers without running a frame (`EthFrame::make_call_frame`, `make_create_frame`), from the configuration. With it on, no give-back of state or history gas credits regular gas: `refill_reservoir` and `refill_history` top up the reservoir alone, `rollback_state_gas` sets the reservoir to `reservoir + state_gas_spent + history_gas_spent` and leaves regular gas as it was, and `absorb_returned_reservoir` takes the returned reservoir as the caller's without unwinding anything. A frame's regular gas then rises within the frame only by the regular gas a child returns. - `state_gas_spilled` counts every part of a state or history charge regular gas paid, and no give-back lowers it: a child that succeeds or reverts adds its count to its caller's (`handle_reservoir_remaining_gas`), and a halt takes it out of the reservoir the rollback set, which leaves the reservoir the frame received (`consume_regular_paid_charges`), before it spends the regular gas. - After a halt of the transaction's frame, `settle_first_frame` gives back only the part of the EIP-2780 first-frame charge the reservoir paid: that charge is the last made before the frame, and every charge there draws the reservoir first, so the part regular gas paid is the last `min(charge, state_gas_spilled)` of the transaction's count. + `state_gas_spilled` counts every part of a state or history charge regular gas paid in a frame and in the frames below it that returned to it, and no give-back lowers it: a child adds its count to its caller's however it ended (`handle_reservoir_remaining_gas`, `add_regular_paid_of`). + A halt takes the part of the count no halt below consumed yet out of the reservoir the rollback set, which leaves the reservoir the frame received, and records the whole count as consumed (`consume_regular_paid_charges`, `halted_regular_paid`), before it spends the regular gas; the record travels up with the count, so a caller's own halt does not take a halted child's part out a second time. + After a halt of the transaction's frame, `settle_first_frame` gives back only the part of the EIP-2780 first-frame charge the reservoir paid: that charge is the last made before the frame, and every charge there draws the reservoir first, so the part regular gas paid is the last `min(charge, paid)` of what the transaction's count held before the frame's joined it. The legacy share is the part of an opcode's state charge regular gas pays before the reservoir pays any of it: `SSTORE`'s fresh slot, a value `CALL`'s new account, a `SELFDESTRUCT`'s new beneficiary and a `CREATE`'s or `CREATE2`'s created account each take `min(charge, entry)` of their schedule entry from regular gas, withheld part first, before the reservoir; a value call's and a creation's before the forward is computed. A frame whose regular gas cannot pay the share and what the reservoir cannot pay runs out of gas, whatever the reservoir holds. The share is state gas, counted with its charge and given back with it, and the switch and the shares are independent: with the switch off a share is part of the spill a give-back unwinds. - **Consumer.** mega-evm keeps a frame's regular gas from rising within the frame by gas spent on state and history, and keeps creating state at its pre-Amsterdam price in regular gas when a transaction carries a reservoir. Every refill, rollback and reservoir merge that credits regular gas is inside revm: an `SSTORE` that writes a slot back refills inside its instruction, and a frame's rollback and the merge of its reservoir into its caller's are revm's settlement, so no hook that sees the gas afterwards can tell what revm credited; and a value call's and a creation's share must come off regular gas before the opcode computes its forward. - **Removal.** When upstream's EIP-8037 credits every give-back to the reservoir and takes a legacy share from regular gas, as ethereum/EIPs#12581 proposes, or when mega-evm stops doing either. -- **Default.** The switch is off and every share entry is zero, so every result is upstream's: `record_state_cost_with_legacy_share` with a share of zero is `record_state_cost`, `consume_regular_paid_charges` finds nothing after an upstream rollback, which zeroed the spill, and the count a revert adds to its caller is zero for the same reason. - The switch is a `bool` in a word the tracker already had, so `GasTracker` stays 88 bytes and every frame result its size; in a format that carries field names it decodes as `false` from encodings that predate it. +- **Default.** The switch is off and every share entry is zero, so every result is upstream's: `record_state_cost_with_legacy_share` with a share of zero is `record_state_cost`, `consume_regular_paid_charges` changes nothing, a failed child's count, which its rollback zeroed, is not added, and `halted_regular_paid` stays zero. + The switch is a `bool` in a word the tracker already had; the record of what halts consumed is a word of its own, so `GasTracker` is 96 bytes and `Gas` 112, `InterpreterResult` 152, `CallOutcome` and `FrameResult` 216 and `CreateOutcome` 200 (64-bit targets), still copied inline; in a format that carries field names the two decode as `false` and zero from encodings that predate them. In instructions, a give-back, a rollback and a merge read one `bool`, a value call that creates an account and the three other share sites read one schedule entry, and every frame's construction reads the switch from the configuration once. ### Amsterdam opcodes and transfer logs below Amsterdam @@ -456,7 +457,7 @@ An id the fork once used for an entry is left unused rather than given a new mea - **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start. - **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's. What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk: a boundary neither resizes nor frees the slots, a successful end does not scan them, and discarding open children clears the retained slots, at a cost proportional to their retained length. - The marks sit in the padding of the values they ride on, so `GasTracker` stays 88 bytes, `Gas` 104, `InterpreterResult` 144, `CallOutcome` and `FrameResult` 208 and `CreateOutcome` 192 (64-bit targets), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. + The marks sit in the padding of the values they ride on, so they add nothing to `GasTracker`, `Gas`, `InterpreterResult`, `CallOutcome`, `FrameResult` and `CreateOutcome` (96, 112, 152, 216, 216 and 200 bytes on 64-bit targets with the give-back record), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror. In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary (and, after a discard with open children, one clear of the retained slots), and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here. Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`. `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's. diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs index 3c09b15e1f..c99ee931ea 100644 --- a/crates/context/interface/src/cfg/gas.rs +++ b/crates/context/interface/src/cfg/gas.rs @@ -123,10 +123,11 @@ pub struct GasTracker { /// propagated to the parent frame so a later parent rollback can return it. /// /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set it is the state and - /// history gas regular gas paid, a legacy share included: no give-back lowers it, and a child - /// that succeeds or reverts adds its own to its caller's, its reverted charges having gone into - /// the reservoir it returns. A halt takes it out of the reservoir and then zeroes it - /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)). + /// history gas regular gas paid in this frame and in every frame below it that returned to + /// it, a legacy share included: no give-back lowers it, and a child adds its own to its + /// caller's however it ends. A halt takes the part of it no halt below consumed yet out of the + /// reservoir ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges), + /// [`halted_regular_paid`](Self::halted_regular_paid)). state_gas_spilled: u64, /// Net history gas spent so far. /// @@ -191,6 +192,14 @@ pub struct GasTracker { /// In a format that carries field names, such as JSON, encodings made before this field existed /// decode it as `false`. reservoir_only_give_backs: bool, + /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set, the part of + /// `state_gas_spilled` that halts already consumed: what frames below this one that halted, or + /// that returned to it from frames that halted below them, paid of state and history gas from + /// regular gas ([`halted_regular_paid`](Self::halted_regular_paid)). Zero with it off. + /// + /// In a format that carries field names, such as JSON, encodings made before this field existed + /// decode it as zero. + halted_regular_paid: u64, /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)). It fits padding /// the tracker already had, in the word `failed_charge_recorded` takes, so the tracker's size /// is unchanged. No part of the tracker's value, and not encoded. @@ -213,6 +222,7 @@ impl core::fmt::Debug for GasTracker { .field("failed_charge_remaining", &self.failed_charge_remaining) .field("failed_charge_recorded", &self.failed_charge_recorded) .field("reservoir_only_give_backs", &self.reservoir_only_give_backs) + .field("halted_regular_paid", &self.halted_regular_paid) .finish() } } @@ -234,6 +244,7 @@ impl GasTracker { failed_charge_remaining: 0, failed_charge_recorded: false, reservoir_only_give_backs: false, + halted_regular_paid: 0, start_mark: StartMark::NONE, } } diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs index 3d359107c1..8108b7f617 100644 --- a/crates/context/interface/src/cfg/gas/encoding.rs +++ b/crates/context/interface/src/cfg/gas/encoding.rs @@ -32,6 +32,8 @@ pub(super) struct Encoded { failed_charge_remaining: Option<u64>, #[serde(default)] reservoir_only_give_backs: bool, + #[serde(default)] + halted_regular_paid: u64, } impl From<GasTracker> for Encoded { @@ -48,6 +50,7 @@ impl From<GasTracker> for Encoded { withheld_crossing: tracker.withheld_crossing, failed_charge_remaining: tracker.failed_charge_remaining(), reservoir_only_give_backs: tracker.reservoir_only_give_backs, + halted_regular_paid: tracker.halted_regular_paid, } } } @@ -67,6 +70,7 @@ impl From<Encoded> for GasTracker { failed_charge_remaining: 0, failed_charge_recorded: false, reservoir_only_give_backs: encoded.reservoir_only_give_backs, + halted_regular_paid: encoded.halted_regular_paid, start_mark: super::StartMark::NONE, }; tracker.set_failed_charge_remaining(encoded.failed_charge_remaining); @@ -80,10 +84,16 @@ mod tests { /// A tracker with every field away from its default: part of its regular gas withheld, a /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a - /// refund, and give-backs that credit the reservoir alone. + /// refund, give-backs that credit the reservoir alone, and a halted child's count. fn every_field_set() -> GasTracker { let mut tracker = GasTracker::new(1_000, 400, 300); tracker.set_reservoir_only_give_backs(true); + let mut halted = GasTracker::new(10, 10, 0); + halted.set_reservoir_only_give_backs(true); + assert!(halted.record_state_cost(4)); + halted.rollback_state_gas(); + halted.consume_regular_paid_charges(); + tracker.add_regular_paid_of(&halted); tracker.withhold(100); assert!(!tracker.record_regular_cost(350)); assert!(tracker.record_state_cost(500)); @@ -100,9 +110,9 @@ mod tests { serde_json::to_string(&every_field_set()).unwrap(), concat!( r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#, - r#""state_gas_spilled":200,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, + r#""state_gas_spilled":204,"history_gas_spent":0,"refunded":-3,"withheld":0,"#, r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#, - r#""reservoir_only_give_backs":true}"#, + r#""reservoir_only_give_backs":true,"halted_regular_paid":4}"#, ) ); assert_eq!( @@ -111,7 +121,7 @@ mod tests { r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#, r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#, r#""withheld_crossing":null,"failed_charge_remaining":null,"#, - r#""reservoir_only_give_backs":false}"#, + r#""reservoir_only_give_backs":false,"halted_regular_paid":0}"#, ) ); } diff --git a/crates/context/interface/src/cfg/gas/give_backs.rs b/crates/context/interface/src/cfg/gas/give_backs.rs index c6e43cc81d..325900d523 100644 --- a/crates/context/interface/src/cfg/gas/give_backs.rs +++ b/crates/context/interface/src/cfg/gas/give_backs.rs @@ -2,7 +2,7 @@ //! //! The switch that makes every give-back of state or history gas credit a [`GasTracker`]'s //! reservoir and never its regular gas, the count of what regular gas paid for state and history -//! that a halt consumes, and the charge that takes a legacy share from regular gas before the +//! and the part of it halts consumed, and the charge that takes a legacy share from regular gas before the //! reservoir. The tracker's own documentation describes how each give-back is credited with the //! switch on and off. @@ -19,8 +19,9 @@ impl GasTracker { /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)) land in the reservoir, so a /// frame's `remaining` rises within the frame only by the regular gas a child returns. /// [`state_gas_spilled`](Self::state_gas_spilled) counts what regular gas paid of state and - /// history charges and no give-back lowers it. A halt consumes the frame's regular gas and - /// the part of its charges regular gas paid, and gives it back the reservoir it received + /// history charges in the frame and in the frames below it that returned to it, however they + /// ended, and no give-back lowers it. A halt consumes the frame's regular gas and the part of + /// its charges regular gas paid, and gives it back the reservoir it received /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)). #[inline] pub const fn reservoir_only_give_backs(&self) -> bool { @@ -79,10 +80,21 @@ impl GasTracker { true } + /// The part of [`state_gas_spilled`](Self::state_gas_spilled) that halts below this frame + /// already consumed, with [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set: + /// what frames that halted paid of state and history gas from regular gas, which their halts + /// took out of the reservoirs they returned. Zero with it off. + #[inline] + pub const fn halted_regular_paid(&self) -> u64 { + self.halted_regular_paid + } + /// Consumes, after [`rollback_state_gas`](Self::rollback_state_gas) of a frame that halts, the - /// part of its state and history charges regular gas paid: the reservoir gives up - /// `state_gas_spilled`, which is then zero, so it holds the reservoir the frame received, and - /// what regular gas paid is consumed with the regular gas the halt spends. + /// part of its state and history charges regular gas paid that no halt below it consumed yet: + /// the reservoir gives up `state_gas_spilled` less + /// [`halted_regular_paid`](Self::halted_regular_paid), so it holds the reservoir the frame + /// received, and what regular gas paid is consumed with the regular gas the halt spends. The + /// count stays, all of it now consumed, for the caller to add to its own. /// /// The rollback put every charge into the reservoir only with /// [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set. With it off the rollback @@ -90,8 +102,28 @@ impl GasTracker { /// changes nothing. #[inline] pub const fn consume_regular_paid_charges(&mut self) { - self.reservoir = self.reservoir.saturating_sub(self.state_gas_spilled); - self.state_gas_spilled = 0; + if !self.reservoir_only_give_backs { + return; + } + let unconsumed = self + .state_gas_spilled + .saturating_sub(self.halted_regular_paid); + self.reservoir = self.reservoir.saturating_sub(unconsumed); + self.halted_regular_paid = self.state_gas_spilled; + } + + /// Adds what a returning `child`'s regular gas paid of state and history gas to this frame's + /// count, with the part of it halts consumed, however the child ended + /// ([`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set): no give-back lowers + /// the count, and a halted child's part is spent like the rest. + #[inline] + pub const fn add_regular_paid_of(&mut self, child: &GasTracker) { + self.state_gas_spilled = self + .state_gas_spilled + .saturating_add(child.state_gas_spilled); + self.halted_regular_paid = self + .halted_regular_paid + .saturating_add(child.halted_regular_paid); } } @@ -206,8 +238,9 @@ mod tests { } /// After a halting frame's rollback, consuming what regular gas paid leaves the reservoir the - /// frame received with the switch on, and changes nothing with it off, where the rollback - /// already credited it to regular gas. + /// frame received with the switch on, and keeps the count, all of it now consumed, for the + /// caller; with it off it changes nothing, where the rollback already credited the spill to + /// regular gas and zeroed it. #[test] fn test_a_halt_gives_back_the_reservoir_the_frame_received() { for on in [false, true] { @@ -220,11 +253,50 @@ mod tests { gas.consume_regular_paid_charges(); gas.spend_all(); assert_eq!(gas.reservoir(), 100, "switch on: {on}"); - assert_eq!(gas.state_gas_spilled(), 0, "switch on: {on}"); + // Regular gas paid 200 and 50 past the reservoir, then the share of 80. + let paid = if on { 330 } else { 0 }; + assert_eq!(gas.state_gas_spilled(), paid, "switch on: {on}"); + assert_eq!(gas.halted_regular_paid(), paid, "switch on: {on}"); assert_eq!(gas.remaining(), 0, "switch on: {on}"); } } + /// A halt consumes only what no halt below it consumed: a frame whose child halted adds the + /// child's count with the record that the child's halt consumed it, so its own halt leaves the + /// reservoir it received rather than taking the child's part out a second time. + #[test] + fn test_a_halt_after_a_halted_child_consumes_the_childs_part_once() { + let mut parent = tracker(10_000, 500, true); + // 500 from the reservoir, 200 from regular gas. + assert!(parent.record_state_cost(700)); + let mut child = tracker(1_000, 0, true); + assert!(child.record_state_cost(40)); + child.rollback_state_gas(); + child.consume_regular_paid_charges(); + child.spend_all(); + assert_eq!( + ( + child.reservoir(), + child.state_gas_spilled(), + child.halted_regular_paid() + ), + (0, 40, 40) + ); + + parent.add_regular_paid_of(&child); + assert_eq!( + (parent.state_gas_spilled(), parent.halted_regular_paid()), + (240, 40) + ); + parent.rollback_state_gas(); + parent.consume_regular_paid_charges(); + assert_eq!(parent.reservoir(), 500, "the reservoir the parent received"); + assert_eq!( + (parent.state_gas_spilled(), parent.halted_regular_paid()), + (240, 240) + ); + } + /// A legacy share is paid from regular gas before the reservoir, which pays the rest; the /// regular part is counted as paid by regular gas, and the whole charge is state gas. #[test] diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs index a3dc97c7e8..b7373e0359 100644 --- a/crates/context/interface/src/cfg/gas/withheld.rs +++ b/crates/context/interface/src/cfg/gas/withheld.rs @@ -236,13 +236,14 @@ mod tests { assert_eq!(size_of::<Option<WithheldCrossing>>(), size_of::<u64>()); } - /// The tracker is 88 bytes: 72 with the withheld part and its record, and two words more for - /// the failed-charge record, whose second word also holds the start mark. Copies of the - /// tracker, and of every `Gas` and frame result that holds one, grow with it, so a new field - /// is measured before this changes. - #[test] - fn test_the_tracker_is_88_bytes() { - assert_eq!(size_of::<GasTracker>(), 88); + /// The tracker is 96 bytes: 72 with the withheld part and its record, two words more for the + /// failed-charge record, whose second word also holds the start mark and the give-back switch, + /// and one for the part of what regular gas paid of state and history that halts consumed. + /// Copies of the tracker, and of every `Gas` and frame result that holds one, grow with it, so + /// a new field is measured before this changes. + #[test] + fn test_the_tracker_is_96_bytes() { + assert_eq!(size_of::<GasTracker>(), 96); } /// Withholding moves gas between the parts and leaves the total alone. diff --git a/crates/handler/src/execution/first_frame.rs b/crates/handler/src/execution/first_frame.rs index f68c1a2dbd..bfada2891f 100644 --- a/crates/handler/src/execution/first_frame.rs +++ b/crates/handler/src/execution/first_frame.rs @@ -48,6 +48,10 @@ where { let instruction_result = frame_result.instruction_result(); + // What the transaction's regular gas paid of the charges made before the frame, read before + // the frame's own count joins it below. + let paid_before_the_frame = gas.state_gas_spilled(); + // All regular gas was forwarded to the first frame: consume it on the // transaction-level gas; the settle below returns the frame's unused // part. @@ -79,11 +83,10 @@ where // With give-backs to the reservoir alone, the part of the charge regular gas paid stays // spent after a halt. The charge is the last one made before the frame, and every charge // made there draws the reservoir first, so that part is the last of what the - // transaction's regular gas paid for state and history, which the halted frame added - // nothing to. Without the switch the refill below credits that part to `remaining`, which - // the halt consumes. + // transaction's regular gas paid for state and history before the frame. Without the + // switch the refill below credits that part to `remaining`, which the halt consumes. let consumed = if instruction_result.is_halt() && gas.reservoir_only_give_backs() { - core::cmp::min(charge, gas.state_gas_spilled()) + core::cmp::min(charge, paid_before_the_frame) } else { 0 }; diff --git a/crates/handler/src/frame.rs b/crates/handler/src/frame.rs index dd77209afc..0a79750ee3 100644 --- a/crates/handler/src/frame.rs +++ b/crates/handler/src/frame.rs @@ -679,10 +679,14 @@ pub const fn handle_reservoir_remaining_gas( // Merge the settled child into the parent. if instruction_result.is_ok_or_revert() { parent_gas.erase_cost(child_gas.remaining()); - // What the child's regular gas paid for state and history: on a success, so a later - // rollback of the parent can return it; on a revert, only with give-backs to the - // reservoir alone, where the rollback kept the count and returned the charges in the - // reservoir. A revert's rollback zeroes it otherwise, and a halt's consumption always. + } + // What the child's regular gas paid for state and history. With give-backs to the reservoir + // alone, however the child ended: no give-back lowers the count, and a halt's part comes with + // the record that the halt consumed it. Otherwise on a success, so a later rollback of the + // parent can return it; a failure's rollback zeroed it. + if child_gas.reservoir_only_give_backs() { + parent_gas.add_regular_paid_of(child_gas); + } else if instruction_result.is_ok_or_revert() { parent_gas.add_state_gas_spilled(child_gas.state_gas_spilled()); } if instruction_result.is_ok() { @@ -1100,15 +1104,15 @@ mod tests { /// With give-backs to the reservoir alone a child that succeeds hands back what it left of /// both pools; one that reverts puts every charge it made, net of the give-backs it received, - /// into the reservoir it returns, and its caller counts what the child's regular gas paid as - /// its own; one that halts returns the reservoir it received and consumes its regular gas with - /// what it paid of the charges. + /// into the reservoir it returns; one that halts returns the reservoir it received and consumes + /// its regular gas with what it paid of the charges. However the child ends, its caller counts + /// what the child's regular gas paid as its own, and, after a halt, that the halt consumed it. #[test] fn test_with_give_backs_to_the_reservoir_a_failed_child_returns_its_charges_as_reservoir() { for (result, expected) in [ (InstructionResult::Stop, (9_700, 50, 1_250, 300)), (InstructionResult::Revert, (9_700, 1_300, 0, 300)), - (InstructionResult::OutOfGas, (5_000, 1_000, 0, 0)), + (InstructionResult::OutOfGas, (5_000, 1_000, 0, 300)), ] { let mut parent = reservoir_only(10_000, 1_000); assert!(parent.record_regular_cost(5_000)); @@ -1120,6 +1124,8 @@ mod tests { handle_reservoir_remaining_gas(result, &mut parent, &mut child); assert_eq!(figures(&parent), expected, "{result:?}"); + let consumed = if result.is_halt() { 300 } else { 0 }; + assert_eq!(parent.halted_regular_paid(), consumed, "{result:?}"); } } diff --git a/crates/handler/tests/frame_result_size.rs b/crates/handler/tests/frame_result_size.rs index 3532791001..1993afde35 100644 --- a/crates/handler/tests/frame_result_size.rs +++ b/crates/handler/tests/frame_result_size.rs @@ -3,17 +3,17 @@ use interpreter::{CallOutcome, CreateOutcome, Gas, InterpreterResult}; use revm_handler::FrameResult; -/// A frame result is 208 bytes on a 64-bit target, and the values it is built from are what that +/// A frame result is 216 bytes on a 64-bit target, and the values it is built from are what that /// takes. The handler moves frame results through its wrappers several times per frame, and past /// about 256 bytes each move is a library copy rather than an inline one, so a field added to any /// of them is measured before this changes. #[cfg(target_pointer_width = "64")] #[test] -fn test_a_frame_result_is_208_bytes() { +fn test_a_frame_result_is_216_bytes() { use core::mem::size_of; - assert_eq!(size_of::<Gas>(), 104); - assert_eq!(size_of::<InterpreterResult>(), 144); - assert_eq!(size_of::<CallOutcome>(), 208); - assert_eq!(size_of::<CreateOutcome>(), 192); - assert_eq!(size_of::<FrameResult>(), 208); + assert_eq!(size_of::<Gas>(), 112); + assert_eq!(size_of::<InterpreterResult>(), 152); + assert_eq!(size_of::<CallOutcome>(), 216); + assert_eq!(size_of::<CreateOutcome>(), 200); + assert_eq!(size_of::<FrameResult>(), 216); } diff --git a/crates/handler/tests/reservoir_only_give_backs.rs b/crates/handler/tests/reservoir_only_give_backs.rs index 0a871a5666..6237b63d32 100644 --- a/crates/handler/tests/reservoir_only_give_backs.rs +++ b/crates/handler/tests/reservoir_only_give_backs.rs @@ -515,7 +515,8 @@ fn test_a_reverting_child_returns_its_regular_paid_charge_as_reservoir() { /// A child that pays a fresh slot from regular gas and halts returns the reservoir it received, /// with the switch on as with it off: what regular gas paid is consumed with its regular gas, and -/// its caller ends as it does without the switch. +/// its caller ends with the pools it has without the switch. With the switch on the caller counts +/// what the halted child's regular gas paid, and that the halt consumed it. #[test] fn test_a_halting_child_returns_the_reservoir_it_received() { let contract = || Code::default().call(Some(500_000), CHILD, 0).op(STOP); @@ -526,7 +527,27 @@ fn test_a_halting_child_returns_the_reservoir_it_received() { assert_eq!(upstream.child().result, InstructionResult::InvalidFEOpcode); assert_eq!(upstream.top().gas.reservoir(), 0); assert_eq!(pools(&reservoir_only.top().gas), pools(&upstream.top().gas)); - assert_eq!(reservoir_only.top().gas.state_gas_spilled(), 0); + assert_eq!(reservoir_only.top().gas.state_gas_spilled(), SSTORE_SET); + assert_eq!(reservoir_only.top().gas.halted_regular_paid(), SSTORE_SET); + assert_eq!(upstream.top().gas.state_gas_spilled(), 0); +} + +/// A creation whose init code pays a fresh slot from regular gas before it halts: the frame's own +/// count joins the transaction's at the settlement, and the created account's state gas still +/// comes back for exactly the part the reservoir paid of it, read off what regular gas paid before +/// the frame, not off the count the frame added to. +#[test] +fn test_a_halting_first_frame_that_paid_a_slot_gives_back_only_what_the_reservoir_paid() { + let reservoir = NEW_ACCOUNT / 3; + let init_code = Code::default().sstore(1).op(INVALID).0; + for setting in [UPSTREAM, RESERVOIR_ONLY] { + let run = run( + context(db(Code::default(), 0, Code::default()), setting), + tx(TxKind::Create, init_code.clone(), REGULAR_CAP + reservoir), + ); + assert_eq!(run.top().result, InstructionResult::InvalidFEOpcode); + assert_eq!(pools(&run.settled), (0, reservoir), "{setting:?}"); + } } /// A creation transaction whose frame halts gives back, with the switch on, the part of its diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index e5781e8afa..468a24cb3a 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -236,6 +236,13 @@ impl Gas { self.tracker.refill_reservoir(amount); } + /// The part of [`state_gas_spilled`](Self::state_gas_spilled) halts below this frame already + /// consumed. See [`GasTracker::halted_regular_paid`]. + #[inline] + pub const fn halted_regular_paid(&self) -> u64 { + self.tracker.halted_regular_paid() + } + /// Consumes, after the rollback of a frame that halts, the part of its charges regular gas /// paid. See [`GasTracker::consume_regular_paid_charges`]. #[inline] diff --git a/crates/interpreter/tests/start_marks.rs b/crates/interpreter/tests/start_marks.rs index 22c4570134..cfe640e868 100644 --- a/crates/interpreter/tests/start_marks.rs +++ b/crates/interpreter/tests/start_marks.rs @@ -11,12 +11,12 @@ use revm_interpreter::{ const TRACKER: &str = "GasTracker { gas_limit: 100, remaining: 90, reservoir: 5, \ state_gas_spent: 0, state_gas_spilled: 0, history_gas_spent: 0, refunded: 3, withheld: 0, \ withheld_crossing: None, failed_charge_remaining: 0, failed_charge_recorded: false, \ - reservoir_only_give_backs: false }"; + reservoir_only_give_backs: false, halted_regular_paid: 0 }"; const RESULT: &str = "InterpreterResult { result: Stop, output: 0x, gas: Gas { tracker: \ GasTracker { gas_limit: 10, remaining: 10, reservoir: 0, state_gas_spent: 0, \ state_gas_spilled: 0, history_gas_spent: 0, refunded: 0, withheld: 0, withheld_crossing: \ None, failed_charge_remaining: 0, failed_charge_recorded: false, \ - reservoir_only_give_backs: false }, memory: MemoryGas { \ + reservoir_only_give_backs: false, halted_regular_paid: 0 }, memory: MemoryGas { \ words_num: 0, expansion_cost: 0 } } }"; const fn tracker() -> GasTracker {